idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
26,500
Double truncate ( Number numberValue ) { double doubleValue = numberValue . doubleValue ( ) ; if ( truncateEnabled ) { final int exponent = Math . getExponent ( doubleValue ) ; if ( Double . isNaN ( doubleValue ) ) { doubleValue = 0.0 ; } else if ( exponent >= MAX_EXPONENT ) { doubleValue = ( doubleValue < 0.0 ) ? - MA...
Adjust a double value so it can be successfully written to cloudwatch . This involves capping values with large exponents to an experimentally determined max value and converting values with large negative exponents to 0 . In addition NaN values will be converted to 0 .
26,501
public static Metric toValidValue ( Metric metric ) { MonitorConfig cfg = metric . getConfig ( ) ; MonitorConfig . Builder cfgBuilder = MonitorConfig . builder ( toValidCharset ( cfg . getName ( ) ) ) ; for ( Tag orig : cfg . getTags ( ) ) { final String key = orig . getKey ( ) ; if ( RELAXED_GROUP_KEYS . contains ( ke...
Return a new metric where the name and all tags are using the valid character set .
26,502
public static List < Metric > toValidValues ( List < Metric > metrics ) { return metrics . stream ( ) . map ( ValidCharacters :: toValidValue ) . collect ( Collectors . toList ( ) ) ; }
Create a new list of metrics where all metrics are using the valid character set .
26,503
public static void tagToJson ( JsonGenerator gen , Tag tag ) throws IOException { final String key = tag . getKey ( ) ; if ( RELAXED_GROUP_KEYS . contains ( key ) ) { gen . writeStringField ( key , toValidCharsetTable ( CHARS_ALLOWED_GROUPS , tag . getValue ( ) ) ) ; } else { gen . writeStringField ( toValidCharset ( t...
Serialize a tag to the given JsonGenerator .
26,504
public void record ( long measurement ) { lastUsed = clock . now ( ) ; if ( isExpired ( ) ) { LOGGER . info ( "Attempting to get the value for an expired monitor: {}." + "Will start computing stats again." , getConfig ( ) . getName ( ) ) ; startComputingStats ( executor , statsConfig . getFrequencyMillis ( ) ) ; } sync...
Record the measurement we want to perform statistics on .
26,505
public Long getValue ( int pollerIndex ) { final long n = getCount ( pollerIndex ) ; return n > 0 ? totalMeasurement . getValue ( pollerIndex ) . longValue ( ) / n : 0L ; }
Get the value of the measurement .
26,506
public List < V > values ( ) { final Collection < Entry < V > > values = map . values ( ) ; final List < V > res = values . stream ( ) . map ( e -> e . value ) . collect ( Collectors . toList ( ) ) ; return Collections . unmodifiableList ( res ) ; }
Get the list of all values that are members of this cache . Does not affect the access time used for eviction .
26,507
public void addPoller ( PollRunnable task , long delay , TimeUnit timeUnit ) { ScheduledExecutorService service = executor . get ( ) ; if ( service != null ) { service . scheduleWithFixedDelay ( task , 0 , delay , timeUnit ) ; } else { throw new IllegalStateException ( "you must start the scheduler before tasks can be ...
Add a tasks to execute at a fixed rate based on the provided delay .
26,508
public void start ( ) { int numThreads = Runtime . getRuntime ( ) . availableProcessors ( ) ; ThreadFactory factory = ThreadFactories . withName ( "ServoPollScheduler-%d" ) ; start ( Executors . newScheduledThreadPool ( numThreads , factory ) ) ; }
Start scheduling tasks with a default thread pool sized based on the number of available processors .
26,509
public void stop ( ) { ScheduledExecutorService service = executor . get ( ) ; if ( service != null && executor . compareAndSet ( service , null ) ) { service . shutdown ( ) ; } else { throw new IllegalStateException ( "scheduler must be started before you stop it" ) ; } }
Stop the poller shutting down the current executor service .
26,510
public static String join ( String separator , Iterator < ? > parts ) { Preconditions . checkNotNull ( separator , "separator" ) ; Preconditions . checkNotNull ( parts , "parts" ) ; StringBuilder builder = new StringBuilder ( ) ; if ( parts . hasNext ( ) ) { builder . append ( parts . next ( ) . toString ( ) ) ; while ...
Join the string representation of each part separated by the given separator string .
26,511
public static < T > T checkNotNull ( T obj , String name ) { if ( obj == null ) { String msg = String . format ( "parameter '%s' cannot be null" , name ) ; throw new NullPointerException ( msg ) ; } return obj ; }
Ensures the object reference is not null .
26,512
public void update ( long v ) { for ( int i = 0 ; i < Pollers . NUM_POLLERS ; ++ i ) { updateMin ( i , v ) ; } }
Update the min if the provided value is smaller than the current min .
26,513
public long getCurrentValue ( int nth ) { long v = min . getCurrent ( nth ) . get ( ) ; return ( v == Long . MAX_VALUE ) ? 0L : v ; }
Returns the current min value since the last reset .
26,514
public List < List < Metric > > getObservations ( ) { List < List < Metric > > builder = new ArrayList < > ( ) ; int pos = next ; for ( List < Metric > ignored : observations ) { if ( observations [ pos ] != null ) { builder . add ( observations [ pos ] ) ; } pos = ( pos + 1 ) % observations . length ; } return Collect...
Returns the current set of observations .
26,515
private MonitorConfig . Builder copy ( ) { return MonitorConfig . builder ( name ) . withTags ( tags ) . withPublishingPolicy ( policy ) ; }
Returns a copy of the current MonitorConfig .
26,516
public void update ( long v ) { spectatorGauge . set ( v ) ; for ( int i = 0 ; i < Pollers . NUM_POLLERS ; ++ i ) { updateMax ( i , v ) ; } }
Update the max if the provided value is larger than the current max .
26,517
public int sendAll ( Iterable < Observable < Integer > > batches , final int numMetrics , long timeoutMillis ) { final AtomicBoolean err = new AtomicBoolean ( false ) ; final AtomicInteger updated = new AtomicInteger ( 0 ) ; LOGGER . debug ( "Got {} ms to send {} metrics" , timeoutMillis , numMetrics ) ; try { final Co...
Attempt to send all the batches totalling numMetrics in the allowed time .
26,518
public Response get ( HttpClientRequest < ByteBuf > req , long timeout , TimeUnit timeUnit ) { final String uri = req . getUri ( ) ; final Response result = new Response ( ) ; try { final Func1 < HttpClientResponse < ByteBuf > , Observable < byte [ ] > > process = response -> { result . status = response . getStatus ( ...
Perform an HTTP get in the allowed time .
26,519
public static void increment ( String name , TagList list ) { final MonitorConfig config = new MonitorConfig . Builder ( name ) . withTags ( list ) . build ( ) ; increment ( config ) ; }
Increment the counter for a given name tagList .
26,520
public static void increment ( String name , TagList list , long delta ) { final MonitorConfig config = MonitorConfig . builder ( name ) . withTags ( list ) . build ( ) ; increment ( config , delta ) ; }
Increment the counter for a given name tagList by a given delta .
26,521
public Collection < Monitor < ? > > getRegisteredMonitors ( ) { if ( updatePending . getAndSet ( false ) ) { monitorList . set ( UnmodifiableList . copyOf ( monitors . values ( ) ) ) ; } return monitorList . get ( ) ; }
The set of registered Monitor objects .
26,522
public void set ( Long n ) { spectatorGauge . set ( n ) ; AtomicLong number = getNumber ( ) ; number . set ( n ) ; }
Set the current value .
26,523
public Long getCount ( int pollerIndex ) { long updates = 0 ; for ( Counter c : bucketCount ) { updates += c . getValue ( pollerIndex ) . longValue ( ) ; } updates += overflowCount . getValue ( pollerIndex ) . longValue ( ) ; return updates ; }
Get the total number of updates .
26,524
private TagList createTagList ( ObjectName name ) { Map < String , String > props = name . getKeyPropertyList ( ) ; SmallTagMap . Builder tagsBuilder = SmallTagMap . builder ( ) ; for ( Map . Entry < String , String > e : props . entrySet ( ) ) { String key = PROP_KEY_PREFIX + "." + e . getKey ( ) ; tagsBuilder . add (...
Creates a tag list from an object name .
26,525
private void addMetric ( List < Metric > metrics , String name , TagList tags , Object value ) { long now = System . currentTimeMillis ( ) ; if ( onlyNumericMetrics ) { value = asNumber ( value ) ; } if ( value != null ) { TagList newTags = counters . matches ( MonitorConfig . builder ( name ) . withTags ( tags ) . bui...
Create a new metric object and add it to the list .
26,526
private static Number asNumber ( Object value ) { Number num = null ; if ( value == null ) { num = null ; } else if ( value instanceof Number ) { num = ( Number ) value ; } else if ( value instanceof Boolean ) { num = ( ( Boolean ) value ) ? 1 : 0 ; } return num ; }
Try to convert an object into a number . Boolean values will return 1 if true and 0 if false . If the value is null or an unknown data type null will be returned .
26,527
public static void set ( String name , double value ) { set ( MonitorConfig . builder ( name ) . build ( ) , value ) ; }
Increment a gauge specified by a name .
26,528
public static void set ( String name , TagList list , double value ) { final MonitorConfig config = MonitorConfig . builder ( name ) . withTags ( list ) . build ( ) ; set ( config , value ) ; }
Set the gauge for a given name tagList by a given value .
26,529
private static String join ( long [ ] a ) { assert ( a . length > 0 ) ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( a [ 0 ] ) ; for ( int i = 1 ; i < a . length ; ++ i ) { builder . append ( ',' ) ; builder . append ( a [ i ] ) ; } return builder . toString ( ) ; }
For debugging . Simple toString for non - empty arrays
26,530
static long [ ] parse ( String pollers ) { String [ ] periods = pollers . split ( ",\\s*" ) ; long [ ] result = new long [ periods . length ] ; boolean errors = false ; Logger logger = LoggerFactory . getLogger ( Pollers . class ) ; for ( int i = 0 ; i < periods . length ; ++ i ) { String period = periods [ i ] ; try {...
Parse the content of the system property that describes the polling intervals and in case of errors use the default of one poller running every minute .
26,531
private List < Container > filterByVolumeAndWeight ( List < Box > boxes , List < Container > containers , int count ) { long volume = 0 ; long minVolume = Long . MAX_VALUE ; long weight = 0 ; long minWeight = Long . MAX_VALUE ; for ( Box box : boxes ) { long boxVolume = box . getVolume ( ) ; volume += boxVolume ; if ( ...
Return a list of containers which can potentially hold the boxes .
26,532
public Box rotate3D ( ) { int height = this . height ; this . height = width ; this . width = depth ; this . depth = height ; return this ; }
Rotate box i . e . in 3D
26,533
boolean fitRotate2D ( Dimension dimension ) { if ( dimension . getHeight ( ) < height ) { return false ; } return fitRotate2D ( dimension . getWidth ( ) , dimension . getDepth ( ) ) ; }
Rotate box within a free space in 2D
26,534
protected boolean fit2D ( List < Box > containerProducts , Container holder , Box usedSpace , Space freeSpace , BooleanSupplier interrupt ) { if ( rotate3D ) { usedSpace . fitRotate3DSmallestFootprint ( freeSpace ) ; } holder . add ( new Placement ( freeSpace , usedSpace ) ) ; if ( containerProducts . isEmpty ( ) ) { u...
Fit in two dimensions
26,535
protected int isBetter2D ( Box a , Box b ) { int compare = Long . compare ( a . getVolume ( ) , b . getVolume ( ) ) ; if ( compare != 0 ) { return compare ; } return Long . compare ( b . getFootprint ( ) , a . getFootprint ( ) ) ; }
Is box b better than a?
26,536
protected int isBetter3D ( Box a , Box b , Space space ) { int compare = Long . compare ( a . getVolume ( ) , b . getVolume ( ) ) ; if ( compare != 0 ) { return compare ; } a . fitRotate3DSmallestFootprint ( space ) ; b . fitRotate3DSmallestFootprint ( space ) ; return Long . compare ( b . getFootprint ( ) , a . getFoo...
Is box b strictly better than a?
26,537
public void removePermutations ( List < Integer > removed ) { int [ ] permutations = new int [ this . permutations . length ] ; int index = 0 ; permutations : for ( int j : this . permutations ) { for ( int i = 0 ; i < removed . size ( ) ; i ++ ) { if ( removed . get ( i ) == j ) { removed . remove ( i ) ; continue per...
Remove permutations if present .
26,538
public Dimension getFreeLevelSpace ( ) { int remainder = height - getStackHeight ( ) ; if ( remainder < 0 ) { throw new IllegalArgumentException ( "Remaining free space is negative at " + remainder + " for " + this ) ; } return new Dimension ( width , depth , remainder ) ; }
Get the free level space i . e . container height with height of levels subtracted .
26,539
public void process ( List < Point3D_F64 > worldPts , List < Point2D_F64 > observed , Se3_F64 solutionModel ) { if ( worldPts . size ( ) < 4 ) throw new IllegalArgumentException ( "Must provide at least 4 points" ) ; if ( worldPts . size ( ) != observed . size ( ) ) throw new IllegalArgumentException ( "Must have the s...
Compute camera motion given a set of features with observations and 3D locations
26,540
private void computeResultFromBest ( Se3_F64 solutionModel ) { double bestScore = Double . MAX_VALUE ; int bestSolution = - 1 ; for ( int i = 0 ; i < numControl ; i ++ ) { double score = score ( solutions . get ( i ) ) ; if ( score < bestScore ) { bestScore = score ; bestSolution = i ; } } double [ ] solution = solutio...
Selects the best motion hypothesis based on the actual observations and optionally optimizes the solution .
26,541
private double score ( double betas [ ] ) { UtilLepetitEPnP . computeCameraControl ( betas , nullPts , solutionPts , numControl ) ; int index = 0 ; double score = 0 ; for ( int i = 0 ; i < numControl ; i ++ ) { Point3D_F64 si = solutionPts . get ( i ) ; Point3D_F64 wi = controlWorldPts . get ( i ) ; for ( int j = i + 1...
Score a solution based on distance between control points . Closer the camera control points are from the world control points the better the score . This is similar to how optimization score works and not the way recommended in the original paper .
26,542
public void selectWorldControlPoints ( List < Point3D_F64 > worldPts , FastQueue < Point3D_F64 > controlWorldPts ) { UtilPoint3D_F64 . mean ( worldPts , meanWorldPts ) ; double c11 = 0 , c12 = 0 , c13 = 0 , c22 = 0 , c23 = 0 , c33 = 0 ; final int N = worldPts . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Point3D_F64 ...
Selects control points along the data s axis and the data s centroid . If the data is determined to be planar then only 3 control points are selected .
26,543
protected static void constructM ( List < Point2D_F64 > obsPts , DMatrixRMaj alphas , DMatrixRMaj M ) { int N = obsPts . size ( ) ; M . reshape ( 3 * alphas . numCols , 2 * N , false ) ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_F64 p2 = obsPts . get ( i ) ; int row = i * 2 ; for ( int j = 0 ; j < alphas . numCols ; j...
Constructs the linear system which is to be solved .
26,544
protected double matchScale ( List < Point3D_F64 > nullPts , FastQueue < Point3D_F64 > controlWorldPts ) { Point3D_F64 meanNull = UtilPoint3D_F64 . mean ( nullPts , numControl , null ) ; Point3D_F64 meanWorld = UtilPoint3D_F64 . mean ( controlWorldPts . toList ( ) , numControl , null ) ; double top = 0 ; double bottom ...
Examines the distance each point is from the centroid to determine the scaling difference between world control points and the null points .
26,545
private double adjustBetaSign ( double beta , List < Point3D_F64 > nullPts ) { if ( beta == 0 ) return 0 ; int N = alphas . numRows ; int positiveCount = 0 ; for ( int i = 0 ; i < N ; i ++ ) { double z = 0 ; for ( int j = 0 ; j < numControl ; j ++ ) { Point3D_F64 c = nullPts . get ( j ) ; z += alphas . get ( i , j ) * ...
Use the positive depth constraint to determine the sign of beta
26,546
protected void estimateCase1 ( double betas [ ] ) { betas [ 0 ] = matchScale ( nullPts [ 0 ] , controlWorldPts ) ; betas [ 0 ] = adjustBetaSign ( betas [ 0 ] , nullPts [ 0 ] ) ; betas [ 1 ] = 0 ; betas [ 2 ] = 0 ; betas [ 3 ] = 0 ; }
Simple analytical solution . Just need to solve for the scale difference in one set of potential control points .
26,547
protected void estimateCase3_planar ( double betas [ ] ) { relinearizeBeta . setNumberControl ( 3 ) ; relinearizeBeta . process ( L_full , y , betas ) ; refine ( betas ) ; }
If the data is planar use relinearize to estimate betas
26,548
private void gaussNewton ( double betas [ ] ) { A_temp . reshape ( L_full . numRows , numControl ) ; v_temp . reshape ( L_full . numRows , 1 ) ; x . reshape ( numControl , 1 , false ) ; if ( numControl == 4 ) { for ( int i = 0 ; i < numIterations ; i ++ ) { UtilLepetitEPnP . jacobian_Control4 ( L_full , betas , A_temp ...
Optimize beta values using Gauss Newton .
26,549
public QrCodeEncoder addAutomatic ( String message ) { if ( containsKanji ( message ) ) { int start = 0 ; boolean kanji = isKanji ( message . charAt ( 0 ) ) ; for ( int i = 0 ; i < message . length ( ) ; i ++ ) { if ( isKanji ( message . charAt ( i ) ) ) { if ( ! kanji ) { addAutomatic ( message . substring ( start , i...
Select the encoding based on the letters in the message . A very simple algorithm is used internally .
26,550
public QrCodeEncoder addAlphanumeric ( String alphaNumeric ) { byte values [ ] = alphanumericToValues ( alphaNumeric ) ; MessageSegment segment = new MessageSegment ( ) ; segment . message = alphaNumeric ; segment . data = values ; segment . length = values . length ; segment . mode = QrCode . Mode . ALPHANUMERIC ; seg...
Creates a QR - Code which encodes data in the alphanumeric format
26,551
public QrCodeEncoder addBytes ( byte [ ] data ) { StringBuilder builder = new StringBuilder ( data . length ) ; for ( int i = 0 ; i < data . length ; i ++ ) { builder . append ( ( char ) data [ i ] ) ; } MessageSegment segment = new MessageSegment ( ) ; segment . message = builder . toString ( ) ; segment . data = data...
Creates a QR - Code which encodes data in the byte format .
26,552
public QrCodeEncoder addKanji ( String message ) { byte [ ] bytes ; try { bytes = message . getBytes ( "Shift_JIS" ) ; } catch ( UnsupportedEncodingException ex ) { throw new IllegalArgumentException ( ex ) ; } MessageSegment segment = new MessageSegment ( ) ; segment . message = message ; segment . data = bytes ; segm...
Creates a QR - Code which encodes Kanji characters
26,553
private static int getLengthBits ( int version , int bitsA , int bitsB , int bitsC ) { int lengthBits ; if ( version < 10 ) lengthBits = bitsA ; else if ( version < 27 ) lengthBits = bitsB ; else lengthBits = bitsC ; return lengthBits ; }
Returns the length of the message length variable in bits . Dependent on version
26,554
public QrCode fixate ( ) { autoSelectVersionAndError ( ) ; int expectedBitSize = bitsAtVersion ( qr . version ) ; qr . message = "" ; for ( MessageSegment m : segments ) { qr . message += m . message ; switch ( m . mode ) { case NUMERIC : encodeNumeric ( m . data , m . length ) ; break ; case ALPHANUMERIC : encodeAlpha...
Call this function after you are done adding to the QR code
26,555
static QrCodeMaskPattern selectMask ( QrCode qr ) { int N = qr . getNumberOfModules ( ) ; int totalBytes = QrCode . VERSION_INFO [ qr . version ] . codewords ; List < Point2D_I32 > locations = QrCode . LOCATION_BITS [ qr . version ] ; QrCodeMaskPattern bestMask = null ; double bestScore = Double . MAX_VALUE ; PackedBit...
Selects a mask by minimizing the appearance of certain patterns . This is inspired by what was described in the reference manual . I had a hard time understanding some of the specifics so I improvised .
26,556
static void detectAdjacentAndPositionPatterns ( int N , QrCodeCodeWordLocations matrix , FoundFeatures features ) { for ( int foo = 0 ; foo < 2 ; foo ++ ) { for ( int row = 0 ; row < N ; row ++ ) { int index = row * N ; for ( int col = 1 ; col < N ; col ++ , index ++ ) { if ( matrix . data [ index ] == matrix . data [ ...
Look for adjacent blocks that are the same color as well as patterns that could be confused for position patterns 1 1 3 1 1 in vertical and horizontal directions
26,557
private int bitsAtVersion ( int version ) { int total = 0 ; for ( int i = 0 ; i < segments . size ( ) ; i ++ ) { total += segments . get ( i ) . sizeInBits ( version ) ; } return total ; }
Computes how many bits it takes to encode the message at this version number
26,558
public boolean process ( DMatrixRMaj F21 , double x1 , double y1 , double x2 , double y2 , Point2D_F64 p1 , Point2D_F64 p2 ) { assignTinv ( T1 , x1 , y1 ) ; assignTinv ( T2 , x2 , y2 ) ; PerspectiveOps . multTranA ( T2 , F21 , T1 , Ft ) ; extract . process ( Ft , e1 , e2 ) ; normalizeEpipole ( e1 ) ; normalizeEpipole (...
Minimizes the geometric error
26,559
public static boolean convert ( LineGeneral2D_F64 [ ] lines , Polygon2D_F64 poly ) { for ( int i = 0 ; i < poly . size ( ) ; i ++ ) { int j = ( i + 1 ) % poly . size ( ) ; if ( null == Intersection2D_F64 . intersection ( lines [ i ] , lines [ j ] , poly . get ( j ) ) ) return false ; } return true ; }
Finds the intersections between the four lines and converts it into a quadrilateral
26,560
public static void process ( GrayU8 orig , GrayF32 deriv ) { deriv . reshape ( orig . width , orig . height ) ; if ( BoofConcurrency . USE_CONCURRENT ) { DerivativeLaplacian_Inner_MT . process ( orig , deriv ) ; } else { DerivativeLaplacian_Inner . process ( orig , deriv ) ; } }
Computes Laplacian on an U8 image but outputs derivative in a F32 image . Removes a step when processing images for feature detection
26,561
public void process ( List < List < SquareNode > > clusters ) { grids . reset ( ) ; for ( int i = 0 ; i < clusters . size ( ) ; i ++ ) { if ( checkPreconditions ( clusters . get ( i ) ) ) processCluster ( clusters . get ( i ) ) ; } }
Converts all the found clusters into grids if they are valid .
26,562
protected boolean checkPreconditions ( List < SquareNode > cluster ) { for ( int i = 0 ; i < cluster . size ( ) ; i ++ ) { SquareNode n = cluster . get ( i ) ; for ( int j = 0 ; j < n . square . size ( ) ; j ++ ) { SquareEdge e0 = n . edges [ j ] ; if ( e0 == null ) continue ; for ( int k = j + 1 ; k < n . square . siz...
Checks basic preconditions . 1 ) No node may be linked two more than once
26,563
protected void processCluster ( List < SquareNode > cluster ) { invalid = false ; if ( cluster . size ( ) == 1 ) { SquareNode n = cluster . get ( 0 ) ; if ( n . getNumberOfConnections ( ) == 0 ) { SquareGrid grid = grids . grow ( ) ; grid . reset ( ) ; grid . columns = grid . rows = 1 ; grid . nodes . add ( n ) ; retur...
Converts the cluster into a grid data structure . If its not a grid then nothing happens
26,564
private SquareGrid assembleGrid ( List < List < SquareNode > > listRows ) { SquareGrid grid = grids . grow ( ) ; grid . reset ( ) ; List < SquareNode > row0 = listRows . get ( 0 ) ; List < SquareNode > row1 = listRows . get ( 1 ) ; int offset = row0 . get ( 0 ) . getNumberOfConnections ( ) == 1 ? 0 : 1 ; grid . columns...
Converts the list of rows into a grid . Since it is a chessboard pattern some of the grid elements will be null .
26,565
private boolean checkEdgeCount ( SquareGrid grid ) { int left = 0 , right = grid . columns - 1 ; int top = 0 , bottom = grid . rows - 1 ; for ( int row = 0 ; row < grid . rows ; row ++ ) { boolean skip = grid . get ( row , 0 ) == null ; for ( int col = 0 ; col < grid . columns ; col ++ ) { SquareNode n = grid . get ( r...
Looks at the edge count in each node and sees if it has the expected number
26,566
List < SquareNode > firstRow1 ( SquareNode seed ) { for ( int i = 0 ; i < seed . square . size ( ) ; i ++ ) { if ( isOpenEdge ( seed , i ) ) { List < SquareNode > list = new ArrayList < > ( ) ; seed . graph = 0 ; int corner = seed . edges [ i ] . destinationSide ( seed ) ; SquareNode dst = seed . edges [ i ] . destinat...
Adds the first row to the list of rows when the seed element has only one edge
26,567
List < SquareNode > firstRow2 ( SquareNode seed ) { int indexLower = lowerEdgeIndex ( seed ) ; int indexUpper = addOffset ( indexLower , 1 , seed . square . size ( ) ) ; List < SquareNode > listDown = new ArrayList < > ( ) ; List < SquareNode > list = new ArrayList < > ( ) ; if ( ! addToRow ( seed , indexUpper , 1 , tr...
Adds the first row to the list of rows when the seed element has two edges
26,568
static int lowerEdgeIndex ( SquareNode node ) { for ( int i = 0 ; i < node . square . size ( ) ; i ++ ) { if ( isOpenEdge ( node , i ) ) { int next = addOffset ( i , 1 , node . square . size ( ) ) ; if ( isOpenEdge ( node , next ) ) { return i ; } if ( i == 0 ) { int previous = node . square . size ( ) - 1 ; if ( isOpe...
Returns the open corner index which is first . Assuming that there are two adjacent corners .
26,569
static boolean isOpenEdge ( SquareNode node , int index ) { if ( node . edges [ index ] == null ) return false ; int marker = node . edges [ index ] . destination ( node ) . graph ; return marker == SquareNode . RESET_GRAPH ; }
Is the edge open and can be traversed to? Can t be null and can t have the marker set to a none RESET_GRAPH value .
26,570
boolean addToRow ( SquareNode n , int corner , int sign , boolean skip , List < SquareNode > row ) { SquareEdge e ; while ( ( e = n . edges [ corner ] ) != null ) { if ( e . a == n ) { n = e . b ; corner = e . sideB ; } else { n = e . a ; corner = e . sideA ; } if ( ! skip ) { if ( n . graph != SquareNode . RESET_GRAPH...
Given a node and the corner to the next node down the line add to the list every other node until it hits the end of the row .
26,571
static SquareNode findSeedNode ( List < SquareNode > cluster ) { SquareNode seed = null ; for ( int i = 0 ; i < cluster . size ( ) ; i ++ ) { SquareNode n = cluster . get ( i ) ; int numConnections = n . getNumberOfConnections ( ) ; if ( numConnections == 0 || numConnections > 2 ) continue ; seed = n ; break ; } return...
Finds a seed with 1 or 2 edges .
26,572
public void process ( GrayF32 input ) { borderImg . setImage ( input ) ; gradient . process ( input , derivX , derivY ) ; interpX . setImage ( derivX ) ; interpY . setImage ( derivY ) ; cornerIntensity . process ( derivX , derivY , intensity ) ; intensityInterp . setImage ( intensity ) ; float featmax = ImageStatistics...
Computes chessboard corners inside the image
26,573
public void meanShiftLocation ( ChessboardCorner c ) { float meanX = ( float ) c . x ; float meanY = ( float ) c . y ; int radius = this . shiRadius * 2 ; for ( int iteration = 0 ; iteration < 5 ; iteration ++ ) { float adjX = 0 ; float adjY = 0 ; float total = 0 ; for ( int y = - radius ; y < radius ; y ++ ) { float y...
Use mean shift to improve the accuracy of the corner s location . A kernel is selected which is slightly larger than the flat intensity of the corner should be when over a chess pattern .
26,574
public void setThreadPoolSize ( int threads ) { if ( threads <= 0 ) throw new IllegalArgumentException ( "Number of threads must be greater than 0" ) ; if ( verbose ) Log . i ( TAG , "setThreadPoolSize(" + threads + ")" ) ; threadPool . setCorePoolSize ( threads ) ; threadPool . setMaximumPoolSize ( threads ) ; }
Specifies the number of threads in the thread - pool . If this is set to a value greater than one you better know how to write concurrent code or else you re going to have a bad time .
26,575
protected int selectResolution ( int widthTexture , int heightTexture , Size [ ] resolutions ) { timeOfLastUpdated = 0 ; int bestIndex = - 1 ; double bestAspect = Double . MAX_VALUE ; double bestArea = 0 ; for ( int i = 0 ; i < resolutions . length ; i ++ ) { Size s = resolutions [ i ] ; int width = s . getWidth ( ) ; ...
Selects a resolution which has the number of pixels closest to the requested value
26,576
protected void setImageType ( ImageType type , ColorFormat colorFormat ) { synchronized ( boofImage . imageLock ) { boofImage . colorFormat = colorFormat ; if ( ! boofImage . imageType . isSameType ( type ) ) { boofImage . imageType = type ; boofImage . stackImages . clear ( ) ; } synchronized ( lockTiming ) { totalCon...
Changes the type of image the camera frame is converted to
26,577
protected void renderBitmapImage ( BitmapMode mode , ImageBase image ) { switch ( mode ) { case UNSAFE : { if ( image . getWidth ( ) == bitmap . getWidth ( ) && image . getHeight ( ) == bitmap . getHeight ( ) ) ConvertBitmap . boofToBitmap ( image , bitmap , bitmapTmp ) ; } break ; case DOUBLE_BUFFER : { if ( image . g...
Renders the bitmap image to output . If you don t wish to have this behavior then override this function . Jsut make sure you respect the bitmap mode or the image might not render as desired or you could crash the app .
26,578
protected void onDrawFrame ( SurfaceView view , Canvas canvas ) { switch ( bitmapMode ) { case UNSAFE : canvas . drawBitmap ( this . bitmap , imageToView , null ) ; break ; case DOUBLE_BUFFER : bitmapLock . lock ( ) ; try { canvas . drawBitmap ( this . bitmap , imageToView , null ) ; } finally { bitmapLock . unlock ( )...
Renders the visualizations . Override and invoke super to add your own
26,579
public static < I extends ImageGray < I > , D extends ImageGray < D > > GeneralFeatureIntensity < I , D > median ( int radius , Class < I > imageType ) { BlurStorageFilter < I > filter = FactoryBlurFilter . median ( ImageType . single ( imageType ) , radius ) ; return new WrapperMedianCornerIntensity < > ( filter ) ; }
Feature intensity for median corner detector .
26,580
public static < I extends ImageGray < I > , D extends ImageGray < D > > GeneralFeatureIntensity < I , D > hessian ( HessianBlobIntensity . Type type , Class < D > derivType ) { return new WrapperHessianBlobIntensity < > ( type , derivType ) ; }
Blob detector which uses the image s second order derivatives directly .
26,581
public List < PointTrack > getInactiveTracks ( List < PointTrack > list ) { if ( list == null ) list = new ArrayList < > ( ) ; return list ; }
KLT does not have inactive tracks since all tracks are dropped if a problem occurs .
26,582
protected void horizontal ( ) { float [ ] dataX = derivX . data ; float [ ] dataY = derivY . data ; float [ ] hXX = horizXX . data ; float [ ] hXY = horizXY . data ; float [ ] hYY = horizYY . data ; final int imgHeight = derivX . getHeight ( ) ; final int imgWidth = derivX . getWidth ( ) ; int windowWidth = radius * 2 ...
Compute the derivative sum along the x - axis while taking advantage of duplicate calculations for each window .
26,583
protected void vertical ( GrayF32 intensity ) { float [ ] hXX = horizXX . data ; float [ ] hXY = horizXY . data ; float [ ] hYY = horizYY . data ; final float [ ] inten = intensity . data ; final int imgHeight = horizXX . getHeight ( ) ; final int imgWidth = horizXX . getWidth ( ) ; final int kernelWidth = radius * 2 +...
Compute the derivative sum along the y - axis while taking advantage of duplicate calculations for each window and avoiding cache misses . Then compute the eigen values
26,584
public static < Input extends ImageGray < Input > , Output extends ImageGray < Output > > void distortSingle ( Input input , Output output , PixelTransform < Point2D_F32 > transform , InterpolationType interpType , BorderType borderType ) { boolean skip = borderType == BorderType . SKIP ; if ( skip ) borderType = Borde...
Applies a pixel transform to a single band image . Easier to use function .
26,585
public static < Input extends ImageGray < Input > , Output extends ImageGray < Output > > void distortSingle ( Input input , Output output , boolean renderAll , PixelTransform < Point2D_F32 > transform , InterpolatePixelS < Input > interp ) { Class < Output > inputType = ( Class < Output > ) input . getClass ( ) ; Imag...
Applies a pixel transform to a single band image . More flexible but order to use function .
26,586
public static < T extends ImageBase < T > > void scale ( T input , T output , BorderType borderType , InterpolationType interpType ) { PixelTransformAffine_F32 model = DistortSupport . transformScale ( output , input , null ) ; if ( input instanceof ImageGray ) { distortSingle ( ( ImageGray ) input , ( ImageGray ) outp...
Rescales the input image and writes the results into the output image . The scale factor is determined independently of the width and height .
26,587
public static RectangleLength2D_I32 boundBox ( int srcWidth , int srcHeight , int dstWidth , int dstHeight , Point2D_F32 work , PixelTransform < Point2D_F32 > transform ) { RectangleLength2D_I32 ret = boundBox ( srcWidth , srcHeight , work , transform ) ; int x0 = ret . x0 ; int y0 = ret . y0 ; int x1 = ret . x0 + ret ...
Finds an axis - aligned bounding box which would contain a image after it has been transformed . A sanity check is done to made sure it is contained inside the destination image s bounds . If it is totally outside then a rectangle with negative width or height is returned .
26,588
public boolean update ( Image input , RectangleRotate_F64 output ) { if ( trackLost ) return false ; trackFeatures ( input , region ) ; if ( pairs . size ( ) < config . numberOfSamples ) { System . out . println ( "Lack of sample pairs" ) ; trackLost = true ; return false ; } if ( ! estimateMotion . process ( pairs . t...
Given the input image compute the new location of the target region and store the results in output .
26,589
private void trackFeatures ( Image input , RectangleRotate_F64 region ) { pairs . reset ( ) ; currentImage . process ( input ) ; for ( int i = 0 ; i < currentImage . getNumLayers ( ) ; i ++ ) { Image layer = currentImage . getLayer ( i ) ; gradient . process ( layer , currentDerivX [ i ] , currentDerivY [ i ] ) ; } flo...
Tracks features from the previous image into the current image . Tracks are created inside the specified region in a grid pattern .
26,590
private void declarePyramid ( int imageWidth , int imageHeight ) { int minSize = ( config . trackerFeatureRadius * 2 + 1 ) * 5 ; int scales [ ] = TldTracker . selectPyramidScale ( imageWidth , imageHeight , minSize ) ; currentImage = FactoryPyramid . discreteGaussian ( scales , - 1 , 1 , false , ImageType . single ( im...
Declares internal data structures
26,591
private void swapImages ( ) { ImagePyramid < Image > tempP ; tempP = currentImage ; currentImage = previousImage ; previousImage = tempP ; Derivative [ ] tempD ; tempD = previousDerivX ; previousDerivX = currentDerivX ; currentDerivX = tempD ; tempD = previousDerivY ; previousDerivY = currentDerivY ; currentDerivY = te...
Swaps the current and previous so that image derivative doesn t need to be recomputed or compied .
26,592
public void invalidateAll ( ) { int N = width * height ; for ( int i = 0 ; i < N ; i ++ ) data [ i ] . x = Float . NaN ; }
Marks all pixels as having an invalid flow
26,593
public boolean process ( EllipseRotated_F64 ellipse ) { if ( numContourPoints <= 0 ) { score = 0 ; return true ; } double cphi = Math . cos ( ellipse . phi ) ; double sphi = Math . sin ( ellipse . phi ) ; averageInside = 0 ; averageOutside = 0 ; int total = 0 ; for ( int contourIndex = 0 ; contourIndex < numContourPoin...
Processes the edge along the ellipse and determines if the edge intensity is strong enough to pass or not
26,594
public void setImage ( GrayF32 image ) { scaleSpace . initialize ( image ) ; usedScales . clear ( ) ; do { for ( int i = 0 ; i < scaleSpace . getNumScales ( ) ; i ++ ) { GrayF32 scaleImage = scaleSpace . getImageScale ( i ) ; double sigma = scaleSpace . computeSigmaScale ( i ) ; double pixelCurrentToInput = scaleSpace ...
Sets the input image . Scale - space is computed and unrolled from this image
26,595
public ImageScale lookup ( double sigma ) { ImageScale best = null ; double bestValue = Double . MAX_VALUE ; for ( int i = 0 ; i < usedScales . size ( ) ; i ++ ) { ImageScale image = usedScales . get ( i ) ; double difference = Math . abs ( sigma - image . sigma ) ; if ( difference < bestValue ) { bestValue = differenc...
Looks up the image which is closest specified sigma
26,596
public void setModel ( BundleAdjustmentCamera model ) { this . model = model ; numIntrinsic = model . getIntrinsicCount ( ) ; if ( numIntrinsic > intrinsic . length ) { intrinsic = new double [ numIntrinsic ] ; } model . getIntrinsic ( intrinsic , 0 ) ; numericalPoint = createNumericalAlgorithm ( funcPoint ) ; numerica...
Specifies the camera model . The current state of its intrinsic parameters
26,597
public void associate ( FastQueue < D > src , FastQueue < D > dst ) { fitQuality . reset ( ) ; pairs . reset ( ) ; workBuffer . reset ( ) ; pairs . resize ( src . size ) ; fitQuality . resize ( src . size ) ; workBuffer . resize ( src . size * dst . size ) ; for ( int i = 0 ; i < src . size ; i ++ ) { D a = src . data ...
Associates the two sets objects against each other by minimizing fit score .
26,598
public boolean process ( T image , QrCode qr ) { this . qr = qr ; qr . alignment . reset ( ) ; reader . setImage ( image ) ; reader . setMarker ( qr ) ; threshold = ( float ) qr . threshCorner ; initializePatterns ( qr ) ; if ( qr . version <= 1 ) return true ; return localizePositionPatterns ( QrCode . VERSION_INFO [ ...
Uses the previously detected position patterns to seed the search for the alignment patterns
26,599
void initializePatterns ( QrCode qr ) { int where [ ] = QrCode . VERSION_INFO [ qr . version ] . alignment ; qr . alignment . reset ( ) ; lookup . reset ( ) ; for ( int row = 0 ; row < where . length ; row ++ ) { for ( int col = 0 ; col < where . length ; col ++ ) { boolean skip = false ; if ( row == 0 && col == 0 ) sk...
Creates a list of alignment patterns to look for and their grid coordinates