name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
zxing_PDF417ScanningDecoder_decode_rdh
// TODO don't pass in minCodewordWidth and maxCodewordWidth, pass in barcode columns for start and stop pattern // columns. That way width can be deducted from the pattern column. // This approach also allows to detect more details about the barcode, e.g. if a bar type (white or black) is wider // than it should be. This can happen if the scanner used a bad blackpoint. public static DecoderResult decode(BitMatrix image, ResultPoint imageTopLeft, ResultPoint imageBottomLeft, ResultPoint imageTopRight, ResultPoint imageBottomRight, int minCodewordWidth, int maxCodewordWidth) throws NotFoundException, FormatException, ChecksumException { BoundingBox boundingBox = new BoundingBox(image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight); DetectionResultRowIndicatorColumn leftRowIndicatorColumn = null; DetectionResultRowIndicatorColumn rightRowIndicatorColumn = null; DetectionResult detectionResult; for (boolean firstPass = true; ; firstPass = false) { if (imageTopLeft != null) { leftRowIndicatorColumn = getRowIndicatorColumn(image, boundingBox, imageTopLeft, true, minCodewordWidth, maxCodewordWidth); } if (imageTopRight != null) { rightRowIndicatorColumn = getRowIndicatorColumn(image, boundingBox, imageTopRight, false, minCodewordWidth, maxCodewordWidth); } detectionResult = merge(leftRowIndicatorColumn, rightRowIndicatorColumn); if (detectionResult == null) { throw NotFoundException.getNotFoundInstance(); } BoundingBox resultBox = detectionResult.getBoundingBox(); if ((firstPass && (resultBox != null)) && ((resultBox.getMinY() < boundingBox.getMinY()) || (resultBox.getMaxY() > boundingBox.getMaxY()))) { boundingBox = resultBox; } else {break; } } detectionResult.setBoundingBox(boundingBox); int maxBarcodeColumn = detectionResult.getBarcodeColumnCount() + 1; detectionResult.setDetectionResultColumn(0, leftRowIndicatorColumn); detectionResult.setDetectionResultColumn(maxBarcodeColumn, rightRowIndicatorColumn); boolean leftToRight = leftRowIndicatorColumn != null; for (int barcodeColumnCount = 1; barcodeColumnCount <= maxBarcodeColumn; barcodeColumnCount++) { int barcodeColumn = (leftToRight) ? barcodeColumnCount : maxBarcodeColumn - barcodeColumnCount;if (detectionResult.getDetectionResultColumn(barcodeColumn) != null) { // This will be the case for the opposite row indicator column, which doesn't need to be decoded again. continue; } DetectionResultColumn detectionResultColumn; if ((barcodeColumn == 0) || (barcodeColumn == maxBarcodeColumn)) { detectionResultColumn = new DetectionResultRowIndicatorColumn(boundingBox, barcodeColumn == 0); } else { detectionResultColumn = new DetectionResultColumn(boundingBox); } detectionResult.setDetectionResultColumn(barcodeColumn, detectionResultColumn); int startColumn = -1; int previousStartColumn = startColumn; // TODO start at a row for which we know the start position, then detect upwards and downwards from there. for (int imageRow = boundingBox.getMinY(); imageRow <= boundingBox.getMaxY(); imageRow++) { startColumn = getStartColumn(detectionResult, barcodeColumn, imageRow, leftToRight); if ((startColumn < 0) || (startColumn > boundingBox.getMaxX())) { if (previousStartColumn == (-1)) { continue; } startColumn = previousStartColumn; } Codeword codeword = detectCodeword(image, boundingBox.getMinX(), boundingBox.getMaxX(), leftToRight, startColumn, imageRow, minCodewordWidth, maxCodewordWidth); if (codeword != null) { detectionResultColumn.setCodeword(imageRow, codeword); previousStartColumn = startColumn; minCodewordWidth = Math.min(minCodewordWidth, codeword.getWidth()); maxCodewordWidth = Math.max(maxCodewordWidth, codeword.getWidth()); } } } return createDecoderResult(detectionResult); }
3.26
zxing_PDF417ScanningDecoder_verifyCodewordCount_rdh
/** * Verify that all is OK with the codeword array. */ private static void verifyCodewordCount(int[] codewords, int numECCodewords) throws FormatException { if (codewords.length < 4) { // Codeword array size should be at least 4 allowing for // Count CW, At least one Data CW, Error Correction CW, Error Correction CW throw FormatException.getFormatInstance(); } // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad // codewords, but excluding the number of error correction codewords. int numberOfCodewords = codewords[0]; if (numberOfCodewords > codewords.length) { throw FormatException.getFormatInstance(); } if (numberOfCodewords == 0) { // Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords) if (numECCodewords < codewords.length) { codewords[0] = codewords.length - numECCodewords;} else { throw FormatException.getFormatInstance(); } } }
3.26
zxing_BizcardResultParser_parse_rdh
// Yes, we extend AbstractDoCoMoResultParser since the format is very much // like the DoCoMo MECARD format, but this is not technically one of // DoCoMo's proposed formats @Override 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);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); }
3.26
zxing_MaskUtil_applyMaskPenaltyRule3_rdh
/** * Apply mask penalty rule 3 and return the penalty. Find consecutive runs of 1:1:3:1:1:4 * starting with black, or 4:1:1:3:1:1 starting with white, and give penalty to them. If we * find patterns like 000010111010000, we give penalty once. */ static int applyMaskPenaltyRule3(ByteMatrix matrix) {int numPenalties = 0; byte[][] array = matrix.getArray(); int width = matrix.getWidth(); int v11 = matrix.getHeight(); for (int y = 0; y < v11; y++) { for (int x = 0; x < width; x++) { byte[] arrayY = array[y];// We can at least optimize this access if ((((((((((x + 6) < width) && (arrayY[x] == 1)) && (arrayY[x + 1] == 0)) && (arrayY[x + 2] == 1)) && (arrayY[x + 3] == 1)) && (arrayY[x + 4] == 1)) && (arrayY[x + 5] == 0)) && (arrayY[x + 6] == 1)) && (isWhiteHorizontal(arrayY, x - 4, x) || isWhiteHorizontal(arrayY, x + 7, x + 11))) { numPenalties++; } if ((((((((((y + 6) < v11) && (array[y][x] == 1)) && (array[y + 1][x] == 0)) && (array[y + 2][x] == 1)) && (array[y + 3][x] == 1)) && (array[y + 4][x] == 1)) && (array[y + 5][x] == 0)) && (array[y + 6][x] == 1)) && (isWhiteVertical(array, x, y - 4, y) || isWhiteVertical(array, x, y + 7, y + 11))) { numPenalties++; } } } return numPenalties * N3; }
3.26
zxing_MaskUtil_applyMaskPenaltyRule1Internal_rdh
/** * Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both * vertical and horizontal orders respectively. */ 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;// Include the cell itself. prevBit = bit; } } if (numSameBitCells >= 5) { penalty += N1 + (numSameBitCells - 5); } } return penalty; }
3.26
zxing_MaskUtil_getDataMaskBit_rdh
/** * Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask * pattern conditions. */ static boolean getDataMaskBit(int maskPattern, int x, int y) { int intermediate; int temp; switch (maskPattern) { case 0 : intermediate = (y + x) & 0x1; break; case 1 : intermediate = y & 0x1; break;case 2 : intermediate = x % 3;break; case 3 : intermediate = (y + x) % 3; break; case 4 : intermediate = ((y / 2) + (x / 3)) & 0x1; break; case 5 : temp = y * x; intermediate = (temp & 0x1) + (temp % 3); break; case 6 : temp = y * x; intermediate = ((temp & 0x1) + (temp % 3)) & 0x1; break; case 7 : temp = y * x; intermediate = ((temp % 3) + ((y + x) & 0x1)) & 0x1; break; default : throw new IllegalArgumentException("Invalid mask pattern: " + maskPattern); } return intermediate == 0; }
3.26
zxing_MaskUtil_applyMaskPenaltyRule4_rdh
/** * Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give * penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance. */ static int applyMaskPenaltyRule4(ByteMatrix matrix) { int numDarkCells = 0; byte[][] array = matrix.getArray(); int width = matrix.getWidth(); int height = matrix.getHeight(); for (int v21 = 0; v21 < height; v21++) { byte[] arrayY = array[v21]; for (int x = 0; x < width; x++) { if (arrayY[x] == 1) { numDarkCells++; } } } int numTotalCells = matrix.getHeight() * matrix.getWidth(); int fivePercentVariances = (Math.abs((numDarkCells * 2) - numTotalCells) * 10) / numTotalCells; return fivePercentVariances * f0; }
3.26
zxing_WifiResultHandler_getDisplayContents_rdh
// Display the name of the network and the network type to the user. @Override public CharSequence getDisplayContents() { WifiParsedResult wifiResult = ((WifiParsedResult) (getResult())); return ((wifiResult.getSsid() + " (") + wifiResult.getNetworkEncryption()) + ')'; }
3.26
zxing_CalendarParsedResult_isStartAllDay_rdh
/** * * @return true if start time was specified as a whole day */ public boolean isStartAllDay() { return startAllDay; }
3.26
zxing_CalendarParsedResult_getStart_rdh
/** * * @return start time * @deprecated use {@link #getStartTimestamp()} */@Deprecated public Date getStart() { return new Date(start); }
3.26
zxing_CalendarParsedResult_parseDate_rdh
/** * Parses a string as a date. RFC 2445 allows the start and end fields to be of type DATE (e.g. 20081021) * or DATE-TIME (e.g. 20081021T123000 for local time, or 20081021T123000Z for UTC). * * @param when * The string to parse * @throws ParseException * if not able to parse as a date */ private static long parseDate(String when) throws ParseException { if (!DATE_TIME.matcher(when).matches()) { throw new ParseException(when, 0); } if (when.length() == 8) { // Show only year/month/day DateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH); // For dates without a time, for purposes of interacting with Android, the resulting timestamp // needs to be midnight of that day in GMT. See: // http://code.google.com/p/android/issues/detail?id=8330 format.setTimeZone(TimeZone.getTimeZone("GMT")); return format.parse(when).getTime(); } // The when string can be local time, or UTC if it ends with a Z if ((when.length() == 16) && (when.charAt(15) == 'Z')) { long milliseconds = parseDateTimeString(when.substring(0, 15)); Calendar calendar = new GregorianCalendar(); // Account for time zone difference milliseconds += calendar.get(Calendar.ZONE_OFFSET); // Might need to correct for daylight savings time, but use target time since // now might be in DST but not then, or vice versa calendar.setTime(new Date(milliseconds)); return milliseconds + calendar.get(Calendar.DST_OFFSET); } return parseDateTimeString(when); }
3.26
zxing_CalendarParsedResult_getEnd_rdh
/** * * @return event end {@link Date}, or {@code null} if event has no duration * @deprecated use {@link #getEndTimestamp()} */@Deprecated public Date getEnd() { return end < 0L ? null : new Date(end); }
3.26
zxing_CalendarParsedResult_getEndTimestamp_rdh
/** * * @return event end {@link Date}, or -1 if event has no duration * @see #getStartTimestamp() */ public long getEndTimestamp() { return end; }
3.26
zxing_CalendarParsedResult_isEndAllDay_rdh
/** * * @return true if end time was specified as a whole day */ public boolean isEndAllDay() { return endAllDay; }
3.26
zxing_CalendarParsedResult_getStartTimestamp_rdh
/** * * @return start time * @see #getEndTimestamp() */ public long getStartTimestamp() { return start; }
3.26
zxing_RSSExpandedReader_checkRows_rdh
// Try to construct a valid rows sequence // Recursion is used to implement backtracking 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, false)) { if (checkChecksum()) { return this.pairs; } List<ExpandedRow> rs = new ArrayList<>(collectedRows); rs.add(row); try { // Recursion: try to add more rows return checkRows(rs, i + 1); } catch (NotFoundException e) { // We failed, try the next candidate } } } throw NotFoundException.getNotFoundInstance(); }
3.26
zxing_RSSExpandedReader_getRows_rdh
// Only used for unit testing List<ExpandedRow> getRows() { return this.rows; }
3.26
zxing_RSSExpandedReader_isPartialRow_rdh
// Returns true when one of the rows already contains all the pairs 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) { // the row 'r' contain all the pairs from 'pairs' return true; } } return false; }
3.26
zxing_RSSExpandedReader_isValidSequence_rdh
// Whether the pairs form a valid finder pattern sequence, either complete or a prefix private static boolean isValidSequence(List<ExpandedPair> pairs, boolean complete) { for (int[] sequence : FINDER_PATTERN_SEQUENCES) { boolean sizeOk = (complete) ? pairs.size() == sequence.length : pairs.size() <= sequence.length; if (sizeOk) { 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; }
3.26
zxing_RSSExpandedReader_mayFollow_rdh
// Whether the pairs, plus another pair of the specified type, would together // form a valid finder pattern sequence, either complete or partial private static boolean mayFollow(List<ExpandedPair> pairs, int value) { if (pairs.isEmpty()) { return true; } for (int[] sequence : FINDER_PATTERN_SEQUENCES) { if ((pairs.size() + 1) <= sequence.length) { // the proposed sequence (i.e. pairs + value) would fit in this allowed sequence for (int i = pairs.size(); i < sequence.length; i++) { if (sequence[i] == value) { // we found our value in this allowed sequence, check to see if the elements preceding it match our existing // pairs; note our existing pairs may not be a full sequence (e.g. if processing a row in a stacked symbol) boolean matched = true; for (int j = 0; j < pairs.size(); j++) { int allowed = sequence[(i - j) - 1]; int actual = pairs.get((pairs.size() - j) - 1).getFinderPattern().getValue(); if (allowed != actual) { matched = false; break; } } if (matched) { return true; } } } } } // the proposed finder pattern sequence is illegal return false; }
3.26
zxing_RSSExpandedReader_removePartialRows_rdh
// Remove all the rows that contains only specified pairs private static void removePartialRows(Collection<ExpandedPair> pairs, Collection<ExpandedRow> rows) { for (Iterator<ExpandedRow> iterator = rows.iterator(); iterator.hasNext();) { ExpandedRow v23 = iterator.next(); if (v23.getPairs().size() != pairs.size()) { boolean allFound = true; for (ExpandedPair p : v23.getPairs()) { if (!pairs.contains(p)) { allFound = false; break; } } if (allFound) { // 'pairs' contains all the pairs from the row 'r' iterator.remove(); } } } }
3.26
zxing_RSSExpandedReader_constructResult_rdh
// Not private for unit testing 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(); Result result = new Result(resultingString, null, new ResultPoint[]{ firstPoints[0], firstPoints[1], lastPoints[0], lastPoints[1] }, BarcodeFormat.RSS_EXPANDED); result.putMetadata(ResultMetadataType.SYMBOLOGY_IDENTIFIER, "]e0"); return result; }
3.26
zxing_RSSExpandedReader_retrieveNextPair_rdh
// not private for testing ExpandedPair retrieveNextPair(BitArray row, List<ExpandedPair> previousPairs, int rowNumber) throws NotFoundException { boolean isOddPattern = (previousPairs.size() % 2) == 0; if (startFromEven) { isOddPattern = !isOddPattern; } FinderPattern pattern; DataCharacter leftChar = null; boolean keepFinding = true; int forcedOffset = -1; do { this.findNextPair(row, previousPairs, forcedOffset); pattern = m0(row, rowNumber, isOddPattern, previousPairs); if (pattern == null) { forcedOffset = getNextSecondBar(row, this.startEnd[0]);// probable false positive, keep looking } else { try { leftChar = this.decodeDataCharacter(row, pattern, isOddPattern, true); keepFinding = false; } catch (NotFoundException ignored) { forcedOffset = getNextSecondBar(row, this.startEnd[0]);// probable false positive, keep looking } } } while (keepFinding ); // When stacked symbol is split over multiple rows, there's no way to guess if this pair can be last or not. // boolean mayBeLast = checkPairSequence(previousPairs, pattern); if ((!previousPairs.isEmpty()) && previousPairs.get(previousPairs.size() - 1).mustBeLast()) { throw NotFoundException.getNotFoundInstance(); } DataCharacter rightChar; try { rightChar = this.decodeDataCharacter(row, pattern, isOddPattern, false); } catch (NotFoundException ignored) { rightChar = null; } return new ExpandedPair(leftChar, rightChar, pattern); }
3.26
zxing_RSSExpandedReader_decodeRow2pairs_rdh
// Not private for testing List<ExpandedPair> decodeRow2pairs(int rowNumber, BitArray row) throws NotFoundException { this.pairs.clear(); boolean done = false; while (!done) { try { this.pairs.add(retrieveNextPair(row, this.pairs, rowNumber)); } catch (NotFoundException nfe) { if (this.pairs.isEmpty()) { throw nfe; } // exit this loop when retrieveNextPair() fails and throws done = true; } } if (checkChecksum() && isValidSequence(this.pairs, true)) { return this.pairs; } boolean tryStackedDecode = !this.rows.isEmpty(); storeRow(rowNumber);// TODO: deal with reversed rows if (tryStackedDecode) { // When the image is 180-rotated, then rows are sorted in wrong direction. // Try twice with both the directions. List<ExpandedPair> ps = checkRows(false); if (ps != null) { return ps; } ps = checkRows(true); if (ps != null) { return ps; } } throw NotFoundException.getNotFoundInstance(); }
3.26
zxing_GeoParsedResult_getLongitude_rdh
/** * * @return longitude in degrees */ public double getLongitude() { return longitude; }
3.26
zxing_GeoParsedResult_getLatitude_rdh
/** * * @return latitude in degrees */ public double getLatitude() { return latitude; }
3.26
zxing_GeoParsedResult_m0_rdh
/** * * @return query string associated with geo URI or null if none exists */ public String m0() { return query; }
3.26
zxing_GeoParsedResult_getAltitude_rdh
/** * * @return altitude in meters. If not specified, in the geo URI, returns 0.0 */ public double getAltitude() { return altitude; }
3.26
zxing_PDF417Reader_decode_rdh
/** * Locates and decodes a PDF417 code in an image. * * @return a String representing the content encoded by the PDF417 code * @throws NotFoundException * if a PDF417 code cannot be found, * @throws FormatException * if a PDF417 cannot be decoded */ @Override public Result decode(BinaryBitmap image) throws NotFoundException, FormatException, ChecksumException { return m0(image, null); }
3.26
zxing_C40Encoder_handleEOD_rdh
/** * Handle "end of data" situations * * @param context * the encoder context * @param buffer * the buffer with the remaining encoded characters */ void handleEOD(EncoderContext context, StringBuilder buffer) { int unwritten = (buffer.length() / 3) * 2; int rest = buffer.length() % 3; int curCodewordCount = context.getCodewordCount() + unwritten; context.updateSymbolInfo(curCodewordCount); int available = context.getSymbolInfo().getDataCapacity() - curCodewordCount; if (rest == 2) { buffer.append('\u0000');// Shift 1 while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } } else if ((available == 1) && (rest == 1)) { while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } // else no unlatch context.pos--; } else if (rest == 0) { while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if ((available > 0) || context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } } else { throw new IllegalStateException("Unexpected case. Please report!"); } context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); }
3.26
zxing_DataMask_unmaskBitMatrix_rdh
// End of enum constants. /** * <p>Implementations of this method reverse the data masking process applied to a QR Code and * make its bits ready to read.</p> * * @param bits * representation of QR Code bits * @param dimension * dimension of QR Code, represented by bits, being unmasked */ final void unmaskBitMatrix(BitMatrix bits, int dimension) { for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { if (isMasked(i, j)) { bits.flip(j, i); } } } }
3.26
zxing_DataMask_isMasked_rdh
/** * 100: mask bits for which (x/2 + y/3) mod 2 == 0 */DATA_MASK_100() {@Override boolean isMasked(int i, int j) { return (((i / 2) + (j / 3)) & 0x1) == 0; }
3.26
zxing_LuminanceSource_crop_rdh
/** * Returns a new object with cropped image data. Implementations may keep a reference to the * original data rather than a copy. Only callable if isCropSupported() is true. * * @param left * The left coordinate, which must be in [0,getWidth()) * @param top * The top coordinate, which must be in [0,getHeight()) * @param width * The width of the rectangle to crop. * @param height * The height of the rectangle to crop. * @return A cropped version of this object. */ public LuminanceSource crop(int left, int top, int width, int height) { throw new UnsupportedOperationException("This luminance source does not support cropping."); }
3.26
zxing_LuminanceSource_rotateCounterClockwise45_rdh
/** * Returns a new object with rotated image data by 45 degrees counterclockwise. * Only callable if {@link #isRotateSupported()} is true. * * @return A rotated version of this object. */ public LuminanceSource rotateCounterClockwise45() { throw new UnsupportedOperationException("This luminance source does not support rotation by 45 degrees."); }
3.26
zxing_LuminanceSource_isCropSupported_rdh
/** * * @return Whether this subclass supports cropping. */ public boolean isCropSupported() { return false; }
3.26
zxing_LuminanceSource_isRotateSupported_rdh
/** * * @return Whether this subclass supports counter-clockwise rotation. */ public boolean isRotateSupported() { return false; } /** * * @return a wrapper of this {@code LuminanceSource}
3.26
zxing_LuminanceSource_rotateCounterClockwise_rdh
/** * Returns a new object with rotated image data by 90 degrees counterclockwise. * Only callable if {@link #isRotateSupported()} is true. * * @return A rotated version of this object. */ public LuminanceSource rotateCounterClockwise() { throw new UnsupportedOperationException("This luminance source does not support rotation by 90 degrees."); }
3.26
zxing_LuminanceSource_getWidth_rdh
/** * * @return The width of the bitmap. */ public final int getWidth() { return width; }
3.26
zxing_LuminanceSource_getHeight_rdh
/** * * @return The height of the bitmap. */ public final int getHeight() { return height; }
3.26
zxing_ShareActivity_showContactAsBarcode_rdh
/** * Takes a contact Uri and does the necessary database lookups to retrieve that person's info, * then sends an Encode intent to render it as a QR Code. * * @param contactUri * A Uri of the form content://contacts/people/17 */private void showContactAsBarcode(Uri contactUri) { if (contactUri == null) { return;// Show error? } ContentResolver resolver = getContentResolver(); String id; String name; boolean hasPhone; try (Cursor cursor = resolver.query(contactUri, null, null, null, null)) { if ((cursor == null) || (!cursor.moveToFirst())) { return; } id = cursor.getString(cursor.getColumnIndex(BaseColumns._ID)); name = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME)); hasPhone = cursor.getInt(cursor.getColumnIndex(Contacts.HAS_PHONE_NUMBER)) > 0; } // Don't require a name to be present, this contact might be just a phone number. Bundle bundle = new Bundle(); if ((name != null) && (!name.isEmpty())) { bundle.putString(Insert.NAME, massageContactData(name)); } if (hasPhone) { try (Cursor phonesCursor = resolver.query(Phone.CONTENT_URI, null, (Phone.CONTACT_ID + '=') + id, null, null)) { if (phonesCursor != null) { int foundPhone = 0; int phonesNumberColumn = phonesCursor.getColumnIndex(Phone.NUMBER); int phoneTypeColumn = phonesCursor.getColumnIndex(Phone.TYPE); while (phonesCursor.moveToNext() && (foundPhone < PHONE_KEYS.length)) { String number = phonesCursor.getString(phonesNumberColumn); if ((number != null) && (!number.isEmpty())) { bundle.putString(Contents.PHONE_KEYS[foundPhone], massageContactData(number)); } int type = phonesCursor.getInt(phoneTypeColumn); bundle.putInt(Contents.PHONE_TYPE_KEYS[foundPhone], type); foundPhone++; } } } } try (Cursor methodsCursor = resolver.query(StructuredPostal.CONTENT_URI, null, (StructuredPostal.CONTACT_ID + '=') + id, null, null)) { if ((methodsCursor != null) && methodsCursor.moveToNext()) { String data = methodsCursor.getString(methodsCursor.getColumnIndex(StructuredPostal.FORMATTED_ADDRESS)); if ((data != null) && (!data.isEmpty())) { bundle.putString(Insert.POSTAL, massageContactData(data)); } } } try (Cursor emailCursor = resolver.query(Email.CONTENT_URI, null, (Email.CONTACT_ID + '=') + id, null, null)) { if (emailCursor != null) { int foundEmail = 0; int emailColumn = emailCursor.getColumnIndex(Email.DATA); while (emailCursor.moveToNext() && (foundEmail < EMAIL_KEYS.length)) { String email = emailCursor.getString(emailColumn); if ((email != null) && (!email.isEmpty())) { bundle.putString(Contents.EMAIL_KEYS[foundEmail], massageContactData(email)); } foundEmail++; } } } Intent intent = buildEncodeIntent(Type.CONTACT); intent.putExtra(Encode.DATA, bundle); startActivity(intent); }
3.26
zxing_GlobalHistogramBinarizer_getBlackRow_rdh
// Applies simple sharpening to the row data to improve performance of the 1D Readers. @Override public BitArray getBlackRow(int y, BitArray row) throws NotFoundException { LuminanceSource source = getLuminanceSource(); int v1 = source.getWidth(); if ((row == null) || (row.getSize() < v1)) { row = new BitArray(v1); } else { row.clear(); } initArrays(v1); byte[] localLuminances = source.getRow(y, luminances); int[] localBuckets = buckets; for (int x = 0; x < v1; x++) { localBuckets[(localLuminances[x] & 0xff) >> LUMINANCE_SHIFT]++; } int blackPoint = estimateBlackPoint(localBuckets); if (v1 < 3) { // Special case for very small images for (int x = 0; x < v1; 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 < (v1 - 1); x++) { int right = localLuminances[x + 1] & 0xff; // A simple -1 4 -1 box filter with a weight of 2. if (((((center * 4) - left) - right) / 2) < blackPoint) { row.set(x); } left = center; center = right; } } return row; }
3.26
zxing_GlobalHistogramBinarizer_getBlackMatrix_rdh
// Does not sharpen the data, as this call is intended to only be used by 2D Readers. @Override public BitMatrix getBlackMatrix() throws NotFoundException { LuminanceSource source = getLuminanceSource(); int width = source.getWidth(); int height = source.getHeight(); BitMatrix matrix = new BitMatrix(width, height); // Quickly calculates the histogram by sampling four rows from the image. This proved to be // more robust on the blackbox tests than sampling a diagonal as we used to do. 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); // We delay reading the entire image luminance until the black point estimation succeeds. // Although we end up reading four rows twice, it is consistent with our motto of // "fail quickly" which is necessary for continuous scanning. byte[] localLuminances = source.getMatrix(); for (int y = 0; y < height; y++) { int v25 = y * width; for (int x = 0; x < width; x++) { int v27 = localLuminances[v25 + x] & 0xff; if (v27 < blackPoint) { matrix.set(x, y); } } }return matrix;}
3.26
zxing_ReedSolomonDecoder_decode_rdh
/** * <p>Decodes given set of received codewords, which include both data and error-correction * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place, * in the input.</p> * * @param received * data and error-correction codewords * @param twoS * number of error-correction codewords available * @throws ReedSolomonException * if decoding fails for any reason */ public void decode(int[] received, int twoS) throws ReedSolomonException { decodeWithECCount(received, twoS); }
3.26
zxing_ReedSolomonDecoder_decodeWithECCount_rdh
/** * <p>Decodes given set of received codewords, which include both data and error-correction * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place, * in the input.</p> * * @param received * data and error-correction codewords * @param twoS * number of error-correction codewords available * @return the number of errors corrected * @throws ReedSolomonException * if decoding fails for any reason */ public int decodeWithECCount(int[] received, int twoS) throws ReedSolomonException { GenericGFPoly poly = new GenericGFPoly(field, received); int[] syndromeCoefficients = new int[twoS]; boolean noError = true; for (int i = 0; i < twoS; i++) { int eval = poly.evaluateAt(field.exp(i + field.getGeneratorBase())); syndromeCoefficients[(syndromeCoefficients.length - 1) - i] = eval; if (eval != 0) { noError = false; } } if (noError) { return 0; } GenericGFPoly syndrome = new GenericGFPoly(field, syndromeCoefficients); GenericGFPoly[] sigmaOmega = runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS); GenericGFPoly sigma = sigmaOmega[0]; GenericGFPoly omega = sigmaOmega[1]; int[] errorLocations = findErrorLocations(sigma); int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations); for (int i = 0; i < errorLocations.length; i++) { int position = (received.length - 1) - field.log(errorLocations[i]); if (position < 0) { throw new ReedSolomonException("Bad error location");} received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]); } return errorLocations.length; }
3.26
zxing_MaxiCodeReader_extractPureBits_rdh
/** * This method detects a code in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a code, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. */ private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException { int[] v4 = image.getEnclosingRectangle(); if (v4 == null) { throw NotFoundException.getNotFoundInstance(); } int left = v4[0]; int top = v4[1]; int width = v4[2]; int height = v4[3]; // Now just read off the bits BitMatrix bits = new BitMatrix(MATRIX_WIDTH, MATRIX_HEIGHT); for (int y = 0; y < MATRIX_HEIGHT; y++) { int iy = top + Math.min(((y * height) + (height / 2)) / MATRIX_HEIGHT, height - 1);for (int x = 0; x < MATRIX_WIDTH; x++) { // srowen: I don't quite understand why the formula below is necessary, but it // can walk off the image if left + width = the right boundary. So cap it. int v13 = left + Math.min((((x * width) + (width / 2)) + (((y & 0x1) * width) / 2)) / MATRIX_WIDTH, width - 1); if (image.get(v13, iy)) { bits.set(x, y); } } } return bits; }
3.26
zxing_MaxiCodeReader_decode_rdh
/** * Locates and decodes a MaxiCode in an image. * * @return a String representing the content encoded by the MaxiCode * @throws NotFoundException * if a MaxiCode cannot be found * @throws FormatException * if a MaxiCode cannot be decoded * @throws ChecksumException * if error correction fails */ @Override public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); }
3.26
zxing_QRCodeReader_extractPureBits_rdh
/** * This method detects a code in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a code, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. */ private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException { int[] leftTopBlack = image.getTopLeftOnBit(); int[] rightBottomBlack = image.getBottomRightOnBit(); if ((leftTopBlack == null) || (rightBottomBlack == null)) { throw NotFoundException.getNotFoundInstance(); } float moduleSize = moduleSize(leftTopBlack, image); int top = leftTopBlack[1]; int bottom = rightBottomBlack[1]; int left = leftTopBlack[0]; int right = rightBottomBlack[0]; // Sanity check! if ((left >= right) || (top >= bottom)) { throw NotFoundException.getNotFoundInstance(); } if ((bottom - top) != (right - left)) { // Special case, where bottom-right module wasn't black so we found something else in the last row // Assume it's a square, so use height as the width right = left + (bottom - top); if (right >= image.getWidth()) { // Abort if that would not make sense -- off image throw NotFoundException.getNotFoundInstance(); } } int matrixWidth = Math.round(((right - left) + 1) / moduleSize); int matrixHeight = Math.round(((bottom - top) + 1) / moduleSize); if ((matrixWidth <= 0) || (matrixHeight <= 0)) { throw NotFoundException.getNotFoundInstance(); } if (matrixHeight != matrixWidth) { // Only possibly decode square regions throw NotFoundException.getNotFoundInstance(); } // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = ((int) (moduleSize / 2.0F)); top += nudge; left += nudge; // But careful that this does not sample off the edge // "right" is the farthest-right valid pixel location -- right+1 is not necessarily // This is positive by how much the inner x loop below would be too large int nudgedTooFarRight = (left + ((int) ((matrixWidth - 1) * moduleSize))) - right; if (nudgedTooFarRight > 0) { if (nudgedTooFarRight > nudge) { // Neither way fits; abort throw NotFoundException.getNotFoundInstance(); } left -= nudgedTooFarRight; } // See logic above int nudgedTooFarDown = (top + ((int) ((matrixHeight - 1) * moduleSize))) - bottom; if (nudgedTooFarDown > 0) { if (nudgedTooFarDown > nudge) { // Neither way fits; abort throw NotFoundException.getNotFoundInstance(); } top -= nudgedTooFarDown; } // Now just read off the bits BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight); for (int y = 0; y < matrixHeight; y++) { int v21 = top + ((int) (y * moduleSize)); for (int x = 0; x < matrixWidth; x++) { if (image.get(left + ((int) (x * moduleSize)), v21)) { bits.set(x, y);} } } return bits; }
3.26
zxing_QRCodeReader_decode_rdh
/** * Locates and decodes a QR code in an image. * * @return a String representing the content encoded by the QR code * @throws NotFoundException * if a QR code cannot be found * @throws FormatException * if a QR code cannot be decoded * @throws ChecksumException * if error correction fails */ @Override public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); }
3.26
zxing_MinimalECIInput_isECI_rdh
/** * Determines if a value is an ECI * * @param index * the index of the value * @return true if the value at position {@code index} is an ECI * @throws IndexOutOfBoundsException * if the {@code index} argument is negative or not less than * {@code length()} */ public boolean isECI(int index) { if ((index < 0) || (index >= length())) { throw new IndexOutOfBoundsException("" + index); } return (bytes[index] > 255) && (bytes[index] <= 999);}
3.26
zxing_MinimalECIInput_length_rdh
/** * Returns the length of this input. The length is the number * of {@code byte}s, FNC1 characters or ECIs in the sequence. * * @return the number of {@code char}s in this sequence */ public int length() { return bytes.length; }
3.26
zxing_MinimalECIInput_charAt_rdh
/** * Returns the {@code byte} value at the specified index. An index ranges from zero * to {@code length() - 1}. The first {@code byte} value of the sequence is at * index zero, the next at index one, and so on, as for array * indexing. * * @param index * the index of the {@code byte} value to be returned * @return the specified {@code byte} value as character or the FNC1 character * @throws IndexOutOfBoundsException * if the {@code index} argument is negative or not less than * {@code length()} * @throws IllegalArgumentException * if the value at the {@code index} argument is an ECI (@see #isECI) */ public char charAt(int index) { if ((index < 0) || (index >= length())) { throw new IndexOutOfBoundsException("" + index); } if (isECI(index)) { throw new IllegalArgumentException(("value at " + index) + " is not a character but an ECI"); } return isFNC1(index) ? ((char) (fnc1)) : ((char) (bytes[index])); }
3.26
zxing_MinimalECIInput_isFNC1_rdh
/** * Determines if a value is the FNC1 character * * @param index * the index of the value * @return true if the value at position {@code index} is the FNC1 character * @throws IndexOutOfBoundsException * if the {@code index} argument is negative or not less than * {@code length()} */ public boolean isFNC1(int index) { if ((index < 0) || (index >= length())) { throw new IndexOutOfBoundsException("" + index); } return bytes[index] == 1000; } /** * Returns the {@code int} ECI value at the specified index. An index ranges from zero * to {@code length() - 1}. The first {@code byte} value of the sequence is at * index zero, the next at index one, and so on, as for array * indexing. * * @param index * the index of the {@code int} value to be returned * @return the specified {@code int}
3.26
zxing_MinimalECIInput_subSequence_rdh
/** * Returns a {@code CharSequence} that is a subsequence of this sequence. * The subsequence starts with the {@code char} value at the specified index and * ends with the {@code char} value at index {@code end - 1}. The length * (in {@code char}s) of the * returned sequence is {@code end - start}, so if {@code start == end} * then an empty sequence is returned. * * @param start * the start index, inclusive * @param end * the end index, exclusive * @return the specified subsequence * @throws IndexOutOfBoundsException * if {@code start} or {@code end} are negative, * if {@code end} is greater than {@code length()}, * or if {@code start} is greater than {@code end} * @throws IllegalArgumentException * if a value in the range {@code start}-{@code end} is an ECI (@see #isECI) */ public CharSequence subSequence(int start, int end) { if (((start < 0) || (start > end)) || (end > length())) { throw new IndexOutOfBoundsException("" + start); } StringBuilder v4 = new StringBuilder(); for (int i = start; i < end; i++) { if (isECI(i)) {throw new IllegalArgumentException(("value at " + i) + " is not a character but an ECI");} v4.append(charAt(i)); } return v4; }
3.26
zxing_PlanarYUVLuminanceSource_getThumbnailHeight_rdh
/** * * @return height of image from {@link #renderThumbnail()} */ public int getThumbnailHeight() { return getHeight() / THUMBNAIL_SCALE_FACTOR; }
3.26
zxing_PlanarYUVLuminanceSource_getThumbnailWidth_rdh
/** * * @return width of image from {@link #renderThumbnail()} */ public int getThumbnailWidth() { return getWidth() / THUMBNAIL_SCALE_FACTOR;}
3.26
zxing_ModulusPoly_getDegree_rdh
/** * * @return degree of this polynomial */ int getDegree() { return coefficients.length - 1; }
3.26
zxing_ModulusPoly_evaluateAt_rdh
/** * * @return evaluation of this polynomial at a given point */ int evaluateAt(int a) { if (a == 0) { // Just return the x^0 coefficient return getCoefficient(0); } if (a == 1) {// Just the sum of the coefficients int result = 0; for (int coefficient : coefficients) { result = field.add(result, coefficient); } return result; } int result = coefficients[0]; int size = coefficients.length; for (int i = 1; i < size; i++) { result = field.add(field.multiply(a, result), coefficients[i]); } return result; }
3.26
zxing_ModulusPoly_getCoefficient_rdh
/** * * @return coefficient of x^degree term in this polynomial */ int getCoefficient(int degree) { return coefficients[(coefficients.length - 1) - degree]; }
3.26
zxing_MathUtils_sum_rdh
/** * * @param array * values to sum * @return sum of values in array */ public static int sum(int[] array) { int count = 0; for (int a : array) {count += a; } return count; }
3.26
zxing_MathUtils_distance_rdh
/** * * @param aX * point A x coordinate * @param aY * point A y coordinate * @param bX * point B x coordinate * @param bY * point B y coordinate * @return Euclidean distance between points A and B */ public static float distance(int aX, int aY, int bX, int bY) { double xDiff = aX - bX; double yDiff = aY - bY;return ((float) (Math.sqrt((xDiff * xDiff) + (yDiff * yDiff)))); }
3.26
zxing_MathUtils_round_rdh
/** * Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its * argument to the nearest int, where x.5 rounds up to x+1. Semantics of this shortcut * differ slightly from {@link Math#round(float)} in that half rounds down for negative * values. -2.5 rounds to -3, not -2. For purposes here it makes no difference. * * @param d * real value to round * @return nearest {@code int} */ public static int round(float d) {return ((int) (d + (d < 0.0F ? -0.5F : 0.5F))); }
3.26
zxing_DataMatrixReader_decode_rdh
/** * Locates and decodes a Data Matrix code in an image. * * @return a String representing the content encoded by the Data Matrix code * @throws NotFoundException * if a Data Matrix code cannot be found * @throws FormatException * if a Data Matrix code cannot be decoded * @throws ChecksumException * if error correction fails */ @Override public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); }
3.26
zxing_DataMatrixReader_extractPureBits_rdh
/** * This method detects a code in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a code, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. */ private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException {int[] leftTopBlack = image.getTopLeftOnBit(); int[] rightBottomBlack = image.getBottomRightOnBit(); if ((leftTopBlack == null) || (rightBottomBlack == null)) { throw NotFoundException.getNotFoundInstance(); } int moduleSize = moduleSize(leftTopBlack, image); int top = leftTopBlack[1]; int bottom = rightBottomBlack[1]; int left = leftTopBlack[0]; int right = rightBottomBlack[0]; int matrixWidth = ((right - left) + 1) / moduleSize; int matrixHeight = ((bottom - top) + 1) / moduleSize; if ((matrixWidth <= 0) || (matrixHeight <= 0)) { throw NotFoundException.getNotFoundInstance();} // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = moduleSize / 2; top += nudge; left += nudge; // Now just read off the bits BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight); for (int y = 0; y < matrixHeight; y++) { int iOffset = top + (y * moduleSize); for (int x = 0; x < matrixWidth; x++) { if (image.get(left + (x * moduleSize), iOffset)) { bits.set(x, y); }} } return bits; }
3.26
zxing_PDF417HighLevelEncoder_determineConsecutiveTextCount_rdh
/** * Determines the number of consecutive characters that are encodable using text compaction. * * @param input * the input * @param startpos * the start position within the input * @return the requested character count */ private static int determineConsecutiveTextCount(ECIInput input, int startpos) { final int len = input.length(); int idx = startpos;while (idx < len) { int numericCount = 0; while ((((numericCount < 13) && (idx < len)) && (!input.isECI(idx))) && isDigit(input.charAt(idx))) { numericCount++; idx++; } if (numericCount >= 13) {return (idx - startpos) - numericCount; } if (numericCount > 0) { // Heuristic: All text-encodable chars or digits are binary encodable continue; } // Check if character is encodable if (input.isECI(idx) || (!isText(input.charAt(idx)))) { break; } idx++; } return idx - startpos; }
3.26
zxing_PDF417HighLevelEncoder_encodeHighLevel_rdh
/** * Performs high-level encoding of a PDF417 message using the algorithm described in annex P * of ISO/IEC 15438:2001(E). If byte compaction has been selected, then only byte compaction * is used. * * @param msg * the message * @param compaction * compaction mode to use * @param encoding * character encoding used to encode in default or byte compaction * or {@code null} for default / not applicable * @param autoECI * encode input minimally using multiple ECIs if needed * If autoECI encoding is specified and additionally {@code encoding} is specified, then the encoder * will use the specified {@link Charset} for any character that can be encoded by it, regardless * if a different encoding would lead to a more compact encoding. When no {@code encoding} is specified * then charsets will be chosen so that the byte representation is minimal. * @return the encoded message (the char values range from 0 to 928) */ static String encodeHighLevel(String msg, Compaction compaction, Charset encoding, boolean autoECI) throws WriterException { if (msg.isEmpty()) { throw new WriterException("Empty message not allowed"); } if ((encoding == null) && (!autoECI)) { for (int i = 0; i < msg.length(); i++) { if (msg.charAt(i) > 255) { throw new WriterException(((("Non-encodable character detected: " + msg.charAt(i)) + " (Unicode: ") + ((int) (msg.charAt(i)))) + "). Consider specifying EncodeHintType.PDF417_AUTO_ECI and/or EncodeTypeHint.CHARACTER_SET."); } } } // the codewords 0..928 are encoded as Unicode characters StringBuilder sb = new StringBuilder(msg.length()); ECIInput input; if (autoECI) { input = new MinimalECIInput(msg, encoding, -1); } else { input = new NoECIInput(msg); if (encoding == null) { encoding = DEFAULT_ENCODING; } else if (!DEFAULT_ENCODING.equals(encoding)) { CharacterSetECI eci = CharacterSetECI.getCharacterSetECI(encoding); if (eci != null) { encodingECI(eci.getValue(), sb); } } } int len = input.length(); int p = 0; int textSubMode = SUBMODE_ALPHA; // User selected encoding mode switch (compaction) { case TEXT : encodeText(input, p, len, sb, textSubMode); break; case BYTE : if (autoECI) { encodeMultiECIBinary(input, 0, input.length(), TEXT_COMPACTION, sb); } else { byte[] msgBytes = input.toString().getBytes(encoding); encodeBinary(msgBytes, p, msgBytes.length, BYTE_COMPACTION, sb);} break; case NUMERIC : sb.append(((char) (LATCH_TO_NUMERIC))); encodeNumeric(input, p, len, sb); break; default : int encodingMode = TEXT_COMPACTION;// Default mode, see 4.4.2.1 while (p < len) { while ((p < len) && input.isECI(p)) { encodingECI(input.getECIValue(p), sb); p++; } if (p >= len) { break; } int n = determineConsecutiveDigitCount(input, p); if (n >= 13) { sb.append(((char) (LATCH_TO_NUMERIC))); encodingMode = NUMERIC_COMPACTION;textSubMode = SUBMODE_ALPHA;// Reset after latch encodeNumeric(input, p, n, sb); p += n; } else { int t = determineConsecutiveTextCount(input, p); if ((t >= 5) || (n == len)) { if (encodingMode != TEXT_COMPACTION) { sb.append(((char) (LATCH_TO_TEXT))); encodingMode = TEXT_COMPACTION; textSubMode = SUBMODE_ALPHA;// start with submode alpha after latch } textSubMode = encodeText(input, p, t, sb, textSubMode); p += t; } else { int b = determineConsecutiveBinaryCount(input, p, autoECI ? null : encoding); if (b == 0) { b = 1; } byte[] bytes = (autoECI) ? null : input.subSequence(p, p + b).toString().getBytes(encoding); if ((((bytes == null) && (b == 1)) || ((bytes != null) && (bytes.length == 1))) && (encodingMode == TEXT_COMPACTION)) { // Switch for one byte (instead of latch) if (autoECI) { encodeMultiECIBinary(input, p, 1, TEXT_COMPACTION, sb); } else { encodeBinary(bytes, 0, 1, TEXT_COMPACTION, sb); } } else { // Mode latch performed by encodeBinary() if (autoECI) { encodeMultiECIBinary(input, p, p + b, encodingMode, sb); } else { encodeBinary(bytes, 0, bytes.length, encodingMode, sb);} encodingMode = BYTE_COMPACTION; textSubMode = SUBMODE_ALPHA;// Reset after latch } p += b;} } } break; } return sb.toString(); }
3.26
zxing_PDF417HighLevelEncoder_determineConsecutiveDigitCount_rdh
/** * Determines the number of consecutive characters that are encodable using numeric compaction. * * @param input * the input * @param startpos * the start position within the input * @return the requested character count */ private static int determineConsecutiveDigitCount(ECIInput input, int startpos) { int count = 0; final int len = input.length();int idx = startpos; if (idx < len) { while (((idx < len) && (!input.isECI(idx))) && isDigit(input.charAt(idx))) { count++; idx++; } } return count; }
3.26
zxing_PDF417HighLevelEncoder_determineConsecutiveBinaryCount_rdh
/** * Determines the number of consecutive characters that are encodable using binary compaction. * * @param input * the input * @param startpos * the start position within the message * @param encoding * the charset used to convert the message to a byte array * @return the requested character count */ private static int determineConsecutiveBinaryCount(ECIInput input, int startpos, Charset encoding) throws WriterException { CharsetEncoder encoder = (encoding == null) ? null : encoding.newEncoder(); int len = input.length(); int idx = startpos; while (idx < len) { int numericCount = 0; int i = idx; while (((numericCount < 13) && (!input.isECI(i))) && isDigit(input.charAt(i))) { numericCount++; // textCount++; i = idx + numericCount; if (i >= len) { break; } } if (numericCount >= 13) { return idx - startpos; } if ((encoder != null) && (!encoder.canEncode(input.charAt(idx)))) { assert input instanceof NoECIInput; char ch = input.charAt(idx); throw new WriterException(((("Non-encodable character detected: " + ch) + " (Unicode: ") + ((int) (ch))) + ')'); } idx++; } return idx - startpos; }
3.26
zxing_PDF417HighLevelEncoder_encodeBinary_rdh
/** * Encode parts of the message using Byte Compaction as described in ISO/IEC 15438:2001(E), * chapter 4.4.3. The Unicode characters will be converted to binary using the cp437 * codepage. * * @param bytes * the message converted to a byte array * @param startpos * the start position within the message * @param count * the number of bytes to encode * @param startmode * the mode from which this method starts * @param sb * receives the encoded codewords */ private static void encodeBinary(byte[] bytes, int startpos, int count, int startmode, StringBuilder sb) { if ((count == 1) && (startmode == TEXT_COMPACTION)) { sb.append(((char) (SHIFT_TO_BYTE))); } else if ((count % 6) == 0) { sb.append(((char) (LATCH_TO_BYTE)));} else { sb.append(((char) (f0))); } int idx = startpos; // Encode sixpacks if (count >= 6) { char[] chars = new char[5]; while (((startpos + count) - idx) >= 6) { long t = 0; for (int i = 0; i < 6; i++) { t <<= 8; t += bytes[idx + i] & 0xff; } for (int i = 0; i < 5; i++) { chars[i] = ((char) (t % 900)); t /= 900; } for (int i = chars.length - 1; i >= 0; i--) { sb.append(chars[i]); } idx += 6; } }// Encode rest (remaining n<5 bytes if any) for (int i = idx; i < (startpos + count); i++) { int ch = bytes[i] & 0xff; sb.append(((char) (ch))); } }
3.26
zxing_PDF417HighLevelEncoder_encodeMultiECIBinary_rdh
/** * Encode all of the message using Byte Compaction as described in ISO/IEC 15438:2001(E) * * @param input * the input * @param startpos * the start position within the message * @param count * the number of bytes to encode * @param startmode * the mode from which this method starts * @param sb * receives the encoded codewords */ private static void encodeMultiECIBinary(ECIInput input, int startpos, int count, int startmode, StringBuilder sb) throws WriterException { final int end = Math.min(startpos + count, input.length()); int localStart = startpos; while (true) { // encode all leading ECIs and advance localStart while ((localStart < end) && input.isECI(localStart)) { encodingECI(input.getECIValue(localStart), sb); localStart++; } int localEnd = localStart; // advance end until before the next ECI while ((localEnd < end) && (!input.isECI(localEnd))) { localEnd++; } final int localCount = localEnd - localStart; if (localCount <= 0) { // done break; } else { // encode the segment encodeBinary(subBytes(input, localStart, localEnd), 0, localCount, localStart == startpos ? startmode : BYTE_COMPACTION, sb); localStart = localEnd; } } }
3.26
zxing_PDF417HighLevelEncoder_encodeText_rdh
/** * Encode parts of the message using Text Compaction as described in ISO/IEC 15438:2001(E), * chapter 4.4.2. * * @param input * the input * @param startpos * the start position within the message * @param count * the number of characters to encode * @param sb * receives the encoded codewords * @param initialSubmode * should normally be SUBMODE_ALPHA * @return the text submode in which this method ends */ private static int encodeText(ECIInput input, int startpos, int count, StringBuilder sb, int initialSubmode) throws WriterException { StringBuilder tmp = new StringBuilder(count); int submode = initialSubmode; int idx = 0; while (true) { if (input.isECI(startpos + idx)) { encodingECI(input.getECIValue(startpos + idx), sb); idx++; } else { char ch = input.charAt(startpos + idx); switch (submode) { case SUBMODE_ALPHA : if (isAlphaUpper(ch)) { if (ch == ' ') { tmp.append(((char) (26)));// space } else { tmp.append(((char) (ch - 65))); } } else if (isAlphaLower(ch)) { submode = SUBMODE_LOWER; tmp.append(((char) (27)));// ll continue; } else if (isMixed(ch)) {submode = SUBMODE_MIXED; tmp.append(((char) (28)));// ml continue; } else { tmp.append(((char) (29)));// ps tmp.append(((char) (PUNCTUATION[ch]))); break; } break; case SUBMODE_LOWER : if (isAlphaLower(ch)) { if (ch == ' ') { tmp.append(((char) (26)));// space } else { tmp.append(((char) (ch - 97))); } } else if (isAlphaUpper(ch)) { tmp.append(((char) (27)));// as tmp.append(((char) (ch - 65))); // space cannot happen here, it is also in "Lower" break; } else if (isMixed(ch)) { submode = SUBMODE_MIXED; tmp.append(((char) (28)));// ml continue; } else { tmp.append(((char) (29)));// ps tmp.append(((char) (PUNCTUATION[ch]))); break; } break; case SUBMODE_MIXED : if (isMixed(ch)) { tmp.append(((char) (MIXED[ch]))); } else if (isAlphaUpper(ch)) { submode = SUBMODE_ALPHA; tmp.append(((char) (28)));// al continue; } else if (isAlphaLower(ch)) { submode = SUBMODE_LOWER; tmp.append(((char) (27)));// ll continue; } else { if (((((startpos + idx) + 1) < count) && (!input.isECI((startpos + idx) + 1))) && isPunctuation(input.charAt((startpos + idx) + 1))) { submode = SUBMODE_PUNCTUATION; tmp.append(((char) (25)));// pl continue; }tmp.append(((char) (29)));// ps tmp.append(((char) (PUNCTUATION[ch]))); } break; default : // SUBMODE_PUNCTUATION if (isPunctuation(ch)) { tmp.append(((char) (PUNCTUATION[ch]))); } else { submode = SUBMODE_ALPHA; tmp.append(((char) (29)));// al continue; } } idx++; if (idx >= count) { break; } } } char h = 0; int len = tmp.length(); for (int i = 0; i < len; i++) { boolean odd = (i % 2) != 0; if (odd) { h = ((char) ((h * 30) + tmp.charAt(i))); sb.append(h); } else { h = tmp.charAt(i); } } if ((len % 2) != 0) {sb.append(((char) ((h * 30) + 29)));// ps }return submode; }
3.26
zxing_SymbolInfo_overrideSymbolSet_rdh
/** * Overrides the symbol info set used by this class. Used for testing purposes. * * @param override * the symbol info set to use */ public static void overrideSymbolSet(SymbolInfo[] override) { symbols = override; }
3.26
zxing_ExpandedRow_equals_rdh
/** * Two rows are equal if they contain the same pairs in the same order. */ @Override public boolean equals(Object o) { if (!(o instanceof ExpandedRow)) { return false; } ExpandedRow that = ((ExpandedRow) (o)); return this.pairs.equals(that.pairs); }
3.26
zxing_Encoder_encode_rdh
/** * Encodes the given binary content as an Aztec symbol * * @param data * input data string * @param minECCPercent * minimal percentage of error check words (According to ISO/IEC 24778:2008, * a minimum of 23% + 3 words is recommended) * @param userSpecifiedLayers * if non-zero, a user-specified value for the number of layers * @param charset * character set to mark using ECI; if null, no ECI code will be inserted, and the * default encoding of ISO/IEC 8859-1 will be assuming by readers. * @return Aztec symbol matrix with metadata */ public static AztecCode encode(byte[] data, int minECCPercent, int userSpecifiedLayers, Charset charset) {// High-level encode BitArray bits = new HighLevelEncoder(data, charset).encode(); // stuff bits and choose symbol size int eccBits = ((bits.getSize() * minECCPercent) / 100) + 11; int totalSizeBits = bits.getSize() + eccBits; boolean compact; int layers; int totalBitsInLayer; int wordSize; BitArray stuffedBits; if (userSpecifiedLayers != DEFAULT_AZTEC_LAYERS) { compact = userSpecifiedLayers < 0; layers = Math.abs(userSpecifiedLayers); if (layers > (compact ? MAX_NB_BITS_COMPACT : MAX_NB_BITS)) { throw new IllegalArgumentException(String.format("Illegal value %s for layers", userSpecifiedLayers));} totalBitsInLayer = totalBitsInLayer(layers, compact); wordSize = WORD_SIZE[layers]; int usableBitsInLayers = totalBitsInLayer - (totalBitsInLayer % wordSize); stuffedBits = m1(bits, wordSize); if ((stuffedBits.getSize() + eccBits) > usableBitsInLayers) { throw new IllegalArgumentException("Data to large for user specified layer"); } if (compact && (stuffedBits.getSize() > (wordSize * 64))) { // Compact format only allows 64 data words, though C4 can hold more words than that throw new IllegalArgumentException("Data to large for user specified layer"); } } else { wordSize = 0; stuffedBits = null; // We look at the possible table sizes in the order Compact1, Compact2, Compact3, // Compact4, Normal4,... Normal(i) for i < 4 isn't typically used since Compact(i+1) // is the same size, but has more data. for (int i = 0; ; i++) { if (i > MAX_NB_BITS) { throw new IllegalArgumentException("Data too large for an Aztec code"); } compact = i <= 3; layers = (compact) ? i + 1 : i; totalBitsInLayer = totalBitsInLayer(layers, compact); if (totalSizeBits > totalBitsInLayer) { continue; } // [Re]stuff the bits if this is the first opportunity, or if the // wordSize has changed if ((stuffedBits == null) || (wordSize != WORD_SIZE[layers])) { wordSize = WORD_SIZE[layers]; stuffedBits = m1(bits, wordSize); } int usableBitsInLayers = totalBitsInLayer - (totalBitsInLayer % wordSize); if (compact && (stuffedBits.getSize() > (wordSize * 64))) { // Compact format only allows 64 data words, though C4 can hold more words than that continue; } if ((stuffedBits.getSize() + eccBits) <= usableBitsInLayers) {break; }} } BitArray messageBits = generateCheckWords(stuffedBits, totalBitsInLayer, wordSize); // generate mode message int messageSizeInWords = stuffedBits.getSize() / wordSize; BitArray modeMessage = generateModeMessage(compact, layers, messageSizeInWords); // allocate symbol int baseMatrixSize = (compact ? 11 : 14) + (layers * 4);// not including alignment lines int[] alignmentMap = new int[baseMatrixSize];int matrixSize; if (compact) { // no alignment marks in compact mode, alignmentMap is a no-op matrixSize = baseMatrixSize; for (int i = 0; i < alignmentMap.length; i++) { alignmentMap[i] = i; } } else { 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; } } BitMatrix matrix = new BitMatrix(matrixSize); // draw data bits for (int i = 0, rowOffset = 0; i < layers; i++) { int rowSize = ((layers - i) * 4) + (compact ? 9 : 12); for (int j = 0; j < rowSize; j++) { int columnOffset = j * 2; for (int k = 0; k < 2; k++) { if (messageBits.get((rowOffset + columnOffset) + k)) { matrix.set(alignmentMap[(i * 2) + k], alignmentMap[(i * 2) + j]); } if (messageBits.get(((rowOffset + (rowSize * 2)) + columnOffset) + k)) { matrix.set(alignmentMap[(i * 2) + j], alignmentMap[((baseMatrixSize - 1) - (i * 2)) - k]); } if (messageBits.get(((rowOffset + (rowSize * 4)) + columnOffset) + k)) { matrix.set(alignmentMap[((baseMatrixSize - 1) - (i * 2)) - k], alignmentMap[((baseMatrixSize - 1) - (i * 2)) - j]); } if (messageBits.get(((rowOffset + (rowSize * 6)) + columnOffset) + k)) { matrix.set(alignmentMap[((baseMatrixSize - 1) - (i * 2)) - j], alignmentMap[(i * 2) + k]); } } } rowOffset += rowSize * 8; } // draw mode message drawModeMessage(matrix, compact, matrixSize, modeMessage); // draw alignment marks if (compact) { drawBullsEye(matrix, matrixSize / 2, 5); } else { drawBullsEye(matrix, matrixSize / 2, 7); for (int i = 0, j = 0; i < ((baseMatrixSize / 2) - 1); i += 15 , j += 16) { for (int k = (matrixSize / 2) & 1; k < matrixSize; k += 2) { matrix.set((matrixSize / 2) - j, k); matrix.set((matrixSize / 2) + j, k); matrix.set(k, (matrixSize / 2) - j); matrix.set(k, (matrixSize / 2) + j); } } } AztecCode aztec = new AztecCode(); aztec.setCompact(compact); aztec.setSize(matrixSize); aztec.setLayers(layers); aztec.setCodeWords(messageSizeInWords); aztec.setMatrix(matrix); return aztec; }
3.26
zxing_Encoder_m0_rdh
/** * Encodes the given string content as an Aztec symbol * * @param data * input data string * @param minECCPercent * minimal percentage of error check words (According to ISO/IEC 24778:2008, * a minimum of 23% + 3 words is recommended) * @param userSpecifiedLayers * if non-zero, a user-specified value for the number of layers * @param charset * character set in which to encode string using ECI; if null, no ECI code * will be inserted, and the string must be encodable as ISO/IEC 8859-1 * (Latin-1), the default encoding of the symbol. * @return Aztec symbol matrix with metadata */ public static AztecCode m0(String data, int minECCPercent, int userSpecifiedLayers, Charset charset) { byte[] bytes = data.getBytes(null != charset ? charset : StandardCharsets.ISO_8859_1);return encode(bytes, minECCPercent, userSpecifiedLayers, charset); }
3.26
zxing_BarcodeValue_setValue_rdh
/** * Add an occurrence of a value */ void setValue(int value) { Integer confidence = values.get(value); if (confidence == null) { confidence = 0; } confidence++; values.put(value, confidence); }
3.26
zxing_BarcodeValue_getValue_rdh
/** * Determines the maximum occurrence of a set value and returns all values which were set with this occurrence. * * @return an array of int, containing the values with the highest occurrence, or null, if no value was set */ 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); }
3.26
zxing_LocaleManager_getBookSearchCountryTLD_rdh
/** * The same as above, but specifically for Google Book Search. * * @param context * application's {@link Context} * @return The top-level domain to use. */ public static String getBookSearchCountryTLD(Context context) { return doGetTLD(GOOGLE_BOOK_SEARCH_COUNTRY_TLD, context); }
3.26
zxing_LocaleManager_isBookSearchUrl_rdh
/** * Does a given URL point to Google Book Search, regardless of domain. * * @param url * The address to check. * @return True if this is a Book Search URL. */ public static boolean isBookSearchUrl(String url) { return url.startsWith("http://google.com/books") || url.startsWith("http://books.google."); }
3.26
zxing_Mode_forBits_rdh
/** * * @param bits * four bits encoding a QR Code data mode * @return Mode encoded by these bits * @throws IllegalArgumentException * if bits do not correspond to a known mode */ public static Mode forBits(int bits) { switch (bits) { case 0x0 : return TERMINATOR; case 0x1 : return NUMERIC; case 0x2 : return ALPHANUMERIC; case 0x3 : return STRUCTURED_APPEND; case 0x4 : return BYTE; case 0x5 : return FNC1_FIRST_POSITION; case 0x7 : return ECI; case 0x8 : return KANJI; case 0x9 : return FNC1_SECOND_POSITION; case 0xd : // 0xD is defined in GBT 18284-2000, may not be supported in foreign country return HANZI; default : throw new IllegalArgumentException();} } /** * * @param version * version in question * @return number of bits used, in this QR Code symbol {@link Version}
3.26
zxing_GridSampler_checkAndNudgePoints_rdh
/** * <p>Checks a set of points that have been transformed to sample points on an image against * the image's dimensions to see if the point are even within the image.</p> * * <p>This method will actually "nudge" the endpoints back onto the image if they are found to be * barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder * patterns in an image where the QR Code runs all the way to the image border.</p> * * <p>For efficiency, the method will check points from either end of the line until one is found * to be within the image. Because the set of points are assumed to be linear, this is valid.</p> * * @param image * image into which the points should map * @param points * actual points in x1,y1,...,xn,yn form * @throws NotFoundException * if an endpoint is lies outside the image boundaries */ protected static void checkAndNudgePoints(BitMatrix image, float[] points) throws NotFoundException { int width = image.getWidth(); int height = image.getHeight(); // Check and nudge points from start until we see some that are OK: boolean nudged = true; int maxOffset = points.length - 1;// points.length must be even for (int offset = 0; (offset < maxOffset) && nudged; offset += 2) { int x = ((int) (points[offset])); int y = ((int) (points[offset + 1])); if ((((x < (-1)) || (x > width)) || (y < (-1))) || (y > height)) { throw NotFoundException.getNotFoundInstance(); } nudged = false; if (x == (-1)) { points[offset] = 0.0F; nudged = true; } else if (x == width) { points[offset] = width - 1; nudged = true; } if (y == (-1)) { points[offset + 1] = 0.0F; nudged = true; } else if (y == height) { points[offset + 1] = height - 1; nudged = true; } } // Check and nudge points from end: nudged = true; for (int offset = points.length - 2; (offset >= 0) && nudged; offset -= 2) { int x = ((int) (points[offset])); int y = ((int) (points[offset + 1])); if ((((x < (-1)) || (x > width)) || (y < (-1))) || (y > height)) { throw NotFoundException.getNotFoundInstance(); } nudged = false; if (x == (-1)) { points[offset] = 0.0F; nudged = true; } else if (x == width) { points[offset] = width - 1; nudged = true; } if (y == (-1)) { points[offset + 1] = 0.0F; nudged = true; } else if (y == height) { points[offset + 1] = height - 1; nudged = true; } } }
3.26
zxing_GridSampler_getInstance_rdh
/** * * @return the current implementation of GridSampler */ public static GridSampler getInstance() { return gridSampler; } /** * Samples an image for a rectangular matrix of bits of the given dimension. The sampling * transformation is determined by the coordinates of 4 points, in the original and transformed * image space. * * @param image * image to sample * @param dimensionX * width of {@link BitMatrix} to sample from image * @param dimensionY * height of {@link BitMatrix} to sample from image * @param p1ToX * point 1 preimage X * @param p1ToY * point 1 preimage Y * @param p2ToX * point 2 preimage X * @param p2ToY * point 2 preimage Y * @param p3ToX * point 3 preimage X * @param p3ToY * point 3 preimage Y * @param p4ToX * point 4 preimage X * @param p4ToY * point 4 preimage Y * @param p1FromX * point 1 image X * @param p1FromY * point 1 image Y * @param p2FromX * point 2 image X * @param p2FromY * point 2 image Y * @param p3FromX * point 3 image X * @param p3FromY * point 3 image Y * @param p4FromX * point 4 image X * @param p4FromY * point 4 image Y * @return {@link BitMatrix}
3.26
zxing_GridSampler_setGridSampler_rdh
/** * Sets the implementation of GridSampler used by the library. One global * instance is stored, which may sound problematic. But, the implementation provided * ought to be appropriate for the entire platform, and all uses of this library * in the whole lifetime of the JVM. For instance, an Android activity can swap in * an implementation that takes advantage of native platform libraries. * * @param newGridSampler * The platform-specific object to install. */ public static void setGridSampler(GridSampler newGridSampler) { gridSampler = newGridSampler; }
3.26
zxing_AlignmentPatternFinder_crossCheckVertical_rdh
/** * <p>After a horizontal scan finds a potential alignment pattern, this method * "cross-checks" by scanning down vertically through the center of the possible * alignment pattern to see if the same proportion is detected.</p> * * @param startI * row where an alignment pattern was detected * @param centerJ * center of the section that appears to cross an alignment pattern * @param maxCount * maximum reasonable number of modules that should be * observed in any reading state, based on the results of the horizontal scan * @return vertical center of alignment pattern, or {@link Float#NaN} if not found */ private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { BitMatrix image = this.image; int maxI = image.getHeight(); int[] v16 = crossCheckStateCount; v16[0] = 0; v16[1] = 0; v16[2] = 0; // Start counting up from center int v17 = startI; while (((v17 >= 0) && image.get(centerJ, v17)) && (v16[1] <= maxCount)) { v16[1]++; v17--; } // If already too many modules in this state or ran off the edge: if ((v17 < 0) || (v16[1] > maxCount)) { return Float.NaN; } while (((v17 >= 0) && (!image.get(centerJ, v17))) && (v16[0] <= maxCount)) { v16[0]++; v17--; } if (v16[0] > maxCount) {return Float.NaN; } // Now also count down from center v17 = startI + 1;while (((v17 < maxI) && image.get(centerJ, v17)) && (v16[1] <= maxCount)) { v16[1]++; v17++; } if ((v17 == maxI) || (v16[1] > maxCount)) { return Float.NaN; } while (((v17 < maxI) && (!image.get(centerJ, v17))) && (v16[2] <= maxCount)) { v16[2]++; v17++; } if (v16[2] > maxCount) { return Float.NaN; } int stateCountTotal = (v16[0] + v16[1]) + v16[2]; if ((5 * Math.abs(stateCountTotal - originalStateCountTotal)) >= (2 * originalStateCountTotal)) { return Float.NaN;} return foundPatternCross(v16) ? centerFromEnd(v16, v17) : Float.NaN; }
3.26
zxing_AlignmentPatternFinder_find_rdh
/** * <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since * it's pretty performance-critical and so is written to be fast foremost.</p> * * @return {@link AlignmentPattern} if found * @throws NotFoundException * if not found */ AlignmentPattern find() throws NotFoundException { int startX = this.startX; int height = this.height; int maxJ = startX + width; int middleI = startY + (height / 2); // We are looking for black/white/black modules in 1:1:1 ratio; // this tracks the number of black/white/black modules seen so far int[] stateCount = new int[3]; for (int iGen = 0; iGen < height; iGen++) {// Search from middle outwards int i = middleI + ((iGen & 0x1) == 0 ? (iGen + 1) / 2 : -((iGen + 1) / 2)); stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; int j = startX; // Burn off leading white pixels before anything else; if we start in the middle of // a white run, it doesn't make sense to count its length, since we don't know if the // white run continued to the left of the start point while ((j < maxJ) && (!image.get(j, i))) { j++; } int currentState = 0;while (j < maxJ) { if (image.get(j, i)) {// Black pixel if (currentState == 1) { // Counting black pixels stateCount[1]++; } else // Counting white pixels if (currentState == 2) { // A winner? if (foundPatternCross(stateCount)) { // Yes AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed != null) { return confirmed; } } stateCount[0] = stateCount[2]; stateCount[1] = 1; stateCount[2] = 0; currentState = 1; } else { stateCount[++currentState]++; } } else { // White pixel if (currentState == 1) { // Counting black pixels currentState++; } stateCount[currentState]++; } j++; } if (foundPatternCross(stateCount)) {AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ); if (confirmed != null) { return confirmed; } } } // Hmm, nothing we saw was observed and confirmed twice. If we had // any guess at all, return it. if (!possibleCenters.isEmpty()) { return possibleCenters.get(0); } throw NotFoundException.getNotFoundInstance(); }
3.26
zxing_AlignmentPatternFinder_centerFromEnd_rdh
/** * Given a count of black/white/black pixels just seen and an end position, * figures the location of the center of this black/white/black run. */ private static float centerFromEnd(int[] stateCount, int end) { return (end - stateCount[2]) - (stateCount[1] / 2.0F); }
3.26
zxing_AlignmentPatternFinder_handlePossibleCenter_rdh
/** * <p>This is called when a horizontal scan finds a possible alignment pattern. It will * cross check with a vertical scan, and if successful, will see if this pattern had been * found on a previous horizontal scan. If so, we consider it confirmed and conclude we have * found the alignment pattern.</p> * * @param stateCount * reading state module counts from horizontal scan * @param i * row where alignment pattern may be found * @param j * end of possible alignment pattern in row * @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not */ private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j) { int stateCountTotal = (stateCount[0] + stateCount[1]) + stateCount[2]; float centerJ = centerFromEnd(stateCount, j); float centerI = crossCheckVertical(i, ((int) (centerJ)), 2 * stateCount[1], stateCountTotal); if (!Float.isNaN(centerI)) { float estimatedModuleSize = ((stateCount[0] + stateCount[1]) + stateCount[2]) / 3.0F; for (AlignmentPattern center : possibleCenters) { // Look for about the same center and module size: if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { return center.combineEstimate(centerI, centerJ, estimatedModuleSize); } } // Hadn't found this before; save it AlignmentPattern point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize); possibleCenters.add(point); if (resultPointCallback != null) { resultPointCallback.foundPossibleResultPoint(point); } } return null; }
3.26
zxing_AddressBookParsedResult_getBirthday_rdh
/** * * @return birthday formatted as yyyyMMdd (e.g. 19780917) */ public String getBirthday() { return birthday; }
3.26
zxing_AddressBookParsedResult_getPronunciation_rdh
/** * In Japanese, the name is written in kanji, which can have multiple readings. Therefore a hint * is often provided, called furigana, which spells the name phonetically. * * @return The pronunciation of the getNames() field, often in hiragana or katakana. */ public String getPronunciation() { return pronunciation;}
3.26
zxing_AddressBookParsedResult_getGeo_rdh
/** * * @return a location as a latitude/longitude pair */ public String[] getGeo() { return geo; }
3.26
zxing_SearchBookContentsActivity_parseResult_rdh
// Available fields: page_id, page_number, snippet_text private SearchBookContentsResult parseResult(JSONObject json) { String pageId; String pageNumber; String snippet; try { pageId = json.getString("page_id"); pageNumber = json.optString("page_number"); snippet = json.optString("snippet_text"); } catch (JSONException e) { Log.w(TAG, e); // Never seen in the wild, just being complete. return new SearchBookContentsResult(getString(string.msg_sbc_no_page_returned), "", "", false); } if ((pageNumber == null) || pageNumber.isEmpty()) { // This can happen for text on the jacket, and possibly other reasons. pageNumber = ""; } else { pageNumber = (getString(string.msg_sbc_page) + ' ') + pageNumber; } boolean valid = (snippet != null) && (!snippet.isEmpty()); if (valid) { // Remove all HTML tags and encoded characters. snippet = TAG_PATTERN.matcher(snippet).replaceAll(""); snippet = LT_ENTITY_PATTERN.matcher(snippet).replaceAll("<"); snippet = GT_ENTITY_PATTERN.matcher(snippet).replaceAll(">"); snippet = QUOTE_ENTITY_PATTERN.matcher(snippet).replaceAll("'"); snippet = QUOT_ENTITY_PATTERN.matcher(snippet).replaceAll("\""); } else { snippet = ('(' + getString(string.msg_sbc_snippet_unavailable)) + ')'; } return new SearchBookContentsResult(pageId, pageNumber, snippet, valid); }
3.26
zxing_SearchBookContentsActivity_handleSearchResults_rdh
// Currently there is no way to distinguish between a query which had no results and a book // which is not searchable - both return zero results. private void handleSearchResults(JSONObject json) { try { int count = json.getInt("number_of_results"); headerView.setText((getString(string.msg_sbc_results) + " : ") + count); if (count > 0) { JSONArray results = json.getJSONArray("search_results"); SearchBookContentsResult.setQuery(queryTextView.getText().toString()); List<SearchBookContentsResult> items = new ArrayList<>(count); for (int x = 0; x < count; x++) { items.add(parseResult(results.getJSONObject(x))); } resultListView.setOnItemClickListener(new BrowseBookListener(SearchBookContentsActivity.this, items)); resultListView.setAdapter(new SearchBookContentsAdapter(SearchBookContentsActivity.this, items)); } else { String searchable = json.optString("searchable"); if ("false".equals(searchable)) { headerView.setText(string.msg_sbc_book_not_searchable); } resultListView.setAdapter(null); } } catch (JSONException e) { Log.w(TAG, "Bad JSON from book search", e); resultListView.setAdapter(null); headerView.setText(string.msg_sbc_failed); } }
3.26
zxing_Code39Reader_toNarrowWidePattern_rdh
// For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions // per image when using some of our blackbox images. private static int toNarrowWidePattern(int[] counters) { int numCounters = counters.length; int maxNarrowCounter = 0; int wideCounters; do { int minCounter = Integer.MAX_VALUE; for (int counter : counters) { if ((counter < minCounter) && (counter > maxNarrowCounter)) {minCounter = counter; } } maxNarrowCounter = minCounter; wideCounters = 0; int totalWideCountersWidth = 0; int pattern = 0; for (int i = 0; i < numCounters; i++) { int counter = counters[i]; if (counter > maxNarrowCounter) { pattern |= 1 << ((numCounters - 1) - i); wideCounters++; totalWideCountersWidth += counter; } } if (wideCounters == 3) { // Found 3 wide counters, but are they close enough in width? // We can perform a cheap, conservative check to see if any individual // counter is more than 1.5 times the average: for (int i = 0; (i < numCounters) && (wideCounters > 0); i++) { int counter = counters[i]; if (counter > maxNarrowCounter) { wideCounters--; // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average if ((counter * 2) >= totalWideCountersWidth) { return -1; } } } return pattern; } } while (wideCounters > 3 ); return -1; }
3.26
zxing_ReaderException_fillInStackTrace_rdh
// Prevent stack traces from being taken @Override public synchronized final Throwable fillInStackTrace() { return null; }
3.26
zxing_CaptureActivity_drawResultPoints_rdh
/** * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode. * * @param barcode * A bitmap of the captured image. * @param scaleFactor * amount by which thumbnail was scaled * @param rawResult * The decoded results which contains the points to draw. */ private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) { ResultPoint[] v24 = rawResult.getResultPoints(); if ((v24 != null) && (v24.length > 0)) { Canvas canvas = new Canvas(barcode); Paint v26 = new Paint(); v26.setColor(getResources().getColor(color.result_points)); if (v24.length == 2) { v26.setStrokeWidth(4.0F); drawLine(canvas, v26, v24[0], v24[1], scaleFactor); } else if ((v24.length == 4) && ((rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A) || (rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13))) { // Hacky special case -- draw two lines, for the barcode and metadata drawLine(canvas, v26, v24[0], v24[1], scaleFactor); drawLine(canvas, v26, v24[2], v24[3], scaleFactor); } else { v26.setStrokeWidth(10.0F); for (ResultPoint point : v24) { if (point != null) { canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), v26); } } } } }
3.26
zxing_CaptureActivity_handleDecode_rdh
/** * A valid barcode has been found, so give an indication of success and show the results. * * @param rawResult * The contents of the barcode. * @param scaleFactor * amount by which thumbnail was scaled * @param barcode * A greyscale bitmap of the camera data which was decoded. */ public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { inactivityTimer.onActivity(); lastResult = rawResult; ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult); boolean fromLiveScan = barcode != null; if (fromLiveScan) { historyManager.addHistoryItem(rawResult, resultHandler); // Then not from history, so beep/vibrate and we have an image to draw on beepManager.playBeepSoundAndVibrate(); drawResultPoints(barcode, scaleFactor, rawResult); } switch (source) { case NATIVE_APP_INTENT : case PRODUCT_SEARCH_LINK : handleDecodeExternally(rawResult, resultHandler, barcode); break; case ZXING_LINK : if ((scanFromWebPageManager == null) || (!scanFromWebPageManager.isScanFromWebPage())) { handleDecodeInternally(rawResult, resultHandler, barcode); } else {handleDecodeExternally(rawResult, resultHandler, barcode); } break; case NONE : SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (fromLiveScan && prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) { Toast.makeText(getApplicationContext(), ((getResources().getString(string.msg_bulk_mode_scanned) + " (") + rawResult.getText()) + ')', Toast.LENGTH_SHORT).show(); m0(resultHandler); // Wait a moment or else it will scan the same barcode continuously about 3 times restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); } else { handleDecodeInternally(rawResult, resultHandler, barcode); } break; } }
3.26
zxing_CaptureActivity_handleDecodeExternally_rdh
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner. private void handleDecodeExternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) { if (barcode != null) { viewfinderView.drawResultBitmap(barcode); } long resultDurationMS; if (getIntent() == null) { resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS; } else { resultDurationMS = getIntent().getLongExtra(Scan.RESULT_DISPLAY_DURATION_MS, DEFAULT_INTENT_RESULT_DURATION_MS); } if (resultDurationMS > 0) { String rawResultString = String.valueOf(rawResult); if (rawResultString.length() > 32) { rawResultString = rawResultString.substring(0, 32) + " ..."; } statusView.setText((getString(resultHandler.getDisplayTitle()) + " : ") + rawResultString); } m0(resultHandler); switch (source) { case NATIVE_APP_INTENT : // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when // the deprecated intent is retired. Intent v49 = new Intent(getIntent().getAction()); v49.addFlags(Intents.FLAG_NEW_DOC); v49.putExtra(Scan.RESULT, rawResult.toString());v49.putExtra(Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString()); byte[] rawBytes = rawResult.getRawBytes(); if ((rawBytes != null) && (rawBytes.length > 0)) { v49.putExtra(Scan.RESULT_BYTES, rawBytes); } Map<ResultMetadataType, ?> metadata = rawResult.getResultMetadata(); if (metadata != null) { if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) { v49.putExtra(Scan.RESULT_UPC_EAN_EXTENSION, metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString()); } Number orientation = ((Number) (metadata.get(ResultMetadataType.ORIENTATION))); if (orientation != null) { v49.putExtra(Scan.RESULT_ORIENTATION, orientation.intValue()); } String ecLevel = ((String) (metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL))); if (ecLevel != null) { v49.putExtra(Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel); } @SuppressWarnings("unchecked") Iterable<byte[]> byteSegments = ((Iterable<byte[]>) (metadata.get(ResultMetadataType.BYTE_SEGMENTS))); if (byteSegments != null) { int i = 0; for (byte[] byteSegment : byteSegments) { v49.putExtra(Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment); i++; } } } sendReplyMessage(id.return_scan_result, v49, resultDurationMS); break; case PRODUCT_SEARCH_LINK : // Reformulate the URL which triggered us into a query, so that the request goes to the same // TLD as the scan URL. int end = sourceUrl.lastIndexOf("/scan"); String productReplyURL = ((sourceUrl.substring(0, end) + "?q=") + resultHandler.getDisplayContents()) + "&source=zxing"; sendReplyMessage(id.launch_product_query, productReplyURL, resultDurationMS); break; case ZXING_LINK : if ((scanFromWebPageManager != null) && scanFromWebPageManager.isScanFromWebPage()) { String linkReplyURL = scanFromWebPageManager.buildReplyURL(rawResult, resultHandler); scanFromWebPageManager = null; sendReplyMessage(id.launch_product_query, linkReplyURL, resultDurationMS); } break; }}
3.26
zxing_CaptureActivity_handleDecodeInternally_rdh
// Put up our own UI for how to handle the decoded contents. private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) { m0(resultHandler); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if ((resultHandler.getDefaultButtonID() != null) && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) { resultHandler.handleButtonPress(resultHandler.getDefaultButtonID()); return; } statusView.setVisibility(View.GONE); viewfinderView.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); ImageView barcodeImageView = ((ImageView) (findViewById(id.barcode_image_view)));if (barcode == null) { barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), drawable.launcher_icon)); } else { barcodeImageView.setImageBitmap(barcode); } TextView formatTextView = ((TextView) (findViewById(id.format_text_view))); formatTextView.setText(rawResult.getBarcodeFormat().toString()); TextView typeTextView = ((TextView) (findViewById(id.type_text_view))); typeTextView.setText(resultHandler.getType().toString()); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); TextView timeTextView = ((TextView) (findViewById(id.time_text_view))); timeTextView.setText(formatter.format(rawResult.getTimestamp())); TextView metaTextView = ((TextView) (findViewById(id.meta_text_view))); View metaTextViewLabel = findViewById(id.meta_text_view_label); metaTextView.setVisibility(View.GONE); metaTextViewLabel.setVisibility(View.GONE); Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata(); if (metadata != null) { StringBuilder metadataText = new StringBuilder(20); for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) { if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) { metadataText.append(entry.getValue()).append('\n'); } } if (metadataText.length() > 0) { metadataText.setLength(metadataText.length() - 1); metaTextView.setText(metadataText); metaTextView.setVisibility(View.VISIBLE); metaTextViewLabel.setVisibility(View.VISIBLE);} } CharSequence displayContents = resultHandler.getDisplayContents();TextView contentsTextView = ((TextView) (findViewById(id.contents_text_view))); contentsTextView.setText(displayContents); int scaledSize = Math.max(22, 32 - (displayContents.length() / 4)); contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize); TextView supplementTextView = ((TextView) (findViewById(id.contents_supplement_text_view))); supplementTextView.setText(""); supplementTextView.setOnClickListener(null);if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(PreferencesActivity.KEY_SUPPLEMENTAL, true)) { SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView, resultHandler.getResult(), historyManager, this); } int buttonCount = resultHandler.getButtonCount(); ViewGroup buttonView = ((ViewGroup) (findViewById(id.result_button_view))); buttonView.requestFocus(); for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) { TextView button = ((TextView) (buttonView.getChildAt(x))); if (x < buttonCount) { button.setVisibility(View.VISIBLE); button.setText(resultHandler.getButtonText(x)); button.setOnClickListener(new ResultButtonListener(resultHandler, x)); } else { button.setVisibility(View.GONE); }} }
3.26
zxing_ECIEncoderSet_getPriorityEncoderIndex_rdh
/* returns -1 if no priority charset was defined */public int getPriorityEncoderIndex() { return priorityEncoderIndex; }
3.26
zxing_WhiteRectangleDetector_containsBlackPoint_rdh
/** * Determines whether a segment contains a black point * * @param a * min value of the scanned coordinate * @param b * max value of the scanned coordinate * @param fixed * value of fixed coordinate * @param horizontal * set to true if scan must be horizontal, false if vertical * @return true if a black point has been found, else false. */ 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; }
3.26
zxing_DecodeWorker_dumpBlackPoint_rdh
/** * Writes out a single PNG which is three times the width of the input image, containing from left * to right: the original image, the row sampling monochrome version, and the 2D sampling * monochrome version. */ private static void dumpBlackPoint(URI uri, BufferedImage image, BinaryBitmap bitmap) throws IOException { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int stride = width * 3; int[] pixels = new int[stride * height]; // The original image int[] argb = new int[width]; for (int y = 0; y < height; y++) { image.getRGB(0, y, width, 1, argb, 0, width); System.arraycopy(argb, 0, pixels, y * stride, width); } // Row sampling BitArray row = new BitArray(width); for (int y = 0; y < height; y++) { try { row = bitmap.getBlackRow(y, row); } catch (NotFoundException nfe) { // If fetching the row failed, draw a red line and keep going. int offset = (y * stride) + width; Arrays.fill(pixels, offset, offset + width, RED); continue; } int offset = (y * stride) + width; for (int x = 0; x < width; x++) { pixels[offset + x] = (row.get(x)) ? BLACK : WHITE; } } // 2D sampling try { for (int y = 0; y < height; y++) { BitMatrix matrix = bitmap.getBlackMatrix(); int offset = (y * stride) + (width * 2); for (int x = 0; x < width; x++) { pixels[offset + x] = (matrix.get(x, y)) ? BLACK : WHITE; } } } catch (NotFoundException ignored) { // continue } writeResultImage(stride, height, pixels, uri, ".mono.png"); }
3.26