repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
burberius/eve-esi | src/main/java/net/troja/eve/esi/auth/OAuth.java | OAuth.getAuthorizationUri | 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 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();
} | [
"public",
"String",
"getAuthorizationUri",
"(",
"final",
"String",
"redirectUri",
",",
"final",
"Set",
"<",
"String",
">",
"scopes",
",",
"final",
"String",
"state",
")",
"{",
"if",
"(",
"account",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",... | Get the authorization uri, where the user logs in.
@param redirectUri
Uri the user is redirected to, after successful authorization.
This must be the same as specified at the Eve Online developer
page.
@param scopes
Scopes of the Eve Online SSO.
@param state
This should be some secret to prevent XRSF, please read:
http://www.thread-safe.com/2014/05/the-correct-use-of-state-
parameter-in.html
@return | [
"Get",
"the",
"authorization",
"uri",
"where",
"the",
"user",
"logs",
"in",
"."
] | 24a941c592cfc15f23471ef849b282fbc582ca13 | https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/auth/OAuth.java#L163-L186 | train |
burberius/eve-esi | src/main/java/net/troja/eve/esi/auth/OAuth.java | OAuth.finishFlow | 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 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());
} | [
"public",
"void",
"finishFlow",
"(",
"final",
"String",
"code",
",",
"final",
"String",
"state",
")",
"throws",
"ApiException",
"{",
"if",
"(",
"account",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Auth is not set\"",
")",
";",
"if"... | Finish the oauth flow after the user was redirected back.
@param code
Code returned by the Eve Online SSO
@param state
This should be some secret to prevent XRSF see
getAuthorizationUri
@throws net.troja.eve.esi.ApiException | [
"Finish",
"the",
"oauth",
"flow",
"after",
"the",
"user",
"was",
"redirected",
"back",
"."
] | 24a941c592cfc15f23471ef849b282fbc582ca13 | https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/auth/OAuth.java#L198-L215 | train |
burberius/eve-esi | src/main/java/net/troja/eve/esi/api/MetaApi.java | MetaApi.getPingWithHttpInfo | 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 ApiResponse<String> getPingWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = getPingValidateBeforeCall(null);
Type localVarReturnType = new TypeToken<String>() {
}.getType();
return apiClient.execute(call, localVarReturnType);
} | [
"public",
"ApiResponse",
"<",
"String",
">",
"getPingWithHttpInfo",
"(",
")",
"throws",
"ApiException",
"{",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"call",
"=",
"getPingValidateBeforeCall",
"(",
"null",
")",
";",
"Type",
"localVarReturnType",
"=",
... | Ping route Ping the ESI routers
@return ApiResponse<String>
@throws ApiException
If fail to call the API, e.g. server error or cannot
deserialize the response body | [
"Ping",
"route",
"Ping",
"the",
"ESI",
"routers"
] | 24a941c592cfc15f23471ef849b282fbc582ca13 | https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/api/MetaApi.java#L218-L223 | train |
burberius/eve-esi | src/main/java/net/troja/eve/esi/ApiClient.java | ApiClient.setHttpClient | 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 | 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;
} | [
"public",
"ApiClient",
"setHttpClient",
"(",
"OkHttpClient",
"newHttpClient",
")",
"{",
"if",
"(",
"!",
"httpClient",
".",
"equals",
"(",
"newHttpClient",
")",
")",
"{",
"newHttpClient",
".",
"networkInterceptors",
"(",
")",
".",
"addAll",
"(",
"httpClient",
"... | Set HTTP client
@param httpClient
An instance of OkHttpClient
@return Api Client | [
"Set",
"HTTP",
"client"
] | 24a941c592cfc15f23471ef849b282fbc582ca13 | https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/ApiClient.java#L174-L183 | train |
burberius/eve-esi | src/main/java/net/troja/eve/esi/ApiClient.java | ApiClient.addProgressInterceptor | 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 | 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;
}
});
} | [
"private",
"void",
"addProgressInterceptor",
"(",
")",
"{",
"httpClient",
".",
"networkInterceptors",
"(",
")",
".",
"add",
"(",
"new",
"Interceptor",
"(",
")",
"{",
"@",
"Override",
"public",
"Response",
"intercept",
"(",
"Interceptor",
".",
"Chain",
"chain",... | Add network interceptor to httpClient to track download progress for
async requests. | [
"Add",
"network",
"interceptor",
"to",
"httpClient",
"to",
"track",
"download",
"progress",
"for",
"async",
"requests",
"."
] | 24a941c592cfc15f23471ef849b282fbc582ca13 | https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/ApiClient.java#L1318-L1332 | train |
burberius/eve-esi | src/main/java/net/troja/eve/esi/api/UserInterfaceApi.java | UserInterfaceApi.postUiAutopilotWaypointCall | 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 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);
} | [
"public",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"postUiAutopilotWaypointCall",
"(",
"Boolean",
"addToBeginning",
",",
"Boolean",
"clearOtherWaypoints",
",",
"Long",
"destinationId",
",",
"String",
"datasource",
",",
"String",
"token",
",",
"final",
"... | Build call for postUiAutopilotWaypoint
@param addToBeginning
Whether this solar system should be added to the beginning of
all waypoints (required)
@param clearOtherWaypoints
Whether clean other waypoints beforing adding this one
(required)
@param destinationId
The destination to travel to, can be solar system, station or
structure's id (required)
@param datasource
The server name you would like data from (optional, default to
tranquility)
@param token
Access token to use if unable to set a header (optional)
@param callback
Callback for upload/download progress
@return Call to execute
@throws ApiException
If fail to serialize the request body object | [
"Build",
"call",
"for",
"postUiAutopilotWaypoint"
] | 24a941c592cfc15f23471ef849b282fbc582ca13 | https://github.com/burberius/eve-esi/blob/24a941c592cfc15f23471ef849b282fbc582ca13/src/main/java/net/troja/eve/esi/api/UserInterfaceApi.java#L77-L125 | train |
lsjwzh/MaterialLoadingProgressBar | materialloadingprogressbar/src/main/java/com/lsjwzh/widget/materialloadingprogressbar/CircleProgressBar.java | CircleProgressBar.setColorSchemeResources | 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 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);
} | [
"public",
"void",
"setColorSchemeResources",
"(",
"int",
"...",
"colorResIds",
")",
"{",
"final",
"Resources",
"res",
"=",
"getResources",
"(",
")",
";",
"int",
"[",
"]",
"colorRes",
"=",
"new",
"int",
"[",
"colorResIds",
".",
"length",
"]",
";",
"for",
... | Set the color resources used in the progress animation from color resources.
The first color will also be the color of the bar that grows in response
to a user swipe gesture.
@param colorResIds | [
"Set",
"the",
"color",
"resources",
"used",
"in",
"the",
"progress",
"animation",
"from",
"color",
"resources",
".",
"The",
"first",
"color",
"will",
"also",
"be",
"the",
"color",
"of",
"the",
"bar",
"that",
"grows",
"in",
"response",
"to",
"a",
"user",
... | 170ae71d5d4f31fdd0a46a1dba9a60cb1361c656 | https://github.com/lsjwzh/MaterialLoadingProgressBar/blob/170ae71d5d4f31fdd0a46a1dba9a60cb1361c656/materialloadingprogressbar/src/main/java/com/lsjwzh/widget/materialloadingprogressbar/CircleProgressBar.java#L288-L295 | train |
lsjwzh/MaterialLoadingProgressBar | materialloadingprogressbar/src/main/java/com/lsjwzh/widget/materialloadingprogressbar/CircleProgressBar.java | CircleProgressBar.setBackgroundColor | public void setBackgroundColor(int colorRes) {
if (getBackground() instanceof ShapeDrawable) {
final Resources res = getResources();
((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));
}
} | java | public void setBackgroundColor(int colorRes) {
if (getBackground() instanceof ShapeDrawable) {
final Resources res = getResources();
((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));
}
} | [
"public",
"void",
"setBackgroundColor",
"(",
"int",
"colorRes",
")",
"{",
"if",
"(",
"getBackground",
"(",
")",
"instanceof",
"ShapeDrawable",
")",
"{",
"final",
"Resources",
"res",
"=",
"getResources",
"(",
")",
";",
"(",
"(",
"ShapeDrawable",
")",
"getBack... | Update the background color of the mBgCircle image view. | [
"Update",
"the",
"background",
"color",
"of",
"the",
"mBgCircle",
"image",
"view",
"."
] | 170ae71d5d4f31fdd0a46a1dba9a60cb1361c656 | https://github.com/lsjwzh/MaterialLoadingProgressBar/blob/170ae71d5d4f31fdd0a46a1dba9a60cb1361c656/materialloadingprogressbar/src/main/java/com/lsjwzh/widget/materialloadingprogressbar/CircleProgressBar.java#L314-L319 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/DataBarExpanded.java | DataBarExpanded.logBinaryStringInfo | 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 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";
} | [
"private",
"void",
"logBinaryStringInfo",
"(",
"StringBuilder",
"binaryString",
")",
"{",
"encodeInfo",
"+=",
"\"Binary Length: \"",
"+",
"binaryString",
".",
"length",
"(",
")",
"+",
"\"\\n\"",
";",
"encodeInfo",
"+=",
"\"Binary String: \"",
";",
"int",
"nibble",
... | Logs binary string as hexadecimal | [
"Logs",
"binary",
"string",
"as",
"hexadecimal"
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/DataBarExpanded.java#L1330-L1368 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/Code128.java | Code128.combineSubsetBlocks | 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 | 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;
} | [
"private",
"int",
"combineSubsetBlocks",
"(",
"Mode",
"[",
"]",
"mode_type",
",",
"int",
"[",
"]",
"mode_length",
",",
"int",
"index_point",
")",
"{",
"/* bring together same type blocks */",
"if",
"(",
"index_point",
">",
"1",
")",
"{",
"for",
"(",
"int",
"... | Modifies the specified mode and length arrays to combine adjacent modes of the same type, returning the updated index point. | [
"Modifies",
"the",
"specified",
"mode",
"and",
"length",
"arrays",
"to",
"combine",
"adjacent",
"modes",
"of",
"the",
"same",
"type",
"returning",
"the",
"updated",
"index",
"point",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/Code128.java#L818-L836 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/OkapiBarcode.java | OkapiBarcode.main | 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 | 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");
}
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"Settings",
"settings",
"=",
"new",
"Settings",
"(",
")",
";",
"new",
"JCommander",
"(",
"settings",
",",
"args",
")",
";",
"if",
"(",
"!",
"settings",
".",
"isGuiSupressed"... | Starts the Okapi Barcode UI.
@param args the command line arguments | [
"Starts",
"the",
"Okapi",
"Barcode",
"UI",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/OkapiBarcode.java#L41-L57 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/MaxiCode.java | MaxiCode.getPrimaryCodewords | 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 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);
}
} | [
"private",
"int",
"[",
"]",
"getPrimaryCodewords",
"(",
")",
"{",
"assert",
"mode",
"==",
"2",
"||",
"mode",
"==",
"3",
";",
"if",
"(",
"primaryData",
".",
"length",
"(",
")",
"!=",
"15",
")",
"{",
"throw",
"new",
"OkapiException",
"(",
"\"Invalid Prim... | Extracts the postal code, country code and service code from the primary data and returns the corresponding primary message
codewords.
@return the primary message codewords | [
"Extracts",
"the",
"postal",
"code",
"country",
"code",
"and",
"service",
"code",
"from",
"the",
"primary",
"data",
"and",
"returns",
"the",
"corresponding",
"primary",
"message",
"codewords",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/MaxiCode.java#L389-L430 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/MaxiCode.java | MaxiCode.getMode2PrimaryCodewords | 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[] 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;
} | [
"private",
"static",
"int",
"[",
"]",
"getMode2PrimaryCodewords",
"(",
"String",
"postcode",
",",
"int",
"country",
",",
"int",
"service",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"postcode",
".",
"length",
"(",
")",
";",
"i",
"++",... | Returns the primary message codewords for mode 2.
@param postcode the postal code
@param country the country code
@param service the service code
@return the primary message, as codewords | [
"Returns",
"the",
"primary",
"message",
"codewords",
"for",
"mode",
"2",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/MaxiCode.java#L440-L464 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/MaxiCode.java | MaxiCode.getMode3PrimaryCodewords | 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 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;
} | [
"private",
"static",
"int",
"[",
"]",
"getMode3PrimaryCodewords",
"(",
"String",
"postcode",
",",
"int",
"country",
",",
"int",
"service",
")",
"{",
"int",
"[",
"]",
"postcodeNums",
"=",
"new",
"int",
"[",
"postcode",
".",
"length",
"(",
")",
"]",
";",
... | Returns the primary message codewords for mode 3.
@param postcode the postal code
@param country the country code
@param service the service code
@return the primary message, as codewords | [
"Returns",
"the",
"primary",
"message",
"codewords",
"for",
"mode",
"3",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/MaxiCode.java#L474-L506 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/MaxiCode.java | MaxiCode.bestSurroundingSet | 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 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];
}
}
} | [
"private",
"int",
"bestSurroundingSet",
"(",
"int",
"index",
",",
"int",
"length",
",",
"int",
"...",
"valid",
")",
"{",
"int",
"option1",
"=",
"set",
"[",
"index",
"-",
"1",
"]",
";",
"if",
"(",
"index",
"+",
"1",
"<",
"length",
")",
"{",
"// we h... | Guesses the best set to use at the specified index by looking at the surrounding sets. In general, characters in
lower-numbered sets are more common, so we choose them if we can. If no good surrounding sets can be found, the default
value returned is the first value from the valid set.
@param index the current index
@param length the maximum length to look at
@param valid the valid sets for this index
@return the best set to use at the specified index | [
"Guesses",
"the",
"best",
"set",
"to",
"use",
"at",
"the",
"specified",
"index",
"by",
"looking",
"at",
"the",
"surrounding",
"sets",
".",
"In",
"general",
"characters",
"in",
"lower",
"-",
"numbered",
"sets",
"are",
"more",
"common",
"so",
"we",
"choose",... | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/MaxiCode.java#L828-L850 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/MaxiCode.java | MaxiCode.insert | 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 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;
} | [
"private",
"void",
"insert",
"(",
"int",
"position",
",",
"int",
"c",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"143",
";",
"i",
">",
"position",
";",
"i",
"--",
")",
"{",
"set",
"[",
"i",
"]",
"=",
"set",
"[",
"i",
"-",
"1",
"]",
";",
"charac... | Moves everything up so that the specified shift or latch character can be inserted.
@param position the position beyond which everything needs to be shifted
@param c the latch or shift character to insert at the specified position, after everything has been shifted | [
"Moves",
"everything",
"up",
"so",
"that",
"the",
"specified",
"shift",
"or",
"latch",
"character",
"can",
"be",
"inserted",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/MaxiCode.java#L858-L864 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/MaxiCode.java | MaxiCode.getErrorCorrection | 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 | 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;
} | [
"private",
"static",
"int",
"[",
"]",
"getErrorCorrection",
"(",
"int",
"[",
"]",
"codewords",
",",
"int",
"ecclen",
")",
"{",
"ReedSolomon",
"rs",
"=",
"new",
"ReedSolomon",
"(",
")",
";",
"rs",
".",
"init_gf",
"(",
"0x43",
")",
";",
"rs",
".",
"ini... | Returns the error correction codewords for the specified data codewords.
@param codewords the codewords that we need error correction codewords for
@param ecclen the number of error correction codewords needed
@return the error correction codewords for the specified data codewords | [
"Returns",
"the",
"error",
"correction",
"codewords",
"for",
"the",
"specified",
"data",
"codewords",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/MaxiCode.java#L873-L886 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/AztecCode.java | AztecCode.setStructuredAppendMessageId | 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 | 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;
} | [
"public",
"void",
"setStructuredAppendMessageId",
"(",
"String",
"messageId",
")",
"{",
"if",
"(",
"messageId",
"!=",
"null",
"&&",
"!",
"messageId",
".",
"matches",
"(",
"\"^[\\\\x21-\\\\x7F]+$\"",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
... | If this Aztec Code symbol is part of a series of Aztec Code symbols appended in a structured format,
this method sets the unique message ID for the series. Values may not contain spaces and must contain
only printable ASCII characters. Message IDs are optional.
@param messageId the unique message ID for the series that this symbol is part of | [
"If",
"this",
"Aztec",
"Code",
"symbol",
"is",
"part",
"of",
"a",
"series",
"of",
"Aztec",
"Code",
"symbols",
"appended",
"in",
"a",
"structured",
"format",
"this",
"method",
"sets",
"the",
"unique",
"message",
"ID",
"for",
"the",
"series",
".",
"Values",
... | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/AztecCode.java#L472-L477 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/AztecCode.java | AztecCode.addErrorCorrection | 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 | 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');
}
}
}
} | [
"private",
"void",
"addErrorCorrection",
"(",
"StringBuilder",
"adjustedString",
",",
"int",
"codewordSize",
",",
"int",
"dataBlocks",
",",
"int",
"eccBlocks",
")",
"{",
"int",
"x",
",",
"poly",
",",
"startWeight",
";",
"/* Split into codewords and calculate Reed-Solo... | Adds error correction data to the specified binary string, which already contains the primary data | [
"Adds",
"error",
"correction",
"data",
"to",
"the",
"specified",
"binary",
"string",
"which",
"already",
"contains",
"the",
"primary",
"data"
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/AztecCode.java#L1698-L1757 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/output/ExtendedOutputStreamWriter.java | ExtendedOutputStreamWriter.append | public ExtendedOutputStreamWriter append(double d) throws IOException {
super.append(String.format(Locale.ROOT, doubleFormat, d));
return this;
} | java | public ExtendedOutputStreamWriter append(double d) throws IOException {
super.append(String.format(Locale.ROOT, doubleFormat, d));
return this;
} | [
"public",
"ExtendedOutputStreamWriter",
"append",
"(",
"double",
"d",
")",
"throws",
"IOException",
"{",
"super",
".",
"append",
"(",
"String",
".",
"format",
"(",
"Locale",
".",
"ROOT",
",",
"doubleFormat",
",",
"d",
")",
")",
";",
"return",
"this",
";",
... | Writes the specified double to the stream, formatted according to the format specified in the constructor.
@param d the double to write to the stream
@return this writer
@throws IOException if an I/O error occurs | [
"Writes",
"the",
"specified",
"double",
"to",
"the",
"stream",
"formatted",
"according",
"to",
"the",
"format",
"specified",
"in",
"the",
"constructor",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/output/ExtendedOutputStreamWriter.java#L65-L68 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/util/Arrays.java | Arrays.positionOf | 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 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.");
} | [
"public",
"static",
"int",
"positionOf",
"(",
"char",
"value",
",",
"char",
"[",
"]",
"array",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"value",
"==",
"array",
"[",
... | Returns the position of the specified value in the specified array.
@param value the value to search for
@param array the array to search in
@return the position of the specified value in the specified array | [
"Returns",
"the",
"position",
"of",
"the",
"specified",
"value",
"in",
"the",
"specified",
"array",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/util/Arrays.java#L39-L46 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/util/Arrays.java | Arrays.insertArray | 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 | 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;
} | [
"public",
"static",
"int",
"[",
"]",
"insertArray",
"(",
"int",
"[",
"]",
"original",
",",
"int",
"index",
",",
"int",
"[",
"]",
"inserted",
")",
"{",
"int",
"[",
"]",
"modified",
"=",
"new",
"int",
"[",
"original",
".",
"length",
"+",
"inserted",
... | Inserts the specified array into the specified original array at the specified index.
@param original the original array into which we want to insert another array
@param index the index at which we want to insert the array
@param inserted the array that we want to insert
@return the combined array | [
"Inserts",
"the",
"specified",
"array",
"into",
"the",
"specified",
"original",
"array",
"at",
"the",
"specified",
"index",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/util/Arrays.java#L105-L111 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/QrCode.java | QrCode.getBinaryLength | 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 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;
} | [
"private",
"static",
"int",
"getBinaryLength",
"(",
"int",
"version",
",",
"QrMode",
"[",
"]",
"inputModeUnoptimized",
",",
"int",
"[",
"]",
"inputData",
",",
"boolean",
"gs1",
",",
"int",
"eciMode",
")",
"{",
"int",
"i",
",",
"j",
";",
"QrMode",
"curren... | Calculate the actual bit length of the proposed binary string. | [
"Calculate",
"the",
"actual",
"bit",
"length",
"of",
"the",
"proposed",
"binary",
"string",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/QrCode.java#L556-L642 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/QrCode.java | QrCode.blockLength | 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 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;
} | [
"private",
"static",
"int",
"blockLength",
"(",
"int",
"start",
",",
"QrMode",
"[",
"]",
"inputMode",
")",
"{",
"QrMode",
"mode",
"=",
"inputMode",
"[",
"start",
"]",
";",
"int",
"count",
"=",
"0",
";",
"int",
"i",
"=",
"start",
";",
"do",
"{",
"co... | Find the length of the block starting from 'start'. | [
"Find",
"the",
"length",
"of",
"the",
"block",
"starting",
"from",
"start",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/QrCode.java#L760-L771 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/QrCode.java | QrCode.tribus | 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 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;
}
} | [
"private",
"static",
"int",
"tribus",
"(",
"int",
"version",
",",
"int",
"a",
",",
"int",
"b",
",",
"int",
"c",
")",
"{",
"if",
"(",
"version",
"<",
"10",
")",
"{",
"return",
"a",
";",
"}",
"else",
"if",
"(",
"version",
">=",
"10",
"&&",
"versi... | Choose from three numbers based on version. | [
"Choose",
"from",
"three",
"numbers",
"based",
"on",
"version",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/QrCode.java#L774-L782 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/QrCode.java | QrCode.addEcc | 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 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];
}
} | [
"private",
"static",
"void",
"addEcc",
"(",
"int",
"[",
"]",
"fullstream",
",",
"int",
"[",
"]",
"datastream",
",",
"int",
"version",
",",
"int",
"data_cw",
",",
"int",
"blocks",
")",
"{",
"int",
"ecc_cw",
"=",
"QR_TOTAL_CODEWORDS",
"[",
"version",
"-",
... | Splits data into blocks, adds error correction and then interleaves the blocks and error correction data. | [
"Splits",
"data",
"into",
"blocks",
"adds",
"error",
"correction",
"and",
"then",
"interleaves",
"the",
"blocks",
"and",
"error",
"correction",
"data",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/QrCode.java#L1047-L1108 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/QrCode.java | QrCode.addFormatInfoEval | 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 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);
} | [
"private",
"static",
"void",
"addFormatInfoEval",
"(",
"byte",
"[",
"]",
"eval",
",",
"int",
"size",
",",
"EccLevel",
"ecc_level",
",",
"int",
"pattern",
")",
"{",
"int",
"format",
"=",
"pattern",
";",
"int",
"seq",
";",
"int",
"i",
";",
"switch",
"(",... | Adds format information to eval. | [
"Adds",
"format",
"information",
"to",
"eval",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/QrCode.java#L1379-L1412 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/QrCode.java | QrCode.addVersionInfo | 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 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;
}
} | [
"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",
"=",
"Q... | Adds version information. | [
"Adds",
"version",
"information",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/QrCode.java#L1645-L1656 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/Pdf417.java | Pdf417.createBlocks | 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 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;
} | [
"private",
"static",
"List",
"<",
"Block",
">",
"createBlocks",
"(",
"int",
"[",
"]",
"data",
",",
"boolean",
"debug",
")",
"{",
"List",
"<",
"Block",
">",
"blocks",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Block",
"current",
"=",
"null",
";",
... | Determines the encoding block groups for the specified data. | [
"Determines",
"the",
"encoding",
"block",
"groups",
"for",
"the",
"specified",
"data",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/Pdf417.java#L1294-L1321 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/Pdf417.java | Pdf417.mergeBlocks | 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 | 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--;
}
}
} | [
"private",
"static",
"void",
"mergeBlocks",
"(",
"List",
"<",
"Block",
">",
"blocks",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"blocks",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"Block",
"b1",
"=",
"blocks",
".",
"get"... | Combines adjacent blocks of the same type. | [
"Combines",
"adjacent",
"blocks",
"of",
"the",
"same",
"type",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/Pdf417.java#L1386-L1397 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/Symbol.java | Symbol.eciProcess | 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 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";
} | [
"protected",
"void",
"eciProcess",
"(",
")",
"{",
"EciMode",
"eci",
"=",
"EciMode",
".",
"of",
"(",
"content",
",",
"\"ISO8859_1\"",
",",
"3",
")",
".",
"or",
"(",
"content",
",",
"\"ISO8859_2\"",
",",
"4",
")",
".",
"or",
"(",
"content",
",",
"\"ISO... | Chooses the ECI mode most suitable for the content of this symbol. | [
"Chooses",
"the",
"ECI",
"mode",
"most",
"suitable",
"for",
"the",
"content",
"of",
"this",
"symbol",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/Symbol.java#L559-L592 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/Symbol.java | Symbol.mergeVerticalBlocks | 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 | 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);
}
}
}
}
} | [
"protected",
"void",
"mergeVerticalBlocks",
"(",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"rectangles",
".",
"size",
"(",
")",
"-",
"1",
";",
"i",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"i",
"+",
"1",
";",
"j",
"<",
... | Search for rectangles which have the same width and x position, and
which join together vertically and merge them together to reduce the
number of rectangles needed to describe a symbol. | [
"Search",
"for",
"rectangles",
"which",
"have",
"the",
"same",
"width",
"and",
"x",
"position",
"and",
"which",
"join",
"together",
"vertically",
"and",
"merge",
"them",
"together",
"to",
"reduce",
"the",
"number",
"of",
"rectangles",
"needed",
"to",
"describe... | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/Symbol.java#L715-L729 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/Symbol.java | Symbol.hibcProcess | 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 | 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;
} | [
"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",
"("... | Adds the HIBC prefix and check digit to the specified data, returning the resultant data string.
@see <a href="https://sourceforge.net/p/zint/code/ci/master/tree/backend/library.c">Corresponding Zint code</a> | [
"Adds",
"the",
"HIBC",
"prefix",
"and",
"check",
"digit",
"to",
"the",
"specified",
"data",
"returning",
"the",
"resultant",
"data",
"string",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/Symbol.java#L736-L760 | train |
woo-j/OkapiBarcode | src/main/java/uk/org/okapibarcode/backend/Symbol.java | Symbol.getPatternAsCodewords | 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 | 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;
}
} | [
"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.\"",
")",
... | Returns this bar code's pattern, converted into a set of corresponding codewords.
Useful for bar codes that encode their content as a pattern.
@param size the number of digits in each codeword
@return this bar code's pattern, converted into a set of corresponding codewords | [
"Returns",
"this",
"bar",
"code",
"s",
"pattern",
"converted",
"into",
"a",
"set",
"of",
"corresponding",
"codewords",
".",
"Useful",
"for",
"bar",
"codes",
"that",
"encode",
"their",
"content",
"as",
"a",
"pattern",
"."
] | d1cb4f4ab64557cd3db64d9a473528a52ce58081 | https://github.com/woo-j/OkapiBarcode/blob/d1cb4f4ab64557cd3db64d9a473528a52ce58081/src/main/java/uk/org/okapibarcode/backend/Symbol.java#L779-L798 | train |
linroid/FilterMenu | library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java | FilterMenuLayout.arcAngle | 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 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;
} | [
"private",
"static",
"double",
"arcAngle",
"(",
"Point",
"center",
",",
"Point",
"a",
",",
"Point",
"b",
",",
"Rect",
"area",
",",
"int",
"radius",
")",
"{",
"double",
"angle",
"=",
"threePointsAngle",
"(",
"center",
",",
"a",
",",
"b",
")",
";",
"Po... | calculate arc angle between point a and point b
@param center
@param a
@param b
@param area
@param radius
@return | [
"calculate",
"arc",
"angle",
"between",
"point",
"a",
"and",
"point",
"b"
] | 5a6e5472631c2304b71a51034683f38271962ef5 | https://github.com/linroid/FilterMenu/blob/5a6e5472631c2304b71a51034683f38271962ef5/library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java#L143-L152 | train |
linroid/FilterMenu | library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java | FilterMenuLayout.findMidnormalPoint | 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 | 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;
} | [
"private",
"static",
"Point",
"findMidnormalPoint",
"(",
"Point",
"center",
",",
"Point",
"a",
",",
"Point",
"b",
",",
"Rect",
"area",
",",
"int",
"radius",
")",
"{",
"if",
"(",
"a",
".",
"y",
"==",
"b",
".",
"y",
")",
"{",
"//top",
"if",
"(",
"a... | find the middle point of two intersect points in circle,only one point will be correct
@param center
@param a
@param b
@param area
@param radius
@return | [
"find",
"the",
"middle",
"point",
"of",
"two",
"intersect",
"points",
"in",
"circle",
"only",
"one",
"point",
"will",
"be",
"correct"
] | 5a6e5472631c2304b71a51034683f38271962ef5 | https://github.com/linroid/FilterMenu/blob/5a6e5472631c2304b71a51034683f38271962ef5/library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java#L164-L194 | train |
linroid/FilterMenu | library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java | FilterMenuLayout.inArea | 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 | 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;
} | [
"public",
"static",
"boolean",
"inArea",
"(",
"Point",
"point",
",",
"Rect",
"area",
",",
"float",
"offsetRatio",
")",
"{",
"int",
"offset",
"=",
"(",
"int",
")",
"(",
"area",
".",
"width",
"(",
")",
"*",
"offsetRatio",
")",
";",
"return",
"point",
"... | judge if an point in the area or not
@param point
@param area
@param offsetRatio
@return | [
"judge",
"if",
"an",
"point",
"in",
"the",
"area",
"or",
"not"
] | 5a6e5472631c2304b71a51034683f38271962ef5 | https://github.com/linroid/FilterMenu/blob/5a6e5472631c2304b71a51034683f38271962ef5/library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java#L212-L216 | train |
linroid/FilterMenu | library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java | FilterMenuLayout.threePointsAngle | 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 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)));
} | [
"private",
"static",
"double",
"threePointsAngle",
"(",
"Point",
"vertex",
",",
"Point",
"A",
",",
"Point",
"B",
")",
"{",
"double",
"b",
"=",
"pointsDistance",
"(",
"vertex",
",",
"A",
")",
";",
"double",
"c",
"=",
"pointsDistance",
"(",
"A",
",",
"B"... | calculate the point a's angle of rectangle consist of point a,point b, point c;
@param vertex
@param A
@param B
@return | [
"calculate",
"the",
"point",
"a",
"s",
"angle",
"of",
"rectangle",
"consist",
"of",
"point",
"a",
"point",
"b",
"point",
"c",
";"
] | 5a6e5472631c2304b71a51034683f38271962ef5 | https://github.com/linroid/FilterMenu/blob/5a6e5472631c2304b71a51034683f38271962ef5/library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java#L226-L233 | train |
linroid/FilterMenu | library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java | FilterMenuLayout.pointsDistance | 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 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);
} | [
"private",
"static",
"double",
"pointsDistance",
"(",
"Point",
"a",
",",
"Point",
"b",
")",
"{",
"int",
"dx",
"=",
"b",
".",
"x",
"-",
"a",
".",
"x",
";",
"int",
"dy",
"=",
"b",
".",
"y",
"-",
"a",
".",
"y",
";",
"return",
"Math",
".",
"sqrt"... | calculate distance of two points
@param a
@param b
@return | [
"calculate",
"distance",
"of",
"two",
"points"
] | 5a6e5472631c2304b71a51034683f38271962ef5 | https://github.com/linroid/FilterMenu/blob/5a6e5472631c2304b71a51034683f38271962ef5/library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java#L242-L246 | train |
linroid/FilterMenu | library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java | FilterMenuLayout.calculateMenuItemPosition | 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 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);
}
} | [
"private",
"void",
"calculateMenuItemPosition",
"(",
")",
"{",
"float",
"itemRadius",
"=",
"(",
"expandedRadius",
"+",
"collapsedRadius",
")",
"/",
"2",
",",
"f",
";",
"RectF",
"area",
"=",
"new",
"RectF",
"(",
"center",
".",
"x",
"-",
"itemRadius",
",",
... | calculate and set position to menu items | [
"calculate",
"and",
"set",
"position",
"to",
"menu",
"items"
] | 5a6e5472631c2304b71a51034683f38271962ef5 | https://github.com/linroid/FilterMenu/blob/5a6e5472631c2304b71a51034683f38271962ef5/library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java#L611-L633 | train |
linroid/FilterMenu | library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java | FilterMenuLayout.isClockwise | 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 | 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;
} | [
"private",
"boolean",
"isClockwise",
"(",
"Point",
"center",
",",
"Point",
"a",
",",
"Point",
"b",
")",
"{",
"double",
"cross",
"=",
"(",
"a",
".",
"x",
"-",
"center",
".",
"x",
")",
"*",
"(",
"b",
".",
"y",
"-",
"center",
".",
"y",
")",
"-",
... | judge a->b is ordered clockwise
@param center
@param a
@param b
@return | [
"judge",
"a",
"-",
">",
"b",
"is",
"ordered",
"clockwise"
] | 5a6e5472631c2304b71a51034683f38271962ef5 | https://github.com/linroid/FilterMenu/blob/5a6e5472631c2304b71a51034683f38271962ef5/library/src/main/java/com/linroid/filtermenu/library/FilterMenuLayout.java#L748-L751 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/forms/FormInput.java | FormInput.inputValues | public void inputValues(boolean... values) {
for (boolean value : values) {
InputValue inputValue = new InputValue();
inputValue.setChecked(value);
this.inputValues.add(inputValue);
}
} | java | public void inputValues(boolean... values) {
for (boolean value : values) {
InputValue inputValue = new InputValue();
inputValue.setChecked(value);
this.inputValues.add(inputValue);
}
} | [
"public",
"void",
"inputValues",
"(",
"boolean",
"...",
"values",
")",
"{",
"for",
"(",
"boolean",
"value",
":",
"values",
")",
"{",
"InputValue",
"inputValue",
"=",
"new",
"InputValue",
"(",
")",
";",
"inputValue",
".",
"setChecked",
"(",
"value",
")",
... | Sets the values of this input field. Only Applicable check-boxes and a radio buttons.
@param values Values to set. | [
"Sets",
"the",
"values",
"of",
"this",
"input",
"field",
".",
"Only",
"Applicable",
"check",
"-",
"boxes",
"and",
"a",
"radio",
"buttons",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/forms/FormInput.java#L141-L148 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/LblTree.java | LblTree.clearTmpData | public void clearTmpData() {
for (Enumeration<?> e = breadthFirstEnumeration(); e.hasMoreElements(); ) {
((LblTree) e.nextElement()).setTmpData(null);
}
} | java | public void clearTmpData() {
for (Enumeration<?> e = breadthFirstEnumeration(); e.hasMoreElements(); ) {
((LblTree) e.nextElement()).setTmpData(null);
}
} | [
"public",
"void",
"clearTmpData",
"(",
")",
"{",
"for",
"(",
"Enumeration",
"<",
"?",
">",
"e",
"=",
"breadthFirstEnumeration",
"(",
")",
";",
"e",
".",
"hasMoreElements",
"(",
")",
";",
")",
"{",
"(",
"(",
"LblTree",
")",
"e",
".",
"nextElement",
"(... | Clear tmpData in subtree rooted in this node. | [
"Clear",
"tmpData",
"in",
"subtree",
"rooted",
"in",
"this",
"node",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/LblTree.java#L171-L175 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/XPathHelper.java | XPathHelper.getXPathExpression | 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 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;
} | [
"public",
"static",
"String",
"getXPathExpression",
"(",
"Node",
"node",
")",
"{",
"Object",
"xpathCache",
"=",
"node",
".",
"getUserData",
"(",
"FULL_XPATH_CACHE",
")",
";",
"if",
"(",
"xpathCache",
"!=",
"null",
")",
"{",
"return",
"xpathCache",
".",
"toSt... | Reverse Engineers an XPath Expression of a given Node in the DOM.
@param node the given node.
@return string xpath expression (e.g., "/html[1]/body[1]/div[3]"). | [
"Reverse",
"Engineers",
"an",
"XPath",
"Expression",
"of",
"a",
"given",
"Node",
"in",
"the",
"DOM",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/XPathHelper.java#L38-L81 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/XPathHelper.java | XPathHelper.getSiblings | 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 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;
} | [
"public",
"static",
"List",
"<",
"Node",
">",
"getSiblings",
"(",
"Node",
"parent",
",",
"Node",
"element",
")",
"{",
"List",
"<",
"Node",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"NodeList",
"list",
"=",
"parent",
".",
"getChildNod... | Get siblings of the same type as element from parent.
@param parent parent node.
@param element element.
@return List of sibling (from element) under parent | [
"Get",
"siblings",
"of",
"the",
"same",
"type",
"as",
"element",
"from",
"parent",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/XPathHelper.java#L90-L103 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/XPathHelper.java | XPathHelper.evaluateXpathExpression | 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(String domStr, String xpathExpr)
throws XPathExpressionException, IOException {
Document dom = DomUtils.asDocument(domStr);
return evaluateXpathExpression(dom, xpathExpr);
} | [
"public",
"static",
"NodeList",
"evaluateXpathExpression",
"(",
"String",
"domStr",
",",
"String",
"xpathExpr",
")",
"throws",
"XPathExpressionException",
",",
"IOException",
"{",
"Document",
"dom",
"=",
"DomUtils",
".",
"asDocument",
"(",
"domStr",
")",
";",
"ret... | Returns the list of nodes which match the expression xpathExpr in the String domStr.
@return the list of nodes which match the query
@throws XPathExpressionException
@throws IOException | [
"Returns",
"the",
"list",
"of",
"nodes",
"which",
"match",
"the",
"expression",
"xpathExpr",
"in",
"the",
"String",
"domStr",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/XPathHelper.java#L112-L116 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/XPathHelper.java | XPathHelper.evaluateXpathExpression | 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 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;
} | [
"public",
"static",
"NodeList",
"evaluateXpathExpression",
"(",
"Document",
"dom",
",",
"String",
"xpathExpr",
")",
"throws",
"XPathExpressionException",
"{",
"XPathFactory",
"factory",
"=",
"XPathFactory",
".",
"newInstance",
"(",
")",
";",
"XPath",
"xpath",
"=",
... | Returns the list of nodes which match the expression xpathExpr in the Document dom.
@param dom the Document to search in
@param xpathExpr the xpath query
@return the list of nodes which match the query
@throws XPathExpressionException On error. | [
"Returns",
"the",
"list",
"of",
"nodes",
"which",
"match",
"the",
"expression",
"xpathExpr",
"in",
"the",
"Document",
"dom",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/XPathHelper.java#L126-L133 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/XPathHelper.java | XPathHelper.getXPathLocation | 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 | 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;
} | [
"public",
"static",
"int",
"getXPathLocation",
"(",
"String",
"dom",
",",
"String",
"xpath",
")",
"{",
"String",
"dom_lower",
"=",
"dom",
".",
"toLowerCase",
"(",
")",
";",
"String",
"xpath_lower",
"=",
"xpath",
".",
"toLowerCase",
"(",
")",
";",
"String",... | returns position of xpath element which match the expression xpath in the String dom.
@param dom the Document to search in
@param xpath the xpath query
@return position of xpath element, if fails returns -1 | [
"returns",
"position",
"of",
"xpath",
"element",
"which",
"match",
"the",
"expression",
"xpath",
"in",
"the",
"String",
"dom",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/XPathHelper.java#L223-L262 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/oraclecomparator/comparators/EditDistanceComparator.java | EditDistanceComparator.getThreshold | double getThreshold(String x, String y, double p) {
return 2 * Math.max(x.length(), y.length()) * (1 - p);
} | java | double getThreshold(String x, String y, double p) {
return 2 * Math.max(x.length(), y.length()) * (1 - p);
} | [
"double",
"getThreshold",
"(",
"String",
"x",
",",
"String",
"y",
",",
"double",
"p",
")",
"{",
"return",
"2",
"*",
"Math",
".",
"max",
"(",
"x",
".",
"length",
"(",
")",
",",
"y",
".",
"length",
"(",
")",
")",
"*",
"(",
"1",
"-",
"p",
")",
... | Calculate a threshold.
@param x first string.
@param y second string.
@param p the threshold coefficient.
@return 2 maxLength(x, y) (1-p) | [
"Calculate",
"a",
"threshold",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/oraclecomparator/comparators/EditDistanceComparator.java#L73-L75 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/condition/JavaScriptCondition.java | JavaScriptCondition.check | @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 | @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;
}
} | [
"@",
"Override",
"public",
"boolean",
"check",
"(",
"EmbeddedBrowser",
"browser",
")",
"{",
"String",
"js",
"=",
"\"try{ if(\"",
"+",
"expression",
"+",
"\"){return '1';}else{\"",
"+",
"\"return '0';}}catch(e){\"",
"+",
"\" return '0';}\"",
";",
"try",
"{",
"Object"... | Check invariant.
@param browser The browser.
@return Whether the condition is satisfied or <code>false</code> when it it isn't or a
{@link CrawljaxException} occurs. | [
"Check",
"invariant",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/condition/JavaScriptCondition.java#L34-L49 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/XMLObject.java | XMLObject.objectToXML | 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 void objectToXML(Object object, String fileName) throws FileNotFoundException {
FileOutputStream fo = new FileOutputStream(fileName);
XMLEncoder encoder = new XMLEncoder(fo);
encoder.writeObject(object);
encoder.close();
} | [
"public",
"static",
"void",
"objectToXML",
"(",
"Object",
"object",
",",
"String",
"fileName",
")",
"throws",
"FileNotFoundException",
"{",
"FileOutputStream",
"fo",
"=",
"new",
"FileOutputStream",
"(",
"fileName",
")",
";",
"XMLEncoder",
"encoder",
"=",
"new",
... | Converts an object to an XML file.
@param object The object to convert.
@param fileName The filename where to save it to.
@throws FileNotFoundException On error. | [
"Converts",
"an",
"object",
"to",
"an",
"XML",
"file",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/XMLObject.java#L25-L30 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/XMLObject.java | XMLObject.xmlToObject | 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 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;
} | [
"public",
"static",
"Object",
"xmlToObject",
"(",
"String",
"fileName",
")",
"throws",
"FileNotFoundException",
"{",
"FileInputStream",
"fi",
"=",
"new",
"FileInputStream",
"(",
"fileName",
")",
";",
"XMLDecoder",
"decoder",
"=",
"new",
"XMLDecoder",
"(",
"fi",
... | Converts an XML file to an object.
@param fileName The filename where to save it to.
@return The object.
@throws FileNotFoundException On error. | [
"Converts",
"an",
"XML",
"file",
"to",
"an",
"object",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/XMLObject.java#L39-L45 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/state/Identification.java | Identification.getWebDriverBy | 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 | 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;
}
} | [
"public",
"By",
"getWebDriverBy",
"(",
")",
"{",
"switch",
"(",
"how",
")",
"{",
"case",
"name",
":",
"return",
"By",
".",
"name",
"(",
"this",
".",
"value",
")",
";",
"case",
"xpath",
":",
"// Work around HLWK driver bug",
"return",
"By",
".",
"xpath",
... | Convert a Identification to a By used in WebDriver Drivers.
@return the correct By specification of the current Identification. | [
"Convert",
"a",
"Identification",
"to",
"a",
"By",
"used",
"in",
"WebDriver",
"Drivers",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/Identification.java#L89-L116 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/configuration/CrawlElement.java | CrawlElement.escapeApostrophes | 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 | 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;
} | [
"protected",
"String",
"escapeApostrophes",
"(",
"String",
"text",
")",
"{",
"String",
"resultString",
";",
"if",
"(",
"text",
".",
"contains",
"(",
"\"'\"",
")",
")",
"{",
"StringBuilder",
"stringBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"string... | Returns a string to resolve apostrophe issue in xpath
@param text
@return the apostrophe resolved xpath value string | [
"Returns",
"a",
"string",
"to",
"resolve",
"apostrophe",
"issue",
"in",
"xpath"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/configuration/CrawlElement.java#L226-L238 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/CrawlController.java | CrawlController.call | @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 | @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();
} | [
"@",
"Override",
"public",
"CrawlSession",
"call",
"(",
")",
"{",
"setMaximumCrawlTimeIfNeeded",
"(",
")",
";",
"plugins",
".",
"runPreCrawlingPlugins",
"(",
"config",
")",
";",
"CrawlTaskConsumer",
"firstConsumer",
"=",
"consumerFactory",
".",
"get",
"(",
")",
... | Run the configured crawl. This method blocks until the crawl is done.
@return the CrawlSession once the crawl is done. | [
"Run",
"the",
"configured",
"crawl",
".",
"This",
"method",
"blocks",
"until",
"the",
"crawl",
"is",
"done",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CrawlController.java#L64-L74 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/CandidateElementExtractor.java | CandidateElementExtractor.extract | 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 | 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);
} | [
"public",
"ImmutableList",
"<",
"CandidateElement",
">",
"extract",
"(",
"StateVertex",
"currentState",
")",
"throws",
"CrawljaxException",
"{",
"LinkedList",
"<",
"CandidateElement",
">",
"results",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"if",
"(",
"!",... | This method extracts candidate elements from the current DOM tree in the browser, based on
the crawl tags defined by the user.
@param currentState the state in which this extract method is requested.
@return a list of candidate elements that are not excluded.
@throws CrawljaxException if the method fails. | [
"This",
"method",
"extracts",
"candidate",
"elements",
"from",
"the",
"current",
"DOM",
"tree",
"in",
"the",
"browser",
"based",
"on",
"the",
"crawl",
"tags",
"defined",
"by",
"the",
"user",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CandidateElementExtractor.java#L110-L133 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/CandidateElementExtractor.java | CandidateElementExtractor.getNodeListForTagElement | 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 | 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();
} | [
"private",
"ImmutableList",
"<",
"Element",
">",
"getNodeListForTagElement",
"(",
"Document",
"dom",
",",
"CrawlElement",
"crawlElement",
",",
"EventableConditionChecker",
"eventableConditionChecker",
")",
"{",
"Builder",
"<",
"Element",
">",
"result",
"=",
"ImmutableLi... | Returns a list of Elements form the DOM tree, matching the tag element. | [
"Returns",
"a",
"list",
"of",
"Elements",
"form",
"the",
"DOM",
"tree",
"matching",
"the",
"tag",
"element",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CandidateElementExtractor.java#L226-L265 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/plugin/Plugins.java | Plugins.runOnInvariantViolationPlugins | 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 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);
}
}
}
} | [
"public",
"void",
"runOnInvariantViolationPlugins",
"(",
"Invariant",
"invariant",
",",
"CrawlerContext",
"context",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Running OnInvariantViolationPlugins...\"",
")",
";",
"counters",
".",
"get",
"(",
"OnInvariantViolationPlugin",
... | Run the OnInvariantViolation plugins when an Invariant is violated. Invariant are checked
when the state machine is updated that is when the dom is changed after a click on a
clickable. When a invariant fails this kind of plugins are executed. Warning the session is
not a clone, changing the session can cause strange behaviour of Crawljax.
@param invariant the failed invariants
@param context the current {@link CrawlerContext} for this crawler. | [
"Run",
"the",
"OnInvariantViolation",
"plugins",
"when",
"an",
"Invariant",
"is",
"violated",
".",
"Invariant",
"are",
"checked",
"when",
"the",
"state",
"machine",
"is",
"updated",
"that",
"is",
"when",
"the",
"dom",
"is",
"changed",
"after",
"a",
"click",
... | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/plugin/Plugins.java#L178-L193 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/plugin/Plugins.java | Plugins.runOnBrowserCreatedPlugins | 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 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);
}
}
}
} | [
"public",
"void",
"runOnBrowserCreatedPlugins",
"(",
"EmbeddedBrowser",
"newBrowser",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Running OnBrowserCreatedPlugins...\"",
")",
";",
"counters",
".",
"get",
"(",
"OnBrowserCreatedPlugin",
".",
"class",
")",
".",
"inc",
"("... | Load and run the OnBrowserCreatedPlugins, this call has been made from the browser pool when a
new browser has been created and ready to be used by the Crawler. The PreCrawling plugins are
executed before these plugins are executed except that the pre-crawling plugins are only
executed on the first created browser.
@param newBrowser the new created browser object | [
"Load",
"and",
"run",
"the",
"OnBrowserCreatedPlugins",
"this",
"call",
"has",
"been",
"made",
"from",
"the",
"browser",
"pool",
"when",
"a",
"new",
"browser",
"has",
"been",
"created",
"and",
"ready",
"to",
"be",
"used",
"by",
"the",
"Crawler",
".",
"The"... | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/plugin/Plugins.java#L323-L337 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/state/Element.java | Element.equalId | public boolean equalId(Element otherElement) {
if (getElementId() == null || otherElement.getElementId() == null) {
return false;
}
return getElementId().equalsIgnoreCase(otherElement.getElementId());
} | java | public boolean equalId(Element otherElement) {
if (getElementId() == null || otherElement.getElementId() == null) {
return false;
}
return getElementId().equalsIgnoreCase(otherElement.getElementId());
} | [
"public",
"boolean",
"equalId",
"(",
"Element",
"otherElement",
")",
"{",
"if",
"(",
"getElementId",
"(",
")",
"==",
"null",
"||",
"otherElement",
".",
"getElementId",
"(",
")",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"getElementId",... | Are both Id's the same?
@param otherElement the other element to compare
@return true if id == otherElement.id | [
"Are",
"both",
"Id",
"s",
"the",
"same?"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/Element.java#L67-L72 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/state/Element.java | Element.getElementId | public String getElementId() {
for (Entry<String, String> attribute : attributes.entrySet()) {
if (attribute.getKey().equalsIgnoreCase("id")) {
return attribute.getValue();
}
}
return null;
} | java | public String getElementId() {
for (Entry<String, String> attribute : attributes.entrySet()) {
if (attribute.getKey().equalsIgnoreCase("id")) {
return attribute.getValue();
}
}
return null;
} | [
"public",
"String",
"getElementId",
"(",
")",
"{",
"for",
"(",
"Entry",
"<",
"String",
",",
"String",
">",
"attribute",
":",
"attributes",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"attribute",
".",
"getKey",
"(",
")",
".",
"equalsIgnoreCase",
"(... | Search for the attribute "id" and return the value.
@return the id of this element or null when not found | [
"Search",
"for",
"the",
"attribute",
"id",
"and",
"return",
"the",
"value",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/Element.java#L89-L96 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/condition/eventablecondition/EventableConditionChecker.java | EventableConditionChecker.checkXpathStartsWithXpathEventableCondition | 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 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);
} | [
"public",
"boolean",
"checkXpathStartsWithXpathEventableCondition",
"(",
"Document",
"dom",
",",
"EventableCondition",
"eventableCondition",
",",
"String",
"xpath",
")",
"throws",
"XPathExpressionException",
"{",
"if",
"(",
"eventableCondition",
"==",
"null",
"||",
"Strin... | Checks whether an XPath expression starts with an XPath eventable condition.
@param dom The DOM String.
@param eventableCondition The eventable condition.
@param xpath The XPath.
@return boolean whether xpath starts with xpath location of eventable condition xpath
condition
@throws XPathExpressionException
@throws CrawljaxException when eventableCondition is null or its inXPath has not been set | [
"Checks",
"whether",
"an",
"XPath",
"expression",
"starts",
"with",
"an",
"XPath",
"eventable",
"condition",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/condition/eventablecondition/EventableConditionChecker.java#L66-L76 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTEDUtils.java | RTEDUtils.getRobustTreeEditDistance | 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 | 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;
} | [
"public",
"static",
"double",
"getRobustTreeEditDistance",
"(",
"String",
"dom1",
",",
"String",
"dom2",
")",
"{",
"LblTree",
"domTree1",
"=",
"null",
",",
"domTree2",
"=",
"null",
";",
"try",
"{",
"domTree1",
"=",
"getDomTree",
"(",
"dom1",
")",
";",
"dom... | Get a scalar value for the DOM diversity using the Robust Tree Edit Distance
@param dom1
@param dom2
@return | [
"Get",
"a",
"scalar",
"value",
"for",
"the",
"DOM",
"diversity",
"using",
"the",
"Robust",
"Tree",
"Edit",
"Distance"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTEDUtils.java#L20-L47 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTEDUtils.java | RTEDUtils.createTree | 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 | 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;
} | [
"private",
"static",
"LblTree",
"createTree",
"(",
"TreeWalker",
"walker",
")",
"{",
"Node",
"parent",
"=",
"walker",
".",
"getCurrentNode",
"(",
")",
";",
"LblTree",
"node",
"=",
"new",
"LblTree",
"(",
"parent",
".",
"getNodeName",
"(",
")",
",",
"-",
"... | Recursively construct a LblTree from DOM tree
@param walker tree walker for DOM tree traversal
@return tree represented by DOM tree | [
"Recursively",
"construct",
"a",
"LblTree",
"from",
"DOM",
"tree"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTEDUtils.java#L69-L77 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/configuration/CrawlActionsBuilder.java | CrawlActionsBuilder.dontClickChildrenOf | public ExcludeByParentBuilder dontClickChildrenOf(String tagName) {
checkNotRead();
Preconditions.checkNotNull(tagName);
ExcludeByParentBuilder exclude = new ExcludeByParentBuilder(
tagName.toUpperCase());
crawlParentsExcluded.add(exclude);
return exclude;
} | java | public ExcludeByParentBuilder dontClickChildrenOf(String tagName) {
checkNotRead();
Preconditions.checkNotNull(tagName);
ExcludeByParentBuilder exclude = new ExcludeByParentBuilder(
tagName.toUpperCase());
crawlParentsExcluded.add(exclude);
return exclude;
} | [
"public",
"ExcludeByParentBuilder",
"dontClickChildrenOf",
"(",
"String",
"tagName",
")",
"{",
"checkNotRead",
"(",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"tagName",
")",
";",
"ExcludeByParentBuilder",
"exclude",
"=",
"new",
"ExcludeByParentBuilder",
"("... | Click no children of the specified parent element.
@param tagName The tag name of which no children should be clicked.
@return The builder to append more options. | [
"Click",
"no",
"children",
"of",
"the",
"specified",
"parent",
"element",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/configuration/CrawlActionsBuilder.java#L147-L154 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/configuration/Form.java | Form.inputField | public FormInput inputField(InputType type, Identification identification) {
FormInput input = new FormInput(type, identification);
this.formInputs.add(input);
return input;
} | java | public FormInput inputField(InputType type, Identification identification) {
FormInput input = new FormInput(type, identification);
this.formInputs.add(input);
return input;
} | [
"public",
"FormInput",
"inputField",
"(",
"InputType",
"type",
",",
"Identification",
"identification",
")",
"{",
"FormInput",
"input",
"=",
"new",
"FormInput",
"(",
"type",
",",
"identification",
")",
";",
"this",
".",
"formInputs",
".",
"add",
"(",
"input",
... | Specifies an input field to assign a value to. Crawljax first tries to match the found HTML
input element's id and then the name attribute.
@param type
the type of input field
@param identification
the locator of the input field
@return an InputField | [
"Specifies",
"an",
"input",
"field",
"to",
"assign",
"a",
"value",
"to",
".",
"Crawljax",
"first",
"tries",
"to",
"match",
"the",
"found",
"HTML",
"input",
"element",
"s",
"id",
"and",
"then",
"the",
"name",
"attribute",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/configuration/Form.java#L55-L59 | train |
crawljax/crawljax | cli/src/main/java/com/crawljax/cli/ParameterInterpeter.java | ParameterInterpeter.getOptions | 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 | 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;
} | [
"private",
"Options",
"getOptions",
"(",
")",
"{",
"Options",
"options",
"=",
"new",
"Options",
"(",
")",
";",
"options",
".",
"addOption",
"(",
"\"h\"",
",",
"HELP",
",",
"false",
",",
"\"print this message\"",
")",
";",
"options",
".",
"addOption",
"(",
... | Create the CML Options.
@return Options expected from command-line. | [
"Create",
"the",
"CML",
"Options",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/cli/src/main/java/com/crawljax/cli/ParameterInterpeter.java#L61-L102 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/FSUtils.java | FSUtils.directoryCheck | public static void directoryCheck(String dir) throws IOException {
final File file = new File(dir);
if (!file.exists()) {
FileUtils.forceMkdir(file);
}
} | java | public static void directoryCheck(String dir) throws IOException {
final File file = new File(dir);
if (!file.exists()) {
FileUtils.forceMkdir(file);
}
} | [
"public",
"static",
"void",
"directoryCheck",
"(",
"String",
"dir",
")",
"throws",
"IOException",
"{",
"final",
"File",
"file",
"=",
"new",
"File",
"(",
"dir",
")",
";",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"FileUtils",
".",
"fo... | Checks the existence of the directory. If it does not exist, the method creates it.
@param dir the directory to check.
@throws IOException if fails. | [
"Checks",
"the",
"existence",
"of",
"the",
"directory",
".",
"If",
"it",
"does",
"not",
"exist",
"the",
"method",
"creates",
"it",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/FSUtils.java#L16-L22 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/FSUtils.java | FSUtils.checkFolderForFile | 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 | 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);
}
} | [
"public",
"static",
"void",
"checkFolderForFile",
"(",
"String",
"fileName",
")",
"throws",
"IOException",
"{",
"if",
"(",
"fileName",
".",
"lastIndexOf",
"(",
"File",
".",
"separator",
")",
">",
"0",
")",
"{",
"String",
"folder",
"=",
"fileName",
".",
"su... | Checks whether the folder exists for fileName, and creates it if necessary.
@param fileName folder name.
@throws IOException an IO exception. | [
"Checks",
"whether",
"the",
"folder",
"exists",
"for",
"fileName",
"and",
"creates",
"it",
"if",
"necessary",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/FSUtils.java#L30-L36 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/CandidateElementManager.java | CandidateElementManager.markChecked | @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 | @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;
}
}
} | [
"@",
"GuardedBy",
"(",
"\"elementsLock\"",
")",
"@",
"Override",
"public",
"boolean",
"markChecked",
"(",
"CandidateElement",
"element",
")",
"{",
"String",
"generalString",
"=",
"element",
".",
"getGeneralString",
"(",
")",
";",
"String",
"uniqueString",
"=",
"... | Mark a given element as checked to prevent duplicate work. A elements is only added when it
is not already in the set of checked elements.
@param element the element that is checked
@return true if !contains(element.uniqueString) | [
"Mark",
"a",
"given",
"element",
"as",
"checked",
"to",
"prevent",
"duplicate",
"work",
".",
"A",
"elements",
"is",
"only",
"added",
"when",
"it",
"is",
"not",
"already",
"in",
"the",
"set",
"of",
"checked",
"elements",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CandidateElementManager.java#L90-L104 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/CrawljaxRunner.java | CrawljaxRunner.readFormDataFromFile | 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 | 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);
}
}
} | [
"private",
"void",
"readFormDataFromFile",
"(",
")",
"{",
"List",
"<",
"FormInput",
">",
"formInputList",
"=",
"FormInputValueHelper",
".",
"deserializeFormInputs",
"(",
"config",
".",
"getSiteDir",
"(",
")",
")",
";",
"if",
"(",
"formInputList",
"!=",
"null",
... | Reads input data from a JSON file in the output directory. | [
"Reads",
"input",
"data",
"from",
"a",
"JSON",
"file",
"in",
"the",
"output",
"directory",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CrawljaxRunner.java#L37-L48 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/CrawljaxRunner.java | CrawljaxRunner.call | @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 | @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;
} | [
"@",
"Override",
"public",
"CrawlSession",
"call",
"(",
")",
"{",
"Injector",
"injector",
"=",
"Guice",
".",
"createInjector",
"(",
"new",
"CoreModule",
"(",
"config",
")",
")",
";",
"controller",
"=",
"injector",
".",
"getInstance",
"(",
"CrawlController",
... | Runs Crawljax with the given configuration.
@return The {@link CrawlSession} once the Crawl is done. | [
"Runs",
"Crawljax",
"with",
"the",
"given",
"configuration",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/CrawljaxRunner.java#L55-L62 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/visual/imagehashes/DHash.java | DHash.distance | public static Integer distance(String h1, String h2) {
HammingDistance distance = new HammingDistance();
return distance.apply(h1, h2);
} | java | public static Integer distance(String h1, String h2) {
HammingDistance distance = new HammingDistance();
return distance.apply(h1, h2);
} | [
"public",
"static",
"Integer",
"distance",
"(",
"String",
"h1",
",",
"String",
"h2",
")",
"{",
"HammingDistance",
"distance",
"=",
"new",
"HammingDistance",
"(",
")",
";",
"return",
"distance",
".",
"apply",
"(",
"h1",
",",
"h2",
")",
";",
"}"
] | Calculate the Hamming distance between two hashes
@param h1
@param h2
@return | [
"Calculate",
"the",
"Hamming",
"distance",
"between",
"two",
"hashes"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/visual/imagehashes/DHash.java#L122-L125 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/forms/FormInputValueHelper.java | FormInputValueHelper.getInstance | public static synchronized FormInputValueHelper getInstance(
InputSpecification inputSpecification, FormFillMode formFillMode) {
if (instance == null)
instance = new FormInputValueHelper(inputSpecification,
formFillMode);
return instance;
} | java | public static synchronized FormInputValueHelper getInstance(
InputSpecification inputSpecification, FormFillMode formFillMode) {
if (instance == null)
instance = new FormInputValueHelper(inputSpecification,
formFillMode);
return instance;
} | [
"public",
"static",
"synchronized",
"FormInputValueHelper",
"getInstance",
"(",
"InputSpecification",
"inputSpecification",
",",
"FormFillMode",
"formFillMode",
")",
"{",
"if",
"(",
"instance",
"==",
"null",
")",
"instance",
"=",
"new",
"FormInputValueHelper",
"(",
"i... | Creates or returns the instance of the helper class.
@param inputSpecification the input specification.
@param formFillMode if random data should be used on the input fields.
@return The singleton instance. | [
"Creates",
"or",
"returns",
"the",
"instance",
"of",
"the",
"helper",
"class",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/forms/FormInputValueHelper.java#L59-L65 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/forms/FormInputValueHelper.java | FormInputValueHelper.formInputMatchingNode | 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 | 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;
} | [
"private",
"FormInput",
"formInputMatchingNode",
"(",
"Node",
"element",
")",
"{",
"NamedNodeMap",
"attributes",
"=",
"element",
".",
"getAttributes",
"(",
")",
";",
"Identification",
"id",
";",
"if",
"(",
"attributes",
".",
"getNamedItem",
"(",
"\"id\"",
")",
... | return the list of FormInputs that match this element
@param element
@return | [
"return",
"the",
"list",
"of",
"FormInputs",
"that",
"match",
"this",
"element"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/forms/FormInputValueHelper.java#L300-L334 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/Crawler.java | Crawler.reset | 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 | 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);
} | [
"public",
"void",
"reset",
"(",
")",
"{",
"CrawlSession",
"session",
"=",
"context",
".",
"getSession",
"(",
")",
";",
"if",
"(",
"crawlpath",
"!=",
"null",
")",
"{",
"session",
".",
"addCrawlPath",
"(",
"crawlpath",
")",
";",
"}",
"List",
"<",
"StateV... | Reset the crawler to its initial state. | [
"Reset",
"the",
"crawler",
"to",
"its",
"initial",
"state",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/Crawler.java#L110-L129 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/Crawler.java | Crawler.fireEvent | 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 | 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
}
} | [
"private",
"boolean",
"fireEvent",
"(",
"Eventable",
"eventable",
")",
"{",
"Eventable",
"eventToFire",
"=",
"eventable",
";",
"if",
"(",
"eventable",
".",
"getIdentification",
"(",
")",
".",
"getHow",
"(",
")",
".",
"toString",
"(",
")",
".",
"equals",
"(... | Try to fire a given event on the Browser.
@param eventable the eventable to fire
@return true iff the event is fired | [
"Try",
"to",
"fire",
"a",
"given",
"event",
"on",
"the",
"Browser",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/Crawler.java#L352-L390 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/Crawler.java | Crawler.crawlIndex | 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 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;
} | [
"public",
"StateVertex",
"crawlIndex",
"(",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Setting up vertex of the index page\"",
")",
";",
"if",
"(",
"basicAuthUrl",
"!=",
"null",
")",
"{",
"browser",
".",
"goToUrl",
"(",
"basicAuthUrl",
")",
";",
"}",
"browser",
... | This method calls the index state. It should be called once per crawl in order to setup the
crawl.
@return The initial state. | [
"This",
"method",
"calls",
"the",
"index",
"state",
".",
"It",
"should",
"be",
"called",
"once",
"per",
"crawl",
"in",
"order",
"to",
"setup",
"the",
"crawl",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/Crawler.java#L620-L647 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTED_InfoTree_Opt.java | RTED_InfoTree_Opt.nonNormalizedTreeDist | public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {
init(t1, t2);
STR = new int[size1][size2];
computeOptimalStrategy();
return computeDistUsingStrArray(it1, it2);
} | java | public double nonNormalizedTreeDist(LblTree t1, LblTree t2) {
init(t1, t2);
STR = new int[size1][size2];
computeOptimalStrategy();
return computeDistUsingStrArray(it1, it2);
} | [
"public",
"double",
"nonNormalizedTreeDist",
"(",
"LblTree",
"t1",
",",
"LblTree",
"t2",
")",
"{",
"init",
"(",
"t1",
",",
"t2",
")",
";",
"STR",
"=",
"new",
"int",
"[",
"size1",
"]",
"[",
"size2",
"]",
";",
"computeOptimalStrategy",
"(",
")",
";",
"... | Computes the tree edit distance between trees t1 and t2.
@param t1
@param t2
@return tree edit distance between trees t1 and t2 | [
"Computes",
"the",
"tree",
"edit",
"distance",
"between",
"trees",
"t1",
"and",
"t2",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTED_InfoTree_Opt.java#L100-L105 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTED_InfoTree_Opt.java | RTED_InfoTree_Opt.init | 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 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;
}
}
}
}
} | [
"public",
"void",
"init",
"(",
"LblTree",
"t1",
",",
"LblTree",
"t2",
")",
"{",
"LabelDictionary",
"ld",
"=",
"new",
"LabelDictionary",
"(",
")",
";",
"it1",
"=",
"new",
"InfoTree",
"(",
"t1",
",",
"ld",
")",
";",
"it2",
"=",
"new",
"InfoTree",
"(",
... | Initialization method.
@param t1
@param t2 | [
"Initialization",
"method",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/RTED_InfoTree_Opt.java#L123-L167 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/state/StateMachine.java | StateMachine.changeState | 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 | 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;
}
} | [
"public",
"boolean",
"changeState",
"(",
"StateVertex",
"nextState",
")",
"{",
"if",
"(",
"nextState",
"==",
"null",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"nextState given is null\"",
")",
";",
"return",
"false",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\... | Change the currentState to the nextState if possible. The next state should already be
present in the graph.
@param nextState the next state.
@return true if currentState is successfully changed. | [
"Change",
"the",
"currentState",
"to",
"the",
"nextState",
"if",
"possible",
".",
"The",
"next",
"state",
"should",
"already",
"be",
"present",
"in",
"the",
"graph",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/StateMachine.java#L67-L88 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/state/StateMachine.java | StateMachine.addStateToCurrentState | 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 | 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;
} | [
"private",
"StateVertex",
"addStateToCurrentState",
"(",
"StateVertex",
"newState",
",",
"Eventable",
"eventable",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"addStateToCurrentState currentState: {} newState {}\"",
",",
"currentState",
".",
"getName",
"(",
")",
",",
"newS... | Adds the newState and the edge between the currentState and the newState on the SFG.
@param newState the new state.
@param eventable the clickable causing the new state.
@return the clone state iff newState is a clone, else returns null | [
"Adds",
"the",
"newState",
"and",
"the",
"edge",
"between",
"the",
"currentState",
"and",
"the",
"newState",
"on",
"the",
"SFG",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/StateMachine.java#L97-L121 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/state/StateMachine.java | StateMachine.switchToStateAndCheckIfClone | 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 | 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;
}
} | [
"public",
"boolean",
"switchToStateAndCheckIfClone",
"(",
"final",
"Eventable",
"event",
",",
"StateVertex",
"newState",
",",
"CrawlerContext",
"context",
")",
"{",
"StateVertex",
"cloneState",
"=",
"this",
".",
"addStateToCurrentState",
"(",
"newState",
",",
"event",... | Adds an edge between the current and new state.
@return true if the new state is not found in the state machine. | [
"Adds",
"an",
"edge",
"between",
"the",
"current",
"and",
"new",
"state",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/state/StateMachine.java#L144-L158 | train |
crawljax/crawljax | cli/src/main/java/com/crawljax/cli/LogUtil.java | LogUtil.logToFile | @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 | @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();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"static",
"void",
"logToFile",
"(",
"String",
"filename",
")",
"{",
"Logger",
"rootLogger",
"=",
"(",
"Logger",
")",
"LoggerFactory",
".",
"getLogger",
"(",
"org",
".",
"slf4j",
".",
"Logger",
".",
"ROOT_LO... | Configure file logging and stop console logging.
@param filename
Log to this file. | [
"Configure",
"file",
"logging",
"and",
"stop",
"console",
"logging",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/cli/src/main/java/com/crawljax/cli/LogUtil.java#L20-L37 | train |
crawljax/crawljax | cli/src/main/java/com/crawljax/cli/JarRunner.java | JarRunner.main | 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 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);
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"try",
"{",
"JarRunner",
"runner",
"=",
"new",
"JarRunner",
"(",
"args",
")",
";",
"runner",
".",
"runIfConfigured",
"(",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",... | Main executable method of Crawljax CLI.
@param args
the arguments. | [
"Main",
"executable",
"method",
"of",
"Crawljax",
"CLI",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/cli/src/main/java/com/crawljax/cli/JarRunner.java#L37-L48 | train |
crawljax/crawljax | plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/model/Serializer.java | Serializer.toPrettyJson | 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 | 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() + "\"";
}
} | [
"public",
"static",
"String",
"toPrettyJson",
"(",
"Object",
"o",
")",
"{",
"try",
"{",
"return",
"MAPPER",
".",
"writerWithDefaultPrettyPrinter",
"(",
")",
".",
"writeValueAsString",
"(",
"o",
")",
";",
"}",
"catch",
"(",
"JsonProcessingException",
"e",
")",
... | Serialize the object JSON. When an error occures return a string with the given error. | [
"Serialize",
"the",
"object",
"JSON",
".",
"When",
"an",
"error",
"occures",
"return",
"a",
"string",
"with",
"the",
"given",
"error",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/model/Serializer.java#L62-L72 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/InfoTree.java | InfoTree.postTraversalProcessing | 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 | 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
}
}
}
} | [
"private",
"void",
"postTraversalProcessing",
"(",
")",
"{",
"int",
"nc1",
"=",
"treeSize",
";",
"info",
"[",
"KR",
"]",
"=",
"new",
"int",
"[",
"leafCount",
"]",
";",
"info",
"[",
"RKR",
"]",
"=",
"new",
"int",
"[",
"leafCount",
"]",
";",
"int",
"... | Gathers information, that couldn't be collected while tree traversal. | [
"Gathers",
"information",
"that",
"couldn",
"t",
"be",
"collected",
"while",
"tree",
"traversal",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/InfoTree.java#L357-L426 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/stateabstractions/dom/RTED/InfoTree.java | InfoTree.toIntArray | 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 | static int[] toIntArray(List<Integer> integers) {
int[] ints = new int[integers.size()];
int i = 0;
for (Integer n : integers) {
ints[i++] = n;
}
return ints;
} | [
"static",
"int",
"[",
"]",
"toIntArray",
"(",
"List",
"<",
"Integer",
">",
"integers",
")",
"{",
"int",
"[",
"]",
"ints",
"=",
"new",
"int",
"[",
"integers",
".",
"size",
"(",
")",
"]",
";",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"Integer",
"n"... | Transforms a list of Integer objects to an array of primitive int values.
@param integers
@return | [
"Transforms",
"a",
"list",
"of",
"Integer",
"objects",
"to",
"an",
"array",
"of",
"primitive",
"int",
"values",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/stateabstractions/dom/RTED/InfoTree.java#L434-L441 | train |
crawljax/crawljax | plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java | CrawlOverview.onNewState | @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 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());
} | [
"@",
"Override",
"public",
"void",
"onNewState",
"(",
"CrawlerContext",
"context",
",",
"StateVertex",
"vertex",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"onNewState\"",
")",
";",
"StateBuilder",
"state",
"=",
"outModelCache",
".",
"addStateIfAbsent",
"(",
"vertex"... | Saves a screenshot of every new state. | [
"Saves",
"a",
"screenshot",
"of",
"every",
"new",
"state",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java#L91-L100 | train |
crawljax/crawljax | plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java | CrawlOverview.preStateCrawling | @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 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");
} | [
"@",
"Override",
"public",
"void",
"preStateCrawling",
"(",
"CrawlerContext",
"context",
",",
"ImmutableList",
"<",
"CandidateElement",
">",
"candidateElements",
",",
"StateVertex",
"state",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"preStateCrawling\"",
")",
";",
"Li... | Logs all the canidate elements so that the plugin knows which elements were the candidate
elements. | [
"Logs",
"all",
"the",
"canidate",
"elements",
"so",
"that",
"the",
"plugin",
"knows",
"which",
"elements",
"were",
"the",
"candidate",
"elements",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java#L139-L160 | train |
crawljax/crawljax | plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java | CrawlOverview.postCrawling | @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 | @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");
} | [
"@",
"Override",
"public",
"void",
"postCrawling",
"(",
"CrawlSession",
"session",
",",
"ExitStatus",
"exitStatus",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"postCrawling\"",
")",
";",
"StateFlowGraph",
"sfg",
"=",
"session",
".",
"getStateFlowGraph",
"(",
")",
"... | Generated the report. | [
"Generated",
"the",
"report",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/plugins/crawloverview-plugin/src/main/java/com/crawljax/plugins/crawloverview/CrawlOverview.java#L199-L222 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/core/configuration/InputSpecification.java | InputSpecification.setValuesInForm | public FormAction setValuesInForm(Form form) {
FormAction formAction = new FormAction();
form.setFormAction(formAction);
this.forms.add(form);
return formAction;
} | java | public FormAction setValuesInForm(Form form) {
FormAction formAction = new FormAction();
form.setFormAction(formAction);
this.forms.add(form);
return formAction;
} | [
"public",
"FormAction",
"setValuesInForm",
"(",
"Form",
"form",
")",
"{",
"FormAction",
"formAction",
"=",
"new",
"FormAction",
"(",
")",
";",
"form",
".",
"setFormAction",
"(",
"formAction",
")",
";",
"this",
".",
"forms",
".",
"add",
"(",
"form",
")",
... | Links the form with an HTML element which can be clicked.
@param form the collection of the input fields
@return a FormAction
@see Form | [
"Links",
"the",
"form",
"with",
"an",
"HTML",
"element",
"which",
"can",
"be",
"clicked",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/core/configuration/InputSpecification.java#L73-L78 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.removeTags | 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 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;
} | [
"public",
"static",
"Document",
"removeTags",
"(",
"Document",
"dom",
",",
"String",
"tagName",
")",
"{",
"NodeList",
"list",
";",
"try",
"{",
"list",
"=",
"XPathHelper",
".",
"evaluateXpathExpression",
"(",
"dom",
",",
"\"//\"",
"+",
"tagName",
".",
"toUppe... | Removes all the given tags from the document.
@param dom the document object.
@param tagName the tag name, examples: script, style, meta
@return the changed dom. | [
"Removes",
"all",
"the",
"given",
"tags",
"from",
"the",
"document",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L171-L193 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.getDocumentToByteArray | 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 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;
} | [
"public",
"static",
"byte",
"[",
"]",
"getDocumentToByteArray",
"(",
"Document",
"dom",
")",
"{",
"try",
"{",
"TransformerFactory",
"tFactory",
"=",
"TransformerFactory",
".",
"newInstance",
"(",
")",
";",
"Transformer",
"transformer",
"=",
"tFactory",
".",
"new... | Serialize the Document object.
@param dom the document to serialize
@return the serialized dom String | [
"Serialize",
"the",
"Document",
"object",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L224-L253 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.addFolderSlashIfNeeded | public static String addFolderSlashIfNeeded(String folderName) {
if (!"".equals(folderName) && !folderName.endsWith("/")) {
return folderName + "/";
} else {
return folderName;
}
} | java | public static String addFolderSlashIfNeeded(String folderName) {
if (!"".equals(folderName) && !folderName.endsWith("/")) {
return folderName + "/";
} else {
return folderName;
}
} | [
"public",
"static",
"String",
"addFolderSlashIfNeeded",
"(",
"String",
"folderName",
")",
"{",
"if",
"(",
"!",
"\"\"",
".",
"equals",
"(",
"folderName",
")",
"&&",
"!",
"folderName",
".",
"endsWith",
"(",
"\"/\"",
")",
")",
"{",
"return",
"folderName",
"+"... | Adds a slash to a path if it doesn't end with a slash.
@param folderName The path to append a possible slash.
@return The new, correct path. | [
"Adds",
"a",
"slash",
"to",
"a",
"path",
"if",
"it",
"doesn",
"t",
"end",
"with",
"a",
"slash",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L349-L355 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.getTemplateAsString | 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 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();
} | [
"public",
"static",
"String",
"getTemplateAsString",
"(",
"String",
"fileName",
")",
"throws",
"IOException",
"{",
"// in .jar file",
"String",
"fNameJar",
"=",
"getFileNameInPath",
"(",
"fileName",
")",
";",
"InputStream",
"inStream",
"=",
"DomUtils",
".",
"class",... | Retrieves the content of the filename. Also reads from JAR Searches for the resource in the
root folder in the jar
@param fileName Filename.
@return The contents of the file.
@throws IOException On error. | [
"Retrieves",
"the",
"content",
"of",
"the",
"filename",
".",
"Also",
"reads",
"from",
"JAR",
"Searches",
"for",
"the",
"resource",
"in",
"the",
"root",
"folder",
"in",
"the",
"jar"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L382-L409 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.writeDocumentToFile | 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 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)));
} | [
"public",
"static",
"void",
"writeDocumentToFile",
"(",
"Document",
"document",
",",
"String",
"filePathname",
",",
"String",
"method",
",",
"int",
"indent",
")",
"throws",
"TransformerException",
",",
"IOException",
"{",
"Transformer",
"transformer",
"=",
"Transfor... | Write the document object to a file.
@param document the document object.
@param filePathname the path name of the file to be written to.
@param method the output method: for instance html, xml, text
@param indent amount of indentation. -1 to use the default.
@throws TransformerException if an exception occurs.
@throws IOException if an IO exception occurs. | [
"Write",
"the",
"document",
"object",
"to",
"a",
"file",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L443-L455 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/DomUtils.java | DomUtils.getTextContent | 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 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;
} | [
"public",
"static",
"String",
"getTextContent",
"(",
"Document",
"document",
",",
"boolean",
"individualTokens",
")",
"{",
"String",
"textContent",
"=",
"null",
";",
"if",
"(",
"individualTokens",
")",
"{",
"List",
"<",
"String",
">",
"tokens",
"=",
"getTextTo... | To get all the textual content in the dom
@param document
@param individualTokens : default True : when set to true, each text node from dom is used to build the
text content : when set to false, the text content of whole is obtained at once.
@return | [
"To",
"get",
"all",
"the",
"textual",
"content",
"in",
"the",
"dom"
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DomUtils.java#L511-L521 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/ElementResolver.java | ElementResolver.equivalent | 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 | 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;
} | [
"public",
"boolean",
"equivalent",
"(",
"Element",
"otherElement",
",",
"boolean",
"logging",
")",
"{",
"if",
"(",
"eventable",
".",
"getElement",
"(",
")",
".",
"equals",
"(",
"otherElement",
")",
")",
"{",
"if",
"(",
"logging",
")",
"{",
"LOGGER",
".",... | Comparator against other element.
@param otherElement The other element.
@param logging Whether to do logging.
@return Whether the elements are equal. | [
"Comparator",
"against",
"other",
"element",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/ElementResolver.java#L105-L138 | train |
crawljax/crawljax | core/src/main/java/com/crawljax/util/DOMComparer.java | DOMComparer.compare | @SuppressWarnings("unchecked")
public List<Difference> compare() {
Diff diff = new Diff(this.controlDOM, this.testDOM);
DetailedDiff detDiff = new DetailedDiff(diff);
return detDiff.getAllDifferences();
} | java | @SuppressWarnings("unchecked")
public List<Difference> compare() {
Diff diff = new Diff(this.controlDOM, this.testDOM);
DetailedDiff detDiff = new DetailedDiff(diff);
return detDiff.getAllDifferences();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"List",
"<",
"Difference",
">",
"compare",
"(",
")",
"{",
"Diff",
"diff",
"=",
"new",
"Diff",
"(",
"this",
".",
"controlDOM",
",",
"this",
".",
"testDOM",
")",
";",
"DetailedDiff",
"detDiff",
... | Compare the controlDOM and testDOM and save and return the differences in a list.
@return list with differences | [
"Compare",
"the",
"controlDOM",
"and",
"testDOM",
"and",
"save",
"and",
"return",
"the",
"differences",
"in",
"a",
"list",
"."
] | d339f4f622ca902ccd35322065821e52a62ec543 | https://github.com/crawljax/crawljax/blob/d339f4f622ca902ccd35322065821e52a62ec543/core/src/main/java/com/crawljax/util/DOMComparer.java#L42-L47 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.