idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
8,000
public static double [ ] colMeans ( RealMatrix matrix ) { double [ ] retval = EMatrixUtils . colSums ( matrix ) ; for ( int i = 0 ; i < retval . length ; i ++ ) { retval [ i ] = retval [ i ] / matrix . getRowDimension ( ) ; } return retval ; }
Returns the means of columns .
8,001
public static double [ ] rowMeans ( RealMatrix matrix ) { double [ ] retval = EMatrixUtils . rowSums ( matrix ) ; for ( int i = 0 ; i < retval . length ; i ++ ) { retval [ i ] = retval [ i ] / matrix . getColumnDimension ( ) ; } return retval ; }
Returns the means of rows .
8,002
public static RealMatrix colSubtract ( RealMatrix matrix , double [ ] vector ) { double [ ] [ ] retval = new double [ matrix . getRowDimension ( ) ] [ matrix . getColumnDimension ( ) ] ; for ( int col = 0 ; col < retval . length ; col ++ ) { for ( int row = 0 ; row < retval [ 0 ] . length ; row ++ ) { retval [ row ] [ col ] = matrix . getEntry ( row , col ) - vector [ row ] ; } } return MatrixUtils . createRealMatrix ( retval ) ; }
Returns a new matrix by subtracting elements column by column .
8,003
public static double [ ] columnStdDevs ( RealMatrix matrix ) { double [ ] retval = new double [ matrix . getColumnDimension ( ) ] ; for ( int i = 0 ; i < retval . length ; i ++ ) { retval [ i ] = new DescriptiveStatistics ( matrix . getColumn ( i ) ) . getStandardDeviation ( ) ; } return retval ; }
Returns the standard deviations of columns .
8,004
public static double [ ] rowStdDevs ( RealMatrix matrix ) { double [ ] retval = new double [ matrix . getRowDimension ( ) ] ; for ( int i = 0 ; i < retval . length ; i ++ ) { retval [ i ] = new DescriptiveStatistics ( matrix . getRow ( i ) ) . getStandardDeviation ( ) ; } return retval ; }
Returns the standard deviations of rows .
8,005
public static RealMatrix rbrMultiply ( RealMatrix matrix , RealVector vector ) { RealMatrix retval = MatrixUtils . createRealMatrix ( matrix . getRowDimension ( ) , matrix . getColumnDimension ( ) ) ; for ( int i = 0 ; i < retval . getRowDimension ( ) ; i ++ ) { retval . setRowVector ( i , matrix . getRowVector ( i ) . ebeMultiply ( vector ) ) ; } return retval ; }
Multiplies the matrix rows using the vector element - by - element .
8,006
public static RealMatrix rbind ( RealMatrix m1 , RealMatrix m2 ) { return MatrixUtils . createRealMatrix ( ArrayUtils . addAll ( m1 . getData ( ) , m2 . getData ( ) ) ) ; }
Appends to matrices by rows .
8,007
public static RealMatrix shuffleRows ( RealMatrix matrix , RandomGenerator randomGenerator ) { int [ ] index = MathArrays . sequence ( matrix . getRowDimension ( ) , 0 , 1 ) ; MathArrays . shuffle ( index , randomGenerator ) ; RealMatrix retval = MatrixUtils . createRealMatrix ( matrix . getRowDimension ( ) , matrix . getColumnDimension ( ) ) ; for ( int row = 0 ; row < index . length ; row ++ ) { retval . setRowVector ( row , matrix . getRowVector ( index [ row ] ) ) ; } return retval ; }
Shuffles rows of a matrix using the provided random number generator .
8,008
private static String getCurrentUserName ( ) { Authentication a = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( a == null ) return null ; org . springframework . security . core . userdetails . User u = ( org . springframework . security . core . userdetails . User ) a . getPrincipal ( ) ; if ( u == null ) return null ; return u . getUsername ( ) ; }
or null if nobody s logged in
8,009
public Object getInstance ( ) { try { if ( prototype ) { return doGetInstance ( ) ; } else { synchronized ( cache ) { if ( ! cache . containsKey ( type ) ) { cache . put ( type , doGetInstance ( ) ) ; } return cache . get ( type ) ; } } } catch ( IrohException e ) { throw e ; } catch ( Exception e ) { throw new FailedConstructionException ( e ) ; } }
Retrieves an instance of this source s type respecting scoping rules .
8,010
private void setNegotiatedContentType ( ) { ConnegHandler . NegotiatedMediaType negotiatedMediaType = exchange . getAttachment ( ConnegHandler . NEGOTIATED_MEDIA_TYPE ) ; MediaType negotiated = negotiatedMediaType == null ? responseContentType : negotiatedMediaType . produces ; setResponseMediaType ( negotiated ) ; }
If client accepts anything json will be used
8,011
public ConcatVector newEmptyClone ( ) { ConcatVector clone = new ConcatVector ( getNumberOfComponents ( ) ) ; for ( int i = 0 ; i < pointers . length ; i ++ ) { if ( pointers [ i ] != null && ! sparse [ i ] ) { clone . pointers [ i ] = new double [ pointers [ i ] . length ] ; clone . sparse [ i ] = false ; } } return clone ; }
Creates a ConcatVector whose dimensions are the same as this one for all dense components but is otherwise completely empty . This is useful to prevent resizing during optimizations where we re adding lots of sparse vectors .
8,012
public void setDenseComponent ( int component , double [ ] values ) { if ( component >= pointers . length ) { increaseSizeTo ( component + 1 ) ; } pointers [ component ] = values ; sparse [ component ] = false ; copyOnWrite [ component ] = true ; }
Sets a single component of the concat vector value as a dense vector . This will make a copy of you values array so you re free to continue mutating it .
8,013
public void setSparseComponent ( int component , int index , double value ) { if ( component >= pointers . length ) { increaseSizeTo ( component + 1 ) ; } double [ ] sparseInfo = new double [ 2 ] ; sparseInfo [ 0 ] = index ; sparseInfo [ 1 ] = value ; pointers [ component ] = sparseInfo ; sparse [ component ] = true ; copyOnWrite [ component ] = false ; }
Sets a single component of the concat vector value as a sparse one hot value .
8,014
public void setSparseComponent ( int component , int [ ] indices , double [ ] values ) { if ( component >= pointers . length ) { increaseSizeTo ( component + 1 ) ; } assert ( indices . length == values . length ) ; if ( indices . length == 0 ) { pointers [ component ] = new double [ 2 ] ; sparse [ component ] = true ; copyOnWrite [ component ] = false ; } else { double [ ] sparseInfo = new double [ indices . length * 2 ] ; for ( int i = 0 ; i < indices . length ; i ++ ) { sparseInfo [ i * 2 ] = indices [ i ] ; sparseInfo [ ( i * 2 ) + 1 ] = values [ i ] ; } pointers [ component ] = sparseInfo ; sparse [ component ] = true ; copyOnWrite [ component ] = false ; } }
Sets a component to a set of sparse indices each with a value .
8,015
public double dotProduct ( ConcatVector other ) { if ( loadedNative ) { return dotProductNative ( other ) ; } else { double sum = 0.0f ; for ( int i = 0 ; i < Math . min ( pointers . length , other . pointers . length ) ; i ++ ) { if ( pointers [ i ] == null || other . pointers [ i ] == null ) continue ; if ( sparse [ i ] && other . sparse [ i ] ) { outer : for ( int j = 0 ; j < pointers [ i ] . length / 2 ; j ++ ) { int sparseIndex = ( int ) pointers [ i ] [ j * 2 ] ; for ( int k = 0 ; k < other . pointers [ i ] . length / 2 ; k ++ ) { int otherSparseIndex = ( int ) other . pointers [ i ] [ k * 2 ] ; if ( sparseIndex == otherSparseIndex ) { sum += pointers [ i ] [ ( j * 2 ) + 1 ] * other . pointers [ i ] [ ( k * 2 ) + 1 ] ; continue outer ; } } } } else if ( sparse [ i ] && ! other . sparse [ i ] ) { for ( int j = 0 ; j < pointers [ i ] . length / 2 ; j ++ ) { int sparseIndex = ( int ) pointers [ i ] [ j * 2 ] ; if ( sparseIndex >= 0 && sparseIndex < other . pointers [ i ] . length ) { sum += other . pointers [ i ] [ sparseIndex ] * pointers [ i ] [ ( j * 2 ) + 1 ] ; } } } else if ( ! sparse [ i ] && other . sparse [ i ] ) { for ( int j = 0 ; j < other . pointers [ i ] . length / 2 ; j ++ ) { int sparseIndex = ( int ) other . pointers [ i ] [ j * 2 ] ; if ( sparseIndex >= 0 && sparseIndex < pointers [ i ] . length ) { sum += pointers [ i ] [ sparseIndex ] * other . pointers [ i ] [ ( j * 2 ) + 1 ] ; } } } else { for ( int j = 0 ; j < Math . min ( pointers [ i ] . length , other . pointers [ i ] . length ) ; j ++ ) { sum += pointers [ i ] [ j ] * other . pointers [ i ] [ j ] ; } } } return sum ; } }
This function assumes both vectors are infinitely padded with 0s so it won t complain if there s a dim mismatch . There are no side effects .
8,016
public void mapInPlace ( Function < Double , Double > fn ) { for ( int i = 0 ; i < pointers . length ; i ++ ) { if ( pointers [ i ] == null ) continue ; if ( copyOnWrite [ i ] ) { copyOnWrite [ i ] = false ; pointers [ i ] = pointers [ i ] . clone ( ) ; } if ( sparse [ i ] ) { for ( int j = 0 ; j < pointers [ i ] . length / 2 ; j ++ ) { pointers [ i ] [ ( j * 2 ) + 1 ] = fn . apply ( pointers [ i ] [ ( j * 2 ) + 1 ] ) ; } } else { for ( int j = 0 ; j < pointers [ i ] . length ; j ++ ) { pointers [ i ] [ j ] = fn . apply ( pointers [ i ] [ j ] ) ; } } } }
Apply a function to every element of every component of this vector and replace with the result .
8,017
public int [ ] getSparseIndices ( int component ) { assert ( sparse [ component ] ) ; int [ ] indices = new int [ pointers [ component ] . length / 2 ] ; for ( int i = 0 ; i < pointers [ component ] . length / 2 ; i ++ ) { indices [ i ] = ( int ) pointers [ component ] [ i * 2 ] ; } return indices ; }
Gets you the indices of multi hot in a component assuming it is sparse . Throws an assert if it isn t .
8,018
public boolean valueEquals ( ConcatVector other , double tolerance ) { for ( int i = 0 ; i < Math . max ( pointers . length , other . pointers . length ) ; i ++ ) { int size = 0 ; if ( i < pointers . length && i < other . pointers . length && pointers [ i ] == null && other . pointers [ i ] == null ) { size = 0 ; } else if ( i >= pointers . length || ( i < pointers . length && pointers [ i ] == null ) ) { if ( i >= other . pointers . length ) { size = 0 ; } else if ( other . sparse [ i ] ) { size = other . getSparseIndex ( i ) + 1 ; } else { size = other . pointers [ i ] . length ; } } else if ( i >= other . pointers . length || ( i < other . pointers . length && other . pointers [ i ] == null ) ) { if ( i >= pointers . length ) { size = 0 ; } else if ( sparse [ i ] ) { size = getSparseIndex ( i ) + 1 ; } else { size = pointers [ i ] . length ; } } else { if ( sparse [ i ] && getSparseIndex ( i ) >= size ) size = getSparseIndex ( i ) + 1 ; else if ( ! sparse [ i ] && pointers [ i ] . length > size ) size = pointers [ i ] . length ; if ( other . sparse [ i ] && other . getSparseIndex ( i ) >= size ) size = other . getSparseIndex ( i ) + 1 ; else if ( ! other . sparse [ i ] && other . pointers [ i ] . length > size ) size = other . pointers [ i ] . length ; } for ( int j = 0 ; j < size ; j ++ ) { if ( Math . abs ( getValueAt ( i , j ) - other . getValueAt ( i , j ) ) > tolerance ) return false ; } } return true ; }
Compares two concat vectors by value . This means that we re 0 padding so a dense and sparse component might both be considered the same if the dense array reflects the same value as the sparse array . This is pretty much only useful for testing . Since it s primarily for testing we went with the slower more obviously correct design .
8,019
private void increaseSizeTo ( int newSize ) { assert ( newSize > pointers . length ) ; double [ ] [ ] pointersBuf = new double [ newSize ] [ ] ; boolean [ ] sparseBuf = new boolean [ newSize ] ; boolean [ ] copyOnWriteBuf = new boolean [ newSize ] ; System . arraycopy ( pointers , 0 , pointersBuf , 0 , pointers . length ) ; System . arraycopy ( sparse , 0 , sparseBuf , 0 , pointers . length ) ; System . arraycopy ( copyOnWrite , 0 , copyOnWriteBuf , 0 , pointers . length ) ; pointers = pointersBuf ; sparse = sparseBuf ; copyOnWrite = copyOnWriteBuf ; }
This increases the length of the vector while preserving its contents
8,020
public final boolean matches ( final String targetPath ) { Contract . requireArgNotNull ( "targetPath" , targetPath ) ; if ( regExpr == null ) { return true ; } return regExpr . matcher ( targetPath ) . find ( ) ; }
Returns if the pattern matches the given path .
8,021
public void connectDevice ( Device device ) throws ShanksException { if ( this . linkedDevices . size ( ) < deviceCapacity ) { if ( ! this . linkedDevices . contains ( device ) ) { this . linkedDevices . add ( device ) ; device . connectToLink ( this ) ; logger . finer ( "Link " + this . getID ( ) + " has Device " + device . getID ( ) + " in its linked device list." ) ; } else { logger . finer ( "Link " + this . getID ( ) + " already has Device " + device . getID ( ) + " in its linked device list." ) ; } } else { if ( ! this . linkedDevices . contains ( device ) ) { logger . warning ( "Link " + this . getID ( ) + " is full of its capacity. Device " + device . getID ( ) + " was not included in its linked device list." ) ; throw new TooManyConnectionException ( this ) ; } else { logger . finer ( "Link " + this . getID ( ) + " already has Device " + device . getID ( ) + " in its linked device list." ) ; } } }
Connect a device to the link
8,022
public void connectDevices ( Device device1 , Device device2 ) throws ShanksException { this . connectDevice ( device1 ) ; try { this . connectDevice ( device2 ) ; } catch ( ShanksException e ) { this . disconnectDevice ( device1 ) ; throw e ; } }
Connect both devices to the link
8,023
public static String findMainClass ( File rootFolder ) throws IOException { return doWithMainClasses ( rootFolder , new ClassNameCallback < String > ( ) { public String doWith ( String className ) { return className ; } } ) ; }
Find the main class from a given folder .
8,024
public static String findSingleMainClass ( File rootFolder ) throws IOException { MainClassesCallback callback = new MainClassesCallback ( ) ; MainClassFinder . doWithMainClasses ( rootFolder , callback ) ; return callback . getMainClass ( ) ; }
Find a single main class from a given folder .
8,025
protected void sendUserCredentials ( ) throws UnknownHostException { this . getTracePrintStream ( ) . printf ( "user = %s, host = %s, name = %s%n" , System . getProperty ( "user.name" ) , InetAddress . getLocalHost ( ) . getHostName ( ) , super . getName ( ) ) ; }
Collects some user credentials and sends them over the network .
8,026
protected void readConfiguration ( XPath xpath , Node node ) throws XPathExpressionException , AbstractTracer . Exception { this . autoflush = "true" . equals ( ( String ) xpath . evaluate ( "./dns:AutoFlush/text()" , node , XPathConstants . STRING ) ) ; this . bufferSize = Integer . parseInt ( ( String ) xpath . evaluate ( "./dns:BufSize/text()" , node , XPathConstants . STRING ) ) ; System . out . println ( "this.autoflush = " + this . autoflush ) ; System . out . println ( "this.bufferSize = " + this . bufferSize ) ; NodeList threadNodes = ( NodeList ) xpath . evaluate ( "./dns:Context/dns:Thread" , node , XPathConstants . NODESET ) ; for ( int i = 0 ; i < threadNodes . getLength ( ) ; i ++ ) { String threadName = threadNodes . item ( i ) . getAttributes ( ) . getNamedItem ( "name" ) . getNodeValue ( ) ; boolean online = "true" . equals ( ( String ) xpath . evaluate ( "./dns:Online/text()" , threadNodes . item ( i ) , XPathConstants . STRING ) ) ; int debugLevel = Integer . parseInt ( ( String ) xpath . evaluate ( "./dns:DebugLevel/text()" , threadNodes . item ( i ) , XPathConstants . STRING ) ) ; System . out . println ( "(*-*)" ) ; System . out . println ( "threadName = " + threadName ) ; System . out . println ( "online = " + online ) ; System . out . println ( "debugLevel = " + debugLevel ) ; this . debugConfigMap . put ( threadName , new DebugConfig ( online , debugLevel ) ) ; } }
Reads the configuration for this particular tracer instance by evaluating the given node with the given xpath engine .
8,027
public TraceMethod entry ( String methodSignature ) { synchronized ( this . syncObject ) { out ( ) . printIndentln ( "ENTRY--" + methodSignature + "--" + Thread . currentThread ( ) . getName ( ) + "[" + Thread . currentThread ( ) . getId ( ) + "]" ) ; } TraceMethod traceMethod = null ; try { traceMethod = new TraceMethod ( methodSignature ) ; if ( ! this . threadMap . push ( traceMethod ) ) traceMethod = null ; } catch ( AbstractThreadMap . RuntimeException ex ) { logMessage ( LogLevel . SEVERE , "Stacksize is exceeded. Tracing is off." , this . getClass ( ) , "entry()" ) ; } return traceMethod ; }
Indicates an entering of a method .
8,028
public TraceMethod wayout ( ) { TraceMethod traceMethod = null ; try { traceMethod = this . threadMap . pop ( ) ; if ( traceMethod != null ) { synchronized ( this . syncObject ) { out ( ) . printIndentln ( "RETURN-" + traceMethod . getSignature ( ) + "--(+" + traceMethod . getElapsedTime ( ) + "ms)--" + "(+" + traceMethod . getElapsedCpuTime ( ) + "ms)--" + Thread . currentThread ( ) . getName ( ) + "[" + Thread . currentThread ( ) . getId ( ) + "]" ) ; if ( this . autoflush == true ) { out ( ) . flush ( ) ; } } } } catch ( AbstractThreadMap . RuntimeException ex ) { logMessage ( LogLevel . SEVERE , "Stack is corrupted. Tracing is off." , this . getClass ( ) , "wayout()" ) ; } return traceMethod ; }
Indicates the exiting of a method .
8,029
public void logMessage ( LogLevel logLevel , String message , Class clazz , String methodName ) { Date timeStamp = new Date ( ) ; char border [ ] = new char [ logLevel . toString ( ) . length ( ) + 4 ] ; Arrays . fill ( border , '*' ) ; synchronized ( this . syncObject ) { this . tracePrintStream . println ( border ) ; this . tracePrintStream . printf ( "* %s * [%tc] [%d,%s] [%s] [%s] \"%s\"%n" , logLevel . toString ( ) , timeStamp , Thread . currentThread ( ) . getId ( ) , Thread . currentThread ( ) . getName ( ) , clazz . getName ( ) , methodName , message ) ; this . tracePrintStream . println ( border ) ; } }
Logs a message with the given logLevel and the originating class .
8,030
public void logException ( LogLevel logLevel , Throwable throwable , Class clazz , String methodName ) { Date timeStamp = new Date ( ) ; char border [ ] = new char [ logLevel . toString ( ) . length ( ) + 4 ] ; Arrays . fill ( border , '*' ) ; String message ; if ( throwable . getMessage ( ) != null ) { message = throwable . getMessage ( ) . trim ( ) ; message = message . replace ( System . getProperty ( "line.separator" ) , " => " ) ; } else { message = "No message." ; } synchronized ( this . syncObject ) { this . tracePrintStream . println ( border ) ; this . tracePrintStream . printf ( "* %s * [%tc] [%d,%s] [%s] [%s] \"%s\"%n" , logLevel . toString ( ) , timeStamp , Thread . currentThread ( ) . getId ( ) , Thread . currentThread ( ) . getName ( ) , clazz . getName ( ) , methodName , message ) ; this . tracePrintStream . println ( border ) ; throwable . printStackTrace ( this . tracePrintStream ) ; } }
Logs an exception with the given logLevel and the originating class .
8,031
public void initCurrentTracingContext ( int debugLevel , boolean online ) { TracingContext tracingContext = this . threadMap . getCurrentTracingContext ( ) ; if ( tracingContext == null ) { System . out . println ( formatContextInfo ( debugLevel , online ) ) ; tracingContext = new TracingContext ( debugLevel , online ) ; this . threadMap . setCurrentTracingContext ( tracingContext ) ; } else { tracingContext . setDebugLevel ( debugLevel ) ; tracingContext . setOnline ( online ) ; } }
Initialises the current tracing context with the given debugLevel and online state .
8,032
public void initCurrentTracingContext ( ) { TracingContext tracingContext = this . threadMap . getCurrentTracingContext ( ) ; if ( tracingContext == null ) { if ( this . debugConfigMap . containsKey ( Thread . currentThread ( ) . getName ( ) ) ) { DebugConfig debugConfig = this . debugConfigMap . get ( Thread . currentThread ( ) . getName ( ) ) ; System . out . println ( formatContextInfo ( debugConfig . getLevel ( ) , debugConfig . isOnline ( ) ) ) ; tracingContext = new TracingContext ( debugConfig ) ; this . threadMap . setCurrentTracingContext ( tracingContext ) ; } } }
Initialises the current tracing context by taking the values for debugLevel and online from the configured debug map .
8,033
protected String formatVersionInfo ( ) { Formatter formatter = new Formatter ( ) ; formatter . format ( "TraceLogger[%s]: Version = %s." , this . name , VERSION ) ; return formatter . toString ( ) ; }
Gives a string representation about the version of this library .
8,034
public static LogManagementPlugin getLogManagementPlugin ( ) { final String loggerImpl = org . slf4j . impl . StaticLoggerBinder . getSingleton ( ) . getLoggerFactoryClassStr ( ) ; if ( "Log4jLoggerFactory".e q uals(l o ggerImpl.s u bstring(l o ggerImpl . lastIndexOf ( "." ) + 1 ) ) ) { return new LogManagementPluginLog4jImpl ( ) ; } else if ( loggerImpl . indexOf ( "logback." ) > 1 && "ContextSelectorStaticBinder" . equals ( loggerImpl . substring ( loggerImpl . lastIndexOf ( "." ) + 1 ) ) ) { return new LogManagementPluginLogbackImpl ( ) ; } throw new UnsupportedOperationException ( ) ; }
Get implementation for log management plugin .
8,035
public Predicate create ( Filter filter ) { List < Predicate > predicates = new ArrayList < > ( filter . getPredicates ( ) . size ( ) ) ; for ( org . cdlflex . fruit . Predicate fp : filter . getPredicates ( ) ) { predicates . add ( create ( fp ) ) ; } return connect ( predicates , filter . getConnective ( ) ) ; }
Creates a joined predicate from the given Filter .
8,036
public Predicate create ( org . cdlflex . fruit . Predicate predicate ) { Path < ? > attribute = resolvePath ( predicate . getKey ( ) ) ; Object value = predicate . getValue ( ) ; Predicate jpaPredicate = create ( predicate . getOp ( ) , attribute , value ) ; return ( predicate . isNot ( ) ) ? jpaPredicate . not ( ) : jpaPredicate ; }
Maps the given API Predicate object to a JPA criteria Predicate .
8,037
public Predicate connect ( List < Predicate > predicates , Connective connective ) { Predicate [ ] predicateArray = predicates . toArray ( new Predicate [ predicates . size ( ) ] ) ; switch ( connective ) { case AND : return cb . and ( predicateArray ) ; case OR : return cb . or ( predicateArray ) ; default : throw new UnsupportedOperationException ( "Unknown connective " + connective ) ; } }
Joins the given predicates using the criteria builder with the given connective .
8,038
public List < Order > create ( OrderBy order ) { List < Order > list = new ArrayList < > ( ) ; for ( SortSpecification sort : order . getSort ( ) ) { if ( sort . getSortOrder ( ) == SortOrder . DESC ) { list . add ( cb . desc ( root . get ( sort . getKey ( ) ) ) ) ; } else if ( sort . getSortOrder ( ) == SortOrder . ASC ) { list . add ( cb . asc ( root . get ( sort . getKey ( ) ) ) ) ; } } return list ; }
Converts an OrderBy clause to a list of javax . persistence Order instances given a Root and a CriteriaBuilder .
8,039
protected void findMatching ( Class < ? extends T > type , BiPredicate < Class < ? extends T > , D > predicate ) { traverseType ( type , predicate , new HashSet < > ( ) ) ; }
Perform matching against the given type . This will go through the hierarchy and interfaces of the type trying to find if this map has an entry for them .
8,040
public static Document resourceFileToXMLDocument ( final String location , final String fileName ) { if ( location == null || fileName == null ) return null ; final InputStream in = ResourceUtilities . class . getResourceAsStream ( location + fileName ) ; if ( in == null ) return null ; final DocumentBuilderFactory dbFactory = DocumentBuilderFactory . newInstance ( ) ; final DocumentBuilder dBuilder ; Document doc = null ; try { dBuilder = dbFactory . newDocumentBuilder ( ) ; doc = dBuilder . parse ( in ) ; } catch ( Exception e ) { LOG . error ( "Failed to parse the resource as XML." , e ) ; } finally { try { in . close ( ) ; } catch ( IOException e ) { LOG . error ( "Failed to close the InputStream" , e ) ; } } return doc ; }
Reads a resource file and converts it into a XML based Document object .
8,041
public static BigInteger gcd ( BigInteger a , BigInteger b ) { return gcd ( a , b , Calculator . BIG_INTEGER_CALCULATOR ) ; }
Gets the greatest common divisor of 2 numbers .
8,042
public static BigInteger lcm ( BigInteger a , BigInteger b ) { return lcm ( a , b , Calculator . BIG_INTEGER_CALCULATOR ) ; }
Gets the least common multiple of 2 numbers .
8,043
public static double round ( double value , int decimals , RoundingMode roundingMode ) { if ( decimals < 0 ) { throw new IllegalArgumentException ( "Invalid number of decimal places" ) ; } BigDecimal bd = new BigDecimal ( value ) ; return bd . setScale ( decimals , roundingMode ) . doubleValue ( ) ; }
Rounds a number to the specified number of decomal places .
8,044
public void write ( Service model , OutputStream os ) throws IOException { objectMapper . writerWithDefaultPrettyPrinter ( ) . writeValue ( os , model ) ; }
Write model to stream .
8,045
public List < T > overlapping ( Span span ) { if ( span == null || root . isNull ( ) ) { return Collections . emptyList ( ) ; } return overlapping ( root , span , new ArrayList < > ( ) ) ; }
Gets all Ts that overlap the given span
8,046
public T floor ( T T ) { if ( T == null ) { return null ; } NodeIterator < T > iterator = new NodeIterator < > ( root , - 1 , T . start ( ) , false ) ; if ( iterator . hasNext ( ) ) { return iterator . next ( ) ; } return null ; }
Floor T .
8,047
public T ceiling ( T T ) { if ( T == null ) { return null ; } NodeIterator < T > iterator = new NodeIterator < > ( root , T . end ( ) , Integer . MAX_VALUE , true ) ; if ( iterator . hasNext ( ) ) { return iterator . next ( ) ; } return null ; }
Ceiling T .
8,048
private void readFrom ( InputStream inputStream , Consumer < GraphicalModel > featurizer ) throws IOException { GraphicalModel read ; while ( ( read = GraphicalModel . readFromStream ( inputStream ) ) != null ) { featurizer . accept ( read ) ; add ( read ) ; } }
Load a batch of models from disk while running the function featurizer on each of the models before adding it to the batch . This gives the loader a chance to experiment with new featurization techniques .
8,049
public void writeToFile ( String filename ) throws IOException { FileOutputStream fos = new FileOutputStream ( filename ) ; writeToStream ( fos ) ; fos . close ( ) ; }
Convenience function to write the current state of the modelBatch out to a file including all factors .
8,050
public void writeToFileWithoutFactors ( String filename ) throws IOException { FileOutputStream fos = new FileOutputStream ( filename ) ; writeToStreamWithoutFactors ( fos ) ; fos . close ( ) ; }
Convenience function to write the current state of the modelBatch out to a file without factors .
8,051
public void writeToStreamWithoutFactors ( OutputStream outputStream ) throws IOException { Set < GraphicalModel . Factor > emptySet = new HashSet < > ( ) ; for ( GraphicalModel model : this ) { Set < GraphicalModel . Factor > cachedFactors = model . factors ; model . factors = emptySet ; model . writeToStream ( outputStream ) ; model . factors = cachedFactors ; } }
This writes the whole batch WITHOUT FACTORS which means that anyone loading this batch will need to include their own featurizer . Make sure that you have sufficient metadata to be able to do full featurizations .
8,052
public static < K , V > Tuple2 < K , V > of ( K key , V value ) { return new Tuple2 < > ( key , value ) ; }
Of tuple 2 .
8,053
private < T > Set < ? extends T > create ( Iterable < Class < ? extends T > > types ) { Set < T > result = new HashSet < > ( ) ; for ( Class < ? extends T > t : types ) { if ( ! Modifier . isAbstract ( t . getModifiers ( ) ) && ! t . isInterface ( ) ) { T instance = factory . create ( t ) ; result . add ( instance ) ; } } return Collections . unmodifiableSet ( result ) ; }
Create the given types .
8,054
private void updateIdleTask ( final Task orig , Task mods ) { String newState = StringUtil . normalize ( mods . getState ( ) ) ; if ( newState != null && ! newState . equals ( Task . IDLE ) && ! newState . equals ( Task . STARTING ) ) { throw new IllegalArgumentException ( "Illegal state transition: " + Task . IDLE + " -> " + newState ) ; } if ( newState != null ) { orig . setState ( newState ) ; } if ( StringUtil . normalize ( mods . getName ( ) ) != null ) { orig . setName ( StringUtil . validate ( "name" , mods . getName ( ) , 256 ) ) ; } if ( StringUtil . normalize ( mods . getType ( ) ) != null ) { orig . setType ( StringUtil . validate ( "type" , mods . getType ( ) , 32 ) ) ; } if ( StringUtil . normalize ( mods . getSchedule ( ) ) != null ) { orig . setSchedule ( StringUtil . validate ( "schedule" , mods . getType ( ) , 1024 ) ) ; } if ( StringUtil . normalize ( mods . getData ( ) ) != null ) { orig . setData ( StringUtil . validate ( "data" , mods . getData ( ) , 32672 ) ) ; } final TaskRunner runner = TaskRunner . getInstance ( orig , this , objectSetDao , objectStoreDao , null , null , new HttpClientConfig ( ) ) ; final int taskId = Integer . parseInt ( orig . getId ( ) ) ; tt . execute ( new TransactionCallbackWithoutResult ( ) { public void doInTransactionWithoutResult ( TransactionStatus status ) { boolean success = false ; try { db . update ( UPDATE_SQL , orig . getName ( ) , orig . getType ( ) , orig . getState ( ) , orig . getSchedule ( ) , orig . getData ( ) , taskId ) ; db . update ( "DELETE FROM TaskSetDeps WHERE taskId = ?" , taskId ) ; db . update ( "DELETE FROM TaskStoreDeps WHERE taskId = ?" , taskId ) ; for ( String setId : runner . getRelatedSetIds ( ) ) { db . update ( INSERT_SQL2 , taskId , Integer . parseInt ( setId ) ) ; } for ( String storeId : runner . getRelatedStoreIds ( ) ) { db . update ( INSERT_SQL3 , taskId , Integer . parseInt ( storeId ) ) ; } success = true ; } finally { if ( ! success ) { status . setRollbackOnly ( ) ; } } } } ) ; }
allow prop changes and state transition to starting
8,055
public < T > T asObject ( Class < T > type ) { return config . asObject ( key , type ) ; }
Get this object as another type .
8,056
public static < T > T getBean ( Class < T > clazz ) throws ReflectionException { return parameterizeObject ( Reflect . onClass ( clazz ) . create ( ) . < T > get ( ) ) ; }
Constructs a new instance of the given class and then sets it properties using configuration .
8,057
public static < T > T parameterizeObject ( T object ) { if ( object == null ) { return null ; } BeanMap beanMap = new BeanMap ( object ) ; List < Class < ? > > list = ReflectionUtils . getAncestorClasses ( object ) ; Collections . reverse ( list ) ; for ( Class < ? > clazz : list ) { doParametrization ( beanMap , clazz . getName ( ) ) ; } return object ; }
Sets properties on an object using the values defined in the Config . Will set properties defined in the Config for all of this object s super classes as well .
8,058
public static MediaType valueOf ( String type ) throws IllegalArgumentException { if ( type == null || type . trim ( ) . isEmpty ( ) || type . startsWith ( SUBTYPE_SEPARATOR ) || type . endsWith ( SUBTYPE_SEPARATOR ) ) { throw new IllegalArgumentException ( "Invalid mime type '" + type + "'" ) ; } String [ ] splitType = type . split ( SUBTYPE_SEPARATOR ) ; if ( splitType . length == 2 ) { nonEmpty ( type , splitType [ 0 ] ) ; nonEmpty ( type , splitType [ 1 ] ) ; Map < String , String > parameters = new HashMap < > ( ) ; String subType = splitType [ 1 ] ; if ( splitType [ 1 ] . contains ( PARAMETERS_SEPARATOR ) ) { String [ ] subTypeWithparameter = splitType [ 1 ] . split ( PARAMETERS_SEPARATOR ) ; String paramString = subTypeWithparameter [ 1 ] . trim ( ) ; subType = subTypeWithparameter [ 0 ] ; parameters = parseParameters ( paramString ) ; } return new MediaType ( splitType [ 0 ] . trim ( ) , subType . trim ( ) , parameters ) ; } if ( ! type . contains ( SUBTYPE_SEPARATOR ) ) { String mimeType = mimeMappings . getMimeType ( type ) ; if ( mimeType != null ) { return valueOf ( mimeType ) ; } } throw new IllegalArgumentException ( "Invalid mime type '" + type + "'" ) ; }
Creates a new instance of MediaType by parsing the supplied string .
8,059
private static Object invoke ( final Object target , final Method method , Object ... args ) { try { return method . invoke ( target , args ) ; } catch ( IllegalAccessException | InvocationTargetException e ) { throw new RuntimeException ( e ) ; } }
Invokes the specified method on the specified object and wrapping all exceptions in a RuntimeException .
8,060
private static Object invokeDefault ( final Object proxy , final Method method , final Object [ ] args ) { final Class < ? > declaringClass = method . getDeclaringClass ( ) ; try { return lookupIn ( declaringClass ) . unreflectSpecial ( method , declaringClass ) . bindTo ( proxy ) . invokeWithArguments ( args ) ; } catch ( Throwable throwable ) { throw new RuntimeException ( throwable ) ; } }
Invokes a default method . Default methods are implemented in an interface which is overrided by applying the interface to the proxy . This method allows to invoke the default method on the proxy itselfs bypassing the overriden method .
8,061
private static MethodHandles . Lookup lookupIn ( final Class < ? > declaringClass ) { try { final Constructor < MethodHandles . Lookup > constructor = MethodHandles . Lookup . class . getDeclaredConstructor ( Class . class , int . class ) ; constructor . setAccessible ( true ) ; return constructor . newInstance ( declaringClass , MethodHandles . Lookup . PRIVATE ) ; } catch ( NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e ) { throw new RuntimeException ( e ) ; } }
Creates a method lookup that is capable of accessing private members of declaring classes this Mixin factory has usually no access to .
8,062
private static Optional < Invocable > newInvocable ( final Object target , final Collection < Supplier < Reader > > scripts ) { Optional < Invocable > invocable ; if ( ! scripts . isEmpty ( ) ) { final ScriptEngine engine = new ScriptEngineManager ( ) . getEngineByName ( "javascript" ) ; engine . put ( "target" , target ) ; scripts . stream ( ) . forEach ( script -> loadScript ( engine , script ) ) ; invocable = Optional . of ( ( Invocable ) engine ) ; } else { invocable = Optional . empty ( ) ; } return invocable ; }
Creates a new invocable proxy . The proxy may be used to create interface implementations that are implemented in javascript .
8,063
private static void loadScript ( ScriptEngine engine , Supplier < Reader > scriptReader ) { try ( Reader reader = scriptReader . get ( ) ) { engine . eval ( reader ) ; } catch ( ScriptException | IOException e ) { throw new RuntimeException ( e ) ; } }
Loads a single script from an URL into the script engine
8,064
public final void addConstructor ( final SgConstructor constructor ) { if ( constructor == null ) { throw new IllegalArgumentException ( "The argument 'constructor' cannot be null!" ) ; } if ( constructor . getOwner ( ) != this ) { throw new IllegalArgumentException ( "The owner of 'constructor' is different from 'this'!" ) ; } if ( ! constructors . contains ( constructor ) ) { constructors . add ( constructor ) ; } }
Adds a constructor to the class . Does nothing if the constructor is already in the list of constructors . You will never need to use this method in your code! A constructor is added automatically to the owning class when it s constructed!
8,065
public final void addMethod ( final SgMethod method ) { if ( method == null ) { throw new IllegalArgumentException ( "The argument 'method' cannot be null!" ) ; } if ( method . getOwner ( ) != this ) { throw new IllegalArgumentException ( "The owner of 'method' is different from 'this'!" ) ; } if ( ! methods . contains ( method ) ) { methods . add ( method ) ; } }
Adds a method to the class . Does nothing if the method is already in the list of methods . You will never need to use this method in your code! A method is added automatically to the owning class when it s constructed!
8,066
public final void addField ( final SgField field ) { if ( field == null ) { throw new IllegalArgumentException ( "The argument 'field' cannot be null!" ) ; } if ( field . getOwner ( ) != this ) { throw new IllegalArgumentException ( "The owner of 'field' is different from 'this'!" ) ; } if ( ! fields . contains ( field ) ) { fields . add ( field ) ; } }
Adds a field to the class . Does nothing if the field is already in the list of fields . You will never need to use this method in your code! A field is added automatically to the owning class when it s constructed!
8,067
public final void addClass ( final SgClass clasz ) { if ( clasz == null ) { throw new IllegalArgumentException ( "The argument 'clasz' cannot be null!" ) ; } if ( ! classes . contains ( clasz ) ) { classes . add ( clasz ) ; } }
Adds an inner to this class . Does nothing if the class is already in the list of inner classes .
8,068
public final SgClass findClassByName ( final String name ) { if ( name == null ) { throw new IllegalArgumentException ( "The argument 'name' cannot be null!" ) ; } for ( int i = 0 ; i < classes . size ( ) ; i ++ ) { final SgClass clasz = classes . get ( i ) ; if ( clasz . getName ( ) . equals ( name ) ) { return clasz ; } } return null ; }
Find an inner class by it s name .
8,069
public final SgMethod findMethodByName ( final String name ) { if ( name == null ) { throw new IllegalArgumentException ( "The argument 'name' cannot be null!" ) ; } for ( int i = 0 ; i < methods . size ( ) ; i ++ ) { final SgMethod method = methods . get ( i ) ; if ( method . getName ( ) . equals ( name ) ) { return method ; } } return null ; }
Find a method by it s name .
8,070
public final SgField findFieldByName ( final String name ) { if ( name == null ) { throw new IllegalArgumentException ( "The argument 'name' cannot be null!" ) ; } for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { final SgField field = fields . get ( i ) ; if ( field . getName ( ) . equals ( name ) ) { return field ; } } return null ; }
Find a field by it s name .
8,071
public final boolean hasInterface ( final SgClass intf ) { if ( intf == null ) { throw new IllegalArgumentException ( "The argument 'intf' cannot be null!" ) ; } if ( ! intf . isInterface ( ) ) { throw new IllegalArgumentException ( "The argument 'intf' is a class an not an interface!" ) ; } for ( int i = 0 ; i < interfaces . size ( ) ; i ++ ) { if ( interfaces . get ( i ) . equals ( intf ) ) { return true ; } } if ( superClass != null ) { return superClass . hasInterface ( intf ) ; } return false ; }
Checks if this class or any of it s super classes has a given interface .
8,072
public static SgClass create ( final SgClassPool pool , final Class < ? > clasz ) { if ( pool == null ) { throw new IllegalArgumentException ( "The argument 'pool' cannot be null!" ) ; } if ( clasz == null ) { throw new IllegalArgumentException ( "The argument 'clasz' cannot be null!" ) ; } final SgClass cached = pool . get ( clasz . getName ( ) ) ; if ( cached != null ) { return cached ; } try { final SgClass cl = createClass ( pool , clasz ) ; addInterfaces ( pool , cl , clasz ) ; addFields ( pool , cl , clasz ) ; addConstructors ( pool , cl , clasz ) ; addMethods ( pool , cl , clasz ) ; addInnerClasses ( pool , cl , clasz ) ; return cl ; } catch ( final RuntimeException ex ) { System . out . println ( "ERROR CLASS: " + clasz ) ; throw ex ; } }
Creates a model class by analyzing the real class .
8,073
public static final SgClass getNonPrimitiveClass ( final SgClassPool pool , final SgClass primitive ) { if ( primitive . equals ( BOOLEAN ) ) { return SgClass . create ( pool , Boolean . class ) ; } if ( primitive . equals ( BYTE ) ) { return SgClass . create ( pool , Byte . class ) ; } if ( primitive . equals ( CHAR ) ) { return SgClass . create ( pool , Character . class ) ; } if ( primitive . equals ( SHORT ) ) { return SgClass . create ( pool , Short . class ) ; } if ( primitive . equals ( INT ) ) { return SgClass . create ( pool , Integer . class ) ; } if ( primitive . equals ( LONG ) ) { return SgClass . create ( pool , Long . class ) ; } if ( primitive . equals ( FLOAT ) ) { return SgClass . create ( pool , Float . class ) ; } if ( primitive . equals ( DOUBLE ) ) { return SgClass . create ( pool , Double . class ) ; } throw new IllegalArgumentException ( "No primitive or 'void' class: '" + primitive . getName ( ) + "'!" ) ; }
Returns the corresponding class for a primitive .
8,074
public String getOpenBrowserUrl ( ) { final String customUrl = getCustomBrowserUrl ( ) ; final String deployUrl = getDeployUrl ( ) ; if ( customUrl == null ) { return deployUrl ; } else if ( customUrl . startsWith ( "http://" ) ) { return customUrl ; } else if ( customUrl . startsWith ( "/" ) ) { return buildUrl ( getPort ( ) , customUrl ) ; } else { return deployUrl + customUrl ; } }
Returns the url to use when the browser opens according to both the deploy url and a custom browser url if set .
8,075
private static int getDeterministicAssignment ( double [ ] distribution ) { int assignment = - 1 ; for ( int i = 0 ; i < distribution . length ; i ++ ) { if ( distribution [ i ] == 1.0 ) { if ( assignment == - 1 ) assignment = i ; else return - 1 ; } else if ( distribution [ i ] != 0.0 ) return - 1 ; } return assignment ; }
Finds the deterministic assignment forced by a distribution or if none exists returns - 1
8,076
public GraphicalModel compileModel ( ) { GraphicalModel compiled = new GraphicalModel ( ) ; for ( GraphicalModel . Factor factor : model . factors ) { compiled . addStaticFactor ( factor . neigborIndices , factor . getDimensions ( ) , assign -> factor . getAssignmentValue ( assign , weights ) ) ; } for ( int var = 0 ; var < model . numVariables ( ) ; ++ var ) { Map < String , String > metadata = model . getVariableMetaDataByReference ( var ) ; if ( metadata . containsKey ( VARIABLE_OBSERVED_VALUE ) ) { compiled . getVariableMetaDataByReference ( var ) . put ( VARIABLE_OBSERVED_VALUE , metadata . get ( VARIABLE_OBSERVED_VALUE ) ) ; } } return compiled ; }
Compile this model into a static model given the model and weights in this clique tree .
8,077
private TableFactor marginalizeMessage ( TableFactor message , int [ ] relevant , MarginalizationMethod marginalize ) { TableFactor result = message ; for ( int i : message . neighborIndices ) { boolean contains = false ; for ( int j : relevant ) { if ( i == j ) { contains = true ; break ; } } if ( ! contains ) { switch ( marginalize ) { case SUM : result = result . sumOut ( i ) ; break ; case MAX : result = result . maxOut ( i ) ; break ; } } } return result ; }
This is a key step in message passing . When we are calculating a message we want to marginalize out all variables not relevant to the recipient of the message . This function does that .
8,078
private boolean domainsOverlap ( TableFactor f1 , TableFactor f2 ) { for ( int n1 : f1 . neighborIndices ) { for ( int n2 : f2 . neighborIndices ) { if ( n1 == n2 ) return true ; } } return false ; }
Just a quick inline to check if two factors have overlapping domains . Since factor neighbor sets are super small this n^2 algorithm is fine .
8,079
public URI getPath ( final org . eclipse . aether . artifact . Artifact artifact ) { return toUri ( pathOf ( new DefaultArtifact ( artifact . getGroupId ( ) , artifact . getArtifactId ( ) , artifact . getBaseVersion ( ) , "" , artifact . getExtension ( ) , artifact . getClassifier ( ) , new DefaultArtifactHandler ( artifact . getExtension ( ) ) ) ) ) ; }
The Aether implementation .
8,080
private URI toUri ( final String path ) { try { return new URI ( null , null , path , null ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } }
Converts from String to URI .
8,081
public final void addBodyLine ( final String line ) { if ( line == null ) { throw new IllegalArgumentException ( "The argument 'line' cannot be NULL!" ) ; } body . add ( line . trim ( ) ) ; }
Add a new line to the body .
8,082
public final String getSignature ( ) { final StringBuffer sb = new StringBuffer ( ) ; if ( getModifiers ( ) . length ( ) > 0 ) { sb . append ( getModifiers ( ) ) ; sb . append ( " " ) ; } sb . append ( returnType . getName ( ) ) ; sb . append ( " " ) ; sb . append ( getName ( ) ) ; sb . append ( "(" ) ; for ( int i = 0 ; i < getArguments ( ) . size ( ) ; i ++ ) { if ( i > 0 ) { sb . append ( ", " ) ; } sb . append ( getArguments ( ) . get ( i ) ) ; } sb . append ( ")" ) ; if ( getExceptions ( ) . size ( ) > 0 ) { sb . append ( " throws " ) ; for ( int i = 0 ; i < getExceptions ( ) . size ( ) ; i ++ ) { if ( i > 0 ) { sb . append ( "," ) ; } sb . append ( getExceptions ( ) . get ( i ) . getName ( ) ) ; } } return sb . toString ( ) ; }
Returns the signature of the method .
8,083
public final String getCallSignature ( ) { final StringBuffer sb = new StringBuffer ( ) ; sb . append ( getName ( ) ) ; sb . append ( "(" ) ; for ( int i = 0 ; i < getArguments ( ) . size ( ) ; i ++ ) { if ( i > 0 ) { sb . append ( ", " ) ; } final SgArgument arg = getArguments ( ) . get ( i ) ; sb . append ( arg . getName ( ) ) ; } sb . append ( ")" ) ; return sb . toString ( ) ; }
Returns the call signature of the method .
8,084
public String getNamespaceURI ( String prefix ) { if ( prefix == null || ! prefix . equals ( "dns" ) ) throw new IllegalArgumentException ( "Accept only default namespace." ) ; return "http://www.christofreichardt.de/java/tracer" ; }
Returns the fixed namespace URI for the prefix dns . Other prefixes will cause an IllegalArgumentException .
8,085
public final String get ( final String key ) { final Property prop = find ( key ) ; if ( prop == null ) { return null ; } return prop . getValue ( ) ; }
Returns a value for a given key .
8,086
public final String getStatus ( final String key ) { final Property prop = find ( key ) ; if ( prop == null ) { return null ; } return prop . getStatus ( ) ; }
Returns a status text for a given key .
8,087
public final void put ( final String key , final String value ) { final Property prop = find ( key ) ; if ( prop == null ) { props . add ( new Property ( key , null , value ) ) ; } else { prop . setValue ( value ) ; } }
Set a value for a property . If a property with the key is already known the value will be changed . Otherwise a new property will be created .
8,088
public final boolean isRemoved ( final String key ) { final Property prop = find ( key ) ; if ( prop == null ) { return true ; } return prop . isDeleted ( ) ; }
Returns if a property has been deleted .
8,089
public final List < String > getKeyList ( ) { final List < String > keys = new ArrayList < > ( ) ; final Iterator < String > it = keyIterator ( ) ; while ( it . hasNext ( ) ) { keys . add ( it . next ( ) ) ; } return keys ; }
Returns a list of all known keys including the deleted ones .
8,090
public final Iterator < String > keyIterator ( ) { return new Iterator < String > ( ) { private final Iterator < Property > it = props . iterator ( ) ; public boolean hasNext ( ) { return it . hasNext ( ) ; } public String next ( ) { final Property prop = it . next ( ) ; return prop . getKey ( ) ; } public void remove ( ) { it . remove ( ) ; } } ; }
Returns a key iterator .
8,091
public final Properties toProperties ( ) { final Properties retVal = new Properties ( ) ; for ( int i = 0 ; i < props . size ( ) ; i ++ ) { final Property prop = props . get ( i ) ; if ( ! prop . isDeleted ( ) ) { retVal . put ( prop . getKey ( ) , prop . getValue ( ) ) ; } } return retVal ; }
Returns a copy of all properties .
8,092
private static < CT , I > Function < CT , I > resolveAndExtend ( Class < CT > contextType , List < MethodResolver < CT > > resolvers , Class < I > typeToExtend ) { ResolvedTypeWithMembers withMembers = Types . resolveMembers ( typeToExtend ) ; Map < Method , MethodInvocationHandler < CT > > handlers = new HashMap < > ( ) ; try { for ( ResolvedMethod method : withMembers . getMemberMethods ( ) ) { if ( ! method . isAbstract ( ) ) continue ; boolean foundInvoker = false ; MethodEncounter encounter = new MethodEncounterImpl ( method ) ; for ( MethodResolver < CT > resolver : resolvers ) { Optional < MethodInvocationHandler < CT > > opt = resolver . create ( encounter ) ; if ( opt . isPresent ( ) ) { foundInvoker = true ; handlers . put ( method . getRawMember ( ) , opt . get ( ) ) ; break ; } } if ( ! foundInvoker ) { throw new ProxyException ( "The method " + method . getName ( ) + " could not be handled" ) ; } } } catch ( ProxyException e ) { throw new ProxyException ( typeToExtend . getName ( ) + ":\n" + e . getMessage ( ) ) ; } catch ( Exception e ) { throw new ProxyException ( typeToExtend . getName ( ) + ":\n" + e . getMessage ( ) , e ) ; } return createFunction ( contextType , typeToExtend , Collections . unmodifiableMap ( handlers ) ) ; }
Internal helper that resolves all the invokers using the given resolvers .
8,093
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) private static < CT , I > Function < CT , I > createFunction ( Class < CT > contextType , Class < I > typeToExtend , Map < Method , MethodInvocationHandler < CT > > invokers ) { try { DynamicType . Builder builder = new ByteBuddy ( ) . subclass ( typeToExtend ) ; builder = builder . defineField ( "context" , contextType , Visibility . PRIVATE ) ; builder = builder . defineConstructor ( Visibility . PUBLIC ) . withParameter ( contextType ) . intercept ( MethodCall . invoke ( Object . class . getDeclaredConstructor ( ) ) . onSuper ( ) . andThen ( FieldAccessor . ofField ( "context" ) . setsArgumentAt ( 0 ) ) ) ; for ( Map . Entry < Method , MethodInvocationHandler < CT > > e : invokers . entrySet ( ) ) { builder = builder . define ( e . getKey ( ) ) . intercept ( MethodDelegation . to ( new Runner ( e . getValue ( ) ) ) ) ; } Class createdClass = builder . make ( ) . load ( typeToExtend . getClassLoader ( ) ) . getLoaded ( ) ; return createFactory ( createdClass , contextType ) ; } catch ( Throwable e ) { if ( e instanceof ProxyException ) throw ( ProxyException ) e ; throw new ProxyException ( e ) ; } }
Create the actual function that creates instances .
8,094
public List < V > find ( Object ... keys ) { Timer timer = getMetrics ( ) . getTimer ( MetricsType . DATA_PROVIDER_FIND . name ( ) ) ; List < Object > parameters = new ArrayList < > ( ) ; Collections . addAll ( parameters , keys ) ; List < V > resultFuture = fetch ( parameters ) ; timer . stop ( ) ; return resultFuture ; }
Get records by specified keys and send result to consumer
8,095
private < Input , Output > ListenableFuture < Output > monitorFuture ( Timer timer , ListenableFuture < Input > listenableFuture , Function < Input , Output > userCallback ) { Futures . addCallback ( listenableFuture , new FutureTimerCallback < > ( timer ) ) ; return Futures . transform ( listenableFuture , new JdkFunctionWrapper < > ( userCallback ) ) ; }
Monitor future completion
8,096
private EntityMetadata build ( Class < V > clazz ) throws MetadataException { return EntityMetadata . buildEntityMetadata ( clazz , getCassandraClient ( ) ) ; }
Build entity metadata from entity class
8,097
final long buildHashCode ( Object ... keys ) { ArrayList < Object > keyList = new ArrayList < > ( ) ; Collections . addAll ( keyList , keys ) ; return buildHashCode ( keyList ) ; }
Build cache key
8,098
@ SuppressWarnings ( "unchecked" ) public static < T > T as ( Object o ) { return o == null ? null : ( T ) o ; }
Casts an object in an unchecked manner .
8,099
public final void addArgument ( final String name , final Object value ) { if ( name == null ) { throw new IllegalArgumentException ( "The argument 'name' cannot be null!" ) ; } if ( value == null ) { throw new IllegalArgumentException ( "The argument 'value' cannot be null!" ) ; } arguments . put ( name . trim ( ) , value ) ; }
Adds an argument .