idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
16,500
private static int applyMaskPenaltyRule1Internal ( ByteMatrix matrix , boolean isHorizontal ) { int penalty = 0 ; int iLimit = isHorizontal ? matrix . getHeight ( ) : matrix . getWidth ( ) ; int jLimit = isHorizontal ? matrix . getWidth ( ) : matrix . getHeight ( ) ; byte [ ] [ ] array = matrix . getArray ( ) ; for ( int i = 0 ; i < iLimit ; i ++ ) { int numSameBitCells = 0 ; int prevBit = - 1 ; for ( int j = 0 ; j < jLimit ; j ++ ) { int bit = isHorizontal ? array [ i ] [ j ] : array [ j ] [ i ] ; if ( bit == prevBit ) { numSameBitCells ++ ; } else { if ( numSameBitCells >= 5 ) { penalty += N1 + ( numSameBitCells - 5 ) ; } numSameBitCells = 1 ; prevBit = bit ; } } if ( numSameBitCells >= 5 ) { penalty += N1 + ( numSameBitCells - 5 ) ; } } return penalty ; }
Helper function for applyMaskPenaltyRule1 . We need this for doing this calculation in both vertical and horizontal orders respectively .
16,501
public AddressBookParsedResult parse ( Result result ) { String rawText = getMassagedText ( result ) ; if ( ! rawText . startsWith ( "BIZCARD:" ) ) { return null ; } String firstName = matchSingleDoCoMoPrefixedField ( "N:" , rawText , true ) ; String lastName = matchSingleDoCoMoPrefixedField ( "X:" , rawText , true ) ; String fullName = buildName ( firstName , lastName ) ; String title = matchSingleDoCoMoPrefixedField ( "T:" , rawText , true ) ; String org = matchSingleDoCoMoPrefixedField ( "C:" , rawText , true ) ; String [ ] addresses = matchDoCoMoPrefixedField ( "A:" , rawText , true ) ; String phoneNumber1 = matchSingleDoCoMoPrefixedField ( "B:" , rawText , true ) ; String phoneNumber2 = matchSingleDoCoMoPrefixedField ( "M:" , rawText , true ) ; String phoneNumber3 = matchSingleDoCoMoPrefixedField ( "F:" , rawText , true ) ; String email = matchSingleDoCoMoPrefixedField ( "E:" , rawText , true ) ; return new AddressBookParsedResult ( maybeWrap ( fullName ) , null , null , buildPhoneNumbers ( phoneNumber1 , phoneNumber2 , phoneNumber3 ) , null , maybeWrap ( email ) , null , null , null , addresses , null , org , null , title , null , null ) ; }
DoCoMo s proposed formats
16,502
public void setRange ( int start , int end ) { if ( end < start || start < 0 || end > size ) { throw new IllegalArgumentException ( ) ; } if ( end == start ) { return ; } end -- ; int firstInt = start / 32 ; int lastInt = end / 32 ; for ( int i = firstInt ; i <= lastInt ; i ++ ) { int firstBit = i > firstInt ? 0 : start & 0x1F ; int lastBit = i < lastInt ? 31 : end & 0x1F ; int mask = ( 2 << lastBit ) - ( 1 << firstBit ) ; bits [ i ] |= mask ; } }
Sets a range of bits .
16,503
public boolean isRange ( int start , int end , boolean value ) { if ( end < start || start < 0 || end > size ) { throw new IllegalArgumentException ( ) ; } if ( end == start ) { return true ; } end -- ; int firstInt = start / 32 ; int lastInt = end / 32 ; for ( int i = firstInt ; i <= lastInt ; i ++ ) { int firstBit = i > firstInt ? 0 : start & 0x1F ; int lastBit = i < lastInt ? 31 : end & 0x1F ; int mask = ( 2 << lastBit ) - ( 1 << firstBit ) ; if ( ( bits [ i ] & mask ) != ( value ? mask : 0 ) ) { return false ; } } return true ; }
Efficient method to check if a range of bits is set or not set .
16,504
public void appendBits ( int value , int numBits ) { if ( numBits < 0 || numBits > 32 ) { throw new IllegalArgumentException ( "Num bits must be between 0 and 32" ) ; } ensureCapacity ( size + numBits ) ; for ( int numBitsLeft = numBits ; numBitsLeft > 0 ; numBitsLeft -- ) { appendBit ( ( ( value >> ( numBitsLeft - 1 ) ) & 0x01 ) == 1 ) ; } }
Appends the least - significant bits from value in order from most - significant to least - significant . For example appending 6 bits from 0x000001E will append the bits 0 1 1 1 1 0 in that order .
16,505
public void reverse ( ) { int [ ] newBits = new int [ bits . length ] ; int len = ( size - 1 ) / 32 ; int oldBitsLen = len + 1 ; for ( int i = 0 ; i < oldBitsLen ; i ++ ) { long x = bits [ i ] ; x = ( ( x >> 1 ) & 0x55555555L ) | ( ( x & 0x55555555L ) << 1 ) ; x = ( ( x >> 2 ) & 0x33333333L ) | ( ( x & 0x33333333L ) << 2 ) ; x = ( ( x >> 4 ) & 0x0f0f0f0fL ) | ( ( x & 0x0f0f0f0fL ) << 4 ) ; x = ( ( x >> 8 ) & 0x00ff00ffL ) | ( ( x & 0x00ff00ffL ) << 8 ) ; x = ( ( x >> 16 ) & 0x0000ffffL ) | ( ( x & 0x0000ffffL ) << 16 ) ; newBits [ len - i ] = ( int ) x ; } if ( size != oldBitsLen * 32 ) { int leftOffset = oldBitsLen * 32 - size ; int currentInt = newBits [ 0 ] >>> leftOffset ; for ( int i = 1 ; i < oldBitsLen ; i ++ ) { int nextInt = newBits [ i ] ; currentInt |= nextInt << ( 32 - leftOffset ) ; newBits [ i - 1 ] = currentInt ; currentInt = nextInt >>> leftOffset ; } newBits [ oldBitsLen - 1 ] = currentInt ; } bits = newBits ; }
Reverses all bits in the array .
16,506
private static int determineConsecutiveTextCount ( CharSequence msg , int startpos ) { int len = msg . length ( ) ; int idx = startpos ; while ( idx < len ) { char ch = msg . charAt ( idx ) ; int numericCount = 0 ; while ( numericCount < 13 && isDigit ( ch ) && idx < len ) { numericCount ++ ; idx ++ ; if ( idx < len ) { ch = msg . charAt ( idx ) ; } } if ( numericCount >= 13 ) { return idx - startpos - numericCount ; } if ( numericCount > 0 ) { continue ; } ch = msg . charAt ( idx ) ; if ( ! isText ( ch ) ) { break ; } idx ++ ; } return idx - startpos ; }
Determines the number of consecutive characters that are encodable using text compaction .
16,507
private static int determineConsecutiveBinaryCount ( String msg , int startpos , Charset encoding ) throws WriterException { CharsetEncoder encoder = encoding . newEncoder ( ) ; int len = msg . length ( ) ; int idx = startpos ; while ( idx < len ) { char ch = msg . charAt ( idx ) ; int numericCount = 0 ; while ( numericCount < 13 && isDigit ( ch ) ) { numericCount ++ ; int i = idx + numericCount ; if ( i >= len ) { break ; } ch = msg . charAt ( i ) ; } if ( numericCount >= 13 ) { return idx - startpos ; } ch = msg . charAt ( idx ) ; if ( ! encoder . canEncode ( ch ) ) { throw new WriterException ( "Non-encodable character detected: " + ch + " (Unicode: " + ( int ) ch + ')' ) ; } idx ++ ; } return idx - startpos ; }
Determines the number of consecutive characters that are encodable using binary compaction .
16,508
public static int determineConsecutiveDigitCount ( CharSequence msg , int startpos ) { int count = 0 ; int len = msg . length ( ) ; int idx = startpos ; if ( idx < len ) { char ch = msg . charAt ( idx ) ; while ( isDigit ( ch ) && idx < len ) { count ++ ; idx ++ ; if ( idx < len ) { ch = msg . charAt ( idx ) ; } } } return count ; }
Determines the number of consecutive characters that are encodable using numeric compaction .
16,509
final void searchMap ( String address ) { launchIntent ( new Intent ( Intent . ACTION_VIEW , Uri . parse ( "geo:0,0?q=" + Uri . encode ( address ) ) ) ) ; }
Do a geo search using the address as the query .
16,510
final void openProductSearch ( String upc ) { Uri uri = Uri . parse ( "http://www.google." + LocaleManager . getProductSearchCountryTLD ( activity ) + "/m/products?q=" + upc + "&source=zxing" ) ; launchIntent ( new Intent ( Intent . ACTION_VIEW , uri ) ) ; }
Uses the mobile - specific version of Product Search which is formatted for small screens .
16,511
private void decode ( byte [ ] data , int width , int height ) { long start = System . nanoTime ( ) ; Result rawResult = null ; PlanarYUVLuminanceSource source = activity . getCameraManager ( ) . buildLuminanceSource ( data , width , height ) ; if ( source != null ) { BinaryBitmap bitmap = new BinaryBitmap ( new HybridBinarizer ( source ) ) ; try { rawResult = multiFormatReader . decodeWithState ( bitmap ) ; } catch ( ReaderException re ) { } finally { multiFormatReader . reset ( ) ; } } Handler handler = activity . getHandler ( ) ; if ( rawResult != null ) { long end = System . nanoTime ( ) ; Log . d ( TAG , "Found barcode in " + TimeUnit . NANOSECONDS . toMillis ( end - start ) + " ms" ) ; if ( handler != null ) { Message message = Message . obtain ( handler , R . id . decode_succeeded , rawResult ) ; Bundle bundle = new Bundle ( ) ; bundleThumbnail ( source , bundle ) ; message . setData ( bundle ) ; message . sendToTarget ( ) ; } } else { if ( handler != null ) { Message message = Message . obtain ( handler , R . id . decode_failed ) ; message . sendToTarget ( ) ; } } }
Decode the data within the viewfinder rectangle and time how long it took . For efficiency reuse the same reader objects from one decode to the next .
16,512
private ResultPoint [ ] detectSolid1 ( ResultPoint [ ] cornerPoints ) { ResultPoint pointA = cornerPoints [ 0 ] ; ResultPoint pointB = cornerPoints [ 1 ] ; ResultPoint pointC = cornerPoints [ 3 ] ; ResultPoint pointD = cornerPoints [ 2 ] ; int trAB = transitionsBetween ( pointA , pointB ) ; int trBC = transitionsBetween ( pointB , pointC ) ; int trCD = transitionsBetween ( pointC , pointD ) ; int trDA = transitionsBetween ( pointD , pointA ) ; int min = trAB ; ResultPoint [ ] points = { pointD , pointA , pointB , pointC } ; if ( min > trBC ) { min = trBC ; points [ 0 ] = pointA ; points [ 1 ] = pointB ; points [ 2 ] = pointC ; points [ 3 ] = pointD ; } if ( min > trCD ) { min = trCD ; points [ 0 ] = pointB ; points [ 1 ] = pointC ; points [ 2 ] = pointD ; points [ 3 ] = pointA ; } if ( min > trDA ) { points [ 0 ] = pointC ; points [ 1 ] = pointD ; points [ 2 ] = pointA ; points [ 3 ] = pointB ; } return points ; }
Detect a solid side which has minimum transition .
16,513
private ResultPoint [ ] detectSolid2 ( ResultPoint [ ] points ) { ResultPoint pointA = points [ 0 ] ; ResultPoint pointB = points [ 1 ] ; ResultPoint pointC = points [ 2 ] ; ResultPoint pointD = points [ 3 ] ; int tr = transitionsBetween ( pointA , pointD ) ; ResultPoint pointBs = shiftPoint ( pointB , pointC , ( tr + 1 ) * 4 ) ; ResultPoint pointCs = shiftPoint ( pointC , pointB , ( tr + 1 ) * 4 ) ; int trBA = transitionsBetween ( pointBs , pointA ) ; int trCD = transitionsBetween ( pointCs , pointD ) ; if ( trBA < trCD ) { points [ 0 ] = pointA ; points [ 1 ] = pointB ; points [ 2 ] = pointC ; points [ 3 ] = pointD ; } else { points [ 0 ] = pointB ; points [ 1 ] = pointC ; points [ 2 ] = pointD ; points [ 3 ] = pointA ; } return points ; }
Detect a second solid side next to first solid side .
16,514
private ResultPoint correctTopRight ( ResultPoint [ ] points ) { ResultPoint pointA = points [ 0 ] ; ResultPoint pointB = points [ 1 ] ; ResultPoint pointC = points [ 2 ] ; ResultPoint pointD = points [ 3 ] ; int trTop = transitionsBetween ( pointA , pointD ) ; int trRight = transitionsBetween ( pointB , pointD ) ; ResultPoint pointAs = shiftPoint ( pointA , pointB , ( trRight + 1 ) * 4 ) ; ResultPoint pointCs = shiftPoint ( pointC , pointB , ( trTop + 1 ) * 4 ) ; trTop = transitionsBetween ( pointAs , pointD ) ; trRight = transitionsBetween ( pointCs , pointD ) ; ResultPoint candidate1 = new ResultPoint ( pointD . getX ( ) + ( pointC . getX ( ) - pointB . getX ( ) ) / ( trTop + 1 ) , pointD . getY ( ) + ( pointC . getY ( ) - pointB . getY ( ) ) / ( trTop + 1 ) ) ; ResultPoint candidate2 = new ResultPoint ( pointD . getX ( ) + ( pointA . getX ( ) - pointB . getX ( ) ) / ( trRight + 1 ) , pointD . getY ( ) + ( pointA . getY ( ) - pointB . getY ( ) ) / ( trRight + 1 ) ) ; if ( ! isValid ( candidate1 ) ) { if ( isValid ( candidate2 ) ) { return candidate2 ; } return null ; } if ( ! isValid ( candidate2 ) ) { return candidate1 ; } int sumc1 = transitionsBetween ( pointAs , candidate1 ) + transitionsBetween ( pointCs , candidate1 ) ; int sumc2 = transitionsBetween ( pointAs , candidate2 ) + transitionsBetween ( pointCs , candidate2 ) ; if ( sumc1 > sumc2 ) { return candidate1 ; } else { return candidate2 ; } }
Calculates the corner position of the white top right module .
16,515
private ResultPoint [ ] shiftToModuleCenter ( ResultPoint [ ] points ) { ResultPoint pointA = points [ 0 ] ; ResultPoint pointB = points [ 1 ] ; ResultPoint pointC = points [ 2 ] ; ResultPoint pointD = points [ 3 ] ; int dimH = transitionsBetween ( pointA , pointD ) + 1 ; int dimV = transitionsBetween ( pointC , pointD ) + 1 ; ResultPoint pointAs = shiftPoint ( pointA , pointB , dimV * 4 ) ; ResultPoint pointCs = shiftPoint ( pointC , pointB , dimH * 4 ) ; dimH = transitionsBetween ( pointAs , pointD ) + 1 ; dimV = transitionsBetween ( pointCs , pointD ) + 1 ; if ( ( dimH & 0x01 ) == 1 ) { dimH += 1 ; } if ( ( dimV & 0x01 ) == 1 ) { dimV += 1 ; } float centerX = ( pointA . getX ( ) + pointB . getX ( ) + pointC . getX ( ) + pointD . getX ( ) ) / 4 ; float centerY = ( pointA . getY ( ) + pointB . getY ( ) + pointC . getY ( ) + pointD . getY ( ) ) / 4 ; pointA = moveAway ( pointA , centerX , centerY ) ; pointB = moveAway ( pointB , centerX , centerY ) ; pointC = moveAway ( pointC , centerX , centerY ) ; pointD = moveAway ( pointD , centerX , centerY ) ; ResultPoint pointBs ; ResultPoint pointDs ; pointAs = shiftPoint ( pointA , pointB , dimV * 4 ) ; pointAs = shiftPoint ( pointAs , pointD , dimH * 4 ) ; pointBs = shiftPoint ( pointB , pointA , dimV * 4 ) ; pointBs = shiftPoint ( pointBs , pointC , dimH * 4 ) ; pointCs = shiftPoint ( pointC , pointD , dimV * 4 ) ; pointCs = shiftPoint ( pointCs , pointB , dimH * 4 ) ; pointDs = shiftPoint ( pointD , pointC , dimV * 4 ) ; pointDs = shiftPoint ( pointDs , pointA , dimH * 4 ) ; return new ResultPoint [ ] { pointAs , pointBs , pointCs , pointDs } ; }
Shift the edge points to the module center .
16,516
protected void startActivityForResult ( Intent intent , int code ) { if ( fragment == null ) { activity . startActivityForResult ( intent , code ) ; } else { fragment . startActivityForResult ( intent , code ) ; } }
Start an activity . This method is defined to allow different methods of activity starting for newer versions of Android and for compatibility library .
16,517
public final AlertDialog shareText ( CharSequence text , CharSequence type ) { Intent intent = new Intent ( ) ; intent . addCategory ( Intent . CATEGORY_DEFAULT ) ; intent . setAction ( BS_PACKAGE + ".ENCODE" ) ; intent . putExtra ( "ENCODE_TYPE" , type ) ; intent . putExtra ( "ENCODE_DATA" , text ) ; String targetAppPackage = findTargetAppPackage ( intent ) ; if ( targetAppPackage == null ) { return showDownloadDialog ( ) ; } intent . setPackage ( targetAppPackage ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_CLEAR_TOP ) ; intent . addFlags ( FLAG_NEW_DOC ) ; attachMoreExtras ( intent ) ; if ( fragment == null ) { activity . startActivity ( intent ) ; } else { fragment . startActivity ( intent ) ; } return null ; }
Shares the given text by encoding it as a barcode such that another user can scan the text off the screen of the device .
16,518
public BitArray getBlackRow ( int y , BitArray row ) throws NotFoundException { LuminanceSource source = getLuminanceSource ( ) ; int width = source . getWidth ( ) ; if ( row == null || row . getSize ( ) < width ) { row = new BitArray ( width ) ; } else { row . clear ( ) ; } initArrays ( width ) ; byte [ ] localLuminances = source . getRow ( y , luminances ) ; int [ ] localBuckets = buckets ; for ( int x = 0 ; x < width ; x ++ ) { localBuckets [ ( localLuminances [ x ] & 0xff ) >> LUMINANCE_SHIFT ] ++ ; } int blackPoint = estimateBlackPoint ( localBuckets ) ; if ( width < 3 ) { for ( int x = 0 ; x < width ; x ++ ) { if ( ( localLuminances [ x ] & 0xff ) < blackPoint ) { row . set ( x ) ; } } } else { int left = localLuminances [ 0 ] & 0xff ; int center = localLuminances [ 1 ] & 0xff ; for ( int x = 1 ; x < width - 1 ; x ++ ) { int right = localLuminances [ x + 1 ] & 0xff ; if ( ( ( center * 4 ) - left - right ) / 2 < blackPoint ) { row . set ( x ) ; } left = center ; center = right ; } } return row ; }
Applies simple sharpening to the row data to improve performance of the 1D Readers .
16,519
public BitMatrix getBlackMatrix ( ) throws NotFoundException { LuminanceSource source = getLuminanceSource ( ) ; int width = source . getWidth ( ) ; int height = source . getHeight ( ) ; BitMatrix matrix = new BitMatrix ( width , height ) ; initArrays ( width ) ; int [ ] localBuckets = buckets ; for ( int y = 1 ; y < 5 ; y ++ ) { int row = height * y / 5 ; byte [ ] localLuminances = source . getRow ( row , luminances ) ; int right = ( width * 4 ) / 5 ; for ( int x = width / 5 ; x < right ; x ++ ) { int pixel = localLuminances [ x ] & 0xff ; localBuckets [ pixel >> LUMINANCE_SHIFT ] ++ ; } } int blackPoint = estimateBlackPoint ( localBuckets ) ; byte [ ] localLuminances = source . getMatrix ( ) ; for ( int y = 0 ; y < height ; y ++ ) { int offset = y * width ; for ( int x = 0 ; x < width ; x ++ ) { int pixel = localLuminances [ offset + x ] & 0xff ; if ( pixel < blackPoint ) { matrix . set ( x , y ) ; } } } return matrix ; }
Does not sharpen the data as this call is intended to only be used by 2D Readers .
16,520
State latchAndAppend ( int mode , int value ) { int bitCount = this . bitCount ; Token token = this . token ; if ( mode != this . mode ) { int latch = HighLevelEncoder . LATCH_TABLE [ this . mode ] [ mode ] ; token = token . add ( latch & 0xFFFF , latch >> 16 ) ; bitCount += latch >> 16 ; } int latchModeBitCount = mode == HighLevelEncoder . MODE_DIGIT ? 4 : 5 ; token = token . add ( value , latchModeBitCount ) ; return new State ( token , mode , 0 , bitCount + latchModeBitCount ) ; }
necessary different ) mode and then a code .
16,521
State shiftAndAppend ( int mode , int value ) { Token token = this . token ; int thisModeBitCount = this . mode == HighLevelEncoder . MODE_DIGIT ? 4 : 5 ; token = token . add ( HighLevelEncoder . SHIFT_TABLE [ this . mode ] [ mode ] , thisModeBitCount ) ; token = token . add ( value , 5 ) ; return new State ( token , this . mode , 0 , this . bitCount + thisModeBitCount + 5 ) ; }
to a different mode to output a single value .
16,522
State addBinaryShiftChar ( int index ) { Token token = this . token ; int mode = this . mode ; int bitCount = this . bitCount ; if ( this . mode == HighLevelEncoder . MODE_PUNCT || this . mode == HighLevelEncoder . MODE_DIGIT ) { int latch = HighLevelEncoder . LATCH_TABLE [ mode ] [ HighLevelEncoder . MODE_UPPER ] ; token = token . add ( latch & 0xFFFF , latch >> 16 ) ; bitCount += latch >> 16 ; mode = HighLevelEncoder . MODE_UPPER ; } int deltaBitCount = ( binaryShiftByteCount == 0 || binaryShiftByteCount == 31 ) ? 18 : ( binaryShiftByteCount == 62 ) ? 9 : 8 ; State result = new State ( token , mode , binaryShiftByteCount + 1 , bitCount + deltaBitCount ) ; if ( result . binaryShiftByteCount == 2047 + 31 ) { result = result . endBinaryShift ( index + 1 ) ; } return result ; }
output in Binary Shift mode .
16,523
State endBinaryShift ( int index ) { if ( binaryShiftByteCount == 0 ) { return this ; } Token token = this . token ; token = token . addBinaryShift ( index - binaryShiftByteCount , binaryShiftByteCount ) ; return new State ( token , mode , 0 , this . bitCount ) ; }
Binary Shift mode .
16,524
boolean isBetterThanOrEqualTo ( State other ) { int newModeBitCount = this . bitCount + ( HighLevelEncoder . LATCH_TABLE [ this . mode ] [ other . mode ] >> 16 ) ; if ( this . binaryShiftByteCount < other . binaryShiftByteCount ) { newModeBitCount += calculateBinaryShiftCost ( other ) - calculateBinaryShiftCost ( this ) ; } else if ( this . binaryShiftByteCount > other . binaryShiftByteCount && other . binaryShiftByteCount > 0 ) { newModeBitCount += 10 ; } return newModeBitCount <= other . bitCount ; }
state under all possible circumstances .
16,525
private static BitMatrix encodeLowLevel ( DefaultPlacement placement , SymbolInfo symbolInfo , int width , int height ) { int symbolWidth = symbolInfo . getSymbolDataWidth ( ) ; int symbolHeight = symbolInfo . getSymbolDataHeight ( ) ; ByteMatrix matrix = new ByteMatrix ( symbolInfo . getSymbolWidth ( ) , symbolInfo . getSymbolHeight ( ) ) ; int matrixY = 0 ; for ( int y = 0 ; y < symbolHeight ; y ++ ) { int matrixX ; if ( ( y % symbolInfo . matrixHeight ) == 0 ) { matrixX = 0 ; for ( int x = 0 ; x < symbolInfo . getSymbolWidth ( ) ; x ++ ) { matrix . set ( matrixX , matrixY , ( x % 2 ) == 0 ) ; matrixX ++ ; } matrixY ++ ; } matrixX = 0 ; for ( int x = 0 ; x < symbolWidth ; x ++ ) { if ( ( x % symbolInfo . matrixWidth ) == 0 ) { matrix . set ( matrixX , matrixY , true ) ; matrixX ++ ; } matrix . set ( matrixX , matrixY , placement . getBit ( x , y ) ) ; matrixX ++ ; if ( ( x % symbolInfo . matrixWidth ) == symbolInfo . matrixWidth - 1 ) { matrix . set ( matrixX , matrixY , ( y % 2 ) == 0 ) ; matrixX ++ ; } } matrixY ++ ; if ( ( y % symbolInfo . matrixHeight ) == symbolInfo . matrixHeight - 1 ) { matrixX = 0 ; for ( int x = 0 ; x < symbolInfo . getSymbolWidth ( ) ; x ++ ) { matrix . set ( matrixX , matrixY , true ) ; matrixX ++ ; } matrixY ++ ; } } return convertByteMatrixToBitMatrix ( matrix , width , height ) ; }
Encode the given symbol info to a bit matrix .
16,526
private static BitMatrix convertByteMatrixToBitMatrix ( ByteMatrix matrix , int reqWidth , int reqHeight ) { int matrixWidth = matrix . getWidth ( ) ; int matrixHeight = matrix . getHeight ( ) ; int outputWidth = Math . max ( reqWidth , matrixWidth ) ; int outputHeight = Math . max ( reqHeight , matrixHeight ) ; int multiple = Math . min ( outputWidth / matrixWidth , outputHeight / matrixHeight ) ; int leftPadding = ( outputWidth - ( matrixWidth * multiple ) ) / 2 ; int topPadding = ( outputHeight - ( matrixHeight * multiple ) ) / 2 ; BitMatrix output ; if ( reqHeight < matrixHeight || reqWidth < matrixWidth ) { leftPadding = 0 ; topPadding = 0 ; output = new BitMatrix ( matrixWidth , matrixHeight ) ; } else { output = new BitMatrix ( reqWidth , reqHeight ) ; } output . clear ( ) ; for ( int inputY = 0 , outputY = topPadding ; inputY < matrixHeight ; inputY ++ , outputY += multiple ) { for ( int inputX = 0 , outputX = leftPadding ; inputX < matrixWidth ; inputX ++ , outputX += multiple ) { if ( matrix . get ( inputX , inputY ) == 1 ) { output . setRegion ( outputX , outputY , multiple , multiple ) ; } } } return output ; }
Convert the ByteMatrix to BitMatrix .
16,527
private static int skipWhiteSpace ( BitArray row ) throws NotFoundException { int width = row . getSize ( ) ; int endStart = row . getNextSet ( 0 ) ; if ( endStart == width ) { throw NotFoundException . getNotFoundInstance ( ) ; } return endStart ; }
Skip all whitespace until we get to the first black line .
16,528
public BitArray getRow ( int y , BitArray row ) { if ( row == null || row . getSize ( ) < width ) { row = new BitArray ( width ) ; } else { row . clear ( ) ; } int offset = y * rowSize ; for ( int x = 0 ; x < rowSize ; x ++ ) { row . setBulk ( x * 32 , bits [ offset + x ] ) ; } return row ; }
A fast method to retrieve one row of data from the matrix as a BitArray .
16,529
public int [ ] getEnclosingRectangle ( ) { int left = width ; int top = height ; int right = - 1 ; int bottom = - 1 ; for ( int y = 0 ; y < height ; y ++ ) { for ( int x32 = 0 ; x32 < rowSize ; x32 ++ ) { int theBits = bits [ y * rowSize + x32 ] ; if ( theBits != 0 ) { if ( y < top ) { top = y ; } if ( y > bottom ) { bottom = y ; } if ( x32 * 32 < left ) { int bit = 0 ; while ( ( theBits << ( 31 - bit ) ) == 0 ) { bit ++ ; } if ( ( x32 * 32 + bit ) < left ) { left = x32 * 32 + bit ; } } if ( x32 * 32 + 31 > right ) { int bit = 31 ; while ( ( theBits >>> bit ) == 0 ) { bit -- ; } if ( ( x32 * 32 + bit ) > right ) { right = x32 * 32 + bit ; } } } } } if ( right < left || bottom < top ) { return null ; } return new int [ ] { left , top , right - left + 1 , bottom - top + 1 } ; }
This is useful in detecting the enclosing rectangle of a pure barcode .
16,530
public int [ ] getTopLeftOnBit ( ) { int bitsOffset = 0 ; while ( bitsOffset < bits . length && bits [ bitsOffset ] == 0 ) { bitsOffset ++ ; } if ( bitsOffset == bits . length ) { return null ; } int y = bitsOffset / rowSize ; int x = ( bitsOffset % rowSize ) * 32 ; int theBits = bits [ bitsOffset ] ; int bit = 0 ; while ( ( theBits << ( 31 - bit ) ) == 0 ) { bit ++ ; } x += bit ; return new int [ ] { x , y } ; }
This is useful in detecting a corner of a pure barcode .
16,531
static void buildMatrix ( BitArray dataBits , ErrorCorrectionLevel ecLevel , Version version , int maskPattern , ByteMatrix matrix ) throws WriterException { clearMatrix ( matrix ) ; embedBasicPatterns ( version , matrix ) ; embedTypeInfo ( ecLevel , maskPattern , matrix ) ; maybeEmbedVersionInfo ( version , matrix ) ; embedDataBits ( dataBits , maskPattern , matrix ) ; }
success store the result in matrix and return true .
16,532
static void embedBasicPatterns ( Version version , ByteMatrix matrix ) throws WriterException { embedPositionDetectionPatternsAndSeparators ( matrix ) ; embedDarkDotAtLeftBottomCorner ( matrix ) ; maybeEmbedPositionAdjustmentPatterns ( version , matrix ) ; embedTimingPatterns ( matrix ) ; }
- Position adjustment patterns if need be
16,533
static void embedTypeInfo ( ErrorCorrectionLevel ecLevel , int maskPattern , ByteMatrix matrix ) throws WriterException { BitArray typeInfoBits = new BitArray ( ) ; makeTypeInfoBits ( ecLevel , maskPattern , typeInfoBits ) ; for ( int i = 0 ; i < typeInfoBits . getSize ( ) ; ++ i ) { boolean bit = typeInfoBits . get ( typeInfoBits . getSize ( ) - 1 - i ) ; int [ ] coordinates = TYPE_INFO_COORDINATES [ i ] ; int x1 = coordinates [ 0 ] ; int y1 = coordinates [ 1 ] ; matrix . set ( x1 , y1 , bit ) ; if ( i < 8 ) { int x2 = matrix . getWidth ( ) - i - 1 ; int y2 = 8 ; matrix . set ( x2 , y2 , bit ) ; } else { int x2 = 8 ; int y2 = matrix . getHeight ( ) - 7 + ( i - 8 ) ; matrix . set ( x2 , y2 , bit ) ; } } }
Embed type information . On success modify the matrix .
16,534
static int calculateBCHCode ( int value , int poly ) { if ( poly == 0 ) { throw new IllegalArgumentException ( "0 polynomial" ) ; } int msbSetInPoly = findMSBSet ( poly ) ; value <<= msbSetInPoly - 1 ; while ( findMSBSet ( value ) >= msbSetInPoly ) { value ^= poly << ( findMSBSet ( value ) - msbSetInPoly ) ; } return value ; }
operations . We don t care if coefficients are positive or negative .
16,535
private static void maybeEmbedPositionAdjustmentPatterns ( Version version , ByteMatrix matrix ) { if ( version . getVersionNumber ( ) < 2 ) { return ; } int index = version . getVersionNumber ( ) - 1 ; int [ ] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE [ index ] ; for ( int y : coordinates ) { if ( y >= 0 ) { for ( int x : coordinates ) { if ( x >= 0 && isEmpty ( matrix . get ( x , y ) ) ) { embedPositionAdjustmentPattern ( x - 2 , y - 2 , matrix ) ; } } } } }
Embed position adjustment patterns if need be .
16,536
List < ExpandedPair > decodeRow2pairs ( int rowNumber , BitArray row ) throws NotFoundException { boolean done = false ; while ( ! done ) { try { this . pairs . add ( retrieveNextPair ( row , this . pairs , rowNumber ) ) ; } catch ( NotFoundException nfe ) { if ( this . pairs . isEmpty ( ) ) { throw nfe ; } done = true ; } } if ( checkChecksum ( ) ) { return this . pairs ; } boolean tryStackedDecode = ! this . rows . isEmpty ( ) ; storeRow ( rowNumber , false ) ; if ( tryStackedDecode ) { List < ExpandedPair > ps = checkRows ( false ) ; if ( ps != null ) { return ps ; } ps = checkRows ( true ) ; if ( ps != null ) { return ps ; } } throw NotFoundException . getNotFoundInstance ( ) ; }
Not private for testing
16,537
private List < ExpandedPair > checkRows ( List < ExpandedRow > collectedRows , int currentRow ) throws NotFoundException { for ( int i = currentRow ; i < rows . size ( ) ; i ++ ) { ExpandedRow row = rows . get ( i ) ; this . pairs . clear ( ) ; for ( ExpandedRow collectedRow : collectedRows ) { this . pairs . addAll ( collectedRow . getPairs ( ) ) ; } this . pairs . addAll ( row . getPairs ( ) ) ; if ( ! isValidSequence ( this . pairs ) ) { continue ; } if ( checkChecksum ( ) ) { return this . pairs ; } List < ExpandedRow > rs = new ArrayList < > ( collectedRows ) ; rs . add ( row ) ; try { return checkRows ( rs , i + 1 ) ; } catch ( NotFoundException e ) { } } throw NotFoundException . getNotFoundInstance ( ) ; }
Recursion is used to implement backtracking
16,538
private static boolean isValidSequence ( List < ExpandedPair > pairs ) { for ( int [ ] sequence : FINDER_PATTERN_SEQUENCES ) { if ( pairs . size ( ) > sequence . length ) { continue ; } boolean stop = true ; for ( int j = 0 ; j < pairs . size ( ) ; j ++ ) { if ( pairs . get ( j ) . getFinderPattern ( ) . getValue ( ) != sequence [ j ] ) { stop = false ; break ; } } if ( stop ) { return true ; } } return false ; }
either complete or a prefix
16,539
private static void removePartialRows ( List < ExpandedPair > pairs , List < ExpandedRow > rows ) { for ( Iterator < ExpandedRow > iterator = rows . iterator ( ) ; iterator . hasNext ( ) ; ) { ExpandedRow r = iterator . next ( ) ; if ( r . getPairs ( ) . size ( ) == pairs . size ( ) ) { continue ; } boolean allFound = true ; for ( ExpandedPair p : r . getPairs ( ) ) { boolean found = false ; for ( ExpandedPair pp : pairs ) { if ( p . equals ( pp ) ) { found = true ; break ; } } if ( ! found ) { allFound = false ; break ; } } if ( allFound ) { iterator . remove ( ) ; } } }
Remove all the rows that contains only specified pairs
16,540
private static boolean isPartialRow ( Iterable < ExpandedPair > pairs , Iterable < ExpandedRow > rows ) { for ( ExpandedRow r : rows ) { boolean allFound = true ; for ( ExpandedPair p : pairs ) { boolean found = false ; for ( ExpandedPair pp : r . getPairs ( ) ) { if ( p . equals ( pp ) ) { found = true ; break ; } } if ( ! found ) { allFound = false ; break ; } } if ( allFound ) { return true ; } } return false ; }
Returns true when one of the rows already contains all the pairs
16,541
static Result constructResult ( List < ExpandedPair > pairs ) throws NotFoundException , FormatException { BitArray binary = BitArrayBuilder . buildBitArray ( pairs ) ; AbstractExpandedDecoder decoder = AbstractExpandedDecoder . createDecoder ( binary ) ; String resultingString = decoder . parseInformation ( ) ; ResultPoint [ ] firstPoints = pairs . get ( 0 ) . getFinderPattern ( ) . getResultPoints ( ) ; ResultPoint [ ] lastPoints = pairs . get ( pairs . size ( ) - 1 ) . getFinderPattern ( ) . getResultPoints ( ) ; return new Result ( resultingString , null , new ResultPoint [ ] { firstPoints [ 0 ] , firstPoints [ 1 ] , lastPoints [ 0 ] , lastPoints [ 1 ] } , BarcodeFormat . RSS_EXPANDED ) ; }
Not private for unit testing
16,542
private static int calculateMaskPenalty ( ByteMatrix matrix ) { return MaskUtil . applyMaskPenaltyRule1 ( matrix ) + MaskUtil . applyMaskPenaltyRule2 ( matrix ) + MaskUtil . applyMaskPenaltyRule3 ( matrix ) + MaskUtil . applyMaskPenaltyRule4 ( matrix ) ; }
Basically it applies four rules and summate all penalties .
16,543
private static Version recommendVersion ( ErrorCorrectionLevel ecLevel , Mode mode , BitArray headerBits , BitArray dataBits ) throws WriterException { int provisionalBitsNeeded = calculateBitsNeeded ( mode , headerBits , dataBits , Version . getVersionForNumber ( 1 ) ) ; Version provisionalVersion = chooseVersion ( provisionalBitsNeeded , ecLevel ) ; int bitsNeeded = calculateBitsNeeded ( mode , headerBits , dataBits , provisionalVersion ) ; return chooseVersion ( bitsNeeded , ecLevel ) ; }
Decides the smallest version of QR code that will contain all of the provided data .
16,544
static void appendLengthInfo ( int numLetters , Version version , Mode mode , BitArray bits ) throws WriterException { int numBits = mode . getCharacterCountBits ( version ) ; if ( numLetters >= ( 1 << numBits ) ) { throw new WriterException ( numLetters + " is bigger than " + ( ( 1 << numBits ) - 1 ) ) ; } bits . appendBits ( numLetters , numBits ) ; }
Append length info . On success store the result in bits .
16,545
public ProductParsedResult parse ( Result result ) { BarcodeFormat format = result . getBarcodeFormat ( ) ; if ( ! ( format == BarcodeFormat . UPC_A || format == BarcodeFormat . UPC_E || format == BarcodeFormat . EAN_8 || format == BarcodeFormat . EAN_13 ) ) { return null ; } String rawText = getMassagedText ( result ) ; if ( ! isStringOfDigits ( rawText , rawText . length ( ) ) ) { return null ; } String normalizedProductID ; if ( format == BarcodeFormat . UPC_E && rawText . length ( ) == 8 ) { normalizedProductID = UPCEReader . convertUPCEtoUPCA ( rawText ) ; } else { normalizedProductID = rawText ; } return new ProductParsedResult ( rawText , normalizedProductID ) ; }
Treat all UPC and EAN variants as UPCs in the sense that they are all product barcodes .
16,546
private int [ ] determineDimensions ( int sourceCodeWords , int errorCorrectionCodeWords ) throws WriterException { float ratio = 0.0f ; int [ ] dimension = null ; for ( int cols = minCols ; cols <= maxCols ; cols ++ ) { int rows = calculateNumberOfRows ( sourceCodeWords , errorCorrectionCodeWords , cols ) ; if ( rows < minRows ) { break ; } if ( rows > maxRows ) { continue ; } float newRatio = ( ( float ) ( 17 * cols + 69 ) * DEFAULT_MODULE_WIDTH ) / ( rows * HEIGHT ) ; if ( dimension != null && Math . abs ( newRatio - PREFERRED_RATIO ) > Math . abs ( ratio - PREFERRED_RATIO ) ) { continue ; } ratio = newRatio ; dimension = new int [ ] { cols , rows } ; } if ( dimension == null ) { int rows = calculateNumberOfRows ( sourceCodeWords , errorCorrectionCodeWords , minCols ) ; if ( rows < minRows ) { dimension = new int [ ] { minCols , minRows } ; } } if ( dimension == null ) { throw new WriterException ( "Unable to fit message in columns" ) ; } return dimension ; }
Determine optimal nr of columns and rows for the specified number of codewords .
16,547
public void applyMirroredCorrection ( ResultPoint [ ] points ) { if ( ! mirrored || points == null || points . length < 3 ) { return ; } ResultPoint bottomLeft = points [ 0 ] ; points [ 0 ] = points [ 2 ] ; points [ 2 ] = bottomLeft ; }
Apply the result points order correction due to mirroring .
16,548
void setValue ( int value ) { Integer confidence = values . get ( value ) ; if ( confidence == null ) { confidence = 0 ; } confidence ++ ; values . put ( value , confidence ) ; }
Add an occurrence of a value
16,549
int [ ] getValue ( ) { int maxConfidence = - 1 ; Collection < Integer > result = new ArrayList < > ( ) ; for ( Entry < Integer , Integer > entry : values . entrySet ( ) ) { if ( entry . getValue ( ) > maxConfidence ) { maxConfidence = entry . getValue ( ) ; result . clear ( ) ; result . add ( entry . getKey ( ) ) ; } else if ( entry . getValue ( ) == maxConfidence ) { result . add ( entry . getKey ( ) ) ; } } return PDF417Common . toIntArray ( result ) ; }
Determines the maximum occurrence of a set value and returns all values which were set with this occurrence .
16,550
private Collection < State > updateStateListForChar ( Iterable < State > states , int index ) { Collection < State > result = new LinkedList < > ( ) ; for ( State state : states ) { updateStateForChar ( state , index , result ) ; } return simplifyStates ( result ) ; }
non - optimal states .
16,551
private void updateStateForChar ( State state , int index , Collection < State > result ) { char ch = ( char ) ( text [ index ] & 0xFF ) ; boolean charInCurrentTable = CHAR_MAP [ state . getMode ( ) ] [ ch ] > 0 ; State stateNoBinary = null ; for ( int mode = 0 ; mode <= MODE_PUNCT ; mode ++ ) { int charInMode = CHAR_MAP [ mode ] [ ch ] ; if ( charInMode > 0 ) { if ( stateNoBinary == null ) { stateNoBinary = state . endBinaryShift ( index ) ; } if ( ! charInCurrentTable || mode == state . getMode ( ) || mode == MODE_DIGIT ) { State latchState = stateNoBinary . latchAndAppend ( mode , charInMode ) ; result . add ( latchState ) ; } if ( ! charInCurrentTable && SHIFT_TABLE [ state . getMode ( ) ] [ mode ] >= 0 ) { State shiftState = stateNoBinary . shiftAndAppend ( mode , charInMode ) ; result . add ( shiftState ) ; } } } if ( state . getBinaryShiftByteCount ( ) > 0 || CHAR_MAP [ state . getMode ( ) ] [ ch ] == 0 ) { State binaryState = state . addBinaryShiftChar ( index ) ; result . add ( binaryState ) ; } }
the result list .
16,552
public CharSequence getDisplayContents ( ) { String contents = getResult ( ) . getDisplayResult ( ) ; contents = contents . replace ( "\r" , "" ) ; return formatPhone ( contents ) ; }
Overriden so we can take advantage of Android s phone number hyphenation routines .
16,553
private void drawResultPoints ( Bitmap barcode , float scaleFactor , Result rawResult ) { ResultPoint [ ] points = rawResult . getResultPoints ( ) ; if ( points != null && points . length > 0 ) { Canvas canvas = new Canvas ( barcode ) ; Paint paint = new Paint ( ) ; paint . setColor ( getResources ( ) . getColor ( R . color . result_points ) ) ; if ( points . length == 2 ) { paint . setStrokeWidth ( 4.0f ) ; drawLine ( canvas , paint , points [ 0 ] , points [ 1 ] , scaleFactor ) ; } else if ( points . length == 4 && ( rawResult . getBarcodeFormat ( ) == BarcodeFormat . UPC_A || rawResult . getBarcodeFormat ( ) == BarcodeFormat . EAN_13 ) ) { drawLine ( canvas , paint , points [ 0 ] , points [ 1 ] , scaleFactor ) ; drawLine ( canvas , paint , points [ 2 ] , points [ 3 ] , scaleFactor ) ; } else { paint . setStrokeWidth ( 10.0f ) ; for ( ResultPoint point : points ) { if ( point != null ) { canvas . drawPoint ( scaleFactor * point . getX ( ) , scaleFactor * point . getY ( ) , paint ) ; } } } } }
Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode .
16,554
private ResultPoint [ ] centerEdges ( ResultPoint y , ResultPoint z , ResultPoint x , ResultPoint t ) { float yi = y . getX ( ) ; float yj = y . getY ( ) ; float zi = z . getX ( ) ; float zj = z . getY ( ) ; float xi = x . getX ( ) ; float xj = x . getY ( ) ; float ti = t . getX ( ) ; float tj = t . getY ( ) ; if ( yi < width / 2.0f ) { return new ResultPoint [ ] { new ResultPoint ( ti - CORR , tj + CORR ) , new ResultPoint ( zi + CORR , zj + CORR ) , new ResultPoint ( xi - CORR , xj - CORR ) , new ResultPoint ( yi + CORR , yj - CORR ) } ; } else { return new ResultPoint [ ] { new ResultPoint ( ti + CORR , tj + CORR ) , new ResultPoint ( zi + CORR , zj - CORR ) , new ResultPoint ( xi - CORR , xj + CORR ) , new ResultPoint ( yi - CORR , yj - CORR ) } ; } }
recenters the points of a constant distance towards the center
16,555
private boolean containsBlackPoint ( int a , int b , int fixed , boolean horizontal ) { if ( horizontal ) { for ( int x = a ; x <= b ; x ++ ) { if ( image . get ( x , fixed ) ) { return true ; } } } else { for ( int y = a ; y <= b ; y ++ ) { if ( image . get ( fixed , y ) ) { return true ; } } } return false ; }
Determines whether a segment contains a black point
16,556
private void addCalendarEvent ( String summary , long start , boolean allDay , long end , String location , String description , String [ ] attendees ) { Intent intent = new Intent ( Intent . ACTION_INSERT ) ; intent . setType ( "vnd.android.cursor.item/event" ) ; intent . putExtra ( "beginTime" , start ) ; if ( allDay ) { intent . putExtra ( "allDay" , true ) ; } if ( end < 0L ) { if ( allDay ) { end = start + 24 * 60 * 60 * 1000 ; } else { end = start ; } } intent . putExtra ( "endTime" , end ) ; intent . putExtra ( "title" , summary ) ; intent . putExtra ( "eventLocation" , location ) ; intent . putExtra ( "description" , description ) ; if ( attendees != null ) { intent . putExtra ( Intent . EXTRA_EMAIL , attendees ) ; } try { rawLaunchIntent ( intent ) ; } catch ( ActivityNotFoundException anfe ) { Log . w ( TAG , "No calendar app available that responds to " + Intent . ACTION_INSERT ) ; intent . setAction ( Intent . ACTION_EDIT ) ; launchIntent ( intent ) ; } }
Sends an intent to create a new calendar event by prepopulating the Add Event UI . Older versions of the system have a bug where the event title will not be filled out .
16,557
private static String getEncodedData ( boolean [ ] correctedBits ) { int endIndex = correctedBits . length ; Table latchTable = Table . UPPER ; Table shiftTable = Table . UPPER ; StringBuilder result = new StringBuilder ( 20 ) ; int index = 0 ; while ( index < endIndex ) { if ( shiftTable == Table . BINARY ) { if ( endIndex - index < 5 ) { break ; } int length = readCode ( correctedBits , index , 5 ) ; index += 5 ; if ( length == 0 ) { if ( endIndex - index < 11 ) { break ; } length = readCode ( correctedBits , index , 11 ) + 31 ; index += 11 ; } for ( int charCount = 0 ; charCount < length ; charCount ++ ) { if ( endIndex - index < 8 ) { index = endIndex ; break ; } int code = readCode ( correctedBits , index , 8 ) ; result . append ( ( char ) code ) ; index += 8 ; } shiftTable = latchTable ; } else { int size = shiftTable == Table . DIGIT ? 4 : 5 ; if ( endIndex - index < size ) { break ; } int code = readCode ( correctedBits , index , size ) ; index += size ; String str = getCharacter ( shiftTable , code ) ; if ( str . startsWith ( "CTRL_" ) ) { latchTable = shiftTable ; shiftTable = getTable ( str . charAt ( 5 ) ) ; if ( str . charAt ( 6 ) == 'L' ) { latchTable = shiftTable ; } } else { result . append ( str ) ; shiftTable = latchTable ; } } } return result . toString ( ) ; }
Gets the string encoded in the aztec code bits
16,558
private static Table getTable ( char t ) { switch ( t ) { case 'L' : return Table . LOWER ; case 'P' : return Table . PUNCT ; case 'M' : return Table . MIXED ; case 'D' : return Table . DIGIT ; case 'B' : return Table . BINARY ; case 'U' : default : return Table . UPPER ; } }
gets the table corresponding to the char passed
16,559
private boolean [ ] extractBits ( BitMatrix matrix ) { boolean compact = ddata . isCompact ( ) ; int layers = ddata . getNbLayers ( ) ; int baseMatrixSize = ( compact ? 11 : 14 ) + layers * 4 ; int [ ] alignmentMap = new int [ baseMatrixSize ] ; boolean [ ] rawbits = new boolean [ totalBitsInLayer ( layers , compact ) ] ; if ( compact ) { for ( int i = 0 ; i < alignmentMap . length ; i ++ ) { alignmentMap [ i ] = i ; } } else { int matrixSize = baseMatrixSize + 1 + 2 * ( ( baseMatrixSize / 2 - 1 ) / 15 ) ; int origCenter = baseMatrixSize / 2 ; int center = matrixSize / 2 ; for ( int i = 0 ; i < origCenter ; i ++ ) { int newOffset = i + i / 15 ; alignmentMap [ origCenter - i - 1 ] = center - newOffset - 1 ; alignmentMap [ origCenter + i ] = center + newOffset + 1 ; } } for ( int i = 0 , rowOffset = 0 ; i < layers ; i ++ ) { int rowSize = ( layers - i ) * 4 + ( compact ? 9 : 12 ) ; int low = i * 2 ; int high = baseMatrixSize - 1 - low ; for ( int j = 0 ; j < rowSize ; j ++ ) { int columnOffset = j * 2 ; for ( int k = 0 ; k < 2 ; k ++ ) { rawbits [ rowOffset + columnOffset + k ] = matrix . get ( alignmentMap [ low + k ] , alignmentMap [ low + j ] ) ; rawbits [ rowOffset + 2 * rowSize + columnOffset + k ] = matrix . get ( alignmentMap [ low + j ] , alignmentMap [ high - k ] ) ; rawbits [ rowOffset + 4 * rowSize + columnOffset + k ] = matrix . get ( alignmentMap [ high - k ] , alignmentMap [ high - j ] ) ; rawbits [ rowOffset + 6 * rowSize + columnOffset + k ] = matrix . get ( alignmentMap [ high - j ] , alignmentMap [ low + k ] ) ; } } rowOffset += rowSize * 8 ; } return rawbits ; }
Gets the array of bits from an Aztec Code matrix
16,560
private static int readCode ( boolean [ ] rawbits , int startIndex , int length ) { int res = 0 ; for ( int i = startIndex ; i < startIndex + length ; i ++ ) { res <<= 1 ; if ( rawbits [ i ] ) { res |= 0x01 ; } } return res ; }
Reads a code of given length and at given index in an array of bits
16,561
private static byte readByte ( boolean [ ] rawbits , int startIndex ) { int n = rawbits . length - startIndex ; if ( n >= 8 ) { return ( byte ) readCode ( rawbits , startIndex , 8 ) ; } return ( byte ) ( readCode ( rawbits , startIndex , n ) << ( 8 - n ) ) ; }
Reads a code of length 8 in an array of bits padding with zeros
16,562
static byte [ ] convertBoolArrayToByteArray ( boolean [ ] boolArr ) { byte [ ] byteArr = new byte [ ( boolArr . length + 7 ) / 8 ] ; for ( int i = 0 ; i < byteArr . length ; i ++ ) { byteArr [ i ] = readByte ( boolArr , 8 * i ) ; } return byteArr ; }
Packs a bit array into bytes most significant bit first
16,563
public static String convertUPCEtoUPCA ( String upce ) { char [ ] upceChars = new char [ 6 ] ; upce . getChars ( 1 , 7 , upceChars , 0 ) ; StringBuilder result = new StringBuilder ( 12 ) ; result . append ( upce . charAt ( 0 ) ) ; char lastChar = upceChars [ 5 ] ; switch ( lastChar ) { case '0' : case '1' : case '2' : result . append ( upceChars , 0 , 2 ) ; result . append ( lastChar ) ; result . append ( "0000" ) ; result . append ( upceChars , 2 , 3 ) ; break ; case '3' : result . append ( upceChars , 0 , 3 ) ; result . append ( "00000" ) ; result . append ( upceChars , 3 , 2 ) ; break ; case '4' : result . append ( upceChars , 0 , 4 ) ; result . append ( "00000" ) ; result . append ( upceChars [ 4 ] ) ; break ; default : result . append ( upceChars , 0 , 5 ) ; result . append ( "0000" ) ; result . append ( lastChar ) ; break ; } if ( upce . length ( ) >= 8 ) { result . append ( upce . charAt ( 7 ) ) ; } return result . toString ( ) ; }
Expands a UPC - E value back into its full equivalent UPC - A code value .
16,564
public Result decode ( BinaryBitmap image , Map < DecodeHintType , ? > hints ) throws NotFoundException { setHints ( hints ) ; return decodeInternal ( image ) ; }
Decode an image using the hints provided . Does not honor existing state .
16,565
private void utah ( int row , int col , int pos ) { module ( row - 2 , col - 2 , pos , 1 ) ; module ( row - 2 , col - 1 , pos , 2 ) ; module ( row - 1 , col - 2 , pos , 3 ) ; module ( row - 1 , col - 1 , pos , 4 ) ; module ( row - 1 , col , pos , 5 ) ; module ( row , col - 2 , pos , 6 ) ; module ( row , col - 1 , pos , 7 ) ; module ( row , col , pos , 8 ) ; }
Places the 8 bits of a utah - shaped symbol character in ECC200 .
16,566
private static String massageURI ( String uri ) { uri = uri . trim ( ) ; int protocolEnd = uri . indexOf ( ':' ) ; if ( protocolEnd < 0 || isColonFollowedByPortNumber ( uri , protocolEnd ) ) { uri = "http://" + uri ; } return uri ; }
Transforms a string that represents a URI into something more proper by adding or canonicalizing the protocol .
16,567
public static SimplePageDecorator first ( ) { List < SimplePageDecorator > decorators = all ( ) ; return decorators . isEmpty ( ) ? null : decorators . get ( 0 ) ; }
The first found LoginDecarator there can only be one .
16,568
protected Map < Computer , T > monitor ( ) throws InterruptedException { Map < Computer , T > data = new HashMap < > ( ) ; for ( Computer c : Jenkins . getInstance ( ) . getComputers ( ) ) { try { Thread . currentThread ( ) . setName ( "Monitoring " + c . getDisplayName ( ) + " for " + getDisplayName ( ) ) ; if ( c . getChannel ( ) == null ) data . put ( c , null ) ; else data . put ( c , monitor ( c ) ) ; } catch ( RuntimeException | IOException e ) { LOGGER . log ( Level . WARNING , "Failed to monitor " + c . getDisplayName ( ) + " for " + getDisplayName ( ) , e ) ; } catch ( InterruptedException e ) { throw ( InterruptedException ) new InterruptedException ( "Node monitoring " + c . getDisplayName ( ) + " for " + getDisplayName ( ) + " aborted." ) . initCause ( e ) ; } } return data ; }
Performs monitoring across the board .
16,569
public T get ( Computer c ) { if ( record == null || ! record . data . containsKey ( c ) ) { triggerUpdate ( ) ; return null ; } return record . data . get ( c ) ; }
Obtains the monitoring result currently available or null if no data is available .
16,570
public boolean isIgnored ( ) { NodeMonitor m = ComputerSet . getMonitors ( ) . get ( this ) ; return m == null || m . isIgnored ( ) ; }
Is this monitor currently ignored?
16,571
protected boolean markOnline ( Computer c ) { if ( isIgnored ( ) || c . isOnline ( ) ) return false ; c . setTemporarilyOffline ( false , null ) ; return true ; }
Utility method to mark the computer online for derived classes .
16,572
protected boolean markOffline ( Computer c , OfflineCause oc ) { if ( isIgnored ( ) || c . isTemporarilyOffline ( ) ) return false ; c . setTemporarilyOffline ( true , oc ) ; MonitorMarkedNodeOffline no = AdministrativeMonitor . all ( ) . get ( MonitorMarkedNodeOffline . class ) ; if ( no != null ) no . active = true ; return true ; }
Utility method to mark the computer offline for derived classes .
16,573
public String getCrumb ( ServletRequest request ) { String crumb = null ; if ( request != null ) { crumb = ( String ) request . getAttribute ( CRUMB_ATTRIBUTE ) ; } if ( crumb == null ) { crumb = issueCrumb ( request , getDescriptor ( ) . getCrumbSalt ( ) ) ; if ( request != null ) { if ( ( crumb != null ) && crumb . length ( ) > 0 ) { request . setAttribute ( CRUMB_ATTRIBUTE , crumb ) ; } else { request . removeAttribute ( CRUMB_ATTRIBUTE ) ; } } } return crumb ; }
Get a crumb value based on user specific information in the request .
16,574
public boolean validateCrumb ( ServletRequest request ) { CrumbIssuerDescriptor < CrumbIssuer > desc = getDescriptor ( ) ; String crumbField = desc . getCrumbRequestField ( ) ; String crumbSalt = desc . getCrumbSalt ( ) ; return validateCrumb ( request , crumbSalt , request . getParameter ( crumbField ) ) ; }
Get a crumb from a request parameter and validate it against other data in the current request . The salt and request parameter that is used is defined by the current configuration .
16,575
public boolean validateCrumb ( ServletRequest request , MultipartFormDataParser parser ) { CrumbIssuerDescriptor < CrumbIssuer > desc = getDescriptor ( ) ; String crumbField = desc . getCrumbRequestField ( ) ; String crumbSalt = desc . getCrumbSalt ( ) ; return validateCrumb ( request , crumbSalt , parser . get ( crumbField ) ) ; }
Get a crumb from multipart form data and validate it against other data in the current request . The salt and request parameter that is used is defined by the current configuration .
16,576
public static void initStaplerCrumbIssuer ( ) { WebApp . get ( Jenkins . getInstance ( ) . servletContext ) . setCrumbIssuer ( new org . kohsuke . stapler . CrumbIssuer ( ) { public String issueCrumb ( StaplerRequest request ) { CrumbIssuer ci = Jenkins . getInstance ( ) . getCrumbIssuer ( ) ; return ci != null ? ci . getCrumb ( request ) : DEFAULT . issueCrumb ( request ) ; } public void validateCrumb ( StaplerRequest request , String submittedCrumb ) { CrumbIssuer ci = Jenkins . getInstance ( ) . getCrumbIssuer ( ) ; if ( ci == null ) { DEFAULT . validateCrumb ( request , submittedCrumb ) ; } else { if ( ! ci . validateCrumb ( request , ci . getDescriptor ( ) . getCrumbSalt ( ) , submittedCrumb ) ) throw new SecurityException ( "Crumb didn't match" ) ; } } } ) ; }
Sets up Stapler to use our crumb issuer .
16,577
public String getPublicKey ( ) { RSAPublicKey key = InstanceIdentityProvider . RSA . getPublicKey ( ) ; if ( key == null ) { return null ; } byte [ ] encoded = Base64 . encodeBase64 ( key . getEncoded ( ) ) ; int index = 0 ; StringBuilder buf = new StringBuilder ( encoded . length + 20 ) ; while ( index < encoded . length ) { int len = Math . min ( 64 , encoded . length - index ) ; if ( index > 0 ) { buf . append ( "\n" ) ; } buf . append ( new String ( encoded , index , len , Charsets . UTF_8 ) ) ; index += len ; } return String . format ( "-----BEGIN PUBLIC KEY-----%n%s%n-----END PUBLIC KEY-----%n" , buf . toString ( ) ) ; }
Returns the PEM encoded public key .
16,578
public String getFingerprint ( ) { RSAPublicKey key = InstanceIdentityProvider . RSA . getPublicKey ( ) ; if ( key == null ) { return null ; } try { MessageDigest digest = MessageDigest . getInstance ( "MD5" ) ; digest . reset ( ) ; byte [ ] bytes = digest . digest ( key . getEncoded ( ) ) ; StringBuilder result = new StringBuilder ( Math . max ( 0 , bytes . length * 3 - 1 ) ) ; for ( int i = 0 ; i < bytes . length ; i ++ ) { if ( i > 0 ) { result . append ( ':' ) ; } int b = bytes [ i ] & 0xFF ; result . append ( Character . forDigit ( ( b >> 4 ) & 0x0f , 16 ) ) . append ( Character . forDigit ( b & 0xf , 16 ) ) ; } return result . toString ( ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalStateException ( "JLS mandates MD5 support" ) ; } }
Returns the fingerprint of the public key .
16,579
public void doJson ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { if ( req . getParameter ( "jsonp" ) == null || permit ( req ) ) { setHeaders ( rsp ) ; rsp . serveExposedBean ( req , bean , req . getParameter ( "jsonp" ) == null ? Flavor . JSON : Flavor . JSONP ) ; } else { rsp . sendError ( HttpURLConnection . HTTP_FORBIDDEN , "jsonp forbidden; implement jenkins.security.SecureRequester" ) ; } }
Exposes the bean as JSON .
16,580
public void doPython ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { setHeaders ( rsp ) ; rsp . serveExposedBean ( req , bean , Flavor . PYTHON ) ; }
Exposes the bean as Python literal .
16,581
@ Restricted ( NoExternalUse . class ) public static CauseAction getBuildCause ( ParameterizedJob job , StaplerRequest req ) { Cause cause ; @ SuppressWarnings ( "deprecation" ) hudson . model . BuildAuthorizationToken authToken = job . getAuthToken ( ) ; if ( authToken != null && authToken . getToken ( ) != null && req . getParameter ( "token" ) != null ) { String causeText = req . getParameter ( "cause" ) ; cause = new Cause . RemoteCause ( req . getRemoteAddr ( ) , causeText ) ; } else { cause = new Cause . UserIdCause ( ) ; } return new CauseAction ( cause ) ; }
Computes the build cause using RemoteCause or UserCause as appropriate .
16,582
public static < T extends Trigger < ? > > T getTrigger ( Job < ? , ? > job , Class < T > clazz ) { if ( ! ( job instanceof ParameterizedJob ) ) { return null ; } for ( Trigger < ? > t : ( ( ParameterizedJob < ? , ? > ) job ) . getTriggers ( ) . values ( ) ) { if ( clazz . isInstance ( t ) ) { return clazz . cast ( t ) ; } } return null ; }
Checks for the existence of a specific trigger on a job .
16,583
public synchronized String get ( ) { ConfidentialStore cs = ConfidentialStore . get ( ) ; if ( secret == null || cs != lastCS ) { lastCS = cs ; try { byte [ ] payload = load ( ) ; if ( payload == null ) { payload = cs . randomBytes ( length / 2 ) ; store ( payload ) ; } secret = Util . toHexString ( payload ) . substring ( 0 , length ) ; } catch ( IOException e ) { throw new Error ( "Failed to load the key: " + getId ( ) , e ) ; } } return secret ; }
Returns the persisted hex string value .
16,584
public void replaceBy ( Map < ? extends K , ? extends V > data ) { Map < K , V > d = copy ( ) ; d . clear ( ) ; d . putAll ( data ) ; update ( d ) ; }
Atomically replaces the entire map by the copy of the specified map .
16,585
public FilePath getWorkspaceRoot ( ) { FilePath r = getRootPath ( ) ; if ( r == null ) return null ; return r . child ( WORKSPACE_ROOT ) ; }
Root directory on this agent where all the job workspaces are laid out .
16,586
public Launcher createLauncher ( TaskListener listener ) { SlaveComputer c = getComputer ( ) ; if ( c == null ) { listener . error ( "Issue with creating launcher for agent " + name + ". Computer has been disconnected" ) ; return new Launcher . DummyLauncher ( listener ) ; } else { Slave node = c . getNode ( ) ; if ( node != this ) { String message = "Issue with creating launcher for agent " + name + ". Computer has been reconnected" ; if ( LOGGER . isLoggable ( Level . WARNING ) ) { LOGGER . log ( Level . WARNING , message , new IllegalStateException ( "Computer has been reconnected, this Node instance cannot be used anymore" ) ) ; } return new Launcher . DummyLauncher ( listener ) ; } final Channel channel = c . getChannel ( ) ; if ( channel == null ) { reportLauncherCreateError ( "The agent has not been fully initialized yet" , "No remoting channel to the agent OR it has not been fully initialized yet" , listener ) ; return new Launcher . DummyLauncher ( listener ) ; } if ( channel . isClosingOrClosed ( ) ) { reportLauncherCreateError ( "The agent is being disconnected" , "Remoting channel is either in the process of closing down or has closed down" , listener ) ; return new Launcher . DummyLauncher ( listener ) ; } final Boolean isUnix = c . isUnix ( ) ; if ( isUnix == null ) { reportLauncherCreateError ( "The agent has not been fully initialized yet" , "Cannot determing if the agent is a Unix one, the System status request has not completed yet. " + "It is an invalid channel state, please report a bug to Jenkins if you see it." , listener ) ; return new Launcher . DummyLauncher ( listener ) ; } return new RemoteLauncher ( listener , channel , isUnix ) . decorateFor ( this ) ; } }
Creates a launcher for the agent .
16,587
public static void skip ( DataInputStream in ) throws IOException { byte [ ] preamble = new byte [ PREAMBLE . length ] ; in . readFully ( preamble ) ; if ( ! Arrays . equals ( preamble , PREAMBLE ) ) return ; DataInputStream decoded = new DataInputStream ( new UnbufferedBase64InputStream ( in ) ) ; int macSz = - decoded . readInt ( ) ; if ( macSz > 0 ) { IOUtils . skip ( decoded , macSz ) ; int sz = decoded . readInt ( ) ; IOUtils . skip ( decoded , sz ) ; } else { int sz = - macSz ; IOUtils . skip ( decoded , sz ) ; } byte [ ] postamble = new byte [ POSTAMBLE . length ] ; in . readFully ( postamble ) ; }
Skips the encoded console note .
16,588
public static int findPreamble ( byte [ ] buf , int start , int len ) { int e = start + len - PREAMBLE . length + 1 ; OUTER : for ( int i = start ; i < e ; i ++ ) { if ( buf [ i ] == PREAMBLE [ 0 ] ) { for ( int j = 1 ; j < PREAMBLE . length ; j ++ ) { if ( buf [ i + j ] != PREAMBLE [ j ] ) continue OUTER ; } return i ; } } return - 1 ; }
Locates the preamble in the given buffer .
16,589
public static List < String > removeNotes ( Collection < String > logLines ) { List < String > r = new ArrayList < > ( logLines . size ( ) ) ; for ( String l : logLines ) r . add ( removeNotes ( l ) ) ; return r ; }
Removes the embedded console notes in the given log lines .
16,590
public static String removeNotes ( String line ) { while ( true ) { int idx = line . indexOf ( PREAMBLE_STR ) ; if ( idx < 0 ) return line ; int e = line . indexOf ( POSTAMBLE_STR , idx ) ; if ( e < 0 ) return line ; line = line . substring ( 0 , idx ) + line . substring ( e + POSTAMBLE_STR . length ( ) ) ; } }
Removes the embedded console notes in the given log line .
16,591
protected String getDisplayNameOf ( Method e , T i ) { Class < ? > c = e . getDeclaringClass ( ) ; String key = displayNameOf ( i ) ; if ( key . length ( ) == 0 ) return c . getSimpleName ( ) + "." + e . getName ( ) ; try { ResourceBundleHolder rb = ResourceBundleHolder . get ( c . getClassLoader ( ) . loadClass ( c . getPackage ( ) . getName ( ) + ".Messages" ) ) ; return rb . format ( key ) ; } catch ( ClassNotFoundException x ) { LOGGER . log ( WARNING , "Failed to load " + x . getMessage ( ) + " for " + e . toString ( ) , x ) ; return key ; } catch ( MissingResourceException x ) { LOGGER . log ( WARNING , "Could not find key '" + key + "' in " + c . getPackage ( ) . getName ( ) + ".Messages" , x ) ; return key ; } }
Obtains the display name of the given initialization task
16,592
protected void invoke ( Method e ) { try { Class < ? > [ ] pt = e . getParameterTypes ( ) ; Object [ ] args = new Object [ pt . length ] ; for ( int i = 0 ; i < args . length ; i ++ ) args [ i ] = lookUp ( pt [ i ] ) ; e . invoke ( Modifier . isStatic ( e . getModifiers ( ) ) ? null : lookUp ( e . getDeclaringClass ( ) ) , args ) ; } catch ( IllegalAccessException x ) { throw ( Error ) new IllegalAccessError ( ) . initCause ( x ) ; } catch ( InvocationTargetException x ) { throw new Error ( x ) ; } }
Invokes the given initialization method .
16,593
private Object lookUp ( Class < ? > type ) { Jenkins j = Jenkins . getInstance ( ) ; assert j != null : "This method is only invoked after the Jenkins singleton instance has been set" ; if ( type == Jenkins . class || type == Hudson . class ) return j ; Injector i = j . getInjector ( ) ; if ( i != null ) return i . getInstance ( type ) ; throw new IllegalArgumentException ( "Unable to inject " + type ) ; }
Determines the parameter injection of the initialization method .
16,594
public String getDescription ( ) { Stapler stapler = Stapler . getCurrent ( ) ; if ( stapler != null ) { try { WebApp webapp = WebApp . getCurrent ( ) ; MetaClass meta = webapp . getMetaClass ( this ) ; Script s = meta . loadTearOff ( JellyClassTearOff . class ) . findScript ( "newInstanceDetail" ) ; if ( s == null ) { return "" ; } DefaultScriptInvoker dsi = new DefaultScriptInvoker ( ) ; StringWriter sw = new StringWriter ( ) ; XMLOutput xml = dsi . createXMLOutput ( sw , true ) ; dsi . invokeScript ( Stapler . getCurrentRequest ( ) , Stapler . getCurrentResponse ( ) , s , this , xml ) ; return sw . toString ( ) ; } catch ( Exception e ) { LOGGER . log ( Level . WARNING , null , e ) ; return "" ; } } else { return "" ; } }
A description of this kind of item type . This description can contain HTML code but it is recommended that you use plain text in order to be consistent with the rest of Jenkins .
16,595
public String getIconFilePath ( String size ) { if ( ! StringUtils . isBlank ( getIconFilePathPattern ( ) ) ) { return getIconFilePathPattern ( ) . replace ( ":size" , size ) ; } return null ; }
An icon file path associated to a specific size .
16,596
public MavenInstallation getMaven ( ) { for ( MavenInstallation i : getDescriptor ( ) . getInstallations ( ) ) { if ( mavenName != null && mavenName . equals ( i . getName ( ) ) ) return i ; } return null ; }
Gets the Maven to invoke or null to invoke the default one .
16,597
protected void buildEnvVars ( EnvVars env , MavenInstallation mi ) throws IOException , InterruptedException { if ( mi != null ) { mi . buildEnvVars ( env ) ; } env . put ( "MAVEN_TERMINATE_CMD" , "on" ) ; String jvmOptions = env . expand ( this . jvmOptions ) ; if ( jvmOptions != null ) env . put ( "MAVEN_OPTS" , jvmOptions . replaceAll ( "[\t\r\n]+" , " " ) ) ; }
Build up the environment variables toward the Maven launch .
16,598
public static boolean checkIsReachable ( InetAddress ia , int timeout ) throws IOException { for ( ComputerPinger pinger : ComputerPinger . all ( ) ) { try { if ( pinger . isReachable ( ia , timeout ) ) { return true ; } } catch ( IOException e ) { LOGGER . fine ( "Error checking reachability with " + pinger + ": " + e . getMessage ( ) ) ; } } return false ; }
Is this computer reachable via the given address?
16,599
protected PluginStrategy createPluginStrategy ( ) { String strategyName = SystemProperties . getString ( PluginStrategy . class . getName ( ) ) ; if ( strategyName != null ) { try { Class < ? > klazz = getClass ( ) . getClassLoader ( ) . loadClass ( strategyName ) ; Object strategy = klazz . getConstructor ( PluginManager . class ) . newInstance ( this ) ; if ( strategy instanceof PluginStrategy ) { LOGGER . info ( "Plugin strategy: " + strategyName ) ; return ( PluginStrategy ) strategy ; } else { LOGGER . warning ( "Plugin strategy (" + strategyName + ") is not an instance of hudson.PluginStrategy" ) ; } } catch ( ClassNotFoundException e ) { LOGGER . warning ( "Plugin strategy class not found: " + strategyName ) ; } catch ( Exception e ) { LOGGER . log ( WARNING , "Could not instantiate plugin strategy: " + strategyName + ". Falling back to ClassicPluginStrategy" , e ) ; } LOGGER . info ( "Falling back to ClassicPluginStrategy" ) ; } return new ClassicPluginStrategy ( this ) ; }
Creates a hudson . PluginStrategy looking at the corresponding system property .