code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
public String getAuthorizationUri(final String redirectUri, final Set<String> scopes, final String state) {
if (account == null)
throw new IllegalArgumentException("Auth is not set");
if (account.getClientId() == null)
throw new IllegalArgumentException("client_id is not set");
StringBuilder builder = new StringBuilder();
builder.append(URI_AUTHENTICATION);
builder.append("?");
builder.append("response_type=");
builder.append(encode("code"));
builder.append("&redirect_uri=");
builder.append(encode(redirectUri));
builder.append("&client_id=");
builder.append(encode(account.getClientId()));
builder.append("&scope=");
builder.append(encode(getScopesString(scopes)));
builder.append("&state=");
builder.append(encode(state));
builder.append("&code_challenge");
builder.append(getCodeChallenge()); // Already url encoded
builder.append("&code_challenge_method=");
builder.append(encode("S256"));
return builder.toString();
} | java |
public void finishFlow(final String code, final String state) throws ApiException {
if (account == null)
throw new IllegalArgumentException("Auth is not set");
if (codeVerifier == null)
throw new IllegalArgumentException("code_verifier is not set");
if (account.getClientId() == null)
throw new IllegalArgumentException("client_id is not set");
StringBuilder builder = new StringBuilder();
builder.append("grant_type=");
builder.append(encode("authorization_code"));
builder.append("&client_id=");
builder.append(encode(account.getClientId()));
builder.append("&code=");
builder.append(encode(code));
builder.append("&code_verifier=");
builder.append(encode(codeVerifier));
update(account, builder.toString());
} | java |
public ApiResponse<String> getPingWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = getPingValidateBeforeCall(null);
Type localVarReturnType = new TypeToken<String>() {
}.getType();
return apiClient.execute(call, localVarReturnType);
} | java |
public ApiClient setHttpClient(OkHttpClient newHttpClient) {
if (!httpClient.equals(newHttpClient)) {
newHttpClient.networkInterceptors().addAll(httpClient.networkInterceptors());
httpClient.networkInterceptors().clear();
newHttpClient.interceptors().addAll(httpClient.interceptors());
httpClient.interceptors().clear();
this.httpClient = newHttpClient;
}
return this;
} | java |
private void addProgressInterceptor() {
httpClient.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
final Request request = chain.request();
final Response originalResponse = chain.proceed(request);
if (request.tag() instanceof ApiCallback) {
final ApiCallback callback = (ApiCallback) request.tag();
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), callback)).build();
}
return originalResponse;
}
});
} | java |
public com.squareup.okhttp.Call postUiAutopilotWaypointCall(Boolean addToBeginning, Boolean clearOtherWaypoints,
Long destinationId, String datasource, String token, final ApiCallback callback) throws ApiException {
Object localVarPostBody = new Object();
// create path and map variables
String localVarPath = "/v2/ui/autopilot/waypoint/";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (addToBeginning != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("add_to_beginning", addToBeginning));
}
if (clearOtherWaypoints != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("clear_other_waypoints", clearOtherWaypoints));
}
if (datasource != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("datasource", datasource));
}
if (destinationId != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("destination_id", destinationId));
}
if (token != null) {
localVarQueryParams.addAll(apiClient.parameterToPair("token", token));
}
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[] { "evesso" };
return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams,
localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);
} | java |
public void setColorSchemeResources(int... colorResIds) {
final Resources res = getResources();
int[] colorRes = new int[colorResIds.length];
for (int i = 0; i < colorResIds.length; i++) {
colorRes[i] = res.getColor(colorResIds[i]);
}
setColorSchemeColors(colorRes);
} | java |
public void setBackgroundColor(int colorRes) {
if (getBackground() instanceof ShapeDrawable) {
final Resources res = getResources();
((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));
}
} | java |
private void logBinaryStringInfo(StringBuilder binaryString) {
encodeInfo += "Binary Length: " + binaryString.length() + "\n";
encodeInfo += "Binary String: ";
int nibble = 0;
for (int i = 0; i < binaryString.length(); i++) {
switch (i % 4) {
case 0:
if (binaryString.charAt(i) == '1') {
nibble += 8;
}
break;
case 1:
if (binaryString.charAt(i) == '1') {
nibble += 4;
}
break;
case 2:
if (binaryString.charAt(i) == '1') {
nibble += 2;
}
break;
case 3:
if (binaryString.charAt(i) == '1') {
nibble += 1;
}
encodeInfo += Integer.toHexString(nibble);
nibble = 0;
break;
}
}
if ((binaryString.length() % 4) != 0) {
encodeInfo += Integer.toHexString(nibble);
}
encodeInfo += "\n";
} | java |
private int combineSubsetBlocks(Mode[] mode_type, int[] mode_length, int index_point) {
/* bring together same type blocks */
if (index_point > 1) {
for (int i = 1; i < index_point; i++) {
if (mode_type[i - 1] == mode_type[i]) {
/* bring together */
mode_length[i - 1] = mode_length[i - 1] + mode_length[i];
/* decrease the list */
for (int j = i + 1; j < index_point; j++) {
mode_length[j - 1] = mode_length[j];
mode_type[j - 1] = mode_type[j];
}
index_point--;
i--;
}
}
}
return index_point;
} | java |
public static void main(String[] args) {
Settings settings = new Settings();
new JCommander(settings, args);
if (!settings.isGuiSupressed()) {
OkapiUI okapiUi = new OkapiUI();
okapiUi.setVisible(true);
} else {
int returnValue;
returnValue = commandLine(settings);
if (returnValue != 0) {
System.out.println("An error occurred");
}
}
} | java |
private int[] getPrimaryCodewords() {
assert mode == 2 || mode == 3;
if (primaryData.length() != 15) {
throw new OkapiException("Invalid Primary String");
}
for (int i = 9; i < 15; i++) { /* check that country code and service are numeric */
if (primaryData.charAt(i) < '0' || primaryData.charAt(i) > '9') {
throw new OkapiException("Invalid Primary String");
}
}
String postcode;
if (mode == 2) {
postcode = primaryData.substring(0, 9);
int index = postcode.indexOf(' ');
if (index != -1) {
postcode = postcode.substring(0, index);
}
} else {
// if (mode == 3)
postcode = primaryData.substring(0, 6);
}
int country = Integer.parseInt(primaryData.substring(9, 12));
int service = Integer.parseInt(primaryData.substring(12, 15));
if (debug) {
System.out.println("Using mode " + mode);
System.out.println(" Postcode: " + postcode);
System.out.println(" Country Code: " + country);
System.out.println(" Service: " + service);
}
if (mode == 2) {
return getMode2PrimaryCodewords(postcode, country, service);
} else { // mode == 3
return getMode3PrimaryCodewords(postcode, country, service);
}
} | java |
private static int[] getMode2PrimaryCodewords(String postcode, int country, int service) {
for (int i = 0; i < postcode.length(); i++) {
if (postcode.charAt(i) < '0' || postcode.charAt(i) > '9') {
postcode = postcode.substring(0, i);
break;
}
}
int postcodeNum = Integer.parseInt(postcode);
int[] primary = new int[10];
primary[0] = ((postcodeNum & 0x03) << 4) | 2;
primary[1] = ((postcodeNum & 0xfc) >> 2);
primary[2] = ((postcodeNum & 0x3f00) >> 8);
primary[3] = ((postcodeNum & 0xfc000) >> 14);
primary[4] = ((postcodeNum & 0x3f00000) >> 20);
primary[5] = ((postcodeNum & 0x3c000000) >> 26) | ((postcode.length() & 0x3) << 4);
primary[6] = ((postcode.length() & 0x3c) >> 2) | ((country & 0x3) << 4);
primary[7] = (country & 0xfc) >> 2;
primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);
primary[9] = ((service & 0x3f0) >> 4);
return primary;
} | java |
private static int[] getMode3PrimaryCodewords(String postcode, int country, int service) {
int[] postcodeNums = new int[postcode.length()];
postcode = postcode.toUpperCase();
for (int i = 0; i < postcodeNums.length; i++) {
postcodeNums[i] = postcode.charAt(i);
if (postcode.charAt(i) >= 'A' && postcode.charAt(i) <= 'Z') {
// (Capital) letters shifted to Code Set A values
postcodeNums[i] -= 64;
}
if (postcodeNums[i] == 27 || postcodeNums[i] == 31 || postcodeNums[i] == 33 || postcodeNums[i] >= 59) {
// Not a valid postal code character, use space instead
postcodeNums[i] = 32;
}
// Input characters lower than 27 (NUL - SUB) in postal code are interpreted as capital
// letters in Code Set A (e.g. LF becomes 'J')
}
int[] primary = new int[10];
primary[0] = ((postcodeNums[5] & 0x03) << 4) | 3;
primary[1] = ((postcodeNums[4] & 0x03) << 4) | ((postcodeNums[5] & 0x3c) >> 2);
primary[2] = ((postcodeNums[3] & 0x03) << 4) | ((postcodeNums[4] & 0x3c) >> 2);
primary[3] = ((postcodeNums[2] & 0x03) << 4) | ((postcodeNums[3] & 0x3c) >> 2);
primary[4] = ((postcodeNums[1] & 0x03) << 4) | ((postcodeNums[2] & 0x3c) >> 2);
primary[5] = ((postcodeNums[0] & 0x03) << 4) | ((postcodeNums[1] & 0x3c) >> 2);
primary[6] = ((postcodeNums[0] & 0x3c) >> 2) | ((country & 0x3) << 4);
primary[7] = (country & 0xfc) >> 2;
primary[8] = ((country & 0x300) >> 8) | ((service & 0xf) << 2);
primary[9] = ((service & 0x3f0) >> 4);
return primary;
} | java |
private int bestSurroundingSet(int index, int length, int... valid) {
int option1 = set[index - 1];
if (index + 1 < length) {
// we have two options to check
int option2 = set[index + 1];
if (contains(valid, option1) && contains(valid, option2)) {
return Math.min(option1, option2);
} else if (contains(valid, option1)) {
return option1;
} else if (contains(valid, option2)) {
return option2;
} else {
return valid[0];
}
} else {
// we only have one option to check
if (contains(valid, option1)) {
return option1;
} else {
return valid[0];
}
}
} | java |
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 |
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 |
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 |
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 |
public ExtendedOutputStreamWriter append(double d) throws IOException {
super.append(String.format(Locale.ROOT, doubleFormat, d));
return this;
} | java |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
public void inputValues(boolean... values) {
for (boolean value : values) {
InputValue inputValue = new InputValue();
inputValue.setChecked(value);
this.inputValues.add(inputValue);
}
} | java |
public void clearTmpData() {
for (Enumeration<?> e = breadthFirstEnumeration(); e.hasMoreElements(); ) {
((LblTree) e.nextElement()).setTmpData(null);
}
} | java |
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 |
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 |
public static NodeList evaluateXpathExpression(String domStr, String xpathExpr)
throws XPathExpressionException, IOException {
Document dom = DomUtils.asDocument(domStr);
return evaluateXpathExpression(dom, xpathExpr);
} | java |
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 |
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 |
double getThreshold(String x, String y, double p) {
return 2 * Math.max(x.length(), y.length()) * (1 - p);
} | java |
@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 |
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 |
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 |
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 |
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 |
@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 |
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 |
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 |
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 |
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 |
public boolean equalId(Element otherElement) {
if (getElementId() == null || otherElement.getElementId() == null) {
return false;
}
return getElementId().equalsIgnoreCase(otherElement.getElementId());
} | java |
public String getElementId() {
for (Entry<String, String> attribute : attributes.entrySet()) {
if (attribute.getKey().equalsIgnoreCase("id")) {
return attribute.getValue();
}
}
return null;
} | java |
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 |
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 |
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 |
public ExcludeByParentBuilder dontClickChildrenOf(String tagName) {
checkNotRead();
Preconditions.checkNotNull(tagName);
ExcludeByParentBuilder exclude = new ExcludeByParentBuilder(
tagName.toUpperCase());
crawlParentsExcluded.add(exclude);
return exclude;
} | java |
public FormInput inputField(InputType type, Identification identification) {
FormInput input = new FormInput(type, identification);
this.formInputs.add(input);
return input;
} | java |
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 |
public static void directoryCheck(String dir) throws IOException {
final File file = new File(dir);
if (!file.exists()) {
FileUtils.forceMkdir(file);
}
} | java |
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 |
@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 |
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 |
@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 |
public static Integer distance(String h1, String h2) {
HammingDistance distance = new HammingDistance();
return distance.apply(h1, h2);
} | java |
public static synchronized FormInputValueHelper getInstance(
InputSpecification inputSpecification, FormFillMode formFillMode) {
if (instance == null)
instance = new FormInputValueHelper(inputSpecification,
formFillMode);
return instance;
} | java |
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 |
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 |
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 |
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 |
public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {
init(t1, t2);
STR = new int[size1][size2];
computeOptimalStrategy();
return computeDistUsingStrArray(it1, it2);
} | java |
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 |
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 |
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 |
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 |
@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 |
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 |
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 |
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 |
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 |
@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 |
@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 |
@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 |
public FormAction setValuesInForm(Form form) {
FormAction formAction = new FormAction();
form.setFormAction(formAction);
this.forms.add(form);
return formAction;
} | java |
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 |
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 |
public static String addFolderSlashIfNeeded(String folderName) {
if (!"".equals(folderName) && !folderName.endsWith("/")) {
return folderName + "/";
} else {
return folderName;
}
} | java |
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 |
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 |
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 |
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 |
@SuppressWarnings("unchecked")
public List<Difference> compare() {
Diff diff = new Diff(this.controlDOM, this.testDOM);
DetailedDiff detDiff = new DetailedDiff(diff);
return detDiff.getAllDifferences();
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.