name
stringlengths 12
178
| code_snippet
stringlengths 8
36.5k
| score
float64 3.26
3.68
|
---|---|---|
zxing_ECIStringBuilder_appendCharacters_rdh | /**
* Appends the characters from {@code value} (unlike all other append methods of this class who append bytes)
*
* @param value
* characters to append
*/
public void appendCharacters(StringBuilder value) {
encodeCurrentBytesIfAny();result.append(value);
} | 3.26 |
zxing_ECIStringBuilder_appendECI_rdh | /**
* Appends ECI value to output.
*
* @param value
* ECI value to append, as an int
* @throws FormatException
* on invalid ECI value
*/
public void appendECI(int value) throws
FormatException {
encodeCurrentBytesIfAny();
CharacterSetECI characterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
if (characterSetECI == null) {
throw FormatException.getFormatInstance();
}
currentCharset = characterSetECI.getCharset();
} | 3.26 |
zxing_ECIStringBuilder_isEmpty_rdh | /**
*
* @return true iff nothing has been appended
*/
public boolean isEmpty() {
return (currentBytes.length() == 0) && ((result == null) || (result.length() == 0));
} | 3.26 |
zxing_ECIStringBuilder_append_rdh | /**
* Append the string repesentation of {@code value} (short for {@code append(String.valueOf(value))})
*
* @param value
* int to append as a string
*/
public void append(int value) {
append(String.valueOf(value));
} | 3.26 |
zxing_ECIStringBuilder_length_rdh | /**
* Short for {@code toString().length()} (if possible, use {@link #isEmpty()} instead)
*
* @return length of string representation in characters
*/
public int length() {
return toString().length();
} | 3.26 |
zxing_EAN13Reader_determineFirstDigit_rdh | /**
* Based on pattern of odd-even ('L' and 'G') patterns used to encoded the explicitly-encoded
* digits in a barcode, determines the implicitly encoded first digit and adds it to the
* result string.
*
* @param resultString
* string to insert decoded first digit into
* @param lgPatternFound
* int whose bits indicates the pattern of odd/even L/G patterns used to
* encode digits
* @throws NotFoundException
* if first digit cannot be determined
*/
private static void determineFirstDigit(StringBuilder resultString, int lgPatternFound) throws NotFoundException {
for (int d = 0; d < 10; d++) {
if (lgPatternFound == FIRST_DIGIT_ENCODINGS[d]) {
resultString.insert(0, ((char) ('0' + d)));
return;
}
}
throw NotFoundException.getNotFoundInstance();
} | 3.26 |
zxing_CameraConfigurationManager_initFromCameraParameters_rdh | /**
* Reads, one time, values from the camera that are needed by the app.
*/
void initFromCameraParameters(OpenCamera camera) {
Camera.Parameters parameters = camera.getCamera().getParameters();
WindowManager manager = ((WindowManager) (context.getSystemService(Context.WINDOW_SERVICE)));
Display display = manager.getDefaultDisplay();
int displayRotation = display.getRotation();
int cwRotationFromNaturalToDisplay;
switch (displayRotation) {
case Surface.ROTATION_0 :
cwRotationFromNaturalToDisplay = 0;
break;
case Surface.ROTATION_90 :
cwRotationFromNaturalToDisplay = 90;
break;
case Surface.ROTATION_180 :
cwRotationFromNaturalToDisplay = 180;
break;
case Surface.ROTATION_270 :
cwRotationFromNaturalToDisplay = 270;
break;
default :
// Have seen this return incorrect values like -90
if ((displayRotation % 90) == 0) {
cwRotationFromNaturalToDisplay =
(360 + displayRotation) % 360;
} else {
throw new IllegalArgumentException("Bad rotation: " + displayRotation);
}
}
Log.i(TAG, "Display at: " + cwRotationFromNaturalToDisplay);
int cwRotationFromNaturalToCamera = camera.getOrientation();
Log.i(TAG, "Camera at: " + cwRotationFromNaturalToCamera);// Still not 100% sure about this. But acts like we need to flip this:
if (camera.getFacing() == CameraFacing.FRONT) {
cwRotationFromNaturalToCamera = (360 - cwRotationFromNaturalToCamera) % 360;
Log.i(TAG, "Front camera overriden to: " + cwRotationFromNaturalToCamera);
}
cwRotationFromDisplayToCamera = ((360 + cwRotationFromNaturalToCamera) - cwRotationFromNaturalToDisplay) %
360;
Log.i(TAG, "Final display orientation: " + cwRotationFromDisplayToCamera);
if (camera.getFacing() == CameraFacing.FRONT) {
Log.i(TAG, "Compensating rotation for front camera");
cwNeededRotation = (360 - cwRotationFromDisplayToCamera) %
360;
} else
{
cwNeededRotation = cwRotationFromDisplayToCamera;
}
Log.i(TAG, "Clockwise rotation from display to camera: " + cwNeededRotation);
Point theScreenResolution = new Point();
display.getSize(theScreenResolution);
screenResolution = theScreenResolution;
Log.i(TAG, "Screen resolution in current orientation: " + screenResolution);
cameraResolution = CameraConfigurationUtils.findBestPreviewSizeValue(parameters, screenResolution);
Log.i(TAG, "Camera resolution: " + cameraResolution);bestPreviewSize = CameraConfigurationUtils.findBestPreviewSizeValue(parameters, screenResolution);
Log.i(TAG, "Best available preview size: " + bestPreviewSize);
boolean isScreenPortrait = screenResolution.x < screenResolution.y;
boolean isPreviewSizePortrait = bestPreviewSize.x
< bestPreviewSize.y;
if (isScreenPortrait == isPreviewSizePortrait) {
previewSizeOnScreen = bestPreviewSize;
} else {
previewSizeOnScreen = new Point(bestPreviewSize.y, bestPreviewSize.x);
}
Log.i(TAG, "Preview size on screen: " + previewSizeOnScreen);
} | 3.26 |
zxing_EmailDoCoMoResultParser_isBasicallyValidEmailAddress_rdh | /**
* This implements only the most basic checking for an email address's validity -- that it contains
* an '@' and contains no characters disallowed by RFC 2822. This is an overly lenient definition of
* validity. We want to generally be lenient here since this class is only intended to encapsulate what's
* in a barcode, not "judge" it.
*/
static boolean isBasicallyValidEmailAddress(String email) {
return ((email != null) && ATEXT_ALPHANUMERIC.matcher(email).matches()) && (email.indexOf('@') >= 0);
} | 3.26 |
zxing_PDF417Writer_bitMatrixFromEncoder_rdh | /**
* Takes encoder, accounts for width/height, and retrieves bit matrix
*/
private static BitMatrix bitMatrixFromEncoder(PDF417 encoder, String contents, int errorCorrectionLevel, int width, int height, int margin, boolean autoECI) throws WriterException {
encoder.generateBarcodeLogic(contents, errorCorrectionLevel, autoECI);int aspectRatio = 4;
byte[][] originalScale = encoder.getBarcodeMatrix().getScaledMatrix(1, aspectRatio);
boolean v8 = false;
if ((height > width) != (originalScale[0].length < originalScale.length)) {
originalScale = rotateArray(originalScale);
v8 = true;
}
int scaleX = width / originalScale[0].length;int v10
= height / originalScale.length;
int scale = Math.min(scaleX, v10);
if (scale
> 1) {
byte[][] scaledMatrix = encoder.getBarcodeMatrix().getScaledMatrix(scale,
scale * aspectRatio);
if (v8) {
scaledMatrix = rotateArray(scaledMatrix);
}
return bitMatrixFromBitArray(scaledMatrix, margin);
}
return bitMatrixFromBitArray(originalScale, margin);
} | 3.26 |
zxing_PDF417Writer_bitMatrixFromBitArray_rdh | /**
* This takes an array holding the values of the PDF 417
*
* @param input
* a byte array of information with 0 is black, and 1 is white
* @param margin
* border around the barcode
* @return BitMatrix of the input
*/
private static BitMatrix bitMatrixFromBitArray(byte[][] input, int margin)
{
// Creates the bit matrix with extra space for whitespace
BitMatrix output = new BitMatrix(input[0].length + (2 * margin), input.length + (2 * margin));
output.clear();
for (int y = 0, yOutput = (output.getHeight() - margin) - 1; y < input.length; y++ , yOutput--) {
byte[] inputY = input[y];
for (int x = 0; x < input[0].length; x++) {
// Zero is white in the byte matrix
if (inputY[x] == 1) {
output.set(x + margin, yOutput);
}
}
}
return output;
} | 3.26 |
zxing_PDF417Writer_rotateArray_rdh | /**
* Takes and rotates the it 90 degrees
*/
private static byte[][] rotateArray(byte[][] bitarray) {
byte[][] temp = new byte[bitarray[0].length][bitarray.length];
for (int ii = 0; ii < bitarray.length; ii++) {
// This makes the direction consistent on screen when rotating the
// screen;
int inverseii = (bitarray.length - ii) - 1;
for (int jj = 0; jj < bitarray[0].length; jj++) {
temp[jj][inverseii]
= bitarray[ii][jj];
}
}
return temp;} | 3.26 |
zxing_BufferedImageLuminanceSource_isRotateSupported_rdh | /**
* This is always true, since the image is a gray-scale image.
*
* @return true
*/
@Override
public boolean isRotateSupported() {return true;
} | 3.26 |
zxing_Code93Writer_appendPattern_rdh | /**
*
* @param target
* output to append to
* @param pos
* start position
* @param pattern
* pattern to append
* @param startColor
* unused
* @return 9
* @deprecated without replacement; intended as an internal-only method
*/
@Deprecated
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) {
for (int bit : pattern) {
target[pos++] = bit != 0;
}
return 9;
} | 3.26 |
zxing_Code93Writer_encode_rdh | /**
*
* @param contents
* barcode contents to encode. It should not be encoded for extended characters.
* @return a {@code boolean[]} of horizontal pixels (false = white, true = black)
*/
@Override
public boolean[] encode(String contents) {
contents = convertToExtended(contents);
int length = contents.length();
if (length > 80) {
throw new IllegalArgumentException(("Requested contents should be less than 80 digits long after " + "converting to extended encoding, but got ") + length);
}
// length of code + 2 start/stop characters + 2 checksums, each of 9 bits, plus a termination bar
int v1 = (((contents.length() + 2) + 2) * 9) + 1;
boolean[] result = new boolean[v1];
// start character (*)
int pos = appendPattern(result, 0, Code93Reader.ASTERISK_ENCODING);
for (int i = 0; i <
length; i++) {
int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i));
pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[indexInString]);
}
// add two checksums
int check1 = computeChecksumIndex(contents, 20);
pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check1]);
// append the contents to reflect the first checksum added
contents += Code93Reader.ALPHABET_STRING.charAt(check1);
int check2 = computeChecksumIndex(contents, 15);
pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check2]);// end character (*)
pos += appendPattern(result, pos, Code93Reader.ASTERISK_ENCODING);
// termination bar (single black bar)
result[pos] = true;
return result;
} | 3.26 |
zxing_AbstractDoCoMoResultParser_matchDoCoMoPrefixedField_rdh | /**
* <p>See
* <a href="http://www.nttdocomo.co.jp/english/service/imode/make/content/barcode/about/s2.html">
* DoCoMo's documentation</a> about the result types represented by subclasses of this class.</p>
*
* <p>Thanks to Jeff Griffin for proposing rewrite of these classes that relies less
* on exception-based mechanisms during parsing.</p>
*
* @author Sean Owen
*/
| 3.26 |
zxing_BarcodeRow_addBar_rdh | /**
*
* @param black
* A boolean which is true if the bar black false if it is white
* @param width
* How many spots wide the bar is.
*/
void addBar(boolean black, int width) {
for (int ii = 0; ii < width; ii++) {
set(currentLocation++, black);
}
} | 3.26 |
zxing_BarcodeRow_getScaledRow_rdh | /**
* This function scales the row
*
* @param scale
* How much you want the image to be scaled, must be greater than or equal to 1.
* @return the scaled row
*/
byte[] getScaledRow(int scale) {
byte[] output = new byte[row.length * scale];
for (int i = 0; i < output.length; i++) {
output[i] = row[i / scale];
}
return output;} | 3.26 |
zxing_BarcodeRow_set_rdh | /**
* Sets a specific location in the bar
*
* @param x
* The location in the bar
* @param black
* Black if true, white if false;
*/
private void set(int x, boolean black) {
row[x] = ((byte) ((black) ? 1 : 0));
} | 3.26 |
zxing_PDF417Common_m0_rdh | /**
*
* @param symbol
* encoded symbol to translate to a codeword
* @return the codeword corresponding to the symbol.
*/
public static int m0(int symbol) {
int i = Arrays.binarySearch(SYMBOL_TABLE, symbol & 0x3ffff);
if (i
< 0) {
return -1;
}
return (CODEWORD_TABLE[i] - 1) % NUMBER_OF_CODEWORDS;
} | 3.26 |
zxing_HttpHelper_downloadViaHttp_rdh | /**
*
* @param uri
* URI to retrieve
* @param type
* expected text-like MIME type of that content
* @param maxChars
* approximate maximum characters to read from the source
* @return content as a {@code String}
* @throws IOException
* if the content can't be retrieved because of a bad URI, network problem, etc.
*/
public static CharSequence downloadViaHttp(String uri,
ContentType type, int maxChars) throws IOException {
String contentTypes;
switch (type) {
case HTML :
contentTypes = "application/xhtml+xml,text/html,text/*,*/*";
break;
case JSON :
contentTypes = "application/json,text/*,*/*";
break;
case XML :
contentTypes = "application/xml,text/*,*/*";
break;
default :
// Includes TEXT
contentTypes = "text/*,*/*";}
return downloadViaHttp(uri, contentTypes, maxChars);
} | 3.26 |
zxing_EmailAddressParsedResult_getMailtoURI_rdh | /**
*
* @return "mailto:"
* @deprecated without replacement
*/
@Deprecated
public String getMailtoURI() {
return "mailto:";
} | 3.26 |
zxing_BitMatrix_set_rdh | /**
* <p>Sets the given bit to true.</p>
*
* @param x
* The horizontal component (i.e. which column)
* @param y
* The vertical component (i.e. which row)
*/
public void set(int x, int y) {
int offset = (y * rowSize) + (x / 32);
bits[offset] |= 1 << (x & 0x1f);
} | 3.26 |
zxing_BitMatrix_toString_rdh | /**
*
* @param setString
* representation of a set bit
* @param unsetString
* representation of an unset bit
* @param lineSeparator
* newline character in string representation
* @return string representation of entire matrix utilizing given strings and line separator
* @deprecated call {@link #toString(String,String)} only, which uses \n line separator always
*/@Deprecated
public String toString(String setString, String unsetString, String lineSeparator) {
return buildToString(setString, unsetString, lineSeparator);
} | 3.26 |
zxing_BitMatrix_getHeight_rdh | /**
*
* @return The height of the matrix
*/
public int getHeight() {
return height;
} | 3.26 |
zxing_BitMatrix_flip_rdh | /**
* <p>Flips every bit in the matrix.</p>
*/
public void flip() {
int max = bits.length; for (int i = 0; i < max; i++) {
bits[i] = ~bits[i];
}
} | 3.26 |
zxing_BitMatrix_getRowSize_rdh | /**
*
* @return The row size of the matrix
*/
public int getRowSize() {
return rowSize;
} | 3.26 |
zxing_BitMatrix_getWidth_rdh | /**
*
* @return The width of the matrix
*/
public int getWidth() {
return width;
} | 3.26 |
zxing_BitMatrix_setRegion_rdh | /**
* <p>Sets a square region of the bit matrix to true.</p>
*
* @param left
* The horizontal position to begin at (inclusive)
* @param top
* The vertical position to begin at (inclusive)
* @param width
* The width of the region
* @param height
* The height of the region
*/
public void setRegion(int left, int top, int width, int height) {
if ((top < 0) || (left < 0)) {
throw new IllegalArgumentException("Left and top must be nonnegative");
}if ((height < 1) || (width < 1)) {
throw new IllegalArgumentException("Height and width must be at least 1");
}
int right = left + width;
int bottom = top + height;
if ((bottom > this.height) || (right > this.width)) {throw
new IllegalArgumentException("The region must fit inside the matrix");
}
for (int y = top; y < bottom; y++) {int offset = y * rowSize;
for (int x = left; x < right; x++)
{
bits[offset + (x / 32)] |= 1 << (x & 0x1f);
}
}
} | 3.26 |
zxing_BitMatrix_clear_rdh | /**
* Clears all bits (sets to false).
*/
public void clear() {
int max = bits.length;
for (int i = 0; i < max; i++) {bits[i] = 0;
}} | 3.26 |
zxing_BitMatrix_rotate_rdh | /**
* Modifies this {@code BitMatrix} to represent the same but rotated the given degrees (0, 90, 180, 270)
*
* @param degrees
* number of degrees to rotate through counter-clockwise (0, 90, 180, 270)
*/
public void rotate(int degrees) {
switch (degrees % 360) {
case 0 :
return;
case 90 :
rotate90();
return;
case 180 :rotate180();
return;
case 270 :
rotate90();
rotate180();
return;
}
throw new IllegalArgumentException("degrees must be a multiple of 0, 90, 180, or 270");
} | 3.26 |
zxing_BitMatrix_xor_rdh | /**
* Exclusive-or (XOR): Flip the bit in this {@code BitMatrix} if the corresponding
* mask bit is set.
*
* @param mask
* XOR mask
*/
public void xor(BitMatrix mask) {
if (((width != mask.width) || (height != mask.height)) || (rowSize != mask.rowSize)) {
throw new IllegalArgumentException("input matrix dimensions do not match");
}
BitArray rowArray = new BitArray(width);
for (int
y = 0; y <
height; y++) {
int offset = y * rowSize;
int[] row = mask.getRow(y, rowArray).getBitArray();
for (int x = 0; x < rowSize; x++)
{
bits[offset + x] ^= row[x];
}
}
} | 3.26 |
zxing_BitMatrix_parse_rdh | /**
* Interprets a 2D array of booleans as a {@code BitMatrix}, where "true" means an "on" bit.
*
* @param image
* bits of the image, as a row-major 2D array. Elements are arrays representing rows
* @return {@code BitMatrix} representation of image
*/
public static BitMatrix parse(boolean[][] image) {int height = image.length;
int width = image[0].length;
BitMatrix bits = new BitMatrix(width, height);
for (int i = 0; i < height; i++) {
boolean[] imageI = image[i];
for (int j = 0; j < width; j++) {
if (imageI[j]) {bits.set(j, i);
}
}
}
return bits;
} | 3.26 |
zxing_BitMatrix_setRow_rdh | /**
*
* @param y
* row to set
* @param row
* {@link BitArray} to copy from
*/
public void setRow(int y, BitArray row) {
System.arraycopy(row.getBitArray(), 0, bits, y * rowSize, rowSize);
} | 3.26 |
zxing_BitMatrix_getTopLeftOnBit_rdh | /**
* This is useful in detecting a corner of a 'pure' barcode.
*
* @return {@code x,y} coordinate of top-left-most 1 bit, or null if it is all white
*/
public int[] getTopLeftOnBit() {
int bitsOffset = 0;
while ((bitsOffset < bits.length) && (bits[bitsOffset] == 0)) {
bitsOffset++;
}
if (bitsOffset == bits.length) {
return null;
}
int y = bitsOffset / rowSize;int x = (bitsOffset % rowSize) * 32;
int theBits = bits[bitsOffset];
int bit = 0;while ((theBits << (31 - bit)) == 0) {
bit++;
}
x += bit;
return new int[]{ x, y };
} | 3.26 |
zxing_BitMatrix_rotate180_rdh | /**
* Modifies this {@code BitMatrix} to represent the same but rotated 180 degrees
*/
public void rotate180() {
BitArray topRow = new BitArray(width);
BitArray bottomRow = new
BitArray(width);
int maxHeight = (height + 1) / 2;for (int i = 0; i < maxHeight; i++) {
topRow = getRow(i, topRow);
int bottomRowIndex = (height - 1) -
i;
bottomRow = getRow(bottomRowIndex, bottomRow);
topRow.reverse();
bottomRow.reverse();
setRow(i, bottomRow);
setRow(bottomRowIndex, topRow);
}
} | 3.26 |
zxing_BitMatrix_get_rdh | /**
* <p>Gets the requested bit, where true means black.</p>
*
* @param x
* The horizontal component (i.e. which column)
* @param y
* The vertical component (i.e. which row)
* @return value of given bit in matrix
*/public boolean get(int x, int y) {
int offset = (y * rowSize) + (x / 32);
return ((bits[offset] >>> (x & 0x1f)) & 1) != 0;
} | 3.26 |
zxing_BitMatrix_getEnclosingRectangle_rdh | /**
* This is useful in detecting the enclosing rectangle of a 'pure' barcode.
*
* @return {@code left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white
*/public int[] getEnclosingRectangle() {
int left = width;
int top = height;
int right
= -1;
int bottom = -1;
for (int v51 = 0; v51 < height; v51++) {
for (int x32 = 0; x32 < rowSize; x32++) {
int theBits = bits[(v51 * rowSize) + x32];
if (theBits != 0) {
if (v51 < top) {
top = v51;
}
if (v51 > bottom) {
bottom = v51;
}
if ((x32 * 32) < left) {
int bit = 0;
while ((theBits << (31 - bit)) == 0) {
bit++;
}
if (((x32 * 32) + bit) < left) {
left = (x32 * 32) + bit;
}
}
if (((x32 * 32) + 31) > right) {int bit = 31;
while ((theBits >>> bit) == 0) {
bit--;
}
if (((x32 * 32) + bit) > right) {
right = (x32 * 32) + bit;
}
}
}
}
}
if ((right < left) || (bottom <
top)) {return
null;
}
return new int[]{ left, top, (right - left) + 1, (bottom - top) + 1 };
} | 3.26 |
zxing_Result_getRawBytes_rdh | /**
*
* @return raw bytes encoded by the barcode, if applicable, otherwise {@code null}
*/
public byte[] getRawBytes() {
return rawBytes;
} | 3.26 |
zxing_Result_getNumBits_rdh | /**
*
* @return how many bits of {@link #getRawBytes()} are valid; typically 8 times its length
* @since 3.3.0
*/
public int getNumBits() {
return numBits; } | 3.26 |
zxing_Result_getBarcodeFormat_rdh | /**
*
* @return {@link BarcodeFormat} representing the format of the barcode that was decoded
*/
public BarcodeFormat getBarcodeFormat() {
return format;
}
/**
*
* @return {@link Map} mapping {@link ResultMetadataType} keys to values. May be
{@code null} | 3.26 |
zxing_Result_getText_rdh | /**
*
* @return raw text encoded by the barcode
*/
public String getText() {
return text;
} | 3.26 |
zxing_AztecReader_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
*/
@Override
public Result decode(BinaryBitmap image) throws NotFoundException, FormatException {
return decode(image, null);
} | 3.26 |
zxing_DetectionResult_adjustRowNumber_rdh | /**
*
* @return true, if row number was adjusted, false otherwise
*/
private static boolean
adjustRowNumber(Codeword codeword,
Codeword otherCodeword) {
if (otherCodeword
== null) {
return false;
}
if (otherCodeword.hasValidRowNumber() && (otherCodeword.getBucket() == codeword.getBucket()))
{
codeword.setRowNumber(otherCodeword.getRowNumber());
return true;
}
return false;
} | 3.26 |
zxing_QRCodeDecoderMetaData_applyMirroredCorrection_rdh | /**
* Apply the result points' order correction due to mirroring.
*
* @param points
* Array of points to apply mirror correction to.
*/
public void applyMirroredCorrection(ResultPoint[] points) {
if (((!mirrored) || (points == null)) || (points.length < 3)) {
return;
}
ResultPoint bottomLeft = points[0];
points[0] = points[2];
points[2] = bottomLeft;
// No need to 'fix' top-left and alignment pattern.
} | 3.26 |
zxing_QRCodeDecoderMetaData_isMirrored_rdh | /**
*
* @return true if the QR Code was mirrored.
*/
public boolean isMirrored() {
return mirrored;
} | 3.26 |
zxing_BitArray_set_rdh | /**
* Sets bit i.
*
* @param i
* bit to set
*/
public void set(int i) {bits[i / 32] |= 1 << (i & 0x1f);
} | 3.26 |
zxing_BitArray_setRange_rdh | /**
* Sets a range of bits.
*
* @param start
* start of range, inclusive.
* @param end
* end of range, exclusive
*/
public void setRange(int start,
int end) {
if (((end < start) || (start < 0)) || (end > size)) {
throw new IllegalArgumentException();
}
if (end == start) {
return;
}
end--;// will be easier to treat this as the last actually set bit -- inclusive
int firstInt = start / 32;
int lastInt = end / 32;
for (int i = firstInt; i <= lastInt; i++) {
int v10 = (i > firstInt) ? 0 : start & 0x1f;
int lastBit = (i < lastInt) ? 31 : end & 0x1f;
// Ones from firstBit to lastBit, inclusive
int mask = (2 << lastBit) - (1 << v10);
bits[i] |= mask;
}
} | 3.26 |
zxing_BitArray_reverse_rdh | /**
* Reverses all bits in the array.
*/
public void reverse() {
int[] newBits = new int[bits.length];
// reverse all int's first
int
len
= (size - 1) / 32;
int oldBitsLen = len + 1;
for (int i
= 0; i < oldBitsLen; i++) {
newBits[len -
i] = Integer.reverse(bits[i]); }
// now correct the int's if the bit size isn't a multiple of 32
if (size != (oldBitsLen * 32)) {
int leftOffset = (oldBitsLen * 32) - size;
int currentInt = newBits[0] >>> leftOffset;
for (int i
= 1; i <
oldBitsLen; i++) {
int nextInt = newBits[i];
currentInt |= nextInt << (32 - leftOffset);
newBits[i - 1] = currentInt;
currentInt = nextInt >>> leftOffset;}
newBits[oldBitsLen - 1] =
currentInt;
}
bits = newBits;
} | 3.26 |
zxing_BitArray_toBytes_rdh | /**
*
* @param bitOffset
* first bit to start writing
* @param array
* array to write into. Bytes are written most-significant byte first. This is the opposite
* of the internal representation, which is exposed by {@link #getBitArray()}
* @param offset
* position in array to start writing
* @param numBytes
* how many bytes to write
*/
public void toBytes(int bitOffset, byte[] array, int offset, int numBytes) {
for (int i = 0; i < numBytes; i++) {
int theByte = 0;
for (int v28 = 0; v28 < 8; v28++) {
if (get(bitOffset)) {
theByte |= 1 << (7 - v28);
}
bitOffset++;
}
array[offset + i] = ((byte) (theByte));
}
} | 3.26 |
zxing_BitArray_clear_rdh | /**
* Clears all bits (sets to false).
*/
public void clear() {
int max = bits.length;
for (int i = 0; i < max; i++) {
bits[i] = 0;
}
} | 3.26 |
zxing_BitArray_getNextUnset_rdh | /**
*
* @param from
* index to start looking for unset bit
* @return index of next unset bit, or {@code size} if none are unset until the end
* @see #getNextSet(int)
*/
public int getNextUnset(int from) {
if (from >= size) {
return size;
}
int
bitsOffset = from / 32;
int currentBits
= ~bits[bitsOffset];// mask off lesser bits first
currentBits &= -(1 << (from & 0x1f));
while (currentBits == 0) {
if ((++bitsOffset) == bits.length) {
return size;
}
currentBits = ~bits[bitsOffset];
}
int result = (bitsOffset * 32) + Integer.numberOfTrailingZeros(currentBits);
return Math.min(result, size);
} | 3.26 |
zxing_BitArray_appendBits_rdh | /**
* Appends the least-significant bits, from value, in order from most-significant to
* least-significant. For example, appending 6 bits from 0x000001E will append the bits
* 0, 1, 1, 1, 1, 0 in that order.
*
* @param value
* {@code int} containing bits to append
* @param numBits
* bits from value to append
*/
public void appendBits(int value, int numBits) {
if ((numBits < 0) || (numBits > 32)) {
throw new IllegalArgumentException("Num bits must be between 0 and 32");
}
int nextSize
= size;
ensureCapacity(nextSize
+ numBits);
for (int numBitsLeft = numBits - 1; numBitsLeft >= 0; numBitsLeft--) {
if ((value &
(1 << numBitsLeft)) != 0) {
bits[nextSize / 32]
|=
1
<< (nextSize & 0x1f);
}
nextSize++;
}
size = nextSize;
} | 3.26 |
zxing_BitArray_setBulk_rdh | /**
* Sets a block of 32 bits, starting at bit i.
*
* @param i
* first bit to set
* @param newBits
* the new value of the next 32 bits. Note again that the least-significant bit
* corresponds to bit i, the next-least-significant to i+1, and so on.
*/
public void setBulk(int i, int newBits) {
bits[i / 32] = newBits;
} | 3.26 |
zxing_BitArray_isRange_rdh | /**
* Efficient method to check if a range of bits is set, or not set.
*
* @param start
* start of range, inclusive.
* @param end
* end of range, exclusive
* @param value
* if true, checks that bits in range are set, otherwise checks that they are not set
* @return true iff all bits are set or not set in range, according to value argument
* @throws IllegalArgumentException
* if end is less than start or the range is not contained in the array
*/
public boolean isRange(int start, int end, boolean value) {
if (((end < start) || (start < 0)) || (end > size)) {
throw new IllegalArgumentException();
}
if (end == start) {
return true;// empty range matches
}
end--;// will be easier to treat this as the last actually set bit -- inclusive
int firstInt = start / 32;
int lastInt = end / 32;
for (int i = firstInt;
i <= lastInt; i++) {
int firstBit = (i > firstInt) ? 0 : start & 0x1f;
int lastBit = (i < lastInt) ? 31 : end & 0x1f;
// Ones from firstBit to lastBit, inclusive
int mask = (2 << lastBit) - (1 << firstBit);
// Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,
// equals the mask, or we're looking for 0s and the masked portion is not all 0s
if ((bits[i] & mask) != (value ? mask : 0)) {
return false;
}
}
return true;
} | 3.26 |
zxing_BitArray_get_rdh | /**
*
* @param i
* bit to get
* @return true iff bit i is set
*/
public boolean get(int i) {
return (bits[i / 32] & (1 << (i & 0x1f))) != 0;
} | 3.26 |
zxing_BitArray_flip_rdh | /**
* Flips bit i.
*
* @param i
* bit to set
*/
public void flip(int i) {
bits[i / 32] ^= 1 << (i & 0x1f);
} | 3.26 |
zxing_BitSource_getByteOffset_rdh | /**
*
* @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
*/
public int getByteOffset() {
return byteOffset;
} | 3.26 |
zxing_BitSource_available_rdh | /**
*
* @return number of bits that can be read successfully
*/
public int available() {
return (8 * (bytes.length - byteOffset)) - bitOffset;
} | 3.26 |
zxing_BitSource_getBitOffset_rdh | /**
*
* @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
*/
public int getBitOffset() {
return bitOffset;
} | 3.26 |
zxing_Version_buildVersions_rdh | /**
* See ISO 16022:2006 5.5.1 Table 7
*/
private static Version[] buildVersions() {
return new Version[]{ new Version(1, 10, 10,
8, 8, new ECBlocks(5, new ECB(1, 3))), new Version(2, 12, 12, 10, 10, new ECBlocks(7, new ECB(1, 5))),
new Version(3,
14, 14, 12, 12, new ECBlocks(10, new ECB(1, 8))), new Version(4, 16, 16, 14, 14, new ECBlocks(12, new ECB(1, 12))), new Version(5, 18, 18, 16, 16, new ECBlocks(14, new ECB(1, 18))), new Version(6, 20, 20, 18, 18, new ECBlocks(18,
new ECB(1, 22))), new Version(7, 22, 22, 20, 20, new ECBlocks(20, new ECB(1, 30))), new Version(8, 24, 24, 22, 22, new ECBlocks(24, new ECB(1, 36))), new Version(9, 26, 26, 24, 24, new ECBlocks(28, new ECB(1, 44))), new Version(10, 32, 32, 14, 14, new ECBlocks(36,
new ECB(1, 62))), new Version(11, 36, 36, 16, 16, new ECBlocks(42, new ECB(1, 86))), new Version(12, 40, 40, 18, 18, new ECBlocks(48, new ECB(1, 114))), new Version(13, 44, 44, 20, 20, new ECBlocks(56, new ECB(1, 144))), new Version(14, 48, 48, 22, 22, new ECBlocks(68, new ECB(1, 174))), new Version(15, 52, 52, 24, 24, new ECBlocks(42, new ECB(2, 102))), new Version(16, 64, 64, 14, 14,
new ECBlocks(56, new ECB(2, 140))), new Version(17, 72, 72, 16, 16, new ECBlocks(36, new
ECB(4, 92))), new Version(18, 80,
80, 18, 18, new ECBlocks(48, new ECB(4, 114))), new Version(19, 88, 88, 20, 20, new ECBlocks(56, new ECB(4, 144))), new Version(20, 96, 96, 22, 22, new ECBlocks(68, new ECB(4, 174))), new
Version(21, 104, 104, 24, 24, new ECBlocks(56, new ECB(6, 136))), new Version(22, 120, 120, 18, 18, new ECBlocks(68, new ECB(6, 175))), new Version(23, 132, 132, 20, 20,
new ECBlocks(62, new ECB(8, 163))), new Version(24, 144, 144, 22, 22, new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))), new Version(25, 8, 18, 6, 16, new ECBlocks(7, new ECB(1, 5))), new Version(26, 8, 32,
6, 14, new ECBlocks(11, new ECB(1, 10))), new Version(27, 12, 26, 10, 24, new ECBlocks(14, new ECB(1, 16))), new Version(28, 12, 36, 10, 16, new ECBlocks(18, new ECB(1, 22))), new Version(29, 16, 36, 14, 16, new ECBlocks(24, new ECB(1, 32))), new Version(30, 16, 48, 14, 22, new ECBlocks(28, new ECB(1, 49))), // extended forms as specified in
// ISO 21471:2020 (DMRE) 5.5.1 Table 7
new Version(31, 8, 48, 6, 22, new ECBlocks(15, new ECB(1, 18))), new Version(32, 8, 64, 6, 14, new ECBlocks(18, new ECB(1, 24))), new Version(33, 8, 80, 6, 18, new ECBlocks(22, new ECB(1, 32))), new Version(34, 8, 96, 6, 22, new ECBlocks(28, new ECB(1, 38))), new Version(35, 8, 120, 6, 18, new ECBlocks(32, new ECB(1, 49))), new Version(36, 8, 144, 6, 22, new ECBlocks(36, new ECB(1, 63))), new Version(37, 12, 64, 10,
14, new ECBlocks(27, new ECB(1, 43))), new Version(38, 12, 88, 10, 20, new ECBlocks(36, new ECB(1, 64))), new Version(39, 16, 64, 14, 14, new ECBlocks(36, new ECB(1, 62))), new Version(40, 20, 36, 18, 16, new ECBlocks(28, new ECB(1, 44))), new Version(41, 20, 44, 18, 20, new ECBlocks(34, new ECB(1, 56))), new Version(42, 20, 64, 18, 14, new ECBlocks(42, new
ECB(1, 84))), new Version(43, 22, 48, 20, 22, new ECBlocks(38, new ECB(1, 72))), new Version(44, 24, 48, 22, 22, new ECBlocks(41, new ECB(1, 80))), new Version(45, 24, 64, 22, 14, new ECBlocks(46, new ECB(1, 108))), new Version(46, 26, 40, 24, 18, new ECBlocks(38, new ECB(1, 70))), new Version(47, 26, 48, 24, 22, new ECBlocks(42, new ECB(1, 90))), new Version(48, 26, 64, 24, 14, new ECBlocks(50, new ECB(1, 118))) };
} | 3.26 |
zxing_ResultHandler_searchMap_rdh | /**
* Do a geo search using the address as the query.
*
* @param address
* The address to find
*/
final void searchMap(String address) {
launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(address))));
} | 3.26 |
zxing_ResultHandler_launchIntent_rdh | /**
* Like {@link #rawLaunchIntent(Intent)} but will show a user dialog if nothing is available to handle.
*/
final void launchIntent(Intent intent) {
try {
rawLaunchIntent(intent);
} catch (ActivityNotFoundException ignored) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(string.app_name);
builder.setMessage(string.msg_intent_failed);
builder.setPositiveButton(string.button_ok, null);
builder.show();
}
} | 3.26 |
zxing_ResultHandler_areContentsSecure_rdh | /**
* Some barcode contents are considered secure, and should not be saved to history, copied to
* the clipboard, or otherwise persisted.
*
* @return If true, do not create any permanent record of these contents.
*/
public boolean areContentsSecure() {
return false;
} | 3.26 |
zxing_ResultHandler_rawLaunchIntent_rdh | /**
* Like {@link #launchIntent(Intent)} but will tell you if it is not handle-able
* via {@link ActivityNotFoundException}.
*
* @throws ActivityNotFoundException
* if Intent can't be handled
*/
final void rawLaunchIntent(Intent intent)
{
if (intent != null) {
intent.addFlags(Intents.FLAG_NEW_DOC);
activity.startActivity(intent);}
} | 3.26 |
zxing_ResultHandler_getDisplayContents_rdh | /**
* Create a possibly styled string for the contents of the current barcode.
*
* @return The text to be displayed.
*/
public CharSequence getDisplayContents() {
String contents = result.getDisplayResult();
return contents.replace("\r", "");
} | 3.26 |
zxing_ResultHandler_openProductSearch_rdh | // Uses the mobile-specific version of Product Search, which is formatted for small screens.
final void openProductSearch(String upc) {
Uri uri = Uri.parse(((("http://www.google." + LocaleManager.getProductSearchCountryTLD(activity)) + "/m/products?q=") + upc) + "&source=zxing");
launchIntent(new Intent(Intent.ACTION_VIEW, uri));
} | 3.26 |
zxing_ResultHandler_getType_rdh | /**
* A convenience method to get the parsed type. Should not be overridden.
*
* @return The parsed type, e.g. URI or ISBN
*/
public final ParsedResultType getType() {
return result.getType();
} | 3.26 |
zxing_Decoder_correctErrors_rdh | /**
* <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
* correct the errors in-place using Reed-Solomon error correction.</p>
*
* @param codewordBytes
* data and error correction codewords
* @param numDataCodewords
* number of codewords that are data bytes
* @return the number of errors corrected
* @throws ChecksumException
* if error correction fails
*/
private int correctErrors(byte[] codewordBytes, int numDataCodewords) throws ChecksumException {
int numCodewords = codewordBytes.length;
// First read into an array of ints
int[] codewordsInts =
new int[numCodewords];
for (int i = 0; i < numCodewords; i++) {codewordsInts[i] = codewordBytes[i] & 0xff;
}
int errorsCorrected = 0;
try {
errorsCorrected = rsDecoder.decodeWithECCount(codewordsInts, codewordBytes.length - numDataCodewords);
} catch (ReedSolomonException ignored) {
throw ChecksumException.getChecksumInstance();
}
// Copy back into array of bytes -- only need to worry about the bytes that were data
// We don't care about errors in the error-correction codewords
for (int i = 0; i < numDataCodewords; i++) {
codewordBytes[i] = ((byte) (codewordsInts[i]));
}
return errorsCorrected;
} | 3.26 |
zxing_Decoder_decode_rdh | /**
* <p>Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.</p>
*
* @param bits
* booleans representing white/black QR Code modules
* @param hints
* decoding hints that should be used to influence decoding
* @return text and bytes encoded within the QR Code
* @throws FormatException
* if the QR Code cannot be decoded
* @throws ChecksumException
* if error correction fails
*/
public DecoderResult decode(BitMatrix bits,
Map<DecodeHintType, ?> hints) throws FormatException, ChecksumException {
// Construct a parser and read version, error-correction level
BitMatrixParser parser = new BitMatrixParser(bits);
FormatException fe = null;
ChecksumException ce = null;
try {
return decode(parser, hints);
} catch (FormatException e) {
fe = e;
} catch (ChecksumException e) {
ce = e;
}
try {
// Revert the bit matrix
parser.remask();// Will be attempting a mirrored reading of the version and format info.
parser.setMirror(true);
// Preemptively read the version.
parser.readVersion();
// Preemptively read the format information.
parser.readFormatInformation();
/* Since we're here, this means we have successfully detected some kind
of version and format information when mirrored. This is a good sign,
that the QR code may be mirrored, and we should try once more with a
mirrored content.
*/
// Prepare for a mirrored reading.
parser.mirror();
DecoderResult result = decode(parser, hints);
// Success! Notify the caller that the code was mirrored.
result.setOther(new
QRCodeDecoderMetaData(true));
return result;
} catch (FormatException | ChecksumException e) {
// Throw the exception from the original reading
if (fe != null) {
throw fe;
}
throw ce;// If fe is null, this can't be
}
} | 3.26 |
zxing_ByteMatrix_getArray_rdh | /**
*
* @return an internal representation as bytes, in row-major order. array[y][x] represents point (x,y)
*/
public byte[][] getArray() {return bytes;
} | 3.26 |
zxing_QRCodeEncoder_encodeContentsFromShareIntent_rdh | // Handles send intents from multitude of Android applications
private void encodeContentsFromShareIntent(Intent intent) throws WriterException {
// Check if this is a plain text encoding, or contact
if (intent.hasExtra(Intent.EXTRA_STREAM)) {
encodeFromStreamExtra(intent);
} else {
encodeFromTextExtras(intent);
}
} | 3.26 |
zxing_QRCodeEncoder_encodeContentsFromZXingIntent_rdh | // It would be nice if the string encoding lived in the core ZXing library,
// but we use platform specific code like PhoneNumberUtils, so it can't.
private void encodeContentsFromZXingIntent(Intent intent) {
// Default to QR_CODE if no format given.
String formatString = intent.getStringExtra(Encode.FORMAT);
format = null;
if (formatString != null) {
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
}
}
if ((format == null) || (format == BarcodeFormat.QR_CODE)) {
String type = intent.getStringExtra(Encode.TYPE);if ((type != null) && (!type.isEmpty())) {
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(intent, type);
}
} else {
String data = intent.getStringExtra(Encode.DATA);
if ((data != null) && (!data.isEmpty())) {
contents = data;
displayContents = data;
title = activity.getString(string.contents_text); }
}
} | 3.26 |
zxing_QRCodeEncoder_encodeFromStreamExtra_rdh | // Handles send intents from the Contacts app, retrieving a contact as a VCARD.
private void encodeFromStreamExtra(Intent intent) throws WriterException {
format = BarcodeFormat.QR_CODE;
Bundle bundle = intent.getExtras();
if (bundle == null) {
throw new WriterException("No extras");
}
Uri uri =
bundle.getParcelable(Intent.EXTRA_STREAM);
if (uri == null) {
throw new WriterException("No EXTRA_STREAM");
}
byte[] vcard;
String vcardString;
try (InputStream stream = activity.getContentResolver().openInputStream(uri)) {
if (stream == null) {
throw new WriterException("Can't open stream for " + uri);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int bytesRead;
while ((bytesRead = stream.read(buffer)) > 0) {
baos.write(buffer, 0, bytesRead);
}
vcard = baos.toByteArray();
vcardString = new String(vcard, 0, vcard.length, StandardCharsets.UTF_8);
} catch (IOException ioe) {
throw new WriterException(ioe);
}
Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE);
ParsedResult v15 = ResultParser.parseResult(result);
if (!(v15 instanceof AddressBookParsedResult)) {
throw new WriterException("Result was not an address");
}
encodeQRCodeContents(((AddressBookParsedResult) (v15)));
if ((contents == null) || contents.isEmpty()) {
throw new WriterException("No content to encode");
}} | 3.26 |
zxing_ErrorCorrection_encodeECC200_rdh | /**
* Creates the ECC200 error correction for an encoded message.
*
* @param codewords
* the codewords
* @param symbolInfo
* information about the symbol to be encoded
* @return the codewords with interleaved error correction.
*/
public static String encodeECC200(String codewords, SymbolInfo symbolInfo) {
if (codewords.length() != symbolInfo.getDataCapacity()) {
throw new IllegalArgumentException("The number of codewords does not match the selected symbol");
}
StringBuilder sb = new StringBuilder(symbolInfo.getDataCapacity() + symbolInfo.getErrorCodewords());
sb.append(codewords);
int blockCount = symbolInfo.getInterleavedBlockCount();
if (blockCount == 1) {
String ecc = createECCBlock(codewords, symbolInfo.getErrorCodewords());
sb.append(ecc);
}
else {
sb.setLength(sb.capacity());
int[] dataSizes = new int[blockCount];
int[] errorSizes
= new int[blockCount];
for (int i = 0; i < blockCount; i++) {
dataSizes[i] = symbolInfo.getDataLengthForInterleavedBlock(i + 1);
errorSizes[i] =
symbolInfo.getErrorLengthForInterleavedBlock(i + 1);
}
for (int block = 0; block < blockCount; block++) {
StringBuilder temp = new StringBuilder(dataSizes[block]);
for (int d = block; d < symbolInfo.getDataCapacity(); d += blockCount) {
temp.append(codewords.charAt(d));
}
String ecc = createECCBlock(temp.toString(), errorSizes[block]);
int pos = 0;
for (int e = block; e < (errorSizes[block] * blockCount); e += blockCount) {
sb.setCharAt(symbolInfo.getDataCapacity() + e, ecc.charAt(pos++));
}
}
}
return sb.toString();
} | 3.26 |
zxing_OneDimensionalCodeWriter_encode_rdh | /**
* Encode the contents following specified format.
* {@code width} and {@code height} are required size. This method may return bigger size
* {@code BitMatrix} when specified size is too small. The user can set both {@code width} and
* {@code height} to zero to get minimum size barcode. If negative value is set to {@code width}
* or {@code height}, {@code IllegalArgumentException} is thrown.
*/
@Override
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) {
if (contents.isEmpty()) {
throw new IllegalArgumentException("Found empty contents");
}
if
((width < 0) || (height < 0)) {
throw new IllegalArgumentException((("Negative size is not allowed. Input: " + width) + 'x') + height);
}
Collection<BarcodeFormat> supportedFormats = getSupportedWriteFormats();
if
((supportedFormats != null) && (!supportedFormats.contains(format))) {
throw new IllegalArgumentException((("Can only encode " + supportedFormats) + ", but got ") + format);
}
int sidesMargin = getDefaultMargin();
if ((hints != null) && hints.containsKey(EncodeHintType.MARGIN)) {
sidesMargin = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
}
boolean[] code = encode(contents, hints);
return renderResult(code, width, height, sidesMargin);
} | 3.26 |
zxing_OneDimensionalCodeWriter_renderResult_rdh | /**
*
* @return a byte array of horizontal pixels (0 = white, 1 = black)
*/
private static BitMatrix renderResult(boolean[] code, int width, int height, int sidesMargin) {
int inputWidth = code.length;
// Add quiet zone on both sides.
int fullWidth = inputWidth + sidesMargin;
int outputWidth = Math.max(width, fullWidth);
int outputHeight = Math.max(1, height);
int multiple = outputWidth / fullWidth;
int v8 = (outputWidth - (inputWidth * multiple)) / 2;
BitMatrix output = new
BitMatrix(outputWidth, outputHeight);
for (int inputX =
0, outputX = v8; inputX < inputWidth; inputX++ , outputX += multiple) {
if (code[inputX]) {
output.setRegion(outputX, 0, multiple, outputHeight);
}
}
return output;
} | 3.26 |
zxing_OneDimensionalCodeWriter_checkNumeric_rdh | /**
*
* @param contents
* string to check for numeric characters
* @throws IllegalArgumentException
* if input contains characters other than digits 0-9.
*/protected static void checkNumeric(String contents) {
if (!NUMERIC.matcher(contents).matches()) {
throw new IllegalArgumentException("Input should only contain digits 0-9");
}
}
/**
*
* @param target
* encode black/white pattern into this array
* @param pos
* position to start encoding at in {@code target} | 3.26 |
zxing_Code128Writer_encode_rdh | /**
* Encode the string starting at position position starting with the character set charset
*/
private int encode(CharSequence contents, Charset charset, int position) {
assert position < contents.length();
int mCost = memoizedCost[charset.ordinal()][position];
if (mCost > 0) {
return mCost;
}
int minCost = Integer.MAX_VALUE;
Latch minLatch = Latch.NONE;
boolean atEnd
= (position + 1) >= contents.length();
Charset[] sets = new Charset[]{ Charset.A, Charset.B };
for (int i = 0; i <= 1; i++) {
if (canEncode(contents, sets[i], position)) {
int cost = 1;
Latch latch = Latch.NONE;
if (charset != sets[i]) {
cost++;
latch = Latch.valueOf(sets[i].toString());
}
if (!atEnd) {
cost += encode(contents, sets[i], position + 1);
}
if (cost < minCost) {
minCost = cost;
minLatch = latch;
}
cost = 1;
if (charset ==
sets[(i + 1) % 2]) {
cost++;
latch = Latch.SHIFT;
if
(!atEnd) {
cost += encode(contents, charset, position
+ 1);
}
if (cost < minCost) {
minCost = cost;
minLatch = latch;
}
}
}
}
if (canEncode(contents, Charset.C, position)) {
int cost = 1;
Latch latch = Latch.NONE;
if (charset != Charset.C) {
cost++;
latch = Latch.C;
}
int advance = (contents.charAt(position) == ESCAPE_FNC_1) ? 1 : 2;
if ((position + advance) < contents.length()) {
cost += encode(contents, Charset.C, position + advance);
}
if (cost < minCost) {
minCost = cost;
minLatch = latch;
}
}
if (minCost == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Bad character in input: ASCII value=" + ((int) (contents.charAt(position))));
}
memoizedCost[charset.ordinal()][position] = minCost;
minPath[charset.ordinal()][position] = minLatch;
return minCost;
} | 3.26 |
zxing_AztecWriter_encode_rdh | /**
* Renders an Aztec code as a {@link BitMatrix}.
*/public final class AztecWriter implements Writer {@Override
public BitMatrix
encode(String contents, BarcodeFormat format, int width, int height) {
return encode(contents, format, width, height, null);
} | 3.26 |
zxing_DecoderResult_getOther_rdh | /**
*
* @return arbitrary additional metadata
*/
public Object getOther() {
return other;
} | 3.26 |
zxing_DecoderResult_m1_rdh | /**
*
* @return text representation of the result
*/
public String m1() {
return text;
} | 3.26 |
zxing_DecoderResult_getRawBytes_rdh | /**
*
* @return raw bytes representing the result, or {@code null} if not applicable
*/
public byte[] getRawBytes() {
return rawBytes;
} | 3.26 |
zxing_DecoderResult_m0_rdh | /**
*
* @return how many bits of {@link #getRawBytes()} are valid; typically 8 times its length
* @since 3.3.0
*/
public int m0() {
return numBits;
} | 3.26 |
zxing_DecoderResult_getECLevel_rdh | /**
*
* @return name of error correction level used, or {@code null} if not applicable
*/
public String getECLevel() {
return ecLevel;
}
/**
*
* @return number of errors corrected, or {@code null} | 3.26 |
zxing_DecoderResult_getErasures_rdh | /**
*
* @return number of erasures corrected, or {@code null} if not applicable
*/
public Integer getErasures() {
return erasures;
} | 3.26 |
zxing_DecoderResult_getByteSegments_rdh | /**
*
* @return list of byte segments in the result, or {@code null} if not applicable
*/
public List<byte[]> getByteSegments() {
return byteSegments;
} | 3.26 |
zxing_DecoderResult_setNumBits_rdh | /**
*
* @param numBits
* overrides the number of bits that are valid in {@link #getRawBytes()}
* @since 3.3.0
*/
public void setNumBits(int numBits) {
this.numBits = numBits;
} | 3.26 |
zxing_Detector_getFirstDifferent_rdh | /**
* Gets the coordinate of the first point with a different color in the given direction
*/
private Point getFirstDifferent(Point init, boolean color, int dx, int dy) {
int x = init.getX() +
dx;
int y = init.getY() + dy;
while (isValid(x, y) && (image.get(x, y) == color)) {
x += dx;
y += dy;
}
x -= dx;
y -= dy;
while (isValid(x, y) && (image.get(x, y) == color)) {
x
+= dx;
}
x -= dx;
while (isValid(x, y) && (image.get(x, y) == color)) {y += dy;
}
y -= dy;
return new Point(x, y);
} | 3.26 |
zxing_Detector_getCorrectedParameterData_rdh | /**
* Corrects the parameter bits using Reed-Solomon algorithm.
*
* @param parameterData
* parameter bits
* @param compact
* true if this is a compact Aztec code
* @return the corrected parameter
* @throws NotFoundException
* if the array contains too many errors
*/
private static CorrectedParameter getCorrectedParameterData(long parameterData, boolean compact) throws NotFoundException {
int numCodewords;
int numDataCodewords;
if (compact) {
numCodewords = 7;
numDataCodewords = 2;
} else {
numCodewords = 10;
numDataCodewords = 4;
}
int
numECCodewords = numCodewords - numDataCodewords;
int[] parameterWords = new int[numCodewords];
for (int i = numCodewords - 1; i >= 0; --i) {
parameterWords[i] = ((int) (parameterData)) & 0xf;
parameterData >>= 4;
}
int errorsCorrected = 0;
try {
ReedSolomonDecoder rsDecoder = new ReedSolomonDecoder(GenericGF.AZTEC_PARAM);
errorsCorrected = rsDecoder.decodeWithECCount(parameterWords, numECCodewords);
} catch (ReedSolomonException ignored) {
throw NotFoundException.getNotFoundInstance();
}
// Toss the error correction. Just return the data as an integer
int result = 0;
for (int
i = 0; i < numDataCodewords; i++) {result = (result << 4) + parameterWords[i];
}
return new CorrectedParameter(result, errorsCorrected);
} | 3.26 |
zxing_Detector_getBullsEyeCorners_rdh | /**
* Finds the corners of a bull-eye centered on the passed point.
* This returns the centers of the diagonal points just outside the bull's eye
* Returns [topRight, bottomRight, bottomLeft, topLeft]
*
* @param pCenter
* Center point
* @return The corners of the bull-eye
* @throws NotFoundException
* If no valid bull-eye can be found
*/
private ResultPoint[] getBullsEyeCorners(Point pCenter) throws NotFoundException { Point pina = pCenter;
Point pinb = pCenter;
Point pinc = pCenter;
Point pind = pCenter;
boolean color = true;
for (nbCenterLayers = 1;
nbCenterLayers < 9; nbCenterLayers++) {
Point v31 = getFirstDifferent(pina, color, 1, -1);
Point poutb = getFirstDifferent(pinb, color, 1, 1);
Point poutc = getFirstDifferent(pinc, color, -1, 1);
Point poutd
= getFirstDifferent(pind, color, -1, -1);
// d a
//
// c b
if (nbCenterLayers > 2) {
float q = (distance(poutd, v31) * nbCenterLayers) / (distance(pind, pina) * (nbCenterLayers + 2));
if (((q < 0.75) || (q > 1.25)) || (!isWhiteOrBlackRectangle(v31, poutb, poutc, poutd))) {
break;
}
}
pina = v31;
pinb = poutb;
pinc = poutc;
pind = poutd;color = !color;
}
if ((nbCenterLayers != 5) && (nbCenterLayers != 7)) {
throw NotFoundException.getNotFoundInstance();
}
compact = nbCenterLayers == 5;
// Expand the square by .5 pixel in each direction so that we're on the border
// between the white square and the black square
ResultPoint pinax = new ResultPoint(pina.getX() + 0.5F, pina.getY() - 0.5F);
ResultPoint pinbx = new ResultPoint(pinb.getX() + 0.5F, pinb.getY() + 0.5F);
ResultPoint pincx = new ResultPoint(pinc.getX() - 0.5F, pinc.getY() + 0.5F);
ResultPoint pindx
= new ResultPoint(pind.getX() - 0.5F,
pind.getY() -
0.5F);
// Expand the square so that its corners are the centers of the points
// just outside the bull's eye.
return expandSquare(new ResultPoint[]{ pinax, pinbx, pincx, pindx }, (2 * nbCenterLayers) - 3, 2 * nbCenterLayers);
} | 3.26 |
zxing_Detector_extractParameters_rdh | /**
* Extracts the number of data layers and data blocks from the layer around the bull's eye.
*
* @param bullsEyeCorners
* the array of bull's eye corners
* @return the number of errors corrected during parameter extraction
* @throws NotFoundException
* in case of too many errors or invalid parameters
*/
private int extractParameters(ResultPoint[] bullsEyeCorners) throws NotFoundException {
if ((((!isValid(bullsEyeCorners[0])) || (!isValid(bullsEyeCorners[1]))) ||
(!isValid(bullsEyeCorners[2]))) || (!isValid(bullsEyeCorners[3]))) {
throw NotFoundException.getNotFoundInstance();
}
int length = 2 * nbCenterLayers;
// Get the bits around the bull's eye
int[] sides = new int[]{ sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length)// Right side
, sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length)// Bottom
, sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length)// Left side
, sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length)// Top
};
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two.
shift = getRotation(sides, length);
// Flatten the parameter bits into a single 28- or 40-bit long
long parameterData = 0;
for (int i = 0; i < 4; i++) {
int side = sides[(shift + i) % 4];
if (compact) {
// Each side of the form ..XXXXXXX. where Xs are parameter data
parameterData <<= 7;
parameterData += (side >> 1) & 0x7f;
} else {
// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
parameterData <<= 10;parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1f);
}
}
// Corrects parameter data using RS. Returns just the data portion
// without the error correction.
CorrectedParameter correctedParam = getCorrectedParameterData(parameterData, compact);
int correctedData = correctedParam.getData();
if (compact) {
// 8 bits: 2 bits layers and 6 bits data blocks
nbLayers = (correctedData >> 6) + 1;
nbDataBlocks = (correctedData & 0x3f) + 1;
} else {
// 16 bits: 5 bits layers and 11 bits data blocks
nbLayers = (correctedData >> 11) + 1;
nbDataBlocks = (correctedData & 0x7ff) + 1;
}
return correctedParam.getErrorsCorrected();
} | 3.26 |
zxing_Detector_detect_rdh | /**
* Detects an Aztec Code in an image.
*
* @param isMirror
* if true, image is a mirror-image of original
* @return {@link AztecDetectorResult} encapsulating results of detecting an Aztec Code
* @throws NotFoundException
* if no Aztec Code can be found
*/
public AztecDetectorResult detect(boolean isMirror) throws NotFoundException {
// 1. Get the center of the aztec matrix
Point
pCenter = getMatrixCenter();
// 2. Get the center points of the four diagonal points just outside the bull's eye
// [topRight, bottomRight, bottomLeft, topLeft]
ResultPoint[] bullsEyeCorners = getBullsEyeCorners(pCenter);
if (isMirror) {
ResultPoint temp = bullsEyeCorners[0];
bullsEyeCorners[0] = bullsEyeCorners[2];bullsEyeCorners[2] = temp;
}
// 3. Get the size of the matrix and other parameters from the bull's eye
int errorsCorrected = extractParameters(bullsEyeCorners);
// 4. Sample the grid
BitMatrix bits = sampleGrid(image, bullsEyeCorners[shift % 4], bullsEyeCorners[(shift + 1) % 4], bullsEyeCorners[(shift + 2) % 4], bullsEyeCorners[(shift +
3) % 4]);
// 5. Get the corners of the matrix.
ResultPoint[] corners = getMatrixCornerPoints(bullsEyeCorners);
return new AztecDetectorResult(bits, corners, compact, nbDataBlocks, nbLayers, errorsCorrected);} | 3.26 |
zxing_Detector_getMatrixCornerPoints_rdh | /**
* Gets the Aztec code corners from the bull's eye corners and the parameters.
*
* @param bullsEyeCorners
* the array of bull's eye corners
* @return the array of aztec code corners
*/
private ResultPoint[] getMatrixCornerPoints(ResultPoint[] bullsEyeCorners) {return expandSquare(bullsEyeCorners, 2 * nbCenterLayers, getDimension());
} | 3.26 |
zxing_Detector_sampleLine_rdh | /**
* Samples a line.
*
* @param p1
* start point (inclusive)
* @param p2
* end point (exclusive)
* @param size
* number of bits
* @return the array of bits as an int (first bit is high-order bit of result)
*/
private int sampleLine(ResultPoint p1, ResultPoint p2, int size) {
int result = 0;
float d = distance(p1, p2);
float moduleSize = d / size;
float v57
= p1.getX();
float py = p1.getY();
float dx = (moduleSize * (p2.getX() -
p1.getX())) / d;
float dy = (moduleSize * (p2.getY() - p1.getY())) / d;
for (int i = 0; i < size; i++) {
if (image.get(MathUtils.round(v57 + (i * dx)), MathUtils.round(py + (i * dy)))) {
result |= 1 <<
((size - i)
- 1);
}
}
return result;
} | 3.26 |
zxing_Detector_getMatrixCenter_rdh | /**
* Finds a candidate center point of an Aztec code from an image
*
* @return the center point
*/
private Point getMatrixCenter() {
ResultPoint pointA;
ResultPoint v41;
ResultPoint pointC;
ResultPoint pointD;
// Get a white rectangle that can be the border of the matrix in center bull's eye or
try {
ResultPoint[] cornerPoints = new WhiteRectangleDetector(image).detect();
pointA = cornerPoints[0];
v41 = cornerPoints[1];
pointC = cornerPoints[2];
pointD = cornerPoints[3];
} catch (NotFoundException e) {
// This exception can be in case the initial rectangle is white
// In that case, surely in the bull's eye, we try to expand the rectangle.
int cx = image.getWidth() / 2;
int v46 = image.getHeight() / 2;
pointA = getFirstDifferent(new Point(cx + 7, v46 - 7), false, 1, -1).toResultPoint();
v41 = getFirstDifferent(new Point(cx + 7, v46 + 7), false, 1, 1).toResultPoint();
pointC = getFirstDifferent(new Point(cx - 7, v46 + 7), false, -1, 1).toResultPoint();
pointD = getFirstDifferent(new Point(cx - 7, v46 - 7), false, -1, -1).toResultPoint();
}
// Compute the center of the rectangle
int cx = MathUtils.round((((pointA.getX() + pointD.getX()) + v41.getX()) + pointC.getX()) / 4.0F);int cy = MathUtils.round((((pointA.getY() + pointD.getY()) + v41.getY()) + pointC.getY())
/ 4.0F);
// Redetermine the white rectangle starting from previously computed center.
// This will ensure that we end up with a white rectangle in center bull's eye
// in order to compute a more accurate center.
try {
ResultPoint[] cornerPoints = new WhiteRectangleDetector(image, 15, cx, cy).detect();
pointA = cornerPoints[0];
v41 = cornerPoints[1]; pointC = cornerPoints[2];
pointD = cornerPoints[3];
} catch (NotFoundException e) {
// This exception can be in case the initial rectangle is white
// In that case we try to expand the rectangle.
pointA = getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
v41 = getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();pointC = getFirstDifferent(new Point(cx - 7, cy + 7), false, -1,
1).toResultPoint();
pointD = getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
}
// Recompute the center of the rectangle
cx = MathUtils.round((((pointA.getX() + pointD.getX()) + v41.getX()) + pointC.getX()) / 4.0F);
cy = MathUtils.round((((pointA.getY() + pointD.getY()) + v41.getY()) + pointC.getY()) / 4.0F);
return new Point(cx, cy);
} | 3.26 |
zxing_Detector_expandSquare_rdh | /**
* Expand the square represented by the corner points by pushing out equally in all directions
*
* @param cornerPoints
* the corners of the square, which has the bull's eye at its center
* @param oldSide
* the original length of the side of the square in the target bit matrix
* @param newSide
* the new length of the size of the square in the target bit matrix
* @return the corners of the expanded square
*/
private static ResultPoint[] expandSquare(ResultPoint[] cornerPoints, int oldSide, int newSide) {
float ratio = newSide / (2.0F * oldSide);
float dx = cornerPoints[0].getX() - cornerPoints[2].getX();
float dy = cornerPoints[0].getY() - cornerPoints[2].getY();
float
centerx = (cornerPoints[0].getX() + cornerPoints[2].getX()) / 2.0F;
float centery = (cornerPoints[0].getY() + cornerPoints[2].getY()) / 2.0F;
ResultPoint result0 = new ResultPoint(centerx + (ratio * dx), centery + (ratio * dy));
ResultPoint result2 = new ResultPoint(centerx - (ratio * dx), centery - (ratio
* dy));
dx = cornerPoints[1].getX() - cornerPoints[3].getX();
dy = cornerPoints[1].getY() - cornerPoints[3].getY();
centerx = (cornerPoints[1].getX() + cornerPoints[3].getX()) / 2.0F; centery = (cornerPoints[1].getY() + cornerPoints[3].getY()) / 2.0F;
ResultPoint result1 = new ResultPoint(centerx + (ratio * dx), centery + (ratio * dy));
ResultPoint result3 = new ResultPoint(centerx - (ratio * dx), centery - (ratio * dy));return new ResultPoint[]{ result0, result1, result2, result3 };
} | 3.26 |
zxing_Detector_getColor_rdh | /**
* Gets the color of a segment
*
* @return 1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else
*/
private int getColor(Point p1, Point p2) {
float d = distance(p1, p2);
if (d == 0.0F) {
return 0;
}
float dx = (p2.getX() - p1.getX()) / d;
float dy = (p2.getY() - p1.getY()) / d;
int error = 0;
float px = p1.getX();
float py = p1.getY();
boolean colorModel = image.get(p1.getX(), p1.getY());
int iMax = ((int) (Math.floor(d)));
for (int i = 0; i < iMax; i++)
{
if (image.get(MathUtils.round(px), MathUtils.round(py)) != colorModel) {
error++;
}
px += dx;
py += dy; }
float errRatio = error / d;
if ((errRatio > 0.1F) && (errRatio < 0.9F)) {
return 0;
}
return (errRatio <= 0.1F) == colorModel ? 1 : -1;
} | 3.26 |
zxing_CalendarResultHandler_addCalendarEvent_rdh | /**
* Sends an intent to create a new calendar event by prepopulating the Add Event UI. Older
* versions of the system have a bug where the event title will not be filled out.
*
* @param summary
* A description of the event
* @param start
* The start time
* @param allDay
* if true, event is considered to be all day starting from start time
* @param end
* The end time (optional; can be < 0 if not specified)
* @param location
* a text description of the event location
* @param description
* a text description of the event itself
* @param attendees
* attendees to invite
*/
private void addCalendarEvent(String summary, long start, boolean allDay, long end, String location, String description, String[] attendees) {
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", start);
if (allDay) {
intent.putExtra("allDay", true);
}
if (end < 0L) {
if (allDay) {
// + 1 day
end = start + (((24 * 60) * 60) * 1000);
} else {
end = start;
}
}
intent.putExtra("endTime", end);
intent.putExtra("title", summary);
intent.putExtra("eventLocation", location);
intent.putExtra("description", description);
if (attendees != null) {
intent.putExtra(Intent.EXTRA_EMAIL, attendees);
// Documentation says this is either a String[] or comma-separated String, which is right?
}
try {
// Do this manually at first
rawLaunchIntent(intent);
} catch (ActivityNotFoundException anfe) {Log.w(TAG,
"No calendar app available that responds to " + Intent.ACTION_INSERT);
// For calendar apps that don't like "INSERT":
intent.setAction(Intent.ACTION_EDIT);
launchIntent(intent);// Fail here for real if nothing can handle it
}
} | 3.26 |
zxing_PDF417ScanningDecoder_createDecoderResultFromAmbiguousValues_rdh | /**
* This method deals with the fact, that the decoding process doesn't always yield a single most likely value. The
* current error correction implementation doesn't deal with erasures very well, so it's better to provide a value
* for these ambiguous codewords instead of treating it as an erasure. The problem is that we don't know which of
* the ambiguous values to choose. We try decode using the first value, and if that fails, we use another of the
* ambiguous values and try to decode again. This usually only happens on very hard to read and decode barcodes,
* so decoding the normal barcodes is not affected by this.
*
* @param erasureArray
* contains the indexes of erasures
* @param ambiguousIndexes
* array with the indexes that have more than one most likely value
* @param ambiguousIndexValues
* two dimensional array that contains the ambiguous values. The first dimension must
* be the same length as the ambiguousIndexes array
*/
private static DecoderResult createDecoderResultFromAmbiguousValues(int ecLevel, int[] codewords, int[] erasureArray, int[] ambiguousIndexes, int[][] ambiguousIndexValues) throws FormatException, ChecksumException {
int[] ambiguousIndexCount = new int[ambiguousIndexes.length];
int tries = 100;
while ((tries--) > 0) {
for (int i = 0; i < ambiguousIndexCount.length; i++) {
codewords[ambiguousIndexes[i]] = ambiguousIndexValues[i][ambiguousIndexCount[i]];
}
try {
return decodeCodewords(codewords, ecLevel, erasureArray);
} catch (ChecksumException ignored) {
//
}
if
(ambiguousIndexCount.length == 0) {
throw ChecksumException.getChecksumInstance();
}
for (int i = 0; i < ambiguousIndexCount.length; i++) {
if (ambiguousIndexCount[i] < (ambiguousIndexValues[i].length - 1)) {
ambiguousIndexCount[i]++;
break;
} else {
ambiguousIndexCount[i] = 0;
if (i == (ambiguousIndexCount.length - 1)) {
throw ChecksumException.getChecksumInstance();
}
}
}
}
throw ChecksumException.getChecksumInstance();
} | 3.26 |
zxing_PDF417ScanningDecoder_correctErrors_rdh | /**
* <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
* correct the errors in-place.</p>
*
* @param codewords
* data and error correction codewords
* @param erasures
* positions of any known erasures
* @param numECCodewords
* number of error correction codewords that are available in codewords
* @throws ChecksumException
* if error correction fails
*/
private static int correctErrors(int[] codewords, int[] erasures, int numECCodewords) throws ChecksumException {
if ((((erasures != null) && (erasures.length > ((numECCodewords / 2) + MAX_ERRORS))) || (numECCodewords < 0)) || (numECCodewords > MAX_EC_CODEWORDS)) {
// Too many errors or EC Codewords is corrupted
throw ChecksumException.getChecksumInstance();
}
return f0.decode(codewords,
numECCodewords, erasures);
} | 3.26 |