_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3900
|
MaxiCode.insert
|
train
|
private void insert(int position, int c) {
for (int i = 143; i > position; i--) {
set[i] = set[i - 1];
character[i] = character[i - 1];
}
character[position] = c;
}
|
java
|
{
"resource": ""
}
|
q3901
|
MaxiCode.getErrorCorrection
|
train
|
private static int[] getErrorCorrection(int[] codewords, int ecclen) {
ReedSolomon rs = new ReedSolomon();
rs.init_gf(0x43);
rs.init_code(ecclen, 1);
rs.encode(codewords.length, codewords);
int[] results = new int[ecclen];
for (int i = 0; i < ecclen; i++) {
results[i] = rs.getResult(results.length - 1 - i);
}
return results;
}
|
java
|
{
"resource": ""
}
|
q3902
|
AztecCode.setStructuredAppendMessageId
|
train
|
public void setStructuredAppendMessageId(String messageId) {
if (messageId != null && !messageId.matches("^[\\x21-\\x7F]+$")) {
throw new IllegalArgumentException("Invalid Aztec Code structured append message ID: " + messageId);
}
this.structuredAppendMessageId = messageId;
}
|
java
|
{
"resource": ""
}
|
q3903
|
AztecCode.addErrorCorrection
|
train
|
private void addErrorCorrection(StringBuilder adjustedString, int codewordSize, int dataBlocks, int eccBlocks) {
int x, poly, startWeight;
/* Split into codewords and calculate Reed-Solomon error correction codes */
switch (codewordSize) {
case 6:
x = 32;
poly = 0x43;
startWeight = 0x20;
break;
case 8:
x = 128;
poly = 0x12d;
startWeight = 0x80;
break;
case 10:
x = 512;
poly = 0x409;
startWeight = 0x200;
break;
case 12:
x = 2048;
poly = 0x1069;
startWeight = 0x800;
break;
default:
throw new OkapiException("Unrecognized codeword size: " + codewordSize);
}
ReedSolomon rs = new ReedSolomon();
int[] data = new int[dataBlocks + 3];
int[] ecc = new int[eccBlocks + 3];
for (int i = 0; i < dataBlocks; i++) {
for (int weight = 0; weight < codewordSize; weight++) {
if (adjustedString.charAt((i * codewordSize) + weight) == '1') {
data[i] += (x >> weight);
}
}
}
rs.init_gf(poly);
rs.init_code(eccBlocks, 1);
rs.encode(dataBlocks, data);
for (int i = 0; i < eccBlocks; i++) {
ecc[i] = rs.getResult(i);
}
for (int i = (eccBlocks - 1); i >= 0; i--) {
for (int weight = startWeight; weight > 0; weight = weight >> 1) {
if ((ecc[i] & weight) != 0) {
adjustedString.append('1');
} else {
adjustedString.append('0');
}
}
}
}
|
java
|
{
"resource": ""
}
|
q3904
|
ExtendedOutputStreamWriter.append
|
train
|
public ExtendedOutputStreamWriter append(double d) throws IOException {
super.append(String.format(Locale.ROOT, doubleFormat, d));
return this;
}
|
java
|
{
"resource": ""
}
|
q3905
|
Arrays.positionOf
|
train
|
public static int positionOf(char value, char[] array) {
for (int i = 0; i < array.length; i++) {
if (value == array[i]) {
return i;
}
}
throw new OkapiException("Unable to find character '" + value + "' in character array.");
}
|
java
|
{
"resource": ""
}
|
q3906
|
Arrays.insertArray
|
train
|
public static int[] insertArray(int[] original, int index, int[] inserted) {
int[] modified = new int[original.length + inserted.length];
System.arraycopy(original, 0, modified, 0, index);
System.arraycopy(inserted, 0, modified, index, inserted.length);
System.arraycopy(original, index, modified, index + inserted.length, modified.length - index - inserted.length);
return modified;
}
|
java
|
{
"resource": ""
}
|
q3907
|
QrCode.getBinaryLength
|
train
|
private static int getBinaryLength(int version, QrMode[] inputModeUnoptimized, int[] inputData, boolean gs1, int eciMode) {
int i, j;
QrMode currentMode;
int inputLength = inputModeUnoptimized.length;
int count = 0;
int alphaLength;
int percent = 0;
// ZINT NOTE: in Zint, this call modifies the input mode array directly; here, we leave
// the original array alone so that subsequent binary length checks don't irrevocably
// optimize the mode array for the wrong QR Code version
QrMode[] inputMode = applyOptimisation(version, inputModeUnoptimized);
currentMode = QrMode.NULL;
if (gs1) {
count += 4;
}
if (eciMode != 3) {
count += 12;
}
for (i = 0; i < inputLength; i++) {
if (inputMode[i] != currentMode) {
count += 4;
switch (inputMode[i]) {
case KANJI:
count += tribus(version, 8, 10, 12);
count += (blockLength(i, inputMode) * 13);
break;
case BINARY:
count += tribus(version, 8, 16, 16);
for (j = i; j < (i + blockLength(i, inputMode)); j++) {
if (inputData[j] > 0xff) {
count += 16;
} else {
count += 8;
}
}
break;
case ALPHANUM:
count += tribus(version, 9, 11, 13);
alphaLength = blockLength(i, inputMode);
// In alphanumeric mode % becomes %%
if (gs1) {
for (j = i; j < (i + alphaLength); j++) { // TODO: need to do this only if in GS1 mode? or is the other code wrong? https://sourceforge.net/p/zint/tickets/104/#227b
if (inputData[j] == '%') {
percent++;
}
}
}
alphaLength += percent;
switch (alphaLength % 2) {
case 0:
count += (alphaLength / 2) * 11;
break;
case 1:
count += ((alphaLength - 1) / 2) * 11;
count += 6;
break;
}
break;
case NUMERIC:
count += tribus(version, 10, 12, 14);
switch (blockLength(i, inputMode) % 3) {
case 0:
count += (blockLength(i, inputMode) / 3) * 10;
break;
case 1:
count += ((blockLength(i, inputMode) - 1) / 3) * 10;
count += 4;
break;
case 2:
count += ((blockLength(i, inputMode) - 2) / 3) * 10;
count += 7;
break;
}
break;
}
currentMode = inputMode[i];
}
}
return count;
}
|
java
|
{
"resource": ""
}
|
q3908
|
QrCode.blockLength
|
train
|
private static int blockLength(int start, QrMode[] inputMode) {
QrMode mode = inputMode[start];
int count = 0;
int i = start;
do {
count++;
} while (((i + count) < inputMode.length) && (inputMode[i + count] == mode));
return count;
}
|
java
|
{
"resource": ""
}
|
q3909
|
QrCode.tribus
|
train
|
private static int tribus(int version, int a, int b, int c) {
if (version < 10) {
return a;
} else if (version >= 10 && version <= 26) {
return b;
} else {
return c;
}
}
|
java
|
{
"resource": ""
}
|
q3910
|
QrCode.addEcc
|
train
|
private static void addEcc(int[] fullstream, int[] datastream, int version, int data_cw, int blocks) {
int ecc_cw = QR_TOTAL_CODEWORDS[version - 1] - data_cw;
int short_data_block_length = data_cw / blocks;
int qty_long_blocks = data_cw % blocks;
int qty_short_blocks = blocks - qty_long_blocks;
int ecc_block_length = ecc_cw / blocks;
int i, j, length_this_block, posn;
int[] data_block = new int[short_data_block_length + 2];
int[] ecc_block = new int[ecc_block_length + 2];
int[] interleaved_data = new int[data_cw + 2];
int[] interleaved_ecc = new int[ecc_cw + 2];
posn = 0;
for (i = 0; i < blocks; i++) {
if (i < qty_short_blocks) {
length_this_block = short_data_block_length;
} else {
length_this_block = short_data_block_length + 1;
}
for (j = 0; j < ecc_block_length; j++) {
ecc_block[j] = 0;
}
for (j = 0; j < length_this_block; j++) {
data_block[j] = datastream[posn + j];
}
ReedSolomon rs = new ReedSolomon();
rs.init_gf(0x11d);
rs.init_code(ecc_block_length, 0);
rs.encode(length_this_block, data_block);
for (j = 0; j < ecc_block_length; j++) {
ecc_block[j] = rs.getResult(j);
}
for (j = 0; j < short_data_block_length; j++) {
interleaved_data[(j * blocks) + i] = data_block[j];
}
if (i >= qty_short_blocks) {
interleaved_data[(short_data_block_length * blocks) + (i - qty_short_blocks)] = data_block[short_data_block_length];
}
for (j = 0; j < ecc_block_length; j++) {
interleaved_ecc[(j * blocks) + i] = ecc_block[ecc_block_length - j - 1];
}
posn += length_this_block;
}
for (j = 0; j < data_cw; j++) {
fullstream[j] = interleaved_data[j];
}
for (j = 0; j < ecc_cw; j++) {
fullstream[j + data_cw] = interleaved_ecc[j];
}
}
|
java
|
{
"resource": ""
}
|
q3911
|
QrCode.addFormatInfoEval
|
train
|
private static void addFormatInfoEval(byte[] eval, int size, EccLevel ecc_level, int pattern) {
int format = pattern;
int seq;
int i;
switch(ecc_level) {
case L: format += 0x08; break;
case Q: format += 0x18; break;
case H: format += 0x10; break;
}
seq = QR_ANNEX_C[format];
for (i = 0; i < 6; i++) {
eval[(i * size) + 8] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);
}
for (i = 0; i < 8; i++) {
eval[(8 * size) + (size - i - 1)] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);
}
for (i = 0; i < 6; i++) {
eval[(8 * size) + (5 - i)] = (byte) ((((seq >> (i + 9)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);
}
for (i = 0; i < 7; i++) {
eval[(((size - 7) + i) * size) + 8] = (byte) ((((seq >> (i + 8)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);
}
eval[(7 * size) + 8] = (byte) ((((seq >> 6) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);
eval[(8 * size) + 8] = (byte) ((((seq >> 7) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);
eval[(8 * size) + 7] = (byte) ((((seq >> 8) & 0x01) != 0) ? (0x01 >> pattern) : 0x00);
}
|
java
|
{
"resource": ""
}
|
q3912
|
QrCode.addVersionInfo
|
train
|
private static void addVersionInfo(byte[] grid, int size, int version) {
// TODO: Zint masks with 0x41 instead of 0x01; which is correct? https://sourceforge.net/p/zint/tickets/110/
long version_data = QR_ANNEX_D[version - 7];
for (int i = 0; i < 6; i++) {
grid[((size - 11) * size) + i] += (version_data >> (i * 3)) & 0x01;
grid[((size - 10) * size) + i] += (version_data >> ((i * 3) + 1)) & 0x01;
grid[((size - 9) * size) + i] += (version_data >> ((i * 3) + 2)) & 0x01;
grid[(i * size) + (size - 11)] += (version_data >> (i * 3)) & 0x01;
grid[(i * size) + (size - 10)] += (version_data >> ((i * 3) + 1)) & 0x01;
grid[(i * size) + (size - 9)] += (version_data >> ((i * 3) + 2)) & 0x01;
}
}
|
java
|
{
"resource": ""
}
|
q3913
|
Pdf417.createBlocks
|
train
|
private static List< Block > createBlocks(int[] data, boolean debug) {
List< Block > blocks = new ArrayList<>();
Block current = null;
for (int i = 0; i < data.length; i++) {
EncodingMode mode = chooseMode(data[i]);
if ((current != null && current.mode == mode) &&
(mode != EncodingMode.NUM || current.length < MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {
current.length++;
} else {
current = new Block(mode);
blocks.add(current);
}
}
if (debug) {
System.out.println("Initial block pattern: " + blocks);
}
smoothBlocks(blocks);
if (debug) {
System.out.println("Final block pattern: " + blocks);
}
return blocks;
}
|
java
|
{
"resource": ""
}
|
q3914
|
Pdf417.mergeBlocks
|
train
|
private static void mergeBlocks(List< Block > blocks) {
for (int i = 1; i < blocks.size(); i++) {
Block b1 = blocks.get(i - 1);
Block b2 = blocks.get(i);
if ((b1.mode == b2.mode) &&
(b1.mode != EncodingMode.NUM || b1.length + b2.length <= MAX_NUMERIC_COMPACTION_BLOCK_SIZE)) {
b1.length += b2.length;
blocks.remove(i);
i--;
}
}
}
|
java
|
{
"resource": ""
}
|
q3915
|
Symbol.eciProcess
|
train
|
protected void eciProcess() {
EciMode eci = EciMode.of(content, "ISO8859_1", 3)
.or(content, "ISO8859_2", 4)
.or(content, "ISO8859_3", 5)
.or(content, "ISO8859_4", 6)
.or(content, "ISO8859_5", 7)
.or(content, "ISO8859_6", 8)
.or(content, "ISO8859_7", 9)
.or(content, "ISO8859_8", 10)
.or(content, "ISO8859_9", 11)
.or(content, "ISO8859_10", 12)
.or(content, "ISO8859_11", 13)
.or(content, "ISO8859_13", 15)
.or(content, "ISO8859_14", 16)
.or(content, "ISO8859_15", 17)
.or(content, "ISO8859_16", 18)
.or(content, "Windows_1250", 21)
.or(content, "Windows_1251", 22)
.or(content, "Windows_1252", 23)
.or(content, "Windows_1256", 24)
.or(content, "SJIS", 20)
.or(content, "UTF8", 26);
if (EciMode.NONE.equals(eci)) {
throw new OkapiException("Unable to determine ECI mode.");
}
eciMode = eci.mode;
inputData = toBytes(content, eci.charset);
encodeInfo += "ECI Mode: " + eci.mode + "\n";
encodeInfo += "ECI Charset: " + eci.charset.name() + "\n";
}
|
java
|
{
"resource": ""
}
|
q3916
|
Symbol.mergeVerticalBlocks
|
train
|
protected void mergeVerticalBlocks() {
for(int i = 0; i < rectangles.size() - 1; i++) {
for(int j = i + 1; j < rectangles.size(); j++) {
Rectangle2D.Double firstRect = rectangles.get(i);
Rectangle2D.Double secondRect = rectangles.get(j);
if (roughlyEqual(firstRect.x, secondRect.x) && roughlyEqual(firstRect.width, secondRect.width)) {
if (roughlyEqual(firstRect.y + firstRect.height, secondRect.y)) {
firstRect.height += secondRect.height;
rectangles.set(i, firstRect);
rectangles.remove(j);
}
}
}
}
}
|
java
|
{
"resource": ""
}
|
q3917
|
Symbol.hibcProcess
|
train
|
private String hibcProcess(String source) {
// HIBC 2.6 allows up to 110 characters, not including the "+" prefix or the check digit
if (source.length() > 110) {
throw new OkapiException("Data too long for HIBC LIC");
}
source = source.toUpperCase();
if (!source.matches("[A-Z0-9-\\. \\$/+\\%]+?")) {
throw new OkapiException("Invalid characters in input");
}
int counter = 41;
for (int i = 0; i < source.length(); i++) {
counter += positionOf(source.charAt(i), HIBC_CHAR_TABLE);
}
counter = counter % 43;
char checkDigit = HIBC_CHAR_TABLE[counter];
encodeInfo += "HIBC Check Digit Counter: " + counter + "\n";
encodeInfo += "HIBC Check Digit: " + checkDigit + "\n";
return "+" + source + checkDigit;
}
|
java
|
{
"resource": ""
}
|
q3918
|
Symbol.getPatternAsCodewords
|
train
|
protected int[] getPatternAsCodewords(int size) {
if (size >= 10) {
throw new IllegalArgumentException("Pattern groups of 10 or more digits are likely to be too large to parse as integers.");
}
if (pattern == null || pattern.length == 0) {
return new int[0];
} else {
int count = (int) Math.ceil(pattern[0].length() / (double) size);
int[] codewords = new int[pattern.length * count];
for (int i = 0; i < pattern.length; i++) {
String row = pattern[i];
for (int j = 0; j < count; j++) {
int substringStart = j * size;
int substringEnd = Math.min((j + 1) * size, row.length());
codewords[(i * count) + j] = Integer.parseInt(row.substring(substringStart, substringEnd));
}
}
return codewords;
}
}
|
java
|
{
"resource": ""
}
|
q3919
|
FilterMenuLayout.arcAngle
|
train
|
private static double arcAngle(Point center, Point a, Point b, Rect area, int radius) {
double angle = threePointsAngle(center, a, b);
Point innerPoint = findMidnormalPoint(center, a, b, area, radius);
Point midInsectPoint = new Point((a.x + b.x) / 2, (a.y + b.y) / 2);
double distance = pointsDistance(midInsectPoint, innerPoint);
if (distance > radius) {
return 360 - angle;
}
return angle;
}
|
java
|
{
"resource": ""
}
|
q3920
|
FilterMenuLayout.findMidnormalPoint
|
train
|
private static Point findMidnormalPoint(Point center, Point a, Point b, Rect area, int radius) {
if (a.y == b.y) {
//top
if (a.y < center.y) {
return new Point((a.x + b.x) / 2, center.y + radius);
}
//bottom
return new Point((a.x + b.x) / 2, center.y - radius);
}
if (a.x == b.x) {
//left
if (a.x < center.x) {
return new Point(center.x + radius, (a.y + b.y) / 2);
}
//right
return new Point(center.x - radius, (a.y + b.y) / 2);
}
//slope of line ab
double abSlope = (a.y - b.y) / (a.x - b.x * 1.0);
//slope of midnormal
double midnormalSlope = -1.0 / abSlope;
double radian = Math.tan(midnormalSlope);
int dy = (int) (radius * Math.sin(radian));
int dx = (int) (radius * Math.cos(radian));
Point point = new Point(center.x + dx, center.y + dy);
if (!inArea(point, area, 0)) {
point = new Point(center.x - dx, center.y - dy);
}
return point;
}
|
java
|
{
"resource": ""
}
|
q3921
|
FilterMenuLayout.inArea
|
train
|
public static boolean inArea(Point point, Rect area, float offsetRatio) {
int offset = (int) (area.width() * offsetRatio);
return point.x >= area.left - offset && point.x <= area.right + offset &&
point.y >= area.top - offset && point.y <= area.bottom + offset;
}
|
java
|
{
"resource": ""
}
|
q3922
|
FilterMenuLayout.threePointsAngle
|
train
|
private static double threePointsAngle(Point vertex, Point A, Point B) {
double b = pointsDistance(vertex, A);
double c = pointsDistance(A, B);
double a = pointsDistance(B, vertex);
return Math.toDegrees(Math.acos((a * a + b * b - c * c) / (2 * a * b)));
}
|
java
|
{
"resource": ""
}
|
q3923
|
FilterMenuLayout.pointsDistance
|
train
|
private static double pointsDistance(Point a, Point b) {
int dx = b.x - a.x;
int dy = b.y - a.y;
return Math.sqrt(dx * dx + dy * dy);
}
|
java
|
{
"resource": ""
}
|
q3924
|
FilterMenuLayout.calculateMenuItemPosition
|
train
|
private void calculateMenuItemPosition() {
float itemRadius = (expandedRadius + collapsedRadius) / 2, f;
RectF area = new RectF(
center.x - itemRadius,
center.y - itemRadius,
center.x + itemRadius,
center.y + itemRadius);
Path path = new Path();
path.addArc(area, (float) fromAngle, (float) (toAngle - fromAngle));
PathMeasure measure = new PathMeasure(path, false);
float len = measure.getLength();
int divisor = getChildCount();
float divider = len / divisor;
for (int i = 0; i < getChildCount(); i++) {
float[] coords = new float[2];
measure.getPosTan(i * divider + divider * .5f, coords, null);
FilterMenu.Item item = (FilterMenu.Item) getChildAt(i).getTag();
item.setX((int) coords[0] - item.getView().getMeasuredWidth() / 2);
item.setY((int) coords[1] - item.getView().getMeasuredHeight() / 2);
}
}
|
java
|
{
"resource": ""
}
|
q3925
|
FilterMenuLayout.isClockwise
|
train
|
private boolean isClockwise(Point center, Point a, Point b) {
double cross = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);
return cross > 0;
}
|
java
|
{
"resource": ""
}
|
q3926
|
FormInput.inputValues
|
train
|
public void inputValues(boolean... values) {
for (boolean value : values) {
InputValue inputValue = new InputValue();
inputValue.setChecked(value);
this.inputValues.add(inputValue);
}
}
|
java
|
{
"resource": ""
}
|
q3927
|
LblTree.clearTmpData
|
train
|
public void clearTmpData() {
for (Enumeration<?> e = breadthFirstEnumeration(); e.hasMoreElements(); ) {
((LblTree) e.nextElement()).setTmpData(null);
}
}
|
java
|
{
"resource": ""
}
|
q3928
|
XPathHelper.getXPathExpression
|
train
|
public static String getXPathExpression(Node node) {
Object xpathCache = node.getUserData(FULL_XPATH_CACHE);
if (xpathCache != null) {
return xpathCache.toString();
}
Node parent = node.getParentNode();
if ((parent == null) || parent.getNodeName().contains("#document")) {
String xPath = "/" + node.getNodeName() + "[1]";
node.setUserData(FULL_XPATH_CACHE, xPath, null);
return xPath;
}
if (node.hasAttributes() && node.getAttributes().getNamedItem("id") != null) {
String xPath = "//" + node.getNodeName() + "[@id = '"
+ node.getAttributes().getNamedItem("id").getNodeValue() + "']";
node.setUserData(FULL_XPATH_CACHE, xPath, null);
return xPath;
}
StringBuffer buffer = new StringBuffer();
if (parent != node) {
buffer.append(getXPathExpression(parent));
buffer.append("/");
}
buffer.append(node.getNodeName());
List<Node> mySiblings = getSiblings(parent, node);
for (int i = 0; i < mySiblings.size(); i++) {
Node el = mySiblings.get(i);
if (el.equals(node)) {
buffer.append('[').append(Integer.toString(i + 1)).append(']');
// Found so break;
break;
}
}
String xPath = buffer.toString();
node.setUserData(FULL_XPATH_CACHE, xPath, null);
return xPath;
}
|
java
|
{
"resource": ""
}
|
q3929
|
XPathHelper.getSiblings
|
train
|
public static List<Node> getSiblings(Node parent, Node element) {
List<Node> result = new ArrayList<>();
NodeList list = parent.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node el = list.item(i);
if (el.getNodeName().equals(element.getNodeName())) {
result.add(el);
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q3930
|
XPathHelper.evaluateXpathExpression
|
train
|
public static NodeList evaluateXpathExpression(String domStr, String xpathExpr)
throws XPathExpressionException, IOException {
Document dom = DomUtils.asDocument(domStr);
return evaluateXpathExpression(dom, xpathExpr);
}
|
java
|
{
"resource": ""
}
|
q3931
|
XPathHelper.evaluateXpathExpression
|
train
|
public static NodeList evaluateXpathExpression(Document dom, String xpathExpr)
throws XPathExpressionException {
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile(xpathExpr);
Object result = expr.evaluate(dom, XPathConstants.NODESET);
return (NodeList) result;
}
|
java
|
{
"resource": ""
}
|
q3932
|
XPathHelper.getXPathLocation
|
train
|
public static int getXPathLocation(String dom, String xpath) {
String dom_lower = dom.toLowerCase();
String xpath_lower = xpath.toLowerCase();
String[] elements = xpath_lower.split("/");
int pos = 0;
int temp;
int number;
for (String element : elements) {
if (!element.isEmpty() && !element.startsWith("@") && !element.contains("()")) {
if (element.contains("[")) {
try {
number =
Integer.parseInt(element.substring(element.indexOf("[") + 1,
element.indexOf("]")));
} catch (NumberFormatException e) {
return -1;
}
} else {
number = 1;
}
for (int i = 0; i < number; i++) {
// find new open element
temp = dom_lower.indexOf("<" + stripEndSquareBrackets(element), pos);
if (temp > -1) {
pos = temp + 1;
// if depth>1 then goto end of current element
if (number > 1 && i < number - 1) {
pos =
getCloseElementLocation(dom_lower, pos,
stripEndSquareBrackets(element));
}
}
}
}
}
return pos - 1;
}
|
java
|
{
"resource": ""
}
|
q3933
|
EditDistanceComparator.getThreshold
|
train
|
double getThreshold(String x, String y, double p) {
return 2 * Math.max(x.length(), y.length()) * (1 - p);
}
|
java
|
{
"resource": ""
}
|
q3934
|
JavaScriptCondition.check
|
train
|
@Override
public boolean check(EmbeddedBrowser browser) {
String js =
"try{ if(" + expression + "){return '1';}else{" + "return '0';}}catch(e){"
+ " return '0';}";
try {
Object object = browser.executeJavaScript(js);
if (object == null) {
return false;
}
return object.toString().equals("1");
} catch (CrawljaxException e) {
// Exception is caught, check failed so return false;
return false;
}
}
|
java
|
{
"resource": ""
}
|
q3935
|
XMLObject.objectToXML
|
train
|
public static void objectToXML(Object object, String fileName) throws FileNotFoundException {
FileOutputStream fo = new FileOutputStream(fileName);
XMLEncoder encoder = new XMLEncoder(fo);
encoder.writeObject(object);
encoder.close();
}
|
java
|
{
"resource": ""
}
|
q3936
|
XMLObject.xmlToObject
|
train
|
public static Object xmlToObject(String fileName) throws FileNotFoundException {
FileInputStream fi = new FileInputStream(fileName);
XMLDecoder decoder = new XMLDecoder(fi);
Object object = decoder.readObject();
decoder.close();
return object;
}
|
java
|
{
"resource": ""
}
|
q3937
|
Identification.getWebDriverBy
|
train
|
public By getWebDriverBy() {
switch (how) {
case name:
return By.name(this.value);
case xpath:
// Work around HLWK driver bug
return By.xpath(this.value.replaceAll("/BODY\\[1\\]/", "/BODY/"));
case id:
return By.id(this.value);
case tag:
return By.tagName(this.value);
case text:
return By.linkText(this.value);
case partialText:
return By.partialLinkText(this.value);
default:
return null;
}
}
|
java
|
{
"resource": ""
}
|
q3938
|
CrawlElement.escapeApostrophes
|
train
|
protected String escapeApostrophes(String text) {
String resultString;
if (text.contains("'")) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("concat('");
stringBuilder.append(text.replace("'", "',\"'\",'"));
stringBuilder.append("')");
resultString = stringBuilder.toString();
} else {
resultString = "'" + text + "'";
}
return resultString;
}
|
java
|
{
"resource": ""
}
|
q3939
|
CrawlController.call
|
train
|
@Override
public CrawlSession call() {
setMaximumCrawlTimeIfNeeded();
plugins.runPreCrawlingPlugins(config);
CrawlTaskConsumer firstConsumer = consumerFactory.get();
StateVertex firstState = firstConsumer.crawlIndex();
crawlSessionProvider.setup(firstState);
plugins.runOnNewStatePlugins(firstConsumer.getContext(), firstState);
executeConsumers(firstConsumer);
return crawlSessionProvider.get();
}
|
java
|
{
"resource": ""
}
|
q3940
|
CandidateElementExtractor.extract
|
train
|
public ImmutableList<CandidateElement> extract(StateVertex currentState)
throws CrawljaxException {
LinkedList<CandidateElement> results = new LinkedList<>();
if (!checkedElements.checkCrawlCondition(browser)) {
LOG.info("State {} did not satisfy the CrawlConditions.", currentState.getName());
return ImmutableList.of();
}
LOG.debug("Looking in state: {} for candidate elements", currentState.getName());
try {
Document dom = DomUtils.asDocument(browser.getStrippedDomWithoutIframeContent());
extractElements(dom, results, "");
} catch (IOException e) {
LOG.error(e.getMessage(), e);
throw new CrawljaxException(e);
}
if (randomizeElementsOrder) {
Collections.shuffle(results);
}
currentState.setElementsFound(results);
LOG.debug("Found {} new candidate elements to analyze!", results.size());
return ImmutableList.copyOf(results);
}
|
java
|
{
"resource": ""
}
|
q3941
|
CandidateElementExtractor.getNodeListForTagElement
|
train
|
private ImmutableList<Element> getNodeListForTagElement(Document dom,
CrawlElement crawlElement,
EventableConditionChecker eventableConditionChecker) {
Builder<Element> result = ImmutableList.builder();
if (crawlElement.getTagName() == null) {
return result.build();
}
EventableCondition eventableCondition =
eventableConditionChecker.getEventableCondition(crawlElement.getId());
// TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent
// performance problems.
ImmutableList<String> expressions = getFullXpathForGivenXpath(dom, eventableCondition);
NodeList nodeList = dom.getElementsByTagName(crawlElement.getTagName());
for (int k = 0; k < nodeList.getLength(); k++) {
Element element = (Element) nodeList.item(k);
boolean matchesXpath =
elementMatchesXpath(eventableConditionChecker, eventableCondition,
expressions, element);
LOG.debug("Element {} matches Xpath={}", DomUtils.getElementString(element),
matchesXpath);
/*
* TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return
* false and when needed to add it can return true. / check if element is a candidate
*/
String id = element.getNodeName() + ": " + DomUtils.getAllElementAttributes(element);
if (matchesXpath && !checkedElements.isChecked(id)
&& !isExcluded(dom, element, eventableConditionChecker)) {
addElement(element, result, crawlElement);
} else {
LOG.debug("Element {} was not added", element);
}
}
return result.build();
}
|
java
|
{
"resource": ""
}
|
q3942
|
Plugins.runOnInvariantViolationPlugins
|
train
|
public void runOnInvariantViolationPlugins(Invariant invariant,
CrawlerContext context) {
LOGGER.debug("Running OnInvariantViolationPlugins...");
counters.get(OnInvariantViolationPlugin.class).inc();
for (Plugin plugin : plugins.get(OnInvariantViolationPlugin.class)) {
if (plugin instanceof OnInvariantViolationPlugin) {
try {
LOGGER.debug("Calling plugin {}", plugin);
((OnInvariantViolationPlugin) plugin).onInvariantViolation(
invariant, context);
} catch (RuntimeException e) {
reportFailingPlugin(plugin, e);
}
}
}
}
|
java
|
{
"resource": ""
}
|
q3943
|
Plugins.runOnBrowserCreatedPlugins
|
train
|
public void runOnBrowserCreatedPlugins(EmbeddedBrowser newBrowser) {
LOGGER.debug("Running OnBrowserCreatedPlugins...");
counters.get(OnBrowserCreatedPlugin.class).inc();
for (Plugin plugin : plugins.get(OnBrowserCreatedPlugin.class)) {
if (plugin instanceof OnBrowserCreatedPlugin) {
LOGGER.debug("Calling plugin {}", plugin);
try {
((OnBrowserCreatedPlugin) plugin)
.onBrowserCreated(newBrowser);
} catch (RuntimeException e) {
reportFailingPlugin(plugin, e);
}
}
}
}
|
java
|
{
"resource": ""
}
|
q3944
|
Element.equalId
|
train
|
public boolean equalId(Element otherElement) {
if (getElementId() == null || otherElement.getElementId() == null) {
return false;
}
return getElementId().equalsIgnoreCase(otherElement.getElementId());
}
|
java
|
{
"resource": ""
}
|
q3945
|
Element.getElementId
|
train
|
public String getElementId() {
for (Entry<String, String> attribute : attributes.entrySet()) {
if (attribute.getKey().equalsIgnoreCase("id")) {
return attribute.getValue();
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q3946
|
EventableConditionChecker.checkXpathStartsWithXpathEventableCondition
|
train
|
public boolean checkXpathStartsWithXpathEventableCondition(Document dom,
EventableCondition eventableCondition, String xpath) throws XPathExpressionException {
if (eventableCondition == null || Strings
.isNullOrEmpty(eventableCondition.getInXPath())) {
throw new CrawljaxException("Eventable has no XPath condition");
}
List<String> expressions =
XPathHelper.getXpathForXPathExpressions(dom, eventableCondition.getInXPath());
return checkXPathUnderXPaths(xpath, expressions);
}
|
java
|
{
"resource": ""
}
|
q3947
|
RTEDUtils.getRobustTreeEditDistance
|
train
|
public static double getRobustTreeEditDistance(String dom1, String dom2) {
LblTree domTree1 = null, domTree2 = null;
try {
domTree1 = getDomTree(dom1);
domTree2 = getDomTree(dom2);
} catch (IOException e) {
e.printStackTrace();
}
double DD = 0.0;
RTED_InfoTree_Opt rted;
double ted;
rted = new RTED_InfoTree_Opt(1, 1, 1);
// compute tree edit distance
rted.init(domTree1, domTree2);
int maxSize = Math.max(domTree1.getNodeCount(), domTree2.getNodeCount());
rted.computeOptimalStrategy();
ted = rted.nonNormalizedTreeDist();
ted /= (double) maxSize;
DD = ted;
return DD;
}
|
java
|
{
"resource": ""
}
|
q3948
|
RTEDUtils.createTree
|
train
|
private static LblTree createTree(TreeWalker walker) {
Node parent = walker.getCurrentNode();
LblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1
for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) {
node.add(createTree(walker));
}
walker.setCurrentNode(parent);
return node;
}
|
java
|
{
"resource": ""
}
|
q3949
|
CrawlActionsBuilder.dontClickChildrenOf
|
train
|
public ExcludeByParentBuilder dontClickChildrenOf(String tagName) {
checkNotRead();
Preconditions.checkNotNull(tagName);
ExcludeByParentBuilder exclude = new ExcludeByParentBuilder(
tagName.toUpperCase());
crawlParentsExcluded.add(exclude);
return exclude;
}
|
java
|
{
"resource": ""
}
|
q3950
|
Form.inputField
|
train
|
public FormInput inputField(InputType type, Identification identification) {
FormInput input = new FormInput(type, identification);
this.formInputs.add(input);
return input;
}
|
java
|
{
"resource": ""
}
|
q3951
|
ParameterInterpeter.getOptions
|
train
|
private Options getOptions() {
Options options = new Options();
options.addOption("h", HELP, false, "print this message");
options.addOption(VERSION, false, "print the version information and exit");
options.addOption("b", BROWSER, true,
"browser type: " + availableBrowsers() + ". Default is Firefox");
options.addOption(BROWSER_REMOTE_URL, true,
"The remote url if you have configured a remote browser");
options.addOption("d", DEPTH, true, "crawl depth level. Default is 2");
options.addOption("s", MAXSTATES, true,
"max number of states to crawl. Default is 0 (unlimited)");
options.addOption("p", PARALLEL, true,
"Number of browsers to use for crawling. Default is 1");
options.addOption("o", OVERRIDE, false, "Override the output directory if non-empty");
options.addOption("a", CRAWL_HIDDEN_ANCHORS, false,
"Crawl anchors even if they are not visible in the browser.");
options.addOption("t", TIME_OUT, true,
"Specify the maximum crawl time in minutes");
options.addOption(CLICK, true,
"a comma separated list of HTML tags that should be clicked. Default is A and BUTTON");
options.addOption(WAIT_AFTER_EVENT, true,
"the time to wait after an event has been fired in milliseconds. Default is "
+ CrawlRules.DEFAULT_WAIT_AFTER_EVENT);
options.addOption(WAIT_AFTER_RELOAD, true,
"the time to wait after an URL has been loaded in milliseconds. Default is "
+ CrawlRules.DEFAULT_WAIT_AFTER_RELOAD);
options.addOption("v", VERBOSE, false, "Be extra verbose");
options.addOption(LOG_FILE, true, "Log to this file instead of the console");
return options;
}
|
java
|
{
"resource": ""
}
|
q3952
|
FSUtils.directoryCheck
|
train
|
public static void directoryCheck(String dir) throws IOException {
final File file = new File(dir);
if (!file.exists()) {
FileUtils.forceMkdir(file);
}
}
|
java
|
{
"resource": ""
}
|
q3953
|
FSUtils.checkFolderForFile
|
train
|
public static void checkFolderForFile(String fileName) throws IOException {
if (fileName.lastIndexOf(File.separator) > 0) {
String folder = fileName.substring(0, fileName.lastIndexOf(File.separator));
directoryCheck(folder);
}
}
|
java
|
{
"resource": ""
}
|
q3954
|
CandidateElementManager.markChecked
|
train
|
@GuardedBy("elementsLock")
@Override
public boolean markChecked(CandidateElement element) {
String generalString = element.getGeneralString();
String uniqueString = element.getUniqueString();
synchronized (elementsLock) {
if (elements.contains(uniqueString)) {
return false;
} else {
elements.add(generalString);
elements.add(uniqueString);
return true;
}
}
}
|
java
|
{
"resource": ""
}
|
q3955
|
CrawljaxRunner.readFormDataFromFile
|
train
|
private void readFormDataFromFile() {
List<FormInput> formInputList =
FormInputValueHelper.deserializeFormInputs(config.getSiteDir());
if (formInputList != null) {
InputSpecification inputSpecs = config.getCrawlRules().getInputSpecification();
for (FormInput input : formInputList) {
inputSpecs.inputField(input);
}
}
}
|
java
|
{
"resource": ""
}
|
q3956
|
CrawljaxRunner.call
|
train
|
@Override
public CrawlSession call() {
Injector injector = Guice.createInjector(new CoreModule(config));
controller = injector.getInstance(CrawlController.class);
CrawlSession session = controller.call();
reason = controller.getReason();
return session;
}
|
java
|
{
"resource": ""
}
|
q3957
|
DHash.distance
|
train
|
public static Integer distance(String h1, String h2) {
HammingDistance distance = new HammingDistance();
return distance.apply(h1, h2);
}
|
java
|
{
"resource": ""
}
|
q3958
|
FormInputValueHelper.getInstance
|
train
|
public static synchronized FormInputValueHelper getInstance(
InputSpecification inputSpecification, FormFillMode formFillMode) {
if (instance == null)
instance = new FormInputValueHelper(inputSpecification,
formFillMode);
return instance;
}
|
java
|
{
"resource": ""
}
|
q3959
|
FormInputValueHelper.formInputMatchingNode
|
train
|
private FormInput formInputMatchingNode(Node element) {
NamedNodeMap attributes = element.getAttributes();
Identification id;
if (attributes.getNamedItem("id") != null
&& formFillMode != FormFillMode.XPATH_TRAINING) {
id = new Identification(Identification.How.id,
attributes.getNamedItem("id").getNodeValue());
FormInput input = this.formInputs.get(id);
if (input != null) {
return input;
}
}
if (attributes.getNamedItem("name") != null
&& formFillMode != FormFillMode.XPATH_TRAINING) {
id = new Identification(Identification.How.name,
attributes.getNamedItem("name").getNodeValue());
FormInput input = this.formInputs.get(id);
if (input != null) {
return input;
}
}
String xpathExpr = XPathHelper.getXPathExpression(element);
if (xpathExpr != null && !xpathExpr.equals("")) {
id = new Identification(Identification.How.xpath, xpathExpr);
FormInput input = this.formInputs.get(id);
if (input != null) {
return input;
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q3960
|
Crawler.reset
|
train
|
public void reset() {
CrawlSession session = context.getSession();
if (crawlpath != null) {
session.addCrawlPath(crawlpath);
}
List<StateVertex> onURLSetTemp = new ArrayList<>();
if (stateMachine != null)
onURLSetTemp = stateMachine.getOnURLSet();
stateMachine = new StateMachine(graphProvider.get(), crawlRules.getInvariants(), plugins,
stateComparator, onURLSetTemp);
context.setStateMachine(stateMachine);
crawlpath = new CrawlPath();
context.setCrawlPath(crawlpath);
browser.handlePopups();
browser.goToUrl(url);
// Checks the landing page for URL and sets the current page accordingly
checkOnURLState();
plugins.runOnUrlLoadPlugins(context);
crawlDepth.set(0);
}
|
java
|
{
"resource": ""
}
|
q3961
|
Crawler.fireEvent
|
train
|
private boolean fireEvent(Eventable eventable) {
Eventable eventToFire = eventable;
if (eventable.getIdentification().getHow().toString().equals("xpath")
&& eventable.getRelatedFrame().equals("")) {
eventToFire = resolveByXpath(eventable, eventToFire);
}
boolean isFired = false;
try {
isFired = browser.fireEventAndWait(eventToFire);
} catch (ElementNotVisibleException | NoSuchElementException e) {
if (crawlRules.isCrawlHiddenAnchors() && eventToFire.getElement() != null
&& "A".equals(eventToFire.getElement().getTag())) {
isFired = visitAnchorHrefIfPossible(eventToFire);
} else {
LOG.debug("Ignoring invisible element {}", eventToFire.getElement());
}
} catch (InterruptedException e) {
LOG.debug("Interrupted during fire event");
interruptThread();
return false;
}
LOG.debug("Event fired={} for eventable {}", isFired, eventable);
if (isFired) {
// Let the controller execute its specified wait operation on the browser thread safe.
waitConditionChecker.wait(browser);
browser.closeOtherWindows();
return true;
} else {
/*
* Execute the OnFireEventFailedPlugins with the current crawlPath with the crawlPath
* removed 1 state to represent the path TO here.
*/
plugins.runOnFireEventFailedPlugins(context, eventable,
crawlpath.immutableCopyWithoutLast());
return false; // no event fired
}
}
|
java
|
{
"resource": ""
}
|
q3962
|
Crawler.crawlIndex
|
train
|
public StateVertex crawlIndex() {
LOG.debug("Setting up vertex of the index page");
if (basicAuthUrl != null) {
browser.goToUrl(basicAuthUrl);
}
browser.goToUrl(url);
// Run url first load plugin to clear the application state
plugins.runOnUrlFirstLoadPlugins(context);
plugins.runOnUrlLoadPlugins(context);
StateVertex index = vertexFactory.createIndex(url.toString(), browser.getStrippedDom(),
stateComparator.getStrippedDom(browser), browser);
Preconditions.checkArgument(index.getId() == StateVertex.INDEX_ID,
"It seems some the index state is crawled more than once.");
LOG.debug("Parsing the index for candidate elements");
ImmutableList<CandidateElement> extract = candidateExtractor.extract(index);
plugins.runPreStateCrawlingPlugins(context, extract, index);
candidateActionCache.addActions(extract, index);
return index;
}
|
java
|
{
"resource": ""
}
|
q3963
|
RTED_InfoTree_Opt.nonNormalizedTreeDist
|
train
|
public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {
init(t1, t2);
STR = new int[size1][size2];
computeOptimalStrategy();
return computeDistUsingStrArray(it1, it2);
}
|
java
|
{
"resource": ""
}
|
q3964
|
RTED_InfoTree_Opt.init
|
train
|
public void init(LblTree t1, LblTree t2) {
LabelDictionary ld = new LabelDictionary();
it1 = new InfoTree(t1, ld);
it2 = new InfoTree(t2, ld);
size1 = it1.getSize();
size2 = it2.getSize();
IJ = new int[Math.max(size1, size2)][Math.max(size1, size2)];
delta = new double[size1][size2];
deltaBit = new byte[size1][size2];
costV = new long[3][size1][size2];
costW = new long[3][size2];
// Calculate delta between every leaf in G (empty tree) and all the nodes in F.
// Calculate it both sides: leafs of F and nodes of G & leafs of G and nodes of
// F.
int[] labels1 = it1.getInfoArray(POST2_LABEL);
int[] labels2 = it2.getInfoArray(POST2_LABEL);
int[] sizes1 = it1.getInfoArray(POST2_SIZE);
int[] sizes2 = it2.getInfoArray(POST2_SIZE);
for (int x = 0; x < sizes1.length; x++) { // for all nodes of initially left tree
for (int y = 0; y < sizes2.length; y++) { // for all nodes of initially right tree
// This is an attempt for distances of single-node subtree and anything alse
// The differences between pairs of labels are stored
if (labels1[x] == labels2[y]) {
deltaBit[x][y] = 0;
} else {
deltaBit[x][y] =
1; // if this set, the labels differ, cost of relabeling is set
// to costMatch
}
if (sizes1[x] == 1 && sizes2[y] == 1) { // both nodes are leafs
delta[x][y] = 0;
} else {
if (sizes1[x] == 1) {
delta[x][y] = sizes2[y] - 1;
}
if (sizes2[y] == 1) {
delta[x][y] = sizes1[x] - 1;
}
}
}
}
}
|
java
|
{
"resource": ""
}
|
q3965
|
StateMachine.changeState
|
train
|
public boolean changeState(StateVertex nextState) {
if (nextState == null) {
LOGGER.info("nextState given is null");
return false;
}
LOGGER.debug("Trying to change to state: '{}' from: '{}'", nextState.getName(),
currentState.getName());
if (stateFlowGraph.canGoTo(currentState, nextState)) {
LOGGER.debug("Changed to state: '{}' from: '{}'", nextState.getName(),
currentState.getName());
setCurrentState(nextState);
return true;
} else {
LOGGER.info("Cannot go to state: '{}' from: '{}'", nextState.getName(),
currentState.getName());
return false;
}
}
|
java
|
{
"resource": ""
}
|
q3966
|
StateMachine.addStateToCurrentState
|
train
|
private StateVertex addStateToCurrentState(StateVertex newState, Eventable eventable) {
LOGGER.debug("addStateToCurrentState currentState: {} newState {}",
currentState.getName(), newState.getName());
// Add the state to the stateFlowGraph. Store the result
StateVertex cloneState = stateFlowGraph.putIfAbsent(newState);
// Is there a clone detected?
if (cloneState != null) {
LOGGER.info("CLONE State detected: {} and {} are the same.", newState.getName(),
cloneState.getName());
LOGGER.debug("CLONE CURRENT STATE: {}", currentState.getName());
LOGGER.debug("CLONE STATE: {}", cloneState.getName());
LOGGER.debug("CLONE CLICKABLE: {}", eventable);
boolean added = stateFlowGraph.addEdge(currentState, cloneState, eventable);
if (!added) {
LOGGER.debug("Clone edge !! Need to fix the crawlPath??");
}
} else {
stateFlowGraph.addEdge(currentState, newState, eventable);
LOGGER.info("State {} added to the StateMachine.", newState.getName());
}
return cloneState;
}
|
java
|
{
"resource": ""
}
|
q3967
|
StateMachine.switchToStateAndCheckIfClone
|
train
|
public boolean switchToStateAndCheckIfClone(final Eventable event, StateVertex newState,
CrawlerContext context) {
StateVertex cloneState = this.addStateToCurrentState(newState, event);
runOnInvariantViolationPlugins(context);
if (cloneState == null) {
changeState(newState);
plugins.runOnNewStatePlugins(context, newState);
return true;
} else {
changeState(cloneState);
return false;
}
}
|
java
|
{
"resource": ""
}
|
q3968
|
LogUtil.logToFile
|
train
|
@SuppressWarnings("unchecked")
static void logToFile(String filename) {
Logger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
FileAppender<ILoggingEvent> fileappender = new FileAppender<>();
fileappender.setContext(rootLogger.getLoggerContext());
fileappender.setFile(filename);
fileappender.setName("FILE");
ConsoleAppender<?> console = (ConsoleAppender<?>) rootLogger.getAppender("STDOUT");
fileappender.setEncoder((Encoder<ILoggingEvent>) console.getEncoder());
fileappender.start();
rootLogger.addAppender(fileappender);
console.stop();
}
|
java
|
{
"resource": ""
}
|
q3969
|
JarRunner.main
|
train
|
public static void main(String[] args) {
try {
JarRunner runner = new JarRunner(args);
runner.runIfConfigured();
} catch (NumberFormatException e) {
System.err.println("Could not parse number " + e.getMessage());
System.exit(1);
} catch (RuntimeException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
|
java
|
{
"resource": ""
}
|
q3970
|
Serializer.toPrettyJson
|
train
|
public static String toPrettyJson(Object o) {
try {
return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(o);
} catch (JsonProcessingException e) {
LoggerFactory
.getLogger(Serializer.class)
.error("Could not serialize the object. This will be ignored and the error will be written instead. Object was {}",
o, e);
return "\"" + e.getMessage() + "\"";
}
}
|
java
|
{
"resource": ""
}
|
q3971
|
InfoTree.postTraversalProcessing
|
train
|
private void postTraversalProcessing() {
int nc1 = treeSize;
info[KR] = new int[leafCount];
info[RKR] = new int[leafCount];
int lc = leafCount;
int i = 0;
// compute left-most leaf descendants
// go along the left-most path, remember each node and assign to it the path's
// leaf
// compute right-most leaf descendants (in reversed postorder)
for (i = 0; i < treeSize; i++) {
if (paths[LEFT][i] == -1) {
info[POST2_LLD][i] = i;
} else {
info[POST2_LLD][i] = info[POST2_LLD][paths[LEFT][i]];
}
if (paths[RIGHT][i] == -1) {
info[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =
(treeSize - 1 - info[POST2_PRE][i]);
} else {
info[RPOST2_RLD][treeSize - 1 - info[POST2_PRE][i]] =
info[RPOST2_RLD][treeSize - 1
- info[POST2_PRE][paths[RIGHT][i]]];
}
}
// compute key root nodes
// compute reversed key root nodes (in revrsed postorder)
boolean[] visited = new boolean[nc1];
boolean[] visitedR = new boolean[nc1];
Arrays.fill(visited, false);
int k = lc - 1;
int kR = lc - 1;
for (i = nc1 - 1; i >= 0; i--) {
if (!visited[info[POST2_LLD][i]]) {
info[KR][k] = i;
visited[info[POST2_LLD][i]] = true;
k--;
}
if (!visitedR[info[RPOST2_RLD][i]]) {
info[RKR][kR] = i;
visitedR[info[RPOST2_RLD][i]] = true;
kR--;
}
}
// compute minimal key roots for every subtree
// compute minimal reversed key roots for every subtree (in reversed postorder)
int parent = -1;
int parentR = -1;
for (i = 0; i < leafCount; i++) {
parent = info[KR][i];
while (parent > -1 && info[POST2_MIN_KR][parent] == -1) {
info[POST2_MIN_KR][parent] = i;
parent = info[POST2_PARENT][parent];
}
parentR = info[RKR][i];
while (parentR > -1 && info[RPOST2_MIN_RKR][parentR] == -1) {
info[RPOST2_MIN_RKR][parentR] = i;
parentR =
info[POST2_PARENT][info[RPOST2_POST][parentR]]; // get parent's postorder
if (parentR > -1) {
parentR = treeSize - 1 - info[POST2_PRE][parentR]; // if parent exists get its
// rev. postorder
}
}
}
}
|
java
|
{
"resource": ""
}
|
q3972
|
InfoTree.toIntArray
|
train
|
static int[] toIntArray(List<Integer> integers) {
int[] ints = new int[integers.size()];
int i = 0;
for (Integer n : integers) {
ints[i++] = n;
}
return ints;
}
|
java
|
{
"resource": ""
}
|
q3973
|
CrawlOverview.onNewState
|
train
|
@Override
public void onNewState(CrawlerContext context, StateVertex vertex) {
LOG.debug("onNewState");
StateBuilder state = outModelCache.addStateIfAbsent(vertex);
visitedStates.putIfAbsent(state.getName(), vertex);
saveScreenshot(context.getBrowser(), state.getName(), vertex);
outputBuilder.persistDom(state.getName(), context.getBrowser().getUnStrippedDom());
}
|
java
|
{
"resource": ""
}
|
q3974
|
CrawlOverview.preStateCrawling
|
train
|
@Override
public void preStateCrawling(CrawlerContext context,
ImmutableList<CandidateElement> candidateElements, StateVertex state) {
LOG.debug("preStateCrawling");
List<CandidateElementPosition> newElements = Lists.newLinkedList();
LOG.info("Prestate found new state {} with {} candidates", state.getName(),
candidateElements.size());
for (CandidateElement element : candidateElements) {
try {
WebElement webElement = getWebElement(context.getBrowser(), element);
if (webElement != null) {
newElements.add(findElement(webElement, element));
}
} catch (WebDriverException e) {
LOG.info("Could not get position for {}", element, e);
}
}
StateBuilder stateOut = outModelCache.addStateIfAbsent(state);
stateOut.addCandidates(newElements);
LOG.trace("preState finished, elements added to state");
}
|
java
|
{
"resource": ""
}
|
q3975
|
CrawlOverview.postCrawling
|
train
|
@Override
public void postCrawling(CrawlSession session, ExitStatus exitStatus) {
LOG.debug("postCrawling");
StateFlowGraph sfg = session.getStateFlowGraph();
checkSFG(sfg);
// TODO: call state abstraction function to get distance matrix and run rscript on it to
// create clusters
String[][] clusters = null;
// generateClusters(session);
result = outModelCache.close(session, exitStatus, clusters);
outputBuilder.write(result, session.getConfig(), clusters);
StateWriter writer =
new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));
for (State state : result.getStates().values()) {
try {
writer.writeHtmlForState(state);
} catch (Exception Ex) {
LOG.info("couldn't write state :" + state.getName());
}
}
LOG.info("Crawl overview plugin has finished");
}
|
java
|
{
"resource": ""
}
|
q3976
|
InputSpecification.setValuesInForm
|
train
|
public FormAction setValuesInForm(Form form) {
FormAction formAction = new FormAction();
form.setFormAction(formAction);
this.forms.add(form);
return formAction;
}
|
java
|
{
"resource": ""
}
|
q3977
|
DomUtils.removeTags
|
train
|
public static Document removeTags(Document dom, String tagName) {
NodeList list;
try {
list = XPathHelper.evaluateXpathExpression(dom,
"//" + tagName.toUpperCase());
while (list.getLength() > 0) {
Node sc = list.item(0);
if (sc != null) {
sc.getParentNode().removeChild(sc);
}
list = XPathHelper.evaluateXpathExpression(dom,
"//" + tagName.toUpperCase());
}
} catch (XPathExpressionException e) {
LOGGER.error("Error while removing tag " + tagName, e);
}
return dom;
}
|
java
|
{
"resource": ""
}
|
q3978
|
DomUtils.getDocumentToByteArray
|
train
|
public static byte[] getDocumentToByteArray(Document dom) {
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer
.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "html");
// TODO should be fixed to read doctype declaration
transformer
.setOutputProperty(
OutputKeys.DOCTYPE_PUBLIC,
"-//W3C//DTD XHTML 1.0 Strict//EN\" "
+ "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
DOMSource source = new DOMSource(dom);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Result result = new StreamResult(out);
transformer.transform(source, result);
return out.toByteArray();
} catch (TransformerException e) {
LOGGER.error("Error while converting the document to a byte array",
e);
}
return null;
}
|
java
|
{
"resource": ""
}
|
q3979
|
DomUtils.addFolderSlashIfNeeded
|
train
|
public static String addFolderSlashIfNeeded(String folderName) {
if (!"".equals(folderName) && !folderName.endsWith("/")) {
return folderName + "/";
} else {
return folderName;
}
}
|
java
|
{
"resource": ""
}
|
q3980
|
DomUtils.getTemplateAsString
|
train
|
public static String getTemplateAsString(String fileName) throws IOException {
// in .jar file
String fNameJar = getFileNameInPath(fileName);
InputStream inStream = DomUtils.class.getResourceAsStream("/"
+ fNameJar);
if (inStream == null) {
// try to find file normally
File f = new File(fileName);
if (f.exists()) {
inStream = new FileInputStream(f);
} else {
throw new IOException("Cannot find " + fileName + " or "
+ fNameJar);
}
}
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inStream));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
|
java
|
{
"resource": ""
}
|
q3981
|
DomUtils.writeDocumentToFile
|
train
|
public static void writeDocumentToFile(Document document,
String filePathname, String method, int indent)
throws TransformerException, IOException {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, method);
transformer.transform(new DOMSource(document), new StreamResult(
new FileOutputStream(filePathname)));
}
|
java
|
{
"resource": ""
}
|
q3982
|
DomUtils.getTextContent
|
train
|
public static String getTextContent(Document document, boolean individualTokens) {
String textContent = null;
if (individualTokens) {
List<String> tokens = getTextTokens(document);
textContent = StringUtils.join(tokens, ",");
} else {
textContent =
document.getDocumentElement().getTextContent().trim().replaceAll("\\s+", ",");
}
return textContent;
}
|
java
|
{
"resource": ""
}
|
q3983
|
ElementResolver.equivalent
|
train
|
public boolean equivalent(Element otherElement, boolean logging) {
if (eventable.getElement().equals(otherElement)) {
if (logging) {
LOGGER.info("Element equal");
}
return true;
}
if (eventable.getElement().equalAttributes(otherElement)) {
if (logging) {
LOGGER.info("Element attributes equal");
}
return true;
}
if (eventable.getElement().equalId(otherElement)) {
if (logging) {
LOGGER.info("Element ID equal");
}
return true;
}
if (!eventable.getElement().getText().equals("")
&& eventable.getElement().equalText(otherElement)) {
if (logging) {
LOGGER.info("Element text equal");
}
return true;
}
return false;
}
|
java
|
{
"resource": ""
}
|
q3984
|
DOMComparer.compare
|
train
|
@SuppressWarnings("unchecked")
public List<Difference> compare() {
Diff diff = new Diff(this.controlDOM, this.testDOM);
DetailedDiff detDiff = new DetailedDiff(diff);
return detDiff.getAllDifferences();
}
|
java
|
{
"resource": ""
}
|
q3985
|
FormHandler.setInputElementValue
|
train
|
protected void setInputElementValue(Node element, FormInput input) {
LOGGER.debug("INPUTFIELD: {} ({})", input.getIdentification(), input.getType());
if (element == null || input.getInputValues().isEmpty()) {
return;
}
try {
switch (input.getType()) {
case TEXT:
case TEXTAREA:
case PASSWORD:
handleText(input);
break;
case HIDDEN:
handleHidden(input);
break;
case CHECKBOX:
handleCheckBoxes(input);
break;
case RADIO:
handleRadioSwitches(input);
break;
case SELECT:
handleSelectBoxes(input);
}
} catch (ElementNotVisibleException e) {
LOGGER.warn("Element not visible, input not completed.");
} catch (BrowserConnectionException e) {
throw e;
} catch (RuntimeException e) {
LOGGER.error("Could not input element values", e);
}
}
|
java
|
{
"resource": ""
}
|
q3986
|
FormHandler.handleHidden
|
train
|
private void handleHidden(FormInput input) {
String text = input.getInputValues().iterator().next().getValue();
if (null == text || text.length() == 0) {
return;
}
WebElement inputElement = browser.getWebElement(input.getIdentification());
JavascriptExecutor js = (JavascriptExecutor) browser.getWebDriver();
js.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);", inputElement,
"value", text);
}
|
java
|
{
"resource": ""
}
|
q3987
|
WebDriverBrowserBuilder.get
|
train
|
@Override
public EmbeddedBrowser get() {
LOGGER.debug("Setting up a Browser");
// Retrieve the config values used
ImmutableSortedSet<String> filterAttributes =
configuration.getCrawlRules().getPreCrawlConfig().getFilterAttributeNames();
long crawlWaitReload = configuration.getCrawlRules().getWaitAfterReloadUrl();
long crawlWaitEvent = configuration.getCrawlRules().getWaitAfterEvent();
// Determine the requested browser type
EmbeddedBrowser browser = null;
EmbeddedBrowser.BrowserType browserType =
configuration.getBrowserConfig().getBrowserType();
try {
switch (browserType) {
case CHROME:
browser = newChromeBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,
false);
break;
case CHROME_HEADLESS:
browser = newChromeBrowser(filterAttributes, crawlWaitReload,
crawlWaitEvent, true);
break;
case FIREFOX:
browser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,
false);
break;
case FIREFOX_HEADLESS:
browser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,
true);
break;
case REMOTE:
browser = WebDriverBackedEmbeddedBrowser.withRemoteDriver(
configuration.getBrowserConfig().getRemoteHubUrl(), filterAttributes,
crawlWaitEvent, crawlWaitReload);
break;
case PHANTOMJS:
browser =
newPhantomJSDriver(filterAttributes, crawlWaitReload, crawlWaitEvent);
break;
default:
throw new IllegalStateException("Unrecognized browser type "
+ configuration.getBrowserConfig().getBrowserType());
}
} catch (IllegalStateException e) {
LOGGER.error("Crawling with {} failed: " + e.getMessage(), browserType.toString());
throw e;
}
/* for Retina display. */
if (browser instanceof WebDriverBackedEmbeddedBrowser) {
int pixelDensity =
this.configuration.getBrowserConfig().getBrowserOptions().getPixelDensity();
if (pixelDensity != -1)
((WebDriverBackedEmbeddedBrowser) browser).setPixelDensity(pixelDensity);
}
plugins.runOnBrowserCreatedPlugins(browser);
return browser;
}
|
java
|
{
"resource": ""
}
|
q3988
|
CrawlPath.asStackTrace
|
train
|
public StackTraceElement[] asStackTrace() {
int i = 1;
StackTraceElement[] list = new StackTraceElement[this.size()];
for (Eventable e : this) {
list[this.size() - i] =
new StackTraceElement(e.getEventType().toString(), e.getIdentification()
.toString(), e.getElement().toString(), i);
i++;
}
return list;
}
|
java
|
{
"resource": ""
}
|
q3989
|
WebDriverBackedEmbeddedBrowser.withRemoteDriver
|
train
|
public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl,
ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,
long crawlWaitReload) {
return WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl),
filterAttributes, crawlWaitEvent,
crawlWaitReload);
}
|
java
|
{
"resource": ""
}
|
q3990
|
WebDriverBackedEmbeddedBrowser.withDriver
|
train
|
public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver,
ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,
long crawlWaitReload) {
return new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent,
crawlWaitReload);
}
|
java
|
{
"resource": ""
}
|
q3991
|
WebDriverBackedEmbeddedBrowser.buildRemoteWebDriver
|
train
|
private static RemoteWebDriver buildRemoteWebDriver(String hubUrl) {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setPlatform(Platform.ANY);
URL url;
try {
url = new URL(hubUrl);
} catch (MalformedURLException e) {
LOGGER.error("The given hub url of the remote server is malformed can not continue!",
e);
return null;
}
HttpCommandExecutor executor = null;
try {
executor = new HttpCommandExecutor(url);
} catch (Exception e) {
// TODO Stefan; refactor this catch, this will definitely result in
// NullPointers, why
// not throw RuntimeException direct?
LOGGER.error(
"Received unknown exception while creating the "
+ "HttpCommandExecutor, can not continue!",
e);
return null;
}
return new RemoteWebDriver(executor, capabilities);
}
|
java
|
{
"resource": ""
}
|
q3992
|
WebDriverBackedEmbeddedBrowser.handlePopups
|
train
|
@Override
public void handlePopups() {
/*
* try { executeJavaScript("window.alert = function(msg){return true;};" +
* "window.confirm = function(msg){return true;};" +
* "window.prompt = function(msg){return true;};"); } catch (CrawljaxException e) {
* LOGGER.error("Handling of PopUp windows failed", e); }
*/
/* Workaround: Popups handling currently not supported in PhantomJS. */
if (browser instanceof PhantomJSDriver) {
return;
}
if (ExpectedConditions.alertIsPresent().apply(browser) != null) {
try {
browser.switchTo().alert().accept();
LOGGER.info("Alert accepted");
} catch (Exception e) {
LOGGER.error("Handling of PopUp windows failed");
}
}
}
|
java
|
{
"resource": ""
}
|
q3993
|
WebDriverBackedEmbeddedBrowser.fireEventWait
|
train
|
private boolean fireEventWait(WebElement webElement, Eventable eventable)
throws ElementNotVisibleException, InterruptedException {
switch (eventable.getEventType()) {
case click:
try {
webElement.click();
} catch (ElementNotVisibleException e) {
throw e;
} catch (WebDriverException e) {
throwIfConnectionException(e);
return false;
}
break;
case hover:
LOGGER.info("EventType hover called but this isn't implemented yet");
break;
default:
LOGGER.info("EventType {} not supported in WebDriver.", eventable.getEventType());
return false;
}
Thread.sleep(this.crawlWaitEvent);
return true;
}
|
java
|
{
"resource": ""
}
|
q3994
|
WebDriverBackedEmbeddedBrowser.filterAttributes
|
train
|
private String filterAttributes(String html) {
String filteredHtml = html;
for (String attribute : this.filterAttributes) {
String regex = "\\s" + attribute + "=\"[^\"]*\"";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(html);
filteredHtml = m.replaceAll("");
}
return filteredHtml;
}
|
java
|
{
"resource": ""
}
|
q3995
|
WebDriverBackedEmbeddedBrowser.fireEventAndWait
|
train
|
@Override
public synchronized boolean fireEventAndWait(Eventable eventable)
throws ElementNotVisibleException, NoSuchElementException, InterruptedException {
try {
boolean handleChanged = false;
boolean result = false;
if (eventable.getRelatedFrame() != null && !eventable.getRelatedFrame().equals("")) {
LOGGER.debug("switching to frame: " + eventable.getRelatedFrame());
try {
switchToFrame(eventable.getRelatedFrame());
} catch (NoSuchFrameException e) {
LOGGER.debug("Frame not found, possibly while back-tracking..", e);
// TODO Stefan, This exception is caught to prevent stopping
// from working
// This was the case on the Gmail case; find out if not switching
// (catching)
// Results in good performance...
}
handleChanged = true;
}
WebElement webElement =
browser.findElement(eventable.getIdentification().getWebDriverBy());
if (webElement != null) {
result = fireEventWait(webElement, eventable);
}
if (handleChanged) {
browser.switchTo().defaultContent();
}
return result;
} catch (ElementNotVisibleException | NoSuchElementException e) {
throw e;
} catch (WebDriverException e) {
throwIfConnectionException(e);
return false;
}
}
|
java
|
{
"resource": ""
}
|
q3996
|
WebDriverBackedEmbeddedBrowser.executeJavaScript
|
train
|
@Override
public Object executeJavaScript(String code) throws CrawljaxException {
try {
JavascriptExecutor js = (JavascriptExecutor) browser;
return js.executeScript(code);
} catch (WebDriverException e) {
throwIfConnectionException(e);
throw new CrawljaxException(e);
}
}
|
java
|
{
"resource": ""
}
|
q3997
|
TrainingFormHandler.getInputValue
|
train
|
private InputValue getInputValue(FormInput input) {
/* Get the DOM element from Selenium. */
WebElement inputElement = browser.getWebElement(input.getIdentification());
switch (input.getType()) {
case TEXT:
case PASSWORD:
case HIDDEN:
case SELECT:
case TEXTAREA:
return new InputValue(inputElement.getAttribute("value"));
case RADIO:
case CHECKBOX:
default:
String value = inputElement.getAttribute("value");
Boolean checked = inputElement.isSelected();
return new InputValue(value, checked);
}
}
|
java
|
{
"resource": ""
}
|
q3998
|
Utils.loadProps
|
train
|
public static Properties loadProps(String filename) {
Properties props = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
props.load(fis);
return props;
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
Closer.closeQuietly(fis);
}
}
|
java
|
{
"resource": ""
}
|
q3999
|
Utils.getProps
|
train
|
public static Properties getProps(Properties props, String name, Properties defaultProperties) {
final String propString = props.getProperty(name);
if (propString == null) return defaultProperties;
String[] propValues = propString.split(",");
if (propValues.length < 1) {
throw new IllegalArgumentException("Illegal format of specifying properties '" + propString + "'");
}
Properties properties = new Properties();
for (int i = 0; i < propValues.length; i++) {
String[] prop = propValues[i].split("=");
if (prop.length != 2) throw new IllegalArgumentException("Illegal format of specifying properties '" + propValues[i] + "'");
properties.put(prop[0], prop[1]);
}
return properties;
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.