code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private boolean openTemplate(String filename)
{
InputStreamReader isr = null;
try
{
isr = new InputStreamReader(IOUtil.newInputStream(filename), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
if (line.length() == 0 || line.charAt(0) == ' ' || line.charAt(0) == '#')
{
continue;
}
else if (line.charAt(0) == 'U')
{
unigramTempls_.add(line.trim());
}
else if (line.charAt(0) == 'B')
{
bigramTempls_.add(line.trim());
}
else
{
System.err.println("unknown type: " + line);
}
}
br.close();
templs_ = makeTempls(unigramTempls_, bigramTempls_);
}
catch (Exception e)
{
if (isr != null)
{
try
{
isr.close();
}
catch (Exception e2)
{
}
}
e.printStackTrace();
System.err.println("Error reading " + filename);
return false;
}
return true;
} } | public class class_name {
private boolean openTemplate(String filename)
{
InputStreamReader isr = null;
try
{
isr = new InputStreamReader(IOUtil.newInputStream(filename), "UTF-8"); // depends on control dependency: [try], data = [none]
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
if (line.length() == 0 || line.charAt(0) == ' ' || line.charAt(0) == '#')
{
continue;
}
else if (line.charAt(0) == 'U')
{
unigramTempls_.add(line.trim()); // depends on control dependency: [if], data = [none]
}
else if (line.charAt(0) == 'B')
{
bigramTempls_.add(line.trim()); // depends on control dependency: [if], data = [none]
}
else
{
System.err.println("unknown type: " + line); // depends on control dependency: [if], data = [none]
}
}
br.close(); // depends on control dependency: [try], data = [none]
templs_ = makeTempls(unigramTempls_, bigramTempls_); // depends on control dependency: [try], data = [none]
}
catch (Exception e)
{
if (isr != null)
{
try
{
isr.close(); // depends on control dependency: [try], data = [none]
}
catch (Exception e2)
{
} // depends on control dependency: [catch], data = [none]
}
e.printStackTrace();
System.err.println("Error reading " + filename);
return false;
} // depends on control dependency: [catch], data = [none]
return true;
} } |
public class class_name {
public void setElementKeyPaths(String... paths) {
resetResults();
elementKeyPaths = new BitSet(elementPaths.length);
for(int i=0;i<paths.length;i++) {
int elementPathIdx = getElementPathIdx(paths[i]);
if(elementPathIdx == -1)
throw new IllegalArgumentException("Key path must have been specified as an element match path. Offending path: " + paths[i]);
elementKeyPaths.set(elementPathIdx);
}
elementNonKeyPaths = new BitSet(elementPaths.length);
elementNonKeyPaths.set(0, elementPaths.length);
elementNonKeyPaths.andNot(elementKeyPaths);
} } | public class class_name {
public void setElementKeyPaths(String... paths) {
resetResults();
elementKeyPaths = new BitSet(elementPaths.length);
for(int i=0;i<paths.length;i++) {
int elementPathIdx = getElementPathIdx(paths[i]);
if(elementPathIdx == -1)
throw new IllegalArgumentException("Key path must have been specified as an element match path. Offending path: " + paths[i]);
elementKeyPaths.set(elementPathIdx); // depends on control dependency: [for], data = [none]
}
elementNonKeyPaths = new BitSet(elementPaths.length);
elementNonKeyPaths.set(0, elementPaths.length);
elementNonKeyPaths.andNot(elementKeyPaths);
} } |
public class class_name {
public RTMClient rtmConnect(String apiToken, boolean fullUserInfoRequired) throws IOException {
try {
RTMConnectResponse response = methods().rtmConnect(RTMConnectRequest.builder().token(apiToken).build());
if (response.isOk()) {
User connectedBotUser = response.getSelf();
if (fullUserInfoRequired) {
String userId = response.getSelf().getId();
UsersInfoResponse resp = this.methods().usersInfo(UsersInfoRequest.builder().token(apiToken).user(userId).build());
if (resp.isOk()) {
connectedBotUser = resp.getUser();
} else {
String errorMessage = "Failed to get fill user info (user id: " + response.getSelf().getId() + ", error: " + resp.getError() + ")";
throw new IllegalStateException(errorMessage);
}
}
return new RTMClient(this, apiToken, response.getUrl(), connectedBotUser);
} else {
throw new IllegalStateException("Failed to the RTM endpoint URL (error: " + response.getError() + ")");
}
} catch (SlackApiException e) {
throw new IllegalStateException(
"Failed to connect to the RTM API endpoint. (" +
"status: " + e.getResponse().code() + ", " +
"error: " + e.getError().getError() +
")", e);
} catch (URISyntaxException e) {
throw new IllegalStateException(
"Failed to connect to the RTM API endpoint. (message: " + e.getMessage() + ")", e);
}
} } | public class class_name {
public RTMClient rtmConnect(String apiToken, boolean fullUserInfoRequired) throws IOException {
try {
RTMConnectResponse response = methods().rtmConnect(RTMConnectRequest.builder().token(apiToken).build());
if (response.isOk()) {
User connectedBotUser = response.getSelf();
if (fullUserInfoRequired) {
String userId = response.getSelf().getId();
UsersInfoResponse resp = this.methods().usersInfo(UsersInfoRequest.builder().token(apiToken).user(userId).build());
if (resp.isOk()) {
connectedBotUser = resp.getUser(); // depends on control dependency: [if], data = [none]
} else {
String errorMessage = "Failed to get fill user info (user id: " + response.getSelf().getId() + ", error: " + resp.getError() + ")";
throw new IllegalStateException(errorMessage); // depends on control dependency: [if], data = [none]
}
}
return new RTMClient(this, apiToken, response.getUrl(), connectedBotUser);
} else {
throw new IllegalStateException("Failed to the RTM endpoint URL (error: " + response.getError() + ")");
}
} catch (SlackApiException e) {
throw new IllegalStateException(
"Failed to connect to the RTM API endpoint. (" +
"status: " + e.getResponse().code() + ", " +
"error: " + e.getError().getError() +
")", e);
} catch (URISyntaxException e) {
throw new IllegalStateException(
"Failed to connect to the RTM API endpoint. (message: " + e.getMessage() + ")", e);
}
} } |
public class class_name {
public ActivityImpl parseTask(Element taskElement, ScopeImpl scope) {
ActivityImpl activity = createActivityOnScope(taskElement, scope);
activity.setActivityBehavior(new TaskActivityBehavior());
parseAsynchronousContinuationForActivity(taskElement, activity);
parseExecutionListenersOnScope(taskElement, activity);
for (BpmnParseListener parseListener : parseListeners) {
parseListener.parseTask(taskElement, scope, activity);
}
// createMessageJobDeclForAsyncActivity(activity, true);
return activity;
} } | public class class_name {
public ActivityImpl parseTask(Element taskElement, ScopeImpl scope) {
ActivityImpl activity = createActivityOnScope(taskElement, scope);
activity.setActivityBehavior(new TaskActivityBehavior());
parseAsynchronousContinuationForActivity(taskElement, activity);
parseExecutionListenersOnScope(taskElement, activity);
for (BpmnParseListener parseListener : parseListeners) {
parseListener.parseTask(taskElement, scope, activity); // depends on control dependency: [for], data = [parseListener]
}
// createMessageJobDeclForAsyncActivity(activity, true);
return activity;
} } |
public class class_name {
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) {
boolean refreshToken = false;
boolean bearer = false;
List<String> authenticateList = response.getHeaders().getAuthenticateAsList();
// TODO(peleyal): this logic should be implemented as a pluggable interface, in the same way we
// implement different AccessMethods
// if authenticate list is not null we will check if one of the entries contains "Bearer"
if (authenticateList != null) {
for (String authenticate : authenticateList) {
if (authenticate.startsWith(BearerToken.AuthorizationHeaderAccessMethod.HEADER_PREFIX)) {
// mark that we found a "Bearer" value, and check if there is a invalid_token error
bearer = true;
refreshToken = BearerToken.INVALID_TOKEN_ERROR.matcher(authenticate).find();
break;
}
}
}
// if "Bearer" wasn't found, we will refresh the token, if we got 401
if (!bearer) {
refreshToken = response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED;
}
if (refreshToken) {
try {
lock.lock();
try {
// need to check if another thread has already refreshed the token
return !Objects.equal(accessToken, method.getAccessTokenFromRequest(request))
|| refreshToken();
} finally {
lock.unlock();
}
} catch (IOException exception) {
LOGGER.log(Level.SEVERE, "unable to refresh token", exception);
}
}
return false;
} } | public class class_name {
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) {
boolean refreshToken = false;
boolean bearer = false;
List<String> authenticateList = response.getHeaders().getAuthenticateAsList();
// TODO(peleyal): this logic should be implemented as a pluggable interface, in the same way we
// implement different AccessMethods
// if authenticate list is not null we will check if one of the entries contains "Bearer"
if (authenticateList != null) {
for (String authenticate : authenticateList) {
if (authenticate.startsWith(BearerToken.AuthorizationHeaderAccessMethod.HEADER_PREFIX)) {
// mark that we found a "Bearer" value, and check if there is a invalid_token error
bearer = true; // depends on control dependency: [if], data = [none]
refreshToken = BearerToken.INVALID_TOKEN_ERROR.matcher(authenticate).find(); // depends on control dependency: [if], data = [none]
break;
}
}
}
// if "Bearer" wasn't found, we will refresh the token, if we got 401
if (!bearer) {
refreshToken = response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED; // depends on control dependency: [if], data = [none]
}
if (refreshToken) {
try {
lock.lock(); // depends on control dependency: [try], data = [none]
try {
// need to check if another thread has already refreshed the token
return !Objects.equal(accessToken, method.getAccessTokenFromRequest(request))
|| refreshToken(); // depends on control dependency: [try], data = [none]
} finally {
lock.unlock();
}
} catch (IOException exception) {
LOGGER.log(Level.SEVERE, "unable to refresh token", exception);
} // depends on control dependency: [catch], data = [none]
}
return false;
} } |
public class class_name {
public long getMin() {
for (int i = 0; i < hits.length(); i++) {
if (hits.get(i) > 0) {
return i == 0 ? 0 : 1 + bins[i - 1];
}
}
return 0;
} } | public class class_name {
public long getMin() {
for (int i = 0; i < hits.length(); i++) {
if (hits.get(i) > 0) {
return i == 0 ? 0 : 1 + bins[i - 1];
// depends on control dependency: [if], data = [none]
}
}
return 0;
} } |
public class class_name {
private void write(PrintWriter writer, Janitor janitor, List messages, String txt) {
if (messages==null || messages.isEmpty()) return;
Iterator iterator = messages.iterator();
while (iterator.hasNext()) {
Message message = (Message) iterator.next();
message.write(writer, janitor);
if (configuration.getDebug() && (message instanceof SyntaxErrorMessage)){
SyntaxErrorMessage sem = (SyntaxErrorMessage) message;
sem.getCause().printStackTrace(writer);
}
writer.println();
}
writer.print(messages.size());
writer.print(" "+txt);
if (messages.size()>1) writer.print("s");
writer.println();
} } | public class class_name {
private void write(PrintWriter writer, Janitor janitor, List messages, String txt) {
if (messages==null || messages.isEmpty()) return;
Iterator iterator = messages.iterator();
while (iterator.hasNext()) {
Message message = (Message) iterator.next();
message.write(writer, janitor); // depends on control dependency: [while], data = [none]
if (configuration.getDebug() && (message instanceof SyntaxErrorMessage)){
SyntaxErrorMessage sem = (SyntaxErrorMessage) message;
sem.getCause().printStackTrace(writer); // depends on control dependency: [if], data = [none]
}
writer.println(); // depends on control dependency: [while], data = [none]
}
writer.print(messages.size());
writer.print(" "+txt);
if (messages.size()>1) writer.print("s");
writer.println();
} } |
public class class_name {
public static void addColTimes(Matrix matrix, long diag, long fromRow, long col, double factor) {
long rows = matrix.getRowCount();
for (long row = fromRow; row < rows; row++) {
matrix.setAsDouble(
matrix.getAsDouble(row, col) - factor * matrix.getAsDouble(row, diag), row, col);
}
} } | public class class_name {
public static void addColTimes(Matrix matrix, long diag, long fromRow, long col, double factor) {
long rows = matrix.getRowCount();
for (long row = fromRow; row < rows; row++) {
matrix.setAsDouble(
matrix.getAsDouble(row, col) - factor * matrix.getAsDouble(row, diag), row, col); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
static GVRPickedObject makeHit(long colliderPointer, float distance, float hitx, float hity, float hitz)
{
GVRCollider collider = GVRCollider.lookup(colliderPointer);
if (collider == null)
{
Log.d(TAG, "makeHit: cannot find collider for %x", colliderPointer);
return null;
}
return new GVRPicker.GVRPickedObject(collider, new float[] { hitx, hity, hitz }, distance);
} } | public class class_name {
static GVRPickedObject makeHit(long colliderPointer, float distance, float hitx, float hity, float hitz)
{
GVRCollider collider = GVRCollider.lookup(colliderPointer);
if (collider == null)
{
Log.d(TAG, "makeHit: cannot find collider for %x", colliderPointer); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
return new GVRPicker.GVRPickedObject(collider, new float[] { hitx, hity, hitz }, distance);
} } |
public class class_name {
public static String createJquery(Chart<?> chart, String divId, String javaScriptVar) {
StringBuilder builder = new StringBuilder();
builder.append("$(document).ready(function(){\r\n");
if (javaScriptVar != null) {
builder.append(" var ").append(javaScriptVar).append("=");
}
builder.append(" $.jqplot('").append(divId).append("', ");
builder.append(chart.getChartData().toJsonString());
builder.append(", ");
builder.append(jqPlotToJson(chart.getChartConfiguration()));
builder.append(");\r\n");
builder.append("});\r\n");
return builder.toString();
} } | public class class_name {
public static String createJquery(Chart<?> chart, String divId, String javaScriptVar) {
StringBuilder builder = new StringBuilder();
builder.append("$(document).ready(function(){\r\n");
if (javaScriptVar != null) {
builder.append(" var ").append(javaScriptVar).append("="); // depends on control dependency: [if], data = [(javaScriptVar]
}
builder.append(" $.jqplot('").append(divId).append("', ");
builder.append(chart.getChartData().toJsonString());
builder.append(", ");
builder.append(jqPlotToJson(chart.getChartConfiguration()));
builder.append(");\r\n");
builder.append("});\r\n");
return builder.toString();
} } |
public class class_name {
private static ClassLoader getInitParent(ClassLoader parent,
boolean isRoot)
{
if (parent == null)
parent = Thread.currentThread().getContextClassLoader();
if (isRoot || parent instanceof DynamicClassLoader)
return parent;
else {
//return RootDynamicClassLoader.create(parent);
return parent;
}
} } | public class class_name {
private static ClassLoader getInitParent(ClassLoader parent,
boolean isRoot)
{
if (parent == null)
parent = Thread.currentThread().getContextClassLoader();
if (isRoot || parent instanceof DynamicClassLoader)
return parent;
else {
//return RootDynamicClassLoader.create(parent);
return parent; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void resetPackageList() {
final Set<PackageDoc> set = new TreeSet<>();
for (final PackageDoc pack : this.root.specifiedPackages()) {
set.add(pack);
}
for (final ClassDoc clazz : this.root.specifiedClasses()) {
set.add(clazz.containingPackage());
}
this.packages = Utils.toArray(this.packages, set);
} } | public class class_name {
private void resetPackageList() {
final Set<PackageDoc> set = new TreeSet<>();
for (final PackageDoc pack : this.root.specifiedPackages()) {
set.add(pack); // depends on control dependency: [for], data = [pack]
}
for (final ClassDoc clazz : this.root.specifiedClasses()) {
set.add(clazz.containingPackage()); // depends on control dependency: [for], data = [clazz]
}
this.packages = Utils.toArray(this.packages, set);
} } |
public class class_name {
public final void mMISC() throws RecognitionException {
try {
int _type = MISC;
int _channel = DEFAULT_TOKEN_CHANNEL;
// src/main/resources/org/drools/compiler/lang/DRL6Lexer.g:342:7: ( '\\'' | '\\\\' | '$' )
// src/main/resources/org/drools/compiler/lang/DRL6Lexer.g:
{
if ( input.LA(1)=='$'||input.LA(1)=='\''||input.LA(1)=='\\' ) {
input.consume();
state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } | public class class_name {
public final void mMISC() throws RecognitionException {
try {
int _type = MISC;
int _channel = DEFAULT_TOKEN_CHANNEL;
// src/main/resources/org/drools/compiler/lang/DRL6Lexer.g:342:7: ( '\\'' | '\\\\' | '$' )
// src/main/resources/org/drools/compiler/lang/DRL6Lexer.g:
{
if ( input.LA(1)=='$'||input.LA(1)=='\''||input.LA(1)=='\\' ) {
input.consume(); // depends on control dependency: [if], data = [none]
state.failed=false; // depends on control dependency: [if], data = [none]
}
else {
if (state.backtracking>0) {state.failed=true; return;} // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse); // depends on control dependency: [if], data = [none]
throw mse;
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} } |
public class class_name {
public boolean isExcludedClass(String className) {
// We rely heavily on reflection to deliver probes
if (className.startsWith("java/lang/reflect")) {
return true;
}
// Miscellaneous sun.misc classes
if (className.startsWith("sun/misc")) {
return true;
}
// Sun VM generated accessors wreak havoc
if (className.startsWith("sun/reflect")) {
return true;
}
// IBM J9 VM internals
if (className.startsWith("com/ibm/oti/")) {
return true;
}
// Don't allow hooking into the monitoring code
if (className.startsWith("com/ibm/ws/monitor/internal")) {
return true;
}
if (className.startsWith("com/ibm/websphere/monitor")) {
return true;
}
if (className.startsWith("com/ibm/ws/boot/delegated/monitoring")) {
return true;
}
if ((className.startsWith("com/ibm/ws/pmi")) || (className.startsWith("com/ibm/websphere/pmi")) || (className.startsWith("com/ibm/wsspi/pmi"))) {
return true;
}
//D89497-Excluding those classes which are not part of the Set.
if ((!(probeMonitorSet.contains((className.replace("/", ".")))))) {
return true;
}
return false;
} } | public class class_name {
public boolean isExcludedClass(String className) {
// We rely heavily on reflection to deliver probes
if (className.startsWith("java/lang/reflect")) {
return true; // depends on control dependency: [if], data = [none]
}
// Miscellaneous sun.misc classes
if (className.startsWith("sun/misc")) {
return true; // depends on control dependency: [if], data = [none]
}
// Sun VM generated accessors wreak havoc
if (className.startsWith("sun/reflect")) {
return true; // depends on control dependency: [if], data = [none]
}
// IBM J9 VM internals
if (className.startsWith("com/ibm/oti/")) {
return true; // depends on control dependency: [if], data = [none]
}
// Don't allow hooking into the monitoring code
if (className.startsWith("com/ibm/ws/monitor/internal")) {
return true; // depends on control dependency: [if], data = [none]
}
if (className.startsWith("com/ibm/websphere/monitor")) {
return true; // depends on control dependency: [if], data = [none]
}
if (className.startsWith("com/ibm/ws/boot/delegated/monitoring")) {
return true; // depends on control dependency: [if], data = [none]
}
if ((className.startsWith("com/ibm/ws/pmi")) || (className.startsWith("com/ibm/websphere/pmi")) || (className.startsWith("com/ibm/wsspi/pmi"))) {
return true; // depends on control dependency: [if], data = [none]
}
//D89497-Excluding those classes which are not part of the Set.
if ((!(probeMonitorSet.contains((className.replace("/", ".")))))) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public void marshall(Spend spend, ProtocolMarshaller protocolMarshaller) {
if (spend == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(spend.getAmount(), AMOUNT_BINDING);
protocolMarshaller.marshall(spend.getUnit(), UNIT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(Spend spend, ProtocolMarshaller protocolMarshaller) {
if (spend == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(spend.getAmount(), AMOUNT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(spend.getUnit(), UNIT_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void deviceTokenDidRefresh(String token, PushType type) {
if (tokenRefreshListener != null) {
getConfigLogger().debug(getAccountId(), "Notifying devicePushTokenDidRefresh: " + token);
tokenRefreshListener.devicePushTokenDidRefresh(token, type);
}
} } | public class class_name {
private void deviceTokenDidRefresh(String token, PushType type) {
if (tokenRefreshListener != null) {
getConfigLogger().debug(getAccountId(), "Notifying devicePushTokenDidRefresh: " + token); // depends on control dependency: [if], data = [none]
tokenRefreshListener.devicePushTokenDidRefresh(token, type); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
boolean removePersona(SPFPersona persona) {
SQLiteDatabase db = getWritableDatabase();
if (persona.getIdentifier().equals("default")) {
return false;
}
String table = Contract.TABLE_PERSONAS;
String selection = Contract.COLUMN_PERSONA + " = ?";
String[] selectionArgs = { persona.getIdentifier() };
if (db.delete(table, selection, selectionArgs) > 0) {
deleteFieldsOf(persona, db);
deleteVisibilityOf(persona, db);
}
return true;
} } | public class class_name {
boolean removePersona(SPFPersona persona) {
SQLiteDatabase db = getWritableDatabase();
if (persona.getIdentifier().equals("default")) {
return false; // depends on control dependency: [if], data = [none]
}
String table = Contract.TABLE_PERSONAS;
String selection = Contract.COLUMN_PERSONA + " = ?";
String[] selectionArgs = { persona.getIdentifier() };
if (db.delete(table, selection, selectionArgs) > 0) {
deleteFieldsOf(persona, db); // depends on control dependency: [if], data = [none]
deleteVisibilityOf(persona, db); // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public Element dereferenceVariable(String name, boolean lookupOnly,
Term[] terms) throws InvalidTermException {
boolean duplicate = false;
Element result = localVariables.get(name);
// If the result is null, then try to look up a global variable.
if (result == null) {
duplicate = true;
result = getGlobalVariable(name);
}
// Now actually dereference the given variable. The caller must deal
// with any invalid term exceptions or evaluation exceptions. We just
// pass those on.
if (result != null) {
if (!(result instanceof Undef)) {
// FIXME: Determine if the result needs to be protected.
result = result.rget(terms, 0, false, lookupOnly);
} else {
// Trying to dereference an undefined value. Therefore, the
// value does not exist; return null to caller.
result = null;
}
}
// FIXME: This is inefficient and should be avoided. However, one must
// ensure that global variables are protected against changes.
// To ensure that global variables are not inadvertently modified via
// copies in local variables, duplicate the result. Do this only AFTER
// the dereference to limit the amount of potentially unnecessary
// cloning.
if (duplicate && result != null) {
result = result.duplicate();
}
return result;
} } | public class class_name {
public Element dereferenceVariable(String name, boolean lookupOnly,
Term[] terms) throws InvalidTermException {
boolean duplicate = false;
Element result = localVariables.get(name);
// If the result is null, then try to look up a global variable.
if (result == null) {
duplicate = true;
result = getGlobalVariable(name);
}
// Now actually dereference the given variable. The caller must deal
// with any invalid term exceptions or evaluation exceptions. We just
// pass those on.
if (result != null) {
if (!(result instanceof Undef)) {
// FIXME: Determine if the result needs to be protected.
result = result.rget(terms, 0, false, lookupOnly); // depends on control dependency: [if], data = [none]
} else {
// Trying to dereference an undefined value. Therefore, the
// value does not exist; return null to caller.
result = null; // depends on control dependency: [if], data = [none]
}
}
// FIXME: This is inefficient and should be avoided. However, one must
// ensure that global variables are protected against changes.
// To ensure that global variables are not inadvertently modified via
// copies in local variables, duplicate the result. Do this only AFTER
// the dereference to limit the amount of potentially unnecessary
// cloning.
if (duplicate && result != null) {
result = result.duplicate();
}
return result;
} } |
public class class_name {
@Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WEditableImage editableImage = (WEditableImage) component;
XmlStringBuilder xml = renderContext.getWriter();
// No image set
if (editableImage.getImage() == null && editableImage.getImageUrl() == null) {
return;
}
WImageRenderer.renderTagOpen(editableImage, xml);
WComponent uploader = editableImage.getEditUploader();
if (uploader != null) {
xml.appendAttribute("data-wc-editor", uploader.getId());
}
xml.appendEnd();
} } | public class class_name {
@Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WEditableImage editableImage = (WEditableImage) component;
XmlStringBuilder xml = renderContext.getWriter();
// No image set
if (editableImage.getImage() == null && editableImage.getImageUrl() == null) {
return; // depends on control dependency: [if], data = [none]
}
WImageRenderer.renderTagOpen(editableImage, xml);
WComponent uploader = editableImage.getEditUploader();
if (uploader != null) {
xml.appendAttribute("data-wc-editor", uploader.getId()); // depends on control dependency: [if], data = [none]
}
xml.appendEnd();
} } |
public class class_name {
public static Pair<INDArray,int[]> pullLastTimeSteps(INDArray pullFrom, INDArray mask){
//Then: work out, from the mask array, which time step of activations we want, extract activations
//Also: record where they came from (so we can do errors later)
int[] fwdPassTimeSteps;
INDArray out;
if (mask == null) {
// FIXME: int cast
//No mask array -> extract same (last) column for all
int lastTS = (int) pullFrom.size(2) - 1;
out = pullFrom.get(NDArrayIndex.all(), NDArrayIndex.all(), NDArrayIndex.point(lastTS));
fwdPassTimeSteps = null; //Null -> last time step for all examples
} else {
val outShape = new long[] {pullFrom.size(0), pullFrom.size(1)};
out = Nd4j.create(outShape);
//Want the index of the last non-zero entry in the mask array
INDArray lastStepArr = BooleanIndexing.lastIndex(mask, Conditions.epsNotEquals(0.0), 1);
fwdPassTimeSteps = lastStepArr.data().asInt();
//Now, get and assign the corresponding subsets of 3d activations:
for (int i = 0; i < fwdPassTimeSteps.length; i++) {
//TODO can optimize using reshape + pullRows
out.putRow(i, pullFrom.get(NDArrayIndex.point(i), NDArrayIndex.all(),
NDArrayIndex.point(fwdPassTimeSteps[i])));
}
}
return new Pair<>(out, fwdPassTimeSteps);
} } | public class class_name {
public static Pair<INDArray,int[]> pullLastTimeSteps(INDArray pullFrom, INDArray mask){
//Then: work out, from the mask array, which time step of activations we want, extract activations
//Also: record where they came from (so we can do errors later)
int[] fwdPassTimeSteps;
INDArray out;
if (mask == null) {
// FIXME: int cast
//No mask array -> extract same (last) column for all
int lastTS = (int) pullFrom.size(2) - 1;
out = pullFrom.get(NDArrayIndex.all(), NDArrayIndex.all(), NDArrayIndex.point(lastTS)); // depends on control dependency: [if], data = [none]
fwdPassTimeSteps = null; //Null -> last time step for all examples // depends on control dependency: [if], data = [none]
} else {
val outShape = new long[] {pullFrom.size(0), pullFrom.size(1)};
out = Nd4j.create(outShape); // depends on control dependency: [if], data = [none]
//Want the index of the last non-zero entry in the mask array
INDArray lastStepArr = BooleanIndexing.lastIndex(mask, Conditions.epsNotEquals(0.0), 1);
fwdPassTimeSteps = lastStepArr.data().asInt(); // depends on control dependency: [if], data = [none]
//Now, get and assign the corresponding subsets of 3d activations:
for (int i = 0; i < fwdPassTimeSteps.length; i++) {
//TODO can optimize using reshape + pullRows
out.putRow(i, pullFrom.get(NDArrayIndex.point(i), NDArrayIndex.all(),
NDArrayIndex.point(fwdPassTimeSteps[i]))); // depends on control dependency: [for], data = [i]
}
}
return new Pair<>(out, fwdPassTimeSteps);
} } |
public class class_name {
public static List<Node> removeNestedChangeScopeNodes(List<Node> scopeNodes) {
Set<Node> uniqueScopeNodes = new LinkedHashSet<>(scopeNodes);
for (Node scopeNode : scopeNodes) {
for (Node ancestor = scopeNode.getParent();
ancestor != null;
ancestor = ancestor.getParent()) {
if (isChangeScopeRoot(ancestor) && uniqueScopeNodes.contains(ancestor)) {
uniqueScopeNodes.remove(scopeNode);
break;
}
}
}
return new ArrayList<>(uniqueScopeNodes);
} } | public class class_name {
public static List<Node> removeNestedChangeScopeNodes(List<Node> scopeNodes) {
Set<Node> uniqueScopeNodes = new LinkedHashSet<>(scopeNodes);
for (Node scopeNode : scopeNodes) {
for (Node ancestor = scopeNode.getParent();
ancestor != null;
ancestor = ancestor.getParent()) {
if (isChangeScopeRoot(ancestor) && uniqueScopeNodes.contains(ancestor)) {
uniqueScopeNodes.remove(scopeNode); // depends on control dependency: [if], data = [none]
break;
}
}
}
return new ArrayList<>(uniqueScopeNodes);
} } |
public class class_name {
public void marshall(ReservedElasticsearchInstance reservedElasticsearchInstance, ProtocolMarshaller protocolMarshaller) {
if (reservedElasticsearchInstance == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(reservedElasticsearchInstance.getReservationName(), RESERVATIONNAME_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getReservedElasticsearchInstanceId(), RESERVEDELASTICSEARCHINSTANCEID_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getReservedElasticsearchInstanceOfferingId(),
RESERVEDELASTICSEARCHINSTANCEOFFERINGID_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getElasticsearchInstanceType(), ELASTICSEARCHINSTANCETYPE_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getStartTime(), STARTTIME_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getDuration(), DURATION_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getFixedPrice(), FIXEDPRICE_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getUsagePrice(), USAGEPRICE_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getCurrencyCode(), CURRENCYCODE_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getElasticsearchInstanceCount(), ELASTICSEARCHINSTANCECOUNT_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getState(), STATE_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getPaymentOption(), PAYMENTOPTION_BINDING);
protocolMarshaller.marshall(reservedElasticsearchInstance.getRecurringCharges(), RECURRINGCHARGES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ReservedElasticsearchInstance reservedElasticsearchInstance, ProtocolMarshaller protocolMarshaller) {
if (reservedElasticsearchInstance == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(reservedElasticsearchInstance.getReservationName(), RESERVATIONNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getReservedElasticsearchInstanceId(), RESERVEDELASTICSEARCHINSTANCEID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getReservedElasticsearchInstanceOfferingId(),
RESERVEDELASTICSEARCHINSTANCEOFFERINGID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getElasticsearchInstanceType(), ELASTICSEARCHINSTANCETYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getStartTime(), STARTTIME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getDuration(), DURATION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getFixedPrice(), FIXEDPRICE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getUsagePrice(), USAGEPRICE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getCurrencyCode(), CURRENCYCODE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getElasticsearchInstanceCount(), ELASTICSEARCHINSTANCECOUNT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getState(), STATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getPaymentOption(), PAYMENTOPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(reservedElasticsearchInstance.getRecurringCharges(), RECURRINGCHARGES_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public java.util.List<Type> getType() {
if (myType == null) {
myType = new java.util.ArrayList<Type>();
}
return myType;
} } | public class class_name {
public java.util.List<Type> getType() {
if (myType == null) {
myType = new java.util.ArrayList<Type>(); // depends on control dependency: [if], data = [none]
}
return myType;
} } |
public class class_name {
public NotificationEntry findNotificationEntryById(final String notificationId) {
// Assertions
if (notificationId == null) {
String msg = "Argument 'notificationId' cannot be null";
throw new IllegalArgumentException(msg);
}
// Providing a brute-force implementation for
// now; we can improve it if it becomes important.
NotificationEntry rslt = null; // default -- means not present
for (NotificationCategory category : categories) {
for (NotificationEntry entry : category.getEntries()) {
if (notificationId.equals(entry.getId())) {
rslt = entry;
break;
}
}
if (rslt != null) {
break;
}
}
return rslt;
} } | public class class_name {
public NotificationEntry findNotificationEntryById(final String notificationId) {
// Assertions
if (notificationId == null) {
String msg = "Argument 'notificationId' cannot be null";
throw new IllegalArgumentException(msg);
}
// Providing a brute-force implementation for
// now; we can improve it if it becomes important.
NotificationEntry rslt = null; // default -- means not present
for (NotificationCategory category : categories) {
for (NotificationEntry entry : category.getEntries()) {
if (notificationId.equals(entry.getId())) {
rslt = entry; // depends on control dependency: [if], data = [none]
break;
}
}
if (rslt != null) {
break;
}
}
return rslt;
} } |
public class class_name {
public void keepAliveSessions(long index, long timestamp) {
log.debug("Resetting session timeouts");
this.currentIndex = index;
this.currentTimestamp = Math.max(currentTimestamp, timestamp);
for (RaftSession session : sessions.getSessions(primitiveId)) {
session.setLastUpdated(timestamp);
}
} } | public class class_name {
public void keepAliveSessions(long index, long timestamp) {
log.debug("Resetting session timeouts");
this.currentIndex = index;
this.currentTimestamp = Math.max(currentTimestamp, timestamp);
for (RaftSession session : sessions.getSessions(primitiveId)) {
session.setLastUpdated(timestamp); // depends on control dependency: [for], data = [session]
}
} } |
public class class_name {
public static MaxEntModel create(String path)
{
MaxEntModel m = new MaxEntModel();
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(IOUtil.newInputStream(path), "UTF-8"));
DataOutputStream out = new DataOutputStream(IOUtil.newOutputStream(path + Predefine.BIN_EXT));
br.readLine(); // type
m.correctionConstant = Integer.parseInt(br.readLine()); // correctionConstant
out.writeInt(m.correctionConstant);
m.correctionParam = Double.parseDouble(br.readLine()); // getCorrectionParameter
out.writeDouble(m.correctionParam);
// label
int numOutcomes = Integer.parseInt(br.readLine());
out.writeInt(numOutcomes);
String[] outcomeLabels = new String[numOutcomes];
m.outcomeNames = outcomeLabels;
for (int i = 0; i < numOutcomes; i++)
{
outcomeLabels[i] = br.readLine();
TextUtility.writeString(outcomeLabels[i], out);
}
// pattern
int numOCTypes = Integer.parseInt(br.readLine());
out.writeInt(numOCTypes);
int[][] outcomePatterns = new int[numOCTypes][];
for (int i = 0; i < numOCTypes; i++)
{
StringTokenizer tok = new StringTokenizer(br.readLine(), " ");
int[] infoInts = new int[tok.countTokens()];
out.writeInt(infoInts.length);
for (int j = 0; tok.hasMoreTokens(); j++)
{
infoInts[j] = Integer.parseInt(tok.nextToken());
out.writeInt(infoInts[j]);
}
outcomePatterns[i] = infoInts;
}
// feature
int NUM_PREDS = Integer.parseInt(br.readLine());
out.writeInt(NUM_PREDS);
String[] predLabels = new String[NUM_PREDS];
m.pmap = new DoubleArrayTrie<Integer>();
TreeMap<String, Integer> tmpMap = new TreeMap<String, Integer>();
for (int i = 0; i < NUM_PREDS; i++)
{
predLabels[i] = br.readLine();
assert !tmpMap.containsKey(predLabels[i]) : "重复的键: " + predLabels[i] + " 请使用 -Dfile.encoding=UTF-8 训练";
TextUtility.writeString(predLabels[i], out);
tmpMap.put(predLabels[i], i);
}
m.pmap.build(tmpMap);
for (Map.Entry<String, Integer> entry : tmpMap.entrySet())
{
out.writeInt(entry.getValue());
}
m.pmap.save(out);
// params
Context[] params = new Context[NUM_PREDS];
int pid = 0;
for (int i = 0; i < outcomePatterns.length; i++)
{
int[] outcomePattern = new int[outcomePatterns[i].length - 1];
for (int k = 1; k < outcomePatterns[i].length; k++)
{
outcomePattern[k - 1] = outcomePatterns[i][k];
}
for (int j = 0; j < outcomePatterns[i][0]; j++)
{
double[] contextParameters = new double[outcomePatterns[i].length - 1];
for (int k = 1; k < outcomePatterns[i].length; k++)
{
contextParameters[k - 1] = Double.parseDouble(br.readLine());
out.writeDouble(contextParameters[k - 1]);
}
params[pid] = new Context(outcomePattern, contextParameters);
pid++;
}
}
// prior
m.prior = new UniformPrior();
m.prior.setLabels(outcomeLabels);
// eval
m.evalParams = new EvalParameters(params, m.correctionParam, m.correctionConstant, outcomeLabels.length);
out.close();
}
catch (Exception e)
{
logger.severe("从" + path + "加载最大熵模型失败!" + TextUtility.exceptionToString(e));
return null;
}
return m;
} } | public class class_name {
public static MaxEntModel create(String path)
{
MaxEntModel m = new MaxEntModel();
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(IOUtil.newInputStream(path), "UTF-8"));
DataOutputStream out = new DataOutputStream(IOUtil.newOutputStream(path + Predefine.BIN_EXT));
br.readLine(); // type // depends on control dependency: [try], data = [none]
m.correctionConstant = Integer.parseInt(br.readLine()); // correctionConstant // depends on control dependency: [try], data = [none]
out.writeInt(m.correctionConstant); // depends on control dependency: [try], data = [none]
m.correctionParam = Double.parseDouble(br.readLine()); // getCorrectionParameter // depends on control dependency: [try], data = [none]
out.writeDouble(m.correctionParam); // depends on control dependency: [try], data = [none]
// label
int numOutcomes = Integer.parseInt(br.readLine());
out.writeInt(numOutcomes); // depends on control dependency: [try], data = [none]
String[] outcomeLabels = new String[numOutcomes];
m.outcomeNames = outcomeLabels; // depends on control dependency: [try], data = [none]
for (int i = 0; i < numOutcomes; i++)
{
outcomeLabels[i] = br.readLine(); // depends on control dependency: [for], data = [i]
TextUtility.writeString(outcomeLabels[i], out); // depends on control dependency: [for], data = [i]
}
// pattern
int numOCTypes = Integer.parseInt(br.readLine());
out.writeInt(numOCTypes); // depends on control dependency: [try], data = [none]
int[][] outcomePatterns = new int[numOCTypes][];
for (int i = 0; i < numOCTypes; i++)
{
StringTokenizer tok = new StringTokenizer(br.readLine(), " ");
int[] infoInts = new int[tok.countTokens()];
out.writeInt(infoInts.length); // depends on control dependency: [for], data = [none]
for (int j = 0; tok.hasMoreTokens(); j++)
{
infoInts[j] = Integer.parseInt(tok.nextToken()); // depends on control dependency: [for], data = [j]
out.writeInt(infoInts[j]); // depends on control dependency: [for], data = [j]
}
outcomePatterns[i] = infoInts; // depends on control dependency: [for], data = [i]
}
// feature
int NUM_PREDS = Integer.parseInt(br.readLine());
out.writeInt(NUM_PREDS); // depends on control dependency: [try], data = [none]
String[] predLabels = new String[NUM_PREDS];
m.pmap = new DoubleArrayTrie<Integer>(); // depends on control dependency: [try], data = [none]
TreeMap<String, Integer> tmpMap = new TreeMap<String, Integer>();
for (int i = 0; i < NUM_PREDS; i++)
{
predLabels[i] = br.readLine(); // depends on control dependency: [for], data = [i]
assert !tmpMap.containsKey(predLabels[i]) : "重复的键: " + predLabels[i] + " 请使用 -Dfile.encoding=UTF-8 训练"; // depends on control dependency: [for], data = [none] // depends on control dependency: [for], data = [i]
TextUtility.writeString(predLabels[i], out); // depends on control dependency: [for], data = [i]
tmpMap.put(predLabels[i], i); // depends on control dependency: [for], data = [i]
}
m.pmap.build(tmpMap); // depends on control dependency: [try], data = [none]
for (Map.Entry<String, Integer> entry : tmpMap.entrySet())
{
out.writeInt(entry.getValue()); // depends on control dependency: [for], data = [entry]
}
m.pmap.save(out); // depends on control dependency: [try], data = [none]
// params
Context[] params = new Context[NUM_PREDS];
int pid = 0;
for (int i = 0; i < outcomePatterns.length; i++)
{
int[] outcomePattern = new int[outcomePatterns[i].length - 1];
for (int k = 1; k < outcomePatterns[i].length; k++)
{
outcomePattern[k - 1] = outcomePatterns[i][k]; // depends on control dependency: [for], data = [k]
}
for (int j = 0; j < outcomePatterns[i][0]; j++)
{
double[] contextParameters = new double[outcomePatterns[i].length - 1];
for (int k = 1; k < outcomePatterns[i].length; k++)
{
contextParameters[k - 1] = Double.parseDouble(br.readLine()); // depends on control dependency: [for], data = [k]
out.writeDouble(contextParameters[k - 1]); // depends on control dependency: [for], data = [k]
}
params[pid] = new Context(outcomePattern, contextParameters); // depends on control dependency: [for], data = [none]
pid++; // depends on control dependency: [for], data = [none]
}
}
// prior
m.prior = new UniformPrior(); // depends on control dependency: [try], data = [none]
m.prior.setLabels(outcomeLabels); // depends on control dependency: [try], data = [none]
// eval
m.evalParams = new EvalParameters(params, m.correctionParam, m.correctionConstant, outcomeLabels.length); // depends on control dependency: [try], data = [none]
out.close(); // depends on control dependency: [try], data = [none]
}
catch (Exception e)
{
logger.severe("从" + path + "加载最大熵模型失败!" + TextUtility.exceptionToString(e));
return null;
} // depends on control dependency: [catch], data = [none]
return m;
} } |
public class class_name {
public DMatrixRMaj next( DMatrixRMaj x )
{
for( int i = 0; i < r.numRows; i++ ) {
r.set(i,0,rand.nextGaussian());
}
x.set(mean);
multAdd(A,r,x);
return x;
} } | public class class_name {
public DMatrixRMaj next( DMatrixRMaj x )
{
for( int i = 0; i < r.numRows; i++ ) {
r.set(i,0,rand.nextGaussian()); // depends on control dependency: [for], data = [i]
}
x.set(mean);
multAdd(A,r,x);
return x;
} } |
public class class_name {
public void setCellEditorValue(Object value) {
dateTimePicker.clear();
if (value == null) {
return;
}
if (value instanceof LocalDateTime) {
LocalDateTime nativeValue = (LocalDateTime) value;
dateTimePicker.setDateTimePermissive(nativeValue);
} else {
String text = value.toString();
String shorterText = InternalUtilities.safeSubstring(text, 0, 100);
dateTimePicker.datePicker.setText(shorterText);
}
} } | public class class_name {
public void setCellEditorValue(Object value) {
dateTimePicker.clear();
if (value == null) {
return; // depends on control dependency: [if], data = [none]
}
if (value instanceof LocalDateTime) {
LocalDateTime nativeValue = (LocalDateTime) value;
dateTimePicker.setDateTimePermissive(nativeValue); // depends on control dependency: [if], data = [none]
} else {
String text = value.toString();
String shorterText = InternalUtilities.safeSubstring(text, 0, 100);
dateTimePicker.datePicker.setText(shorterText); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public MatcherPattern findMatcherPattern(int patternCode) {
MatcherPattern result = null;
for (MatcherPattern entry : this.matcherPatterns) {
if (entry.getPatternCode() == patternCode) {
result = entry;
break;
}
}
return result;
} } | public class class_name {
public MatcherPattern findMatcherPattern(int patternCode) {
MatcherPattern result = null;
for (MatcherPattern entry : this.matcherPatterns) {
if (entry.getPatternCode() == patternCode) {
result = entry; // depends on control dependency: [if], data = [none]
break;
}
}
return result;
} } |
public class class_name {
static final byte[] toCouponByteArray(final AbstractCoupons impl, final boolean dstCompact) {
final int srcCouponCount = impl.getCouponCount();
final int srcLgCouponArrInts = impl.getLgCouponArrInts();
final int srcCouponArrInts = 1 << srcLgCouponArrInts;
final byte[] byteArrOut;
final boolean list = impl.getCurMode() == CurMode.LIST;
//prepare switch
final int sw = (impl.isMemory() ? 0 : 4) | (impl.isCompact() ? 0 : 2) | (dstCompact ? 0 : 1);
switch (sw) {
case 0: { //Src Memory, Src Compact, Dst Compact
final Memory srcMem = impl.getMemory();
final int bytesOut = impl.getMemDataStart() + (srcCouponCount << 2);
byteArrOut = new byte[bytesOut];
srcMem.getByteArray(0, byteArrOut, 0, bytesOut);
break;
}
case 1: { //Src Memory, Src Compact, Dst Updatable
final int dataStart = impl.getMemDataStart();
final int bytesOut = dataStart + (srcCouponArrInts << 2);
byteArrOut = new byte[bytesOut];
final WritableMemory memOut = WritableMemory.wrap(byteArrOut);
copyCommonListAndSet(impl, memOut);
insertCompactFlag(memOut, dstCompact);
final int[] tgtCouponIntArr = new int[srcCouponArrInts];
final PairIterator itr = impl.iterator();
while (itr.nextValid()) {
final int pair = itr.getPair();
final int idx = find(tgtCouponIntArr, srcLgCouponArrInts, pair);
if (idx < 0) { //found EMPTY
tgtCouponIntArr[~idx] = pair; //insert
continue;
}
throw new SketchesStateException("Error: found duplicate.");
}
memOut.putIntArray(dataStart, tgtCouponIntArr, 0, srcCouponArrInts);
if (list) {
insertListCount(memOut, srcCouponCount);
} else {
insertHashSetCount(memOut, srcCouponCount);
}
break;
}
case 2: { //Src Memory, Src Updatable, Dst Compact
final int dataStart = impl.getMemDataStart();
final int bytesOut = dataStart + (srcCouponCount << 2);
byteArrOut = new byte[bytesOut];
final WritableMemory memOut = WritableMemory.wrap(byteArrOut);
copyCommonListAndSet(impl, memOut);
insertCompactFlag(memOut, dstCompact);
final PairIterator itr = impl.iterator();
int cnt = 0;
while (itr.nextValid()) {
insertInt(memOut, dataStart + (cnt++ << 2), itr.getPair());
}
if (list) {
insertListCount(memOut, srcCouponCount);
} else {
insertHashSetCount(memOut, srcCouponCount);
}
break;
}
case 3: { //Src Memory, Src Updatable, Dst Updatable
final Memory srcMem = impl.getMemory();
final int bytesOut = impl.getMemDataStart() + (srcCouponArrInts << 2);
byteArrOut = new byte[bytesOut];
srcMem.getByteArray(0, byteArrOut, 0, bytesOut);
break;
}
case 6: { //Src Heap, Src Updatable, Dst Compact
final int dataStart = impl.getMemDataStart();
final int bytesOut = dataStart + (srcCouponCount << 2);
byteArrOut = new byte[bytesOut];
final WritableMemory memOut = WritableMemory.wrap(byteArrOut);
copyCommonListAndSet(impl, memOut);
insertCompactFlag(memOut, dstCompact);
final PairIterator itr = impl.iterator();
int cnt = 0;
while (itr.nextValid()) {
insertInt(memOut, dataStart + (cnt++ << 2), itr.getPair());
}
if (list) {
insertListCount(memOut, srcCouponCount);
} else {
insertHashSetCount(memOut, srcCouponCount);
}
break;
}
case 7: { //Src Heap, Src Updatable, Dst Updatable
final int dataStart = impl.getMemDataStart();
final int bytesOut = dataStart + (srcCouponArrInts << 2);
byteArrOut = new byte[bytesOut];
final WritableMemory memOut = WritableMemory.wrap(byteArrOut);
copyCommonListAndSet(impl, memOut);
memOut.putIntArray(dataStart, impl.getCouponIntArr(), 0, srcCouponArrInts);
if (list) {
insertListCount(memOut, srcCouponCount);
} else {
insertHashSetCount(memOut, srcCouponCount);
}
break;
}
default: throw new SketchesStateException("Corruption, should not happen: " + sw);
}
return byteArrOut;
} } | public class class_name {
static final byte[] toCouponByteArray(final AbstractCoupons impl, final boolean dstCompact) {
final int srcCouponCount = impl.getCouponCount();
final int srcLgCouponArrInts = impl.getLgCouponArrInts();
final int srcCouponArrInts = 1 << srcLgCouponArrInts;
final byte[] byteArrOut;
final boolean list = impl.getCurMode() == CurMode.LIST;
//prepare switch
final int sw = (impl.isMemory() ? 0 : 4) | (impl.isCompact() ? 0 : 2) | (dstCompact ? 0 : 1);
switch (sw) {
case 0: { //Src Memory, Src Compact, Dst Compact
final Memory srcMem = impl.getMemory();
final int bytesOut = impl.getMemDataStart() + (srcCouponCount << 2);
byteArrOut = new byte[bytesOut];
srcMem.getByteArray(0, byteArrOut, 0, bytesOut);
break;
}
case 1: { //Src Memory, Src Compact, Dst Updatable
final int dataStart = impl.getMemDataStart();
final int bytesOut = dataStart + (srcCouponArrInts << 2);
byteArrOut = new byte[bytesOut];
final WritableMemory memOut = WritableMemory.wrap(byteArrOut);
copyCommonListAndSet(impl, memOut);
insertCompactFlag(memOut, dstCompact);
final int[] tgtCouponIntArr = new int[srcCouponArrInts];
final PairIterator itr = impl.iterator();
while (itr.nextValid()) {
final int pair = itr.getPair();
final int idx = find(tgtCouponIntArr, srcLgCouponArrInts, pair);
if (idx < 0) { //found EMPTY
tgtCouponIntArr[~idx] = pair; //insert // depends on control dependency: [if], data = [none]
continue;
}
throw new SketchesStateException("Error: found duplicate.");
}
memOut.putIntArray(dataStart, tgtCouponIntArr, 0, srcCouponArrInts);
if (list) {
insertListCount(memOut, srcCouponCount); // depends on control dependency: [if], data = [none]
} else {
insertHashSetCount(memOut, srcCouponCount); // depends on control dependency: [if], data = [none]
}
break;
}
case 2: { //Src Memory, Src Updatable, Dst Compact
final int dataStart = impl.getMemDataStart();
final int bytesOut = dataStart + (srcCouponCount << 2);
byteArrOut = new byte[bytesOut];
final WritableMemory memOut = WritableMemory.wrap(byteArrOut);
copyCommonListAndSet(impl, memOut);
insertCompactFlag(memOut, dstCompact);
final PairIterator itr = impl.iterator();
int cnt = 0;
while (itr.nextValid()) {
insertInt(memOut, dataStart + (cnt++ << 2), itr.getPair()); // depends on control dependency: [while], data = [none]
}
if (list) {
insertListCount(memOut, srcCouponCount); // depends on control dependency: [if], data = [none]
} else {
insertHashSetCount(memOut, srcCouponCount); // depends on control dependency: [if], data = [none]
}
break;
}
case 3: { //Src Memory, Src Updatable, Dst Updatable
final Memory srcMem = impl.getMemory();
final int bytesOut = impl.getMemDataStart() + (srcCouponArrInts << 2);
byteArrOut = new byte[bytesOut];
srcMem.getByteArray(0, byteArrOut, 0, bytesOut);
break;
}
case 6: { //Src Heap, Src Updatable, Dst Compact
final int dataStart = impl.getMemDataStart();
final int bytesOut = dataStart + (srcCouponCount << 2);
byteArrOut = new byte[bytesOut];
final WritableMemory memOut = WritableMemory.wrap(byteArrOut);
copyCommonListAndSet(impl, memOut);
insertCompactFlag(memOut, dstCompact);
final PairIterator itr = impl.iterator();
int cnt = 0;
while (itr.nextValid()) {
insertInt(memOut, dataStart + (cnt++ << 2), itr.getPair()); // depends on control dependency: [while], data = [none]
}
if (list) {
insertListCount(memOut, srcCouponCount); // depends on control dependency: [if], data = [none]
} else {
insertHashSetCount(memOut, srcCouponCount); // depends on control dependency: [if], data = [none]
}
break;
}
case 7: { //Src Heap, Src Updatable, Dst Updatable
final int dataStart = impl.getMemDataStart();
final int bytesOut = dataStart + (srcCouponArrInts << 2);
byteArrOut = new byte[bytesOut];
final WritableMemory memOut = WritableMemory.wrap(byteArrOut);
copyCommonListAndSet(impl, memOut);
memOut.putIntArray(dataStart, impl.getCouponIntArr(), 0, srcCouponArrInts);
if (list) {
insertListCount(memOut, srcCouponCount); // depends on control dependency: [if], data = [none]
} else {
insertHashSetCount(memOut, srcCouponCount); // depends on control dependency: [if], data = [none]
}
break;
}
default: throw new SketchesStateException("Corruption, should not happen: " + sw);
}
return byteArrOut;
} } |
public class class_name {
public ModifyImageAttributeRequest withProductCodes(String... productCodes) {
if (this.productCodes == null) {
setProductCodes(new com.amazonaws.internal.SdkInternalList<String>(productCodes.length));
}
for (String ele : productCodes) {
this.productCodes.add(ele);
}
return this;
} } | public class class_name {
public ModifyImageAttributeRequest withProductCodes(String... productCodes) {
if (this.productCodes == null) {
setProductCodes(new com.amazonaws.internal.SdkInternalList<String>(productCodes.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : productCodes) {
this.productCodes.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public CmsPermissionSet getPermissions(CmsObject cms, CmsResource resource) {
String cacheKey = getPermissionsCacheKey(cms, resource);
CmsPermissionSetCustom permissions;
if (cacheKey != null) {
permissions = m_permissionsCache.get(cacheKey);
if (permissions != null) {
return permissions;
}
}
CmsAccessControlList acl = (CmsAccessControlList)m_accessControlList.clone();
CmsUser user = cms.getRequestContext().getCurrentUser();
List<CmsGroup> groups = null;
try {
groups = cms.getGroupsOfUser(user.getName(), false);
} catch (CmsException e) {
// error reading the groups of the current user
LOG.error(Messages.get().getBundle().key(Messages.LOG_READ_GROUPS_OF_USER_FAILED_1, user.getName()), e);
}
List<CmsRole> roles = null;
try {
roles = OpenCms.getRoleManager().getRolesForResource(cms, user, resource);
} catch (CmsException e) {
// error reading the roles of the current user
LOG.error(Messages.get().getBundle().key(Messages.LOG_READ_GROUPS_OF_USER_FAILED_1, user.getName()), e);
}
String defaultPermissions = m_accessControl.get(PRINCIPAL_DEFAULT);
// add the default permissions to the acl
if ((defaultPermissions != null) && !user.isGuestUser()) {
boolean found = false;
if (acl.getPermissions(user.getId()) != null) {
// acl already contains the user, no need for default
found = true;
}
if (!found && (groups != null)) {
// look up all groups to see if we need the default
Iterator<CmsGroup> itGroups = groups.iterator();
while (itGroups.hasNext()) {
CmsGroup group = itGroups.next();
if (acl.getPermissions(group.getId()) != null) {
// acl already contains the group, no need for default
found = true;
break;
}
}
}
if (!found && (roles != null)) {
// look up all roles to see if we need the default
Iterator<CmsRole> itRoles = roles.iterator();
while (itRoles.hasNext()) {
CmsRole role = itRoles.next();
if (acl.getPermissions(role.getId()) != null) {
// acl already contains the group, no need for default
found = true;
break;
}
}
}
if (!found) {
// add default access control settings for current user
CmsAccessControlEntry entry = new CmsAccessControlEntry(null, user.getId(), defaultPermissions);
acl.add(entry);
}
}
permissions = acl.getPermissions(user, groups, roles);
if (cacheKey != null) {
m_permissionsCache.put(cacheKey, permissions);
}
return permissions;
} } | public class class_name {
public CmsPermissionSet getPermissions(CmsObject cms, CmsResource resource) {
String cacheKey = getPermissionsCacheKey(cms, resource);
CmsPermissionSetCustom permissions;
if (cacheKey != null) {
permissions = m_permissionsCache.get(cacheKey); // depends on control dependency: [if], data = [(cacheKey]
if (permissions != null) {
return permissions; // depends on control dependency: [if], data = [none]
}
}
CmsAccessControlList acl = (CmsAccessControlList)m_accessControlList.clone();
CmsUser user = cms.getRequestContext().getCurrentUser();
List<CmsGroup> groups = null;
try {
groups = cms.getGroupsOfUser(user.getName(), false); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
// error reading the groups of the current user
LOG.error(Messages.get().getBundle().key(Messages.LOG_READ_GROUPS_OF_USER_FAILED_1, user.getName()), e);
} // depends on control dependency: [catch], data = [none]
List<CmsRole> roles = null;
try {
roles = OpenCms.getRoleManager().getRolesForResource(cms, user, resource); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
// error reading the roles of the current user
LOG.error(Messages.get().getBundle().key(Messages.LOG_READ_GROUPS_OF_USER_FAILED_1, user.getName()), e);
} // depends on control dependency: [catch], data = [none]
String defaultPermissions = m_accessControl.get(PRINCIPAL_DEFAULT);
// add the default permissions to the acl
if ((defaultPermissions != null) && !user.isGuestUser()) {
boolean found = false;
if (acl.getPermissions(user.getId()) != null) {
// acl already contains the user, no need for default
found = true; // depends on control dependency: [if], data = [none]
}
if (!found && (groups != null)) {
// look up all groups to see if we need the default
Iterator<CmsGroup> itGroups = groups.iterator();
while (itGroups.hasNext()) {
CmsGroup group = itGroups.next();
if (acl.getPermissions(group.getId()) != null) {
// acl already contains the group, no need for default
found = true; // depends on control dependency: [if], data = [none]
break;
}
}
}
if (!found && (roles != null)) {
// look up all roles to see if we need the default
Iterator<CmsRole> itRoles = roles.iterator();
while (itRoles.hasNext()) {
CmsRole role = itRoles.next();
if (acl.getPermissions(role.getId()) != null) {
// acl already contains the group, no need for default
found = true; // depends on control dependency: [if], data = [none]
break;
}
}
}
if (!found) {
// add default access control settings for current user
CmsAccessControlEntry entry = new CmsAccessControlEntry(null, user.getId(), defaultPermissions);
acl.add(entry); // depends on control dependency: [if], data = [none]
}
}
permissions = acl.getPermissions(user, groups, roles);
if (cacheKey != null) {
m_permissionsCache.put(cacheKey, permissions); // depends on control dependency: [if], data = [(cacheKey]
}
return permissions;
} } |
public class class_name {
static Reflections createReflections(ClassLoader classLoader, String packagePrefix) {
// We set up reflections to use the classLoader for loading classes
// and also to use the classLoader to determine the list of URLs:
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder().addClassLoader(classLoader);
if (StringUtils.isNotBlank(packagePrefix)) {
configurationBuilder.addUrls(ClasspathHelper.forPackage(packagePrefix, classLoader));
} else {
configurationBuilder.addUrls(ClasspathHelper.forClassLoader(classLoader));
}
Reflections reflections = new Reflections(configurationBuilder);
log.info("Reflections URLs: {}", reflections.getConfiguration().getUrls());
if (Main.configuration.classesReloadable && reflections.getConfiguration().getUrls().size() == 0 && StringUtils.isNotEmpty(Main.configuration.packagePrefix)) {
log.info("It looks like no reloadable classes were found. Is '{}' the correct package prefix for your app?", Main.configuration.packagePrefix);
}
return reflections;
} } | public class class_name {
static Reflections createReflections(ClassLoader classLoader, String packagePrefix) {
// We set up reflections to use the classLoader for loading classes
// and also to use the classLoader to determine the list of URLs:
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder().addClassLoader(classLoader);
if (StringUtils.isNotBlank(packagePrefix)) {
configurationBuilder.addUrls(ClasspathHelper.forPackage(packagePrefix, classLoader)); // depends on control dependency: [if], data = [none]
} else {
configurationBuilder.addUrls(ClasspathHelper.forClassLoader(classLoader)); // depends on control dependency: [if], data = [none]
}
Reflections reflections = new Reflections(configurationBuilder);
log.info("Reflections URLs: {}", reflections.getConfiguration().getUrls());
if (Main.configuration.classesReloadable && reflections.getConfiguration().getUrls().size() == 0 && StringUtils.isNotEmpty(Main.configuration.packagePrefix)) {
log.info("It looks like no reloadable classes were found. Is '{}' the correct package prefix for your app?", Main.configuration.packagePrefix); // depends on control dependency: [if], data = [none]
}
return reflections;
} } |
public class class_name {
final String excludeQuoted(final String datePattern) {
final Pattern pattern = Pattern.compile("'('{2}|[^'])+'");
final Matcher matcher = pattern.matcher(datePattern);
final StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, "");
}
matcher.appendTail(buffer);
LogLog.debug("DatePattern reduced to " + buffer.toString()
+ " for computation of time-based rollover strategy (full pattern"
+ " will be used for actual roll-file naming)");
return buffer.toString();
} } | public class class_name {
final String excludeQuoted(final String datePattern) {
final Pattern pattern = Pattern.compile("'('{2}|[^'])+'");
final Matcher matcher = pattern.matcher(datePattern);
final StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, ""); // depends on control dependency: [while], data = [none]
}
matcher.appendTail(buffer);
LogLog.debug("DatePattern reduced to " + buffer.toString()
+ " for computation of time-based rollover strategy (full pattern"
+ " will be used for actual roll-file naming)");
return buffer.toString();
} } |
public class class_name {
private static String formatBubble(final BubbleWrap bubble, final String message, final int longestLine) {
String newLine = System.getProperty("line.separator");
String[] lines = message.split(newLine);
StringBuilder sb = new StringBuilder();
sb.append(bubble.buildTop(longestLine));
if (lines.length > 1) {
sb.append(bubble.formatMultiOpen(lines[0], longestLine));
for (int i = 1; i < (lines.length - 1); i++) {
sb.append(bubble.formatMultiMid(lines[i], longestLine));
}
sb.append(bubble.formatMultiEnd(lines[(lines.length - 1)], longestLine));
} else {
sb.append(bubble.formatSingle(lines[0]));
}
sb.append(bubble.buildBottom(longestLine));
return sb.toString();
} } | public class class_name {
private static String formatBubble(final BubbleWrap bubble, final String message, final int longestLine) {
String newLine = System.getProperty("line.separator");
String[] lines = message.split(newLine);
StringBuilder sb = new StringBuilder();
sb.append(bubble.buildTop(longestLine));
if (lines.length > 1) {
sb.append(bubble.formatMultiOpen(lines[0], longestLine)); // depends on control dependency: [if], data = [none]
for (int i = 1; i < (lines.length - 1); i++) {
sb.append(bubble.formatMultiMid(lines[i], longestLine)); // depends on control dependency: [for], data = [i]
}
sb.append(bubble.formatMultiEnd(lines[(lines.length - 1)], longestLine)); // depends on control dependency: [if], data = [(lines.length]
} else {
sb.append(bubble.formatSingle(lines[0])); // depends on control dependency: [if], data = [none]
}
sb.append(bubble.buildBottom(longestLine));
return sb.toString();
} } |
public class class_name {
public void marshall(RemoveTargetsRequest removeTargetsRequest, ProtocolMarshaller protocolMarshaller) {
if (removeTargetsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(removeTargetsRequest.getRule(), RULE_BINDING);
protocolMarshaller.marshall(removeTargetsRequest.getIds(), IDS_BINDING);
protocolMarshaller.marshall(removeTargetsRequest.getForce(), FORCE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(RemoveTargetsRequest removeTargetsRequest, ProtocolMarshaller protocolMarshaller) {
if (removeTargetsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(removeTargetsRequest.getRule(), RULE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(removeTargetsRequest.getIds(), IDS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(removeTargetsRequest.getForce(), FORCE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
int localPort = request.getLocalPort();
if (mode == MODE_ALLOW && !portHit(localPort) ||
mode == MODE_DENY && portHit(localPort)){
if (message == null){
((HttpServletResponse) response).sendError(statusCode, ((HttpServletRequest)request).getRequestURI());
}else if (message.length() == 0){
((HttpServletResponse) response).sendError(statusCode);
}else{
((HttpServletResponse) response).sendError(statusCode, message);
}
}else{
chain.doFilter(request, response);
}
} } | public class class_name {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
int localPort = request.getLocalPort();
if (mode == MODE_ALLOW && !portHit(localPort) ||
mode == MODE_DENY && portHit(localPort)){
if (message == null){
((HttpServletResponse) response).sendError(statusCode, ((HttpServletRequest)request).getRequestURI());
// depends on control dependency: [if], data = [none]
}else if (message.length() == 0){
((HttpServletResponse) response).sendError(statusCode);
// depends on control dependency: [if], data = [none]
}else{
((HttpServletResponse) response).sendError(statusCode, message);
// depends on control dependency: [if], data = [none]
}
}else{
chain.doFilter(request, response);
}
} } |
public class class_name {
public synchronized RequestResult getLastResult() {
if (this.requestResults == null || this.requestResults.size() == 0) {
return null;
}
else {
return this.requestResults.get(this.requestResults.size() - 1);
}
} } | public class class_name {
public synchronized RequestResult getLastResult() {
if (this.requestResults == null || this.requestResults.size() == 0) {
return null; // depends on control dependency: [if], data = [none]
}
else {
return this.requestResults.get(this.requestResults.size() - 1); // depends on control dependency: [if], data = [(this.requestResults]
}
} } |
public class class_name {
public void createOrUpdateData(String indexName, String type, List<NutMap> list) {
BulkRequestBuilder bulkRequest = getClient().prepareBulk();
if (list.size() > 0) {
for (NutMap nutMap : list) {
bulkRequest.add(getClient().prepareIndex(indexName, type).setId(nutMap.getString("id")).setSource(Lang.obj2map(nutMap.get("obj"))));
}
bulkRequest.execute().actionGet();
}
} } | public class class_name {
public void createOrUpdateData(String indexName, String type, List<NutMap> list) {
BulkRequestBuilder bulkRequest = getClient().prepareBulk();
if (list.size() > 0) {
for (NutMap nutMap : list) {
bulkRequest.add(getClient().prepareIndex(indexName, type).setId(nutMap.getString("id")).setSource(Lang.obj2map(nutMap.get("obj")))); // depends on control dependency: [for], data = [nutMap]
}
bulkRequest.execute().actionGet(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void ensureCapacity(final int index, final int length)
{
if (index < 0)
{
throw new IndexOutOfBoundsException("index cannot be negative: index=" + index);
}
final long resultingPosition = index + (long)length;
final int currentArrayLength = byteArray.length;
if (resultingPosition > currentArrayLength)
{
if (currentArrayLength >= MAX_ARRAY_LENGTH)
{
throw new IndexOutOfBoundsException(
"index=" + index + " length=" + length + " maxCapacity=" + MAX_ARRAY_LENGTH);
}
byteArray = Arrays.copyOf(byteArray, calculateExpansion(currentArrayLength, (int)resultingPosition));
}
} } | public class class_name {
private void ensureCapacity(final int index, final int length)
{
if (index < 0)
{
throw new IndexOutOfBoundsException("index cannot be negative: index=" + index);
}
final long resultingPosition = index + (long)length;
final int currentArrayLength = byteArray.length;
if (resultingPosition > currentArrayLength)
{
if (currentArrayLength >= MAX_ARRAY_LENGTH)
{
throw new IndexOutOfBoundsException(
"index=" + index + " length=" + length + " maxCapacity=" + MAX_ARRAY_LENGTH);
}
byteArray = Arrays.copyOf(byteArray, calculateExpansion(currentArrayLength, (int)resultingPosition)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public QName getXMLSchemaType() {
boolean yearSet = isSet(DatatypeConstants.YEARS);
boolean monthSet = isSet(DatatypeConstants.MONTHS);
boolean daySet = isSet(DatatypeConstants.DAYS);
boolean hourSet = isSet(DatatypeConstants.HOURS);
boolean minuteSet = isSet(DatatypeConstants.MINUTES);
boolean secondSet = isSet(DatatypeConstants.SECONDS);
// DURATION
if (yearSet
&& monthSet
&& daySet
&& hourSet
&& minuteSet
&& secondSet) {
return DatatypeConstants.DURATION;
}
// DURATION_DAYTIME
if (!yearSet
&& !monthSet
&& daySet
&& hourSet
&& minuteSet
&& secondSet) {
return DatatypeConstants.DURATION_DAYTIME;
}
// DURATION_YEARMONTH
if (yearSet
&& monthSet
&& !daySet
&& !hourSet
&& !minuteSet
&& !secondSet) {
return DatatypeConstants.DURATION_YEARMONTH;
}
// nothing matches
throw new IllegalStateException(
"javax.xml.datatype.Duration#getXMLSchemaType():"
+ " this Duration does not match one of the XML Schema date/time datatypes:"
+ " year set = " + yearSet
+ " month set = " + monthSet
+ " day set = " + daySet
+ " hour set = " + hourSet
+ " minute set = " + minuteSet
+ " second set = " + secondSet
);
} } | public class class_name {
public QName getXMLSchemaType() {
boolean yearSet = isSet(DatatypeConstants.YEARS);
boolean monthSet = isSet(DatatypeConstants.MONTHS);
boolean daySet = isSet(DatatypeConstants.DAYS);
boolean hourSet = isSet(DatatypeConstants.HOURS);
boolean minuteSet = isSet(DatatypeConstants.MINUTES);
boolean secondSet = isSet(DatatypeConstants.SECONDS);
// DURATION
if (yearSet
&& monthSet
&& daySet
&& hourSet
&& minuteSet
&& secondSet) {
return DatatypeConstants.DURATION; // depends on control dependency: [if], data = [none]
}
// DURATION_DAYTIME
if (!yearSet
&& !monthSet
&& daySet
&& hourSet
&& minuteSet
&& secondSet) {
return DatatypeConstants.DURATION_DAYTIME; // depends on control dependency: [if], data = [none]
}
// DURATION_YEARMONTH
if (yearSet
&& monthSet
&& !daySet
&& !hourSet
&& !minuteSet
&& !secondSet) {
return DatatypeConstants.DURATION_YEARMONTH; // depends on control dependency: [if], data = [none]
}
// nothing matches
throw new IllegalStateException(
"javax.xml.datatype.Duration#getXMLSchemaType():"
+ " this Duration does not match one of the XML Schema date/time datatypes:"
+ " year set = " + yearSet
+ " month set = " + monthSet
+ " day set = " + daySet
+ " hour set = " + hourSet
+ " minute set = " + minuteSet
+ " second set = " + secondSet
);
} } |
public class class_name {
private List<AlluxioURI> getNestedPaths(AlluxioURI alluxioUri, int startComponentIndex) {
try {
String[] fullComponents = PathUtils.getPathComponents(alluxioUri.getPath());
String[] baseComponents = Arrays.copyOfRange(fullComponents, 0, startComponentIndex);
AlluxioURI uri = new AlluxioURI(
PathUtils.concatPath(AlluxioURI.SEPARATOR, baseComponents));
List<AlluxioURI> components = new ArrayList<>(fullComponents.length - startComponentIndex);
for (int i = startComponentIndex; i < fullComponents.length; i++) {
uri = uri.joinUnsafe(fullComponents[i]);
components.add(uri);
}
return components;
} catch (InvalidPathException e) {
return Collections.emptyList();
}
} } | public class class_name {
private List<AlluxioURI> getNestedPaths(AlluxioURI alluxioUri, int startComponentIndex) {
try {
String[] fullComponents = PathUtils.getPathComponents(alluxioUri.getPath());
String[] baseComponents = Arrays.copyOfRange(fullComponents, 0, startComponentIndex);
AlluxioURI uri = new AlluxioURI(
PathUtils.concatPath(AlluxioURI.SEPARATOR, baseComponents));
List<AlluxioURI> components = new ArrayList<>(fullComponents.length - startComponentIndex);
for (int i = startComponentIndex; i < fullComponents.length; i++) {
uri = uri.joinUnsafe(fullComponents[i]); // depends on control dependency: [for], data = [i]
components.add(uri); // depends on control dependency: [for], data = [none]
}
return components; // depends on control dependency: [try], data = [none]
} catch (InvalidPathException e) {
return Collections.emptyList();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public String name(String name, Meter.Type type, @Nullable String baseUnit) {
String sanitizedName = NAME_CLEANUP_PATTERN.matcher(delegate.name(name, type, baseUnit)).replaceAll("_");
// add name prefix if prefix exists
if (namePrefix != null) {
return namePrefix + "." + sanitizedName;
}
return sanitizedName;
} } | public class class_name {
@Override
public String name(String name, Meter.Type type, @Nullable String baseUnit) {
String sanitizedName = NAME_CLEANUP_PATTERN.matcher(delegate.name(name, type, baseUnit)).replaceAll("_");
// add name prefix if prefix exists
if (namePrefix != null) {
return namePrefix + "." + sanitizedName; // depends on control dependency: [if], data = [none]
}
return sanitizedName;
} } |
public class class_name {
public static void parseValidateAttributes(final Cell cell,
final String newComment,
final CellAttributesMap cellAttributesMap) {
if ((newComment == null) || (newComment.isEmpty())) {
return;
}
if (!newComment.startsWith(TieConstants.METHOD_VALIDATE_PREFIX)) {
return;
}
String values = getStringBetweenBracket(newComment);
if (values == null) {
return;
}
// map's key is sheetName!$columnIndex$rowIndex
String key = getAttributeKeyInMapByCell(cell);
List<CellFormAttributes> attrs = cellAttributesMap
.getCellValidateAttributes().get(key);
if (attrs == null) {
attrs = new ArrayList<>();
cellAttributesMap.getCellValidateAttributes().put(key, attrs);
}
parseValidateAttributes(attrs, values);
} } | public class class_name {
public static void parseValidateAttributes(final Cell cell,
final String newComment,
final CellAttributesMap cellAttributesMap) {
if ((newComment == null) || (newComment.isEmpty())) {
return;
// depends on control dependency: [if], data = [none]
}
if (!newComment.startsWith(TieConstants.METHOD_VALIDATE_PREFIX)) {
return;
// depends on control dependency: [if], data = [none]
}
String values = getStringBetweenBracket(newComment);
if (values == null) {
return;
// depends on control dependency: [if], data = [none]
}
// map's key is sheetName!$columnIndex$rowIndex
String key = getAttributeKeyInMapByCell(cell);
List<CellFormAttributes> attrs = cellAttributesMap
.getCellValidateAttributes().get(key);
if (attrs == null) {
attrs = new ArrayList<>();
// depends on control dependency: [if], data = [none]
cellAttributesMap.getCellValidateAttributes().put(key, attrs);
// depends on control dependency: [if], data = [none]
}
parseValidateAttributes(attrs, values);
} } |
public class class_name {
public T loadXml(InputStream inputStream, Object source) {
try {
Object unmarshalledObject = getOrCreateUnmarshaller().unmarshal(inputStream);
T jaxbBean = this.xmlBeanClass.cast(unmarshalledObject);
validate(jaxbBean);
return jaxbBean;
} catch (JAXBException e) {
throw new XmlInvalidException(e, source);
}
} } | public class class_name {
public T loadXml(InputStream inputStream, Object source) {
try {
Object unmarshalledObject = getOrCreateUnmarshaller().unmarshal(inputStream);
T jaxbBean = this.xmlBeanClass.cast(unmarshalledObject);
validate(jaxbBean); // depends on control dependency: [try], data = [none]
return jaxbBean; // depends on control dependency: [try], data = [none]
} catch (JAXBException e) {
throw new XmlInvalidException(e, source);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public ByteSink getByteSink()
{
ByteSink bs = byteSink;
if ( progressListener != null ) {
bs = new ProgressByteSink( bs, progressListener );
}
return bs;
} } | public class class_name {
public ByteSink getByteSink()
{
ByteSink bs = byteSink;
if ( progressListener != null ) {
bs = new ProgressByteSink( bs, progressListener ); // depends on control dependency: [if], data = [none]
}
return bs;
} } |
public class class_name {
public static void removeLastOverlay() {
if (!m_overlays.isEmpty()) {
CmsInlineEditOverlay last = m_overlays.remove(m_overlays.size() - 1);
last.removeFromParent();
}
if (!m_overlays.isEmpty()) {
m_overlays.get(m_overlays.size() - 1).setVisible(true);
}
} } | public class class_name {
public static void removeLastOverlay() {
if (!m_overlays.isEmpty()) {
CmsInlineEditOverlay last = m_overlays.remove(m_overlays.size() - 1);
last.removeFromParent();
// depends on control dependency: [if], data = [none]
}
if (!m_overlays.isEmpty()) {
m_overlays.get(m_overlays.size() - 1).setVisible(true);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void printMethodsDetails(ClassDoc classDoc) {
MethodDoc[] methodDocs = TestAPIDoclet.getTestAPIComponentMethods(classDoc);
if (methodDocs.length > 0) {
mOut.println(" <P>");
mOut.println("<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" CELLSPACING=\"0\" SUMMARY=\"\">");
mOut.println("<TR BGCOLOR=\"#CCCCFF\"><TH ALIGN=\"left\" COLSPAN=\"2\"><FONT SIZE=\"+2\"><B>Methods "
+ "Detail</B></FONT></TH></TR>");
mOut.println("</TABLE>");
for (int m = 0; m < methodDocs.length; m++) {
MethodDoc methodDoc = methodDocs[m];
String methodName = methodDoc.name();
// get return type
String returnTypeString = getTypeString(methodDoc.returnType());
int returnTypeLength = returnTypeString.replaceAll("<.*?>", "").replace("<", "<").replace(">", ">")
.length(); // length without HTML tags and >/< entities
Parameter[] parameters = methodDoc.parameters();
String[] parameterSignatures = new String[parameters.length];
for (int i = 0; i < parameterSignatures.length; i++) {
Parameter parameter = parameters[i];
parameterSignatures[i] = getTypeString(parameter.type()) + " " + parameter.name();
}
String parameterSeparator = ",\n";
for (int i = 0; i < returnTypeLength + methodName.length() + 2; i++) {
parameterSeparator += " ";
}
// begin output
mOut.println("<A NAME=\"" + methodName + "\"><A NAME=\"" + methodName + methodDoc.flatSignature() + "\"> <H3>"
+ methodName + "</H3></A></A>");
mOut.print("<PRE>" + returnTypeString + " <B>" + methodName + "</B>(" + Strings
.join(parameterSignatures, parameterSeparator) + ")");
Type[] exceptions = methodDoc.thrownExceptionTypes();
if (exceptions.length > 0) {
String[] exceptionNames = new String[exceptions.length];
for (int i = 0; i < exceptions.length; i++) {
exceptionNames[i] = getTypeString(exceptions[i]);
}
mOut.print(parameterSeparator.substring(1, parameterSeparator.length() - 7) + "throws " + Strings
.join(exceptionNames, parameterSeparator));
}
mOut.println("</PRE>");
mOut.print("<DL><DD>");
printInlineTags(methodDoc.inlineTags(), classDoc);
mOut.println("<P><DD><DL>");
// param tags
ParamTag[] paramTags = methodDoc.paramTags();
if (parameters.length > 0) {
mOut.println("<DT><B>Parameters:</B></DT>");
for (Parameter parameter : parameters) {
ParamTag paramTag = null;
for (ParamTag tag : paramTags) {
if (tag.parameterName().equals(parameter.name())) {
paramTag = tag;
}
}
mOut.println("<DD><CODE>" + parameter.name() + "</CODE> - ");
if (paramTag != null) {
if (!paramTag.parameterComment().isEmpty()) {
printInlineTags(paramTag.inlineTags(), classDoc);
} else {
System.out.println(
"No description in @param tag for " + parameter.name() + " in " + classDoc.name() + "."
+ methodDoc.name());
}
} else {
System.out.println(
"No @param tag for " + parameter.name() + " in " + classDoc.name() + "." + methodDoc.name());
}
mOut.println("</DD>");
}
}
// return tag
Tag[] returnTags = methodDoc.tags("@return");
if (returnTags.length > 0) {
mOut.println("<DT><B>Returns:</B></DT>");
mOut.println("<DD>" + returnTags[0].text() + "</DD>");
}
// throws tag
ThrowsTag[] throwsTags = methodDoc.throwsTags();
if (throwsTags.length > 0) {
mOut.println("<DT><B>Throws:</B></DT>");
for (ThrowsTag throwsTag : throwsTags) {
String exceptionName = throwsTag.exceptionName();
// remove "com.qspin.qtaste.testsuite." prefix if any
if (exceptionName.startsWith("com.qspin.qtaste.testsuite.")) {
exceptionName = exceptionName.substring("com.qspin.qtaste.testsuite.".length());
}
mOut.println("<DD><CODE>" + exceptionName + "</CODE> - ");
printInlineTags(throwsTag.inlineTags(), classDoc);
mOut.println("</DD>");
}
}
mOut.println("</DL></DD></DL>");
if (m != methodDocs.length - 1) {
mOut.println("<HR>");
}
}
}
} } | public class class_name {
public void printMethodsDetails(ClassDoc classDoc) {
MethodDoc[] methodDocs = TestAPIDoclet.getTestAPIComponentMethods(classDoc);
if (methodDocs.length > 0) {
mOut.println(" <P>");
mOut.println("<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" CELLSPACING=\"0\" SUMMARY=\"\">");
mOut.println("<TR BGCOLOR=\"#CCCCFF\"><TH ALIGN=\"left\" COLSPAN=\"2\"><FONT SIZE=\"+2\"><B>Methods "
+ "Detail</B></FONT></TH></TR>");
mOut.println("</TABLE>");
for (int m = 0; m < methodDocs.length; m++) {
MethodDoc methodDoc = methodDocs[m];
String methodName = methodDoc.name();
// get return type
String returnTypeString = getTypeString(methodDoc.returnType());
int returnTypeLength = returnTypeString.replaceAll("<.*?>", "").replace("<", "<").replace(">", ">")
.length(); // length without HTML tags and >/< entities
Parameter[] parameters = methodDoc.parameters();
String[] parameterSignatures = new String[parameters.length];
for (int i = 0; i < parameterSignatures.length; i++) {
Parameter parameter = parameters[i];
parameterSignatures[i] = getTypeString(parameter.type()) + " " + parameter.name(); // depends on control dependency: [for], data = [i]
}
String parameterSeparator = ",\n";
for (int i = 0; i < returnTypeLength + methodName.length() + 2; i++) {
parameterSeparator += " "; // depends on control dependency: [for], data = [none]
}
// begin output
mOut.println("<A NAME=\"" + methodName + "\"><A NAME=\"" + methodName + methodDoc.flatSignature() + "\"> <H3>"
+ methodName + "</H3></A></A>");
mOut.print("<PRE>" + returnTypeString + " <B>" + methodName + "</B>(" + Strings
.join(parameterSignatures, parameterSeparator) + ")");
Type[] exceptions = methodDoc.thrownExceptionTypes();
if (exceptions.length > 0) {
String[] exceptionNames = new String[exceptions.length];
for (int i = 0; i < exceptions.length; i++) {
exceptionNames[i] = getTypeString(exceptions[i]); // depends on control dependency: [for], data = [i]
}
mOut.print(parameterSeparator.substring(1, parameterSeparator.length() - 7) + "throws " + Strings
.join(exceptionNames, parameterSeparator)); // depends on control dependency: [if], data = [none]
}
mOut.println("</PRE>");
mOut.print("<DL><DD>");
printInlineTags(methodDoc.inlineTags(), classDoc);
mOut.println("<P><DD><DL>");
// param tags
ParamTag[] paramTags = methodDoc.paramTags();
if (parameters.length > 0) {
mOut.println("<DT><B>Parameters:</B></DT>"); // depends on control dependency: [if], data = [none]
for (Parameter parameter : parameters) {
ParamTag paramTag = null;
for (ParamTag tag : paramTags) {
if (tag.parameterName().equals(parameter.name())) {
paramTag = tag; // depends on control dependency: [if], data = [none]
}
}
mOut.println("<DD><CODE>" + parameter.name() + "</CODE> - "); // depends on control dependency: [for], data = [parameter]
if (paramTag != null) {
if (!paramTag.parameterComment().isEmpty()) {
printInlineTags(paramTag.inlineTags(), classDoc); // depends on control dependency: [if], data = [none]
} else {
System.out.println(
"No description in @param tag for " + parameter.name() + " in " + classDoc.name() + "."
+ methodDoc.name()); // depends on control dependency: [if], data = [none]
}
} else {
System.out.println(
"No @param tag for " + parameter.name() + " in " + classDoc.name() + "." + methodDoc.name()); // depends on control dependency: [if], data = [none]
}
mOut.println("</DD>"); // depends on control dependency: [for], data = [none]
}
}
// return tag
Tag[] returnTags = methodDoc.tags("@return");
if (returnTags.length > 0) {
mOut.println("<DT><B>Returns:</B></DT>"); // depends on control dependency: [if], data = [none]
mOut.println("<DD>" + returnTags[0].text() + "</DD>"); // depends on control dependency: [if], data = [none]
}
// throws tag
ThrowsTag[] throwsTags = methodDoc.throwsTags();
if (throwsTags.length > 0) {
mOut.println("<DT><B>Throws:</B></DT>");
for (ThrowsTag throwsTag : throwsTags) {
String exceptionName = throwsTag.exceptionName();
// remove "com.qspin.qtaste.testsuite." prefix if any
if (exceptionName.startsWith("com.qspin.qtaste.testsuite.")) {
exceptionName = exceptionName.substring("com.qspin.qtaste.testsuite.".length());
}
mOut.println("<DD><CODE>" + exceptionName + "</CODE> - ");
printInlineTags(throwsTag.inlineTags(), classDoc);
mOut.println("</DD>");
}
}
mOut.println("</DL></DD></DL>");
if (m != methodDocs.length - 1) {
mOut.println("<HR>");
}
}
}
} } |
public class class_name {
@Override
public MatchResponse getMatchResponse(String resourceName, String method) {
if (securityConstraints == null || securityConstraints.isEmpty()) {
return MatchResponse.NO_MATCH_RESPONSE;
}
return MatchingStrategy.match(this, resourceName, method);
} } | public class class_name {
@Override
public MatchResponse getMatchResponse(String resourceName, String method) {
if (securityConstraints == null || securityConstraints.isEmpty()) {
return MatchResponse.NO_MATCH_RESPONSE; // depends on control dependency: [if], data = [none]
}
return MatchingStrategy.match(this, resourceName, method);
} } |
public class class_name {
public static <K, V> List<Entry<K, V>> sortEntryToList(Collection<Entry<K, V>> collection) {
List<Entry<K, V>> list = new LinkedList<>(collection);
Collections.sort(list, new Comparator<Entry<K, V>>() {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2) {
V v1 = o1.getValue();
V v2 = o2.getValue();
if (v1 instanceof Comparable) {
return ((Comparable) v1).compareTo(v2);
} else {
return v1.toString().compareTo(v2.toString());
}
}
});
return list;
} } | public class class_name {
public static <K, V> List<Entry<K, V>> sortEntryToList(Collection<Entry<K, V>> collection) {
List<Entry<K, V>> list = new LinkedList<>(collection);
Collections.sort(list, new Comparator<Entry<K, V>>() {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2) {
V v1 = o1.getValue();
V v2 = o2.getValue();
if (v1 instanceof Comparable) {
return ((Comparable) v1).compareTo(v2);
// depends on control dependency: [if], data = [none]
} else {
return v1.toString().compareTo(v2.toString());
// depends on control dependency: [if], data = [none]
}
}
});
return list;
} } |
public class class_name {
public EEnum getMODCAInterchangeSetIStype() {
if (modcaInterchangeSetIStypeEEnum == null) {
modcaInterchangeSetIStypeEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(97);
}
return modcaInterchangeSetIStypeEEnum;
} } | public class class_name {
public EEnum getMODCAInterchangeSetIStype() {
if (modcaInterchangeSetIStypeEEnum == null) {
modcaInterchangeSetIStypeEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(97); // depends on control dependency: [if], data = [none]
}
return modcaInterchangeSetIStypeEEnum;
} } |
public class class_name {
public com.google.protobuf.AnyOrBuilder getResponseOrBuilder() {
if (resultCase_ == 5) {
return (com.google.protobuf.Any) result_;
}
return com.google.protobuf.Any.getDefaultInstance();
} } | public class class_name {
public com.google.protobuf.AnyOrBuilder getResponseOrBuilder() {
if (resultCase_ == 5) {
return (com.google.protobuf.Any) result_; // depends on control dependency: [if], data = [none]
}
return com.google.protobuf.Any.getDefaultInstance();
} } |
public class class_name {
@Override
public/* final */Date fromBytes(Class targetClass, byte[] bytes)
{
try
{
if (bytes == null)
{
return null;
}
try
{
// In case date.getTime() is stored in DB.
LongAccessor longAccessor = new LongAccessor();
return new Date(longAccessor.fromBytes(targetClass, bytes));
}
catch (NumberFormatException nfex)
{
return getDateByPattern(new String(bytes, Constants.ENCODING));
}
}
catch (Exception e)
{
log.error("Caused by {}.", e);
throw new PropertyAccessException(e);
}
} } | public class class_name {
@Override
public/* final */Date fromBytes(Class targetClass, byte[] bytes)
{
try
{
if (bytes == null)
{
return null;
// depends on control dependency: [if], data = [none]
}
try
{
// In case date.getTime() is stored in DB.
LongAccessor longAccessor = new LongAccessor();
return new Date(longAccessor.fromBytes(targetClass, bytes));
// depends on control dependency: [try], data = [none]
}
catch (NumberFormatException nfex)
{
return getDateByPattern(new String(bytes, Constants.ENCODING));
}
// depends on control dependency: [catch], data = [none]
}
catch (Exception e)
{
log.error("Caused by {}.", e);
throw new PropertyAccessException(e);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected Server getServer(MuleAgentConfig pConfig) {
Server newServer = new Server();
Connector connector = createConnector(newServer);
if (pConfig.getHost() != null) {
ClassUtil.applyMethod(connector, "setHost", pConfig.getHost());
}
ClassUtil.applyMethod(connector,"setPort",pConfig.getPort());
newServer.setConnectors(new Connector[]{connector});
return newServer;
} } | public class class_name {
protected Server getServer(MuleAgentConfig pConfig) {
Server newServer = new Server();
Connector connector = createConnector(newServer);
if (pConfig.getHost() != null) {
ClassUtil.applyMethod(connector, "setHost", pConfig.getHost()); // depends on control dependency: [if], data = [none]
}
ClassUtil.applyMethod(connector,"setPort",pConfig.getPort());
newServer.setConnectors(new Connector[]{connector});
return newServer;
} } |
public class class_name {
protected CompletableFuture<ExecutionResult> completeValueForScalar(ExecutionContext executionContext, ExecutionStrategyParameters parameters, GraphQLScalarType scalarType, Object result) {
Object serialized;
try {
serialized = scalarType.getCoercing().serialize(result);
} catch (CoercingSerializeException e) {
serialized = handleCoercionProblem(executionContext, parameters, e);
}
// TODO: fix that: this should not be handled here
//6.6.1 http://facebook.github.io/graphql/#sec-Field-entries
if (serialized instanceof Double && ((Double) serialized).isNaN()) {
serialized = null;
}
try {
serialized = parameters.getNonNullFieldValidator().validate(parameters.getPath(), serialized);
} catch (NonNullableFieldWasNullException e) {
return exceptionallyCompletedFuture(e);
}
return completedFuture(new ExecutionResultImpl(serialized, null));
} } | public class class_name {
protected CompletableFuture<ExecutionResult> completeValueForScalar(ExecutionContext executionContext, ExecutionStrategyParameters parameters, GraphQLScalarType scalarType, Object result) {
Object serialized;
try {
serialized = scalarType.getCoercing().serialize(result); // depends on control dependency: [try], data = [none]
} catch (CoercingSerializeException e) {
serialized = handleCoercionProblem(executionContext, parameters, e);
} // depends on control dependency: [catch], data = [none]
// TODO: fix that: this should not be handled here
//6.6.1 http://facebook.github.io/graphql/#sec-Field-entries
if (serialized instanceof Double && ((Double) serialized).isNaN()) {
serialized = null; // depends on control dependency: [if], data = [none]
}
try {
serialized = parameters.getNonNullFieldValidator().validate(parameters.getPath(), serialized); // depends on control dependency: [try], data = [none]
} catch (NonNullableFieldWasNullException e) {
return exceptionallyCompletedFuture(e);
} // depends on control dependency: [catch], data = [none]
return completedFuture(new ExecutionResultImpl(serialized, null));
} } |
public class class_name {
private boolean handleClosedLedgers(List<Write> writes) {
if (writes.size() == 0 || !writes.get(0).getWriteLedger().ledger.isClosed()) {
// Nothing to do. We only need to check the first write since, if a Write failed with LedgerClosed, then the
// first write must have failed for that reason (a Ledger is closed implies all ledgers before it are closed too).
return false;
}
long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "handleClosedLedgers", writes.size());
WriteLedger currentLedger = getWriteLedger();
Map<Long, Long> lastAddsConfirmed = new HashMap<>();
boolean anythingChanged = false;
for (Write w : writes) {
if (w.isDone() || !w.getWriteLedger().ledger.isClosed()) {
continue;
}
// Write likely failed because of LedgerClosedException. Need to check the LastAddConfirmed for each
// involved Ledger and see if the write actually made it through or not.
long lac = fetchLastAddConfirmed(w.getWriteLedger(), lastAddsConfirmed);
if (w.getEntryId() >= 0 && w.getEntryId() <= lac) {
// Write was actually successful. Complete it and move on.
completeWrite(w);
anythingChanged = true;
} else if (currentLedger.ledger.getId() != w.getWriteLedger().ledger.getId()) {
// Current ledger has changed; attempt to write to the new one.
w.setWriteLedger(currentLedger);
anythingChanged = true;
}
}
LoggerHelpers.traceLeave(log, this.traceObjectId, "handleClosedLedgers", traceId, writes.size(), anythingChanged);
return anythingChanged;
} } | public class class_name {
private boolean handleClosedLedgers(List<Write> writes) {
if (writes.size() == 0 || !writes.get(0).getWriteLedger().ledger.isClosed()) {
// Nothing to do. We only need to check the first write since, if a Write failed with LedgerClosed, then the
// first write must have failed for that reason (a Ledger is closed implies all ledgers before it are closed too).
return false; // depends on control dependency: [if], data = [none]
}
long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "handleClosedLedgers", writes.size());
WriteLedger currentLedger = getWriteLedger();
Map<Long, Long> lastAddsConfirmed = new HashMap<>();
boolean anythingChanged = false;
for (Write w : writes) {
if (w.isDone() || !w.getWriteLedger().ledger.isClosed()) {
continue;
}
// Write likely failed because of LedgerClosedException. Need to check the LastAddConfirmed for each
// involved Ledger and see if the write actually made it through or not.
long lac = fetchLastAddConfirmed(w.getWriteLedger(), lastAddsConfirmed);
if (w.getEntryId() >= 0 && w.getEntryId() <= lac) {
// Write was actually successful. Complete it and move on.
completeWrite(w); // depends on control dependency: [if], data = [none]
anythingChanged = true; // depends on control dependency: [if], data = [none]
} else if (currentLedger.ledger.getId() != w.getWriteLedger().ledger.getId()) {
// Current ledger has changed; attempt to write to the new one.
w.setWriteLedger(currentLedger); // depends on control dependency: [if], data = [none]
anythingChanged = true; // depends on control dependency: [if], data = [none]
}
}
LoggerHelpers.traceLeave(log, this.traceObjectId, "handleClosedLedgers", traceId, writes.size(), anythingChanged);
return anythingChanged;
} } |
public class class_name {
public DetectFacesResult withFaceDetails(FaceDetail... faceDetails) {
if (this.faceDetails == null) {
setFaceDetails(new java.util.ArrayList<FaceDetail>(faceDetails.length));
}
for (FaceDetail ele : faceDetails) {
this.faceDetails.add(ele);
}
return this;
} } | public class class_name {
public DetectFacesResult withFaceDetails(FaceDetail... faceDetails) {
if (this.faceDetails == null) {
setFaceDetails(new java.util.ArrayList<FaceDetail>(faceDetails.length)); // depends on control dependency: [if], data = [none]
}
for (FaceDetail ele : faceDetails) {
this.faceDetails.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public String getQueryString(MultiValueMap<String, String> params) {
if (params.isEmpty()) {
return "";
}
StringBuilder query = new StringBuilder();
Map<String, Object> singles = new HashMap<>();
for (String param : params.keySet()) {
int i = 0;
for (String value : params.get(param)) {
query.append("&");
query.append(param);
if (!"".equals(value)) { // don't add =, if original is ?wsdl, output is
// not ?wsdl=
String key = param;
// if form feed is already part of param name double
// since form feed is used as the colon replacement below
if (key.contains("\f")) {
key = (FORM_FEED_PATTERN.matcher(key).replaceAll("\f\f"));
}
// colon is special to UriTemplate
if (key.contains(":")) {
key = COLON_PATTERN.matcher(key).replaceAll("\f");
}
key = key + i;
singles.put(key, value);
query.append("={");
query.append(key);
query.append("}");
}
i++;
}
}
UriTemplate template = new UriTemplate("?" + query.toString().substring(1));
return template.expand(singles).toString();
} } | public class class_name {
public String getQueryString(MultiValueMap<String, String> params) {
if (params.isEmpty()) {
return ""; // depends on control dependency: [if], data = [none]
}
StringBuilder query = new StringBuilder();
Map<String, Object> singles = new HashMap<>();
for (String param : params.keySet()) {
int i = 0;
for (String value : params.get(param)) {
query.append("&"); // depends on control dependency: [for], data = [none]
query.append(param); // depends on control dependency: [for], data = [none]
if (!"".equals(value)) { // don't add =, if original is ?wsdl, output is
// not ?wsdl=
String key = param;
// if form feed is already part of param name double
// since form feed is used as the colon replacement below
if (key.contains("\f")) {
key = (FORM_FEED_PATTERN.matcher(key).replaceAll("\f\f")); // depends on control dependency: [if], data = [none]
}
// colon is special to UriTemplate
if (key.contains(":")) {
key = COLON_PATTERN.matcher(key).replaceAll("\f"); // depends on control dependency: [if], data = [none]
}
key = key + i; // depends on control dependency: [if], data = [none]
singles.put(key, value); // depends on control dependency: [if], data = [none]
query.append("={"); // depends on control dependency: [if], data = [none]
query.append(key); // depends on control dependency: [if], data = [none]
query.append("}"); // depends on control dependency: [if], data = [none]
}
i++; // depends on control dependency: [for], data = [none]
}
}
UriTemplate template = new UriTemplate("?" + query.toString().substring(1));
return template.expand(singles).toString();
} } |
public class class_name {
public void build(final Class<?> clazz, final Field field, final DeviceImpl device, final Object businessObject)
throws DevFailed {
xlogger.entry();
try {
// Inject each device property
final DeviceProperty annot = field.getAnnotation(DeviceProperty.class);
final String fieldName = field.getName();
String propName;
if (annot.name().equals("")) {
propName = fieldName;
} else {
propName = annot.name();
}
logger.debug("Has a DeviceProperty : {}", propName);
BuilderUtils.checkStatic(field);
String setterName = BuilderUtils.SET + fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH)
+ fieldName.substring(1);
Method setter = null;
try {
setter = businessObject.getClass().getMethod(setterName, field.getType());
} catch (final NoSuchMethodException e) {
if (fieldName.startsWith(BuilderUtils.IS)) {
setterName = BuilderUtils.SET + fieldName.substring(2);
try {
setter = businessObject.getClass().getMethod(setterName, field.getType());
} catch (final NoSuchMethodException e1) {
throw DevFailedUtils.newDevFailed(e);
}
} else {
throw DevFailedUtils.newDevFailed(e);
}
}
final DevicePropertyImpl property = new DevicePropertyImpl(propName, annot.description(), setter,
businessObject, device.getName(), device.getClassName(), annot.isMandatory(), annot.defaultValue());
device.addDeviceProperty(property);
} catch (final IllegalArgumentException e) {
throw DevFailedUtils.newDevFailed(e);
}
xlogger.exit();
} } | public class class_name {
public void build(final Class<?> clazz, final Field field, final DeviceImpl device, final Object businessObject)
throws DevFailed {
xlogger.entry();
try {
// Inject each device property
final DeviceProperty annot = field.getAnnotation(DeviceProperty.class);
final String fieldName = field.getName();
String propName;
if (annot.name().equals("")) {
propName = fieldName; // depends on control dependency: [if], data = [none]
} else {
propName = annot.name(); // depends on control dependency: [if], data = [none]
}
logger.debug("Has a DeviceProperty : {}", propName);
BuilderUtils.checkStatic(field);
String setterName = BuilderUtils.SET + fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH)
+ fieldName.substring(1);
Method setter = null;
try {
setter = businessObject.getClass().getMethod(setterName, field.getType()); // depends on control dependency: [try], data = [none]
} catch (final NoSuchMethodException e) {
if (fieldName.startsWith(BuilderUtils.IS)) {
setterName = BuilderUtils.SET + fieldName.substring(2); // depends on control dependency: [if], data = [none]
try {
setter = businessObject.getClass().getMethod(setterName, field.getType()); // depends on control dependency: [try], data = [none]
} catch (final NoSuchMethodException e1) {
throw DevFailedUtils.newDevFailed(e);
} // depends on control dependency: [catch], data = [none]
} else {
throw DevFailedUtils.newDevFailed(e);
}
} // depends on control dependency: [catch], data = [none]
final DevicePropertyImpl property = new DevicePropertyImpl(propName, annot.description(), setter,
businessObject, device.getName(), device.getClassName(), annot.isMandatory(), annot.defaultValue());
device.addDeviceProperty(property);
} catch (final IllegalArgumentException e) {
throw DevFailedUtils.newDevFailed(e);
}
xlogger.exit();
} } |
public class class_name {
public String toExternalForm() {
// pre-compute length of StringBuffer
int len = this.getProtocol().length() + 1;
if (this.getAuthority() != null && this.getAuthority().length() > 0) {
len += 2 + this.getAuthority().length();
}
if (this.getPath() != null) {
len += this.getPath().length();
}
if (this.getQuery() != null) {
len += 1 + this.getQuery().length();
}
if (this.getRef() != null) {
len += 1 + this.getRef().length();
}
final StringBuffer result = new StringBuffer(len);
result.append(this.getProtocol());
result.append(':');
if (this.getAuthority() != null && this.getAuthority().length() > 0) {
result.append("//");
result.append(this.getAuthority());
}
if (this.getPath() != null) {
result.append(this.getPath());
}
if (this.getQuery() != null) {
result.append('?');
result.append(this.getQuery());
}
if (this.getRef() != null) {
result.append('#');
result.append(this.getRef());
}
return result.toString();
} } | public class class_name {
public String toExternalForm() {
// pre-compute length of StringBuffer
int len = this.getProtocol().length() + 1;
if (this.getAuthority() != null && this.getAuthority().length() > 0) {
len += 2 + this.getAuthority().length(); // depends on control dependency: [if], data = [none]
}
if (this.getPath() != null) {
len += this.getPath().length(); // depends on control dependency: [if], data = [none]
}
if (this.getQuery() != null) {
len += 1 + this.getQuery().length(); // depends on control dependency: [if], data = [none]
}
if (this.getRef() != null) {
len += 1 + this.getRef().length(); // depends on control dependency: [if], data = [none]
}
final StringBuffer result = new StringBuffer(len);
result.append(this.getProtocol());
result.append(':');
if (this.getAuthority() != null && this.getAuthority().length() > 0) {
result.append("//");
result.append(this.getAuthority()); // depends on control dependency: [if], data = [none]
}
if (this.getPath() != null) {
result.append(this.getPath()); // depends on control dependency: [if], data = [(this.getPath()]
}
if (this.getQuery() != null) {
result.append('?'); // depends on control dependency: [if], data = [none]
result.append(this.getQuery()); // depends on control dependency: [if], data = [(this.getQuery()]
}
if (this.getRef() != null) {
result.append('#'); // depends on control dependency: [if], data = [none]
result.append(this.getRef()); // depends on control dependency: [if], data = [(this.getRef()]
}
return result.toString();
} } |
public class class_name {
protected boolean doesStartingTimeAllowServiceAccess() {
if (this.startingDateTime != null) {
val st = DateTimeUtils.zonedDateTimeOf(this.startingDateTime);
if (st != null) {
val now = ZonedDateTime.now(ZoneOffset.UTC);
if (now.isBefore(st)) {
LOGGER.warn("Service access not allowed because it starts at [{}]. Zoned now is [{}]", this.startingDateTime, now);
return false;
}
} else {
val stLocal = DateTimeUtils.localDateTimeOf(this.startingDateTime);
if (stLocal != null) {
val now = LocalDateTime.now(ZoneOffset.UTC);
if (now.isBefore(stLocal)) {
LOGGER.warn("Service access not allowed because it starts at [{}]. Local now is [{}]", this.startingDateTime, now);
return false;
}
}
}
}
return true;
} } | public class class_name {
protected boolean doesStartingTimeAllowServiceAccess() {
if (this.startingDateTime != null) {
val st = DateTimeUtils.zonedDateTimeOf(this.startingDateTime);
if (st != null) {
val now = ZonedDateTime.now(ZoneOffset.UTC);
if (now.isBefore(st)) {
LOGGER.warn("Service access not allowed because it starts at [{}]. Zoned now is [{}]", this.startingDateTime, now); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
} else {
val stLocal = DateTimeUtils.localDateTimeOf(this.startingDateTime);
if (stLocal != null) {
val now = LocalDateTime.now(ZoneOffset.UTC);
if (now.isBefore(stLocal)) {
LOGGER.warn("Service access not allowed because it starts at [{}]. Local now is [{}]", this.startingDateTime, now); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
}
}
}
return true;
} } |
public class class_name {
public void processProjectProperties(List<Row> rows, Integer projectID)
{
if (rows.isEmpty() == false)
{
Row row = rows.get(0);
ProjectProperties properties = m_project.getProjectProperties();
properties.setCreationDate(row.getDate("create_date"));
properties.setFinishDate(row.getDate("plan_end_date"));
properties.setName(row.getString("proj_short_name"));
properties.setStartDate(row.getDate("plan_start_date")); // data_date?
properties.setDefaultTaskType(TASK_TYPE_MAP.get(row.getString("def_duration_type")));
properties.setStatusDate(row.getDate("last_recalc_date"));
properties.setFiscalYearStartMonth(row.getInteger("fy_start_month_num"));
properties.setUniqueID(projectID == null ? null : projectID.toString());
properties.setExportFlag(row.getBoolean("export_flag"));
// cannot assign actual calendar yet as it has not been read yet
m_defaultCalendarID = row.getInteger("clndr_id");
}
} } | public class class_name {
public void processProjectProperties(List<Row> rows, Integer projectID)
{
if (rows.isEmpty() == false)
{
Row row = rows.get(0);
ProjectProperties properties = m_project.getProjectProperties();
properties.setCreationDate(row.getDate("create_date")); // depends on control dependency: [if], data = [none]
properties.setFinishDate(row.getDate("plan_end_date")); // depends on control dependency: [if], data = [none]
properties.setName(row.getString("proj_short_name")); // depends on control dependency: [if], data = [none]
properties.setStartDate(row.getDate("plan_start_date")); // data_date? // depends on control dependency: [if], data = [none]
properties.setDefaultTaskType(TASK_TYPE_MAP.get(row.getString("def_duration_type"))); // depends on control dependency: [if], data = [none]
properties.setStatusDate(row.getDate("last_recalc_date")); // depends on control dependency: [if], data = [none]
properties.setFiscalYearStartMonth(row.getInteger("fy_start_month_num")); // depends on control dependency: [if], data = [none]
properties.setUniqueID(projectID == null ? null : projectID.toString()); // depends on control dependency: [if], data = [none]
properties.setExportFlag(row.getBoolean("export_flag")); // depends on control dependency: [if], data = [none]
// cannot assign actual calendar yet as it has not been read yet
m_defaultCalendarID = row.getInteger("clndr_id"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {
List<RuleMatch> ruleMatches = new ArrayList<>();
// Let's get all the tokens (i.e. words) of this sentence, but not the spaces:
AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace();
// No let's iterate over those - note that the first token will
// be a special token that indicates the start of a sentence:
for (AnalyzedTokenReadings token : tokens) {
System.out.println("Token: " + token.getToken()); // the original word from the input text
// A word can have more than one reading, e.g. 'dance' can be a verb or a noun,
// so we iterate over the readings:
for (AnalyzedToken analyzedToken : token.getReadings()) {
System.out.println(" Lemma: " + analyzedToken.getLemma());
System.out.println(" POS: " + analyzedToken.getPOSTag());
}
// You can add your own logic here to find errors. Here, we just consider
// the word "demo" an error and create a rule match that LanguageTool will
// then show to the user:
if (token.getToken().equals("demo")) {
RuleMatch ruleMatch = new RuleMatch(this, sentence, token.getStartPos(), token.getEndPos(), "The demo rule thinks this looks wrong");
ruleMatch.setSuggestedReplacement("blablah"); // the user will see this as a suggested correction
ruleMatches.add(ruleMatch);
}
}
return toRuleMatchArray(ruleMatches);
} } | public class class_name {
@Override
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {
List<RuleMatch> ruleMatches = new ArrayList<>();
// Let's get all the tokens (i.e. words) of this sentence, but not the spaces:
AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace();
// No let's iterate over those - note that the first token will
// be a special token that indicates the start of a sentence:
for (AnalyzedTokenReadings token : tokens) {
System.out.println("Token: " + token.getToken()); // the original word from the input text
// A word can have more than one reading, e.g. 'dance' can be a verb or a noun,
// so we iterate over the readings:
for (AnalyzedToken analyzedToken : token.getReadings()) {
System.out.println(" Lemma: " + analyzedToken.getLemma()); // depends on control dependency: [for], data = [analyzedToken]
System.out.println(" POS: " + analyzedToken.getPOSTag()); // depends on control dependency: [for], data = [analyzedToken]
}
// You can add your own logic here to find errors. Here, we just consider
// the word "demo" an error and create a rule match that LanguageTool will
// then show to the user:
if (token.getToken().equals("demo")) {
RuleMatch ruleMatch = new RuleMatch(this, sentence, token.getStartPos(), token.getEndPos(), "The demo rule thinks this looks wrong");
ruleMatch.setSuggestedReplacement("blablah"); // the user will see this as a suggested correction // depends on control dependency: [if], data = [none]
ruleMatches.add(ruleMatch); // depends on control dependency: [if], data = [none]
}
}
return toRuleMatchArray(ruleMatches);
} } |
public class class_name {
@Override
protected String createDialogHtml(String dialog) {
StringBuffer result = new StringBuffer(512);
result.append(createWidgetTableStart());
// show error header once if there were validation errors
result.append(createWidgetErrorHeader());
if (dialog.equals(PAGES[0])) {
// create the widgets for the first dialog page
result.append(dialogBlockStart(key(Messages.GUI_LIST_FIELDCONFIGURATION_ACTION_DELETE_NAME_0)));
result.append(createWidgetTableStart());
result.append(key(
Messages.GUI_LIST_FIELDCONFIGURATION_ACTION_DELETE_CONF_1,
new Object[] {m_fieldconfiguration.getName()}));
result.append(createWidgetTableEnd());
result.append(dialogBlockEnd());
}
result.append(createWidgetTableEnd());
// See CmsWidgetDialog.dialogButtonsCustom(): if no widgets are defined that are non-display-only widgets,
// no dialog buttons (Ok, Cancel) will be visible....
result.append(dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL}, new String[2]));
return result.toString();
} } | public class class_name {
@Override
protected String createDialogHtml(String dialog) {
StringBuffer result = new StringBuffer(512);
result.append(createWidgetTableStart());
// show error header once if there were validation errors
result.append(createWidgetErrorHeader());
if (dialog.equals(PAGES[0])) {
// create the widgets for the first dialog page
result.append(dialogBlockStart(key(Messages.GUI_LIST_FIELDCONFIGURATION_ACTION_DELETE_NAME_0))); // depends on control dependency: [if], data = [none]
result.append(createWidgetTableStart()); // depends on control dependency: [if], data = [none]
result.append(key(
Messages.GUI_LIST_FIELDCONFIGURATION_ACTION_DELETE_CONF_1,
new Object[] {m_fieldconfiguration.getName()})); // depends on control dependency: [if], data = [none]
result.append(createWidgetTableEnd()); // depends on control dependency: [if], data = [none]
result.append(dialogBlockEnd()); // depends on control dependency: [if], data = [none]
}
result.append(createWidgetTableEnd());
// See CmsWidgetDialog.dialogButtonsCustom(): if no widgets are defined that are non-display-only widgets,
// no dialog buttons (Ok, Cancel) will be visible....
result.append(dialogButtons(new int[] {BUTTON_OK, BUTTON_CANCEL}, new String[2]));
return result.toString();
} } |
public class class_name {
public void updateUserMeta(final long userId, final String key, final String value) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(firstUserMetaIdSQL);
stmt.setLong(1, userId);
stmt.setString(2, key);
rs = stmt.executeQuery();
if(rs.next()) {
long umetaId = rs.getLong(1);
SQLUtil.closeQuietly(stmt, rs);
stmt = null;
rs = null;
stmt = conn.prepareStatement(updateUserMetaSQL);
stmt.setString(1, value);
stmt.setLong(2, umetaId);
stmt.executeUpdate();
} else {
SQLUtil.closeQuietly(stmt, rs);
stmt = null;
rs = null;
stmt = conn.prepareStatement(insertUserMetaSQL);
stmt.setLong(1, userId);
stmt.setString(2, key);
stmt.setString(3, value);
stmt.executeUpdate();
}
} finally {
SQLUtil.closeQuietly(conn, stmt, rs);
}
} } | public class class_name {
public void updateUserMeta(final long userId, final String key, final String value) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(firstUserMetaIdSQL);
stmt.setLong(1, userId);
stmt.setString(2, key);
rs = stmt.executeQuery();
if(rs.next()) {
long umetaId = rs.getLong(1);
SQLUtil.closeQuietly(stmt, rs); // depends on control dependency: [if], data = [none]
stmt = null; // depends on control dependency: [if], data = [none]
rs = null; // depends on control dependency: [if], data = [none]
stmt = conn.prepareStatement(updateUserMetaSQL); // depends on control dependency: [if], data = [none]
stmt.setString(1, value); // depends on control dependency: [if], data = [none]
stmt.setLong(2, umetaId); // depends on control dependency: [if], data = [none]
stmt.executeUpdate(); // depends on control dependency: [if], data = [none]
} else {
SQLUtil.closeQuietly(stmt, rs); // depends on control dependency: [if], data = [none]
stmt = null; // depends on control dependency: [if], data = [none]
rs = null; // depends on control dependency: [if], data = [none]
stmt = conn.prepareStatement(insertUserMetaSQL); // depends on control dependency: [if], data = [none]
stmt.setLong(1, userId); // depends on control dependency: [if], data = [none]
stmt.setString(2, key); // depends on control dependency: [if], data = [none]
stmt.setString(3, value); // depends on control dependency: [if], data = [none]
stmt.executeUpdate(); // depends on control dependency: [if], data = [none]
}
} finally {
SQLUtil.closeQuietly(conn, stmt, rs);
}
} } |
public class class_name {
protected static InputStream getConfigurationFileFromAssets(Context context,
String fileName) {
if (context == null) {
return null;
}
AssetManager assets = context.getAssets();
if (assets == null) {
return null;
}
try {
return assets.open(fileName);
} catch (IOException e) {
return null;
}
} } | public class class_name {
protected static InputStream getConfigurationFileFromAssets(Context context,
String fileName) {
if (context == null) {
return null; // depends on control dependency: [if], data = [none]
}
AssetManager assets = context.getAssets();
if (assets == null) {
return null; // depends on control dependency: [if], data = [none]
}
try {
return assets.open(fileName); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private RelBuilder convertSingletonDistinct(RelBuilder relBuilder,
Aggregate aggregate, Set<Pair<List<Integer>, Integer>> argLists) {
// In this case, we are assuming that there is a single distinct function.
// So make sure that argLists is of size one.
Preconditions.checkArgument(argLists.size() == 1);
// For example,
// SELECT deptno, COUNT(*), SUM(bonus), MIN(DISTINCT sal)
// FROM emp
// GROUP BY deptno
//
// becomes
//
// SELECT deptno, SUM(cnt), SUM(bonus), MIN(sal)
// FROM (
// SELECT deptno, COUNT(*) as cnt, SUM(bonus), sal
// FROM EMP
// GROUP BY deptno, sal) // Aggregate B
// GROUP BY deptno // Aggregate A
relBuilder.push(aggregate.getInput());
final List<AggregateCall> originalAggCalls = aggregate.getAggCallList();
final ImmutableBitSet originalGroupSet = aggregate.getGroupSet();
// Add the distinct aggregate column(s) to the group-by columns,
// if not already a part of the group-by
final SortedSet<Integer> bottomGroupSet = new TreeSet<>();
bottomGroupSet.addAll(aggregate.getGroupSet().asList());
for (AggregateCall aggCall : originalAggCalls) {
if (aggCall.isDistinct()) {
bottomGroupSet.addAll(aggCall.getArgList());
break; // since we only have single distinct call
}
}
// Generate the intermediate aggregate B, the one on the bottom that converts
// a distinct call to group by call.
// Bottom aggregate is the same as the original aggregate, except that
// the bottom aggregate has converted the DISTINCT aggregate to a group by clause.
final List<AggregateCall> bottomAggregateCalls = new ArrayList<>();
for (AggregateCall aggCall : originalAggCalls) {
// Project the column corresponding to the distinct aggregate. Project
// as-is all the non-distinct aggregates
if (!aggCall.isDistinct()) {
final AggregateCall newCall =
AggregateCall.create(aggCall.getAggregation(), false,
aggCall.isApproximate(), aggCall.getArgList(), -1,
ImmutableBitSet.of(bottomGroupSet).cardinality(),
relBuilder.peek(), null, aggCall.name);
bottomAggregateCalls.add(newCall);
}
}
// Generate the aggregate B (see the reference example above)
relBuilder.push(
aggregate.copy(
aggregate.getTraitSet(), relBuilder.build(),
false, ImmutableBitSet.of(bottomGroupSet), null, bottomAggregateCalls));
// Add aggregate A (see the reference example above), the top aggregate
// to handle the rest of the aggregation that the bottom aggregate hasn't handled
final List<AggregateCall> topAggregateCalls = com.google.common.collect.Lists.newArrayList();
// Use the remapped arguments for the (non)distinct aggregate calls
int nonDistinctAggCallProcessedSoFar = 0;
for (AggregateCall aggCall : originalAggCalls) {
final AggregateCall newCall;
if (aggCall.isDistinct()) {
List<Integer> newArgList = new ArrayList<>();
for (int arg : aggCall.getArgList()) {
newArgList.add(bottomGroupSet.headSet(arg).size());
}
newCall =
AggregateCall.create(aggCall.getAggregation(),
false,
aggCall.isApproximate(),
newArgList,
-1,
originalGroupSet.cardinality(),
relBuilder.peek(),
aggCall.getType(),
aggCall.name);
} else {
// If aggregate B had a COUNT aggregate call the corresponding aggregate at
// aggregate A must be SUM. For other aggregates, it remains the same.
final List<Integer> newArgs =
com.google.common.collect.Lists.newArrayList(
bottomGroupSet.size() + nonDistinctAggCallProcessedSoFar);
if (aggCall.getAggregation().getKind() == SqlKind.COUNT) {
newCall =
AggregateCall.create(new SqlSumEmptyIsZeroAggFunction(), false,
aggCall.isApproximate(), newArgs, -1,
originalGroupSet.cardinality(), relBuilder.peek(),
aggCall.getType(), aggCall.getName());
} else {
newCall =
AggregateCall.create(aggCall.getAggregation(), false,
aggCall.isApproximate(), newArgs, -1,
originalGroupSet.cardinality(),
relBuilder.peek(), aggCall.getType(), aggCall.name);
}
nonDistinctAggCallProcessedSoFar++;
}
topAggregateCalls.add(newCall);
}
// Populate the group-by keys with the remapped arguments for aggregate A
// The top groupset is basically an identity (first X fields of aggregate B's
// output), minus the distinct aggCall's input.
final Set<Integer> topGroupSet = new HashSet<>();
int groupSetToAdd = 0;
for (int bottomGroup : bottomGroupSet) {
if (originalGroupSet.get(bottomGroup)) {
topGroupSet.add(groupSetToAdd);
}
groupSetToAdd++;
}
relBuilder.push(
aggregate.copy(aggregate.getTraitSet(),
relBuilder.build(), aggregate.indicator,
ImmutableBitSet.of(topGroupSet), null, topAggregateCalls));
return relBuilder;
} } | public class class_name {
private RelBuilder convertSingletonDistinct(RelBuilder relBuilder,
Aggregate aggregate, Set<Pair<List<Integer>, Integer>> argLists) {
// In this case, we are assuming that there is a single distinct function.
// So make sure that argLists is of size one.
Preconditions.checkArgument(argLists.size() == 1);
// For example,
// SELECT deptno, COUNT(*), SUM(bonus), MIN(DISTINCT sal)
// FROM emp
// GROUP BY deptno
//
// becomes
//
// SELECT deptno, SUM(cnt), SUM(bonus), MIN(sal)
// FROM (
// SELECT deptno, COUNT(*) as cnt, SUM(bonus), sal
// FROM EMP
// GROUP BY deptno, sal) // Aggregate B
// GROUP BY deptno // Aggregate A
relBuilder.push(aggregate.getInput());
final List<AggregateCall> originalAggCalls = aggregate.getAggCallList();
final ImmutableBitSet originalGroupSet = aggregate.getGroupSet();
// Add the distinct aggregate column(s) to the group-by columns,
// if not already a part of the group-by
final SortedSet<Integer> bottomGroupSet = new TreeSet<>();
bottomGroupSet.addAll(aggregate.getGroupSet().asList());
for (AggregateCall aggCall : originalAggCalls) {
if (aggCall.isDistinct()) {
bottomGroupSet.addAll(aggCall.getArgList()); // depends on control dependency: [if], data = [none]
break; // since we only have single distinct call
}
}
// Generate the intermediate aggregate B, the one on the bottom that converts
// a distinct call to group by call.
// Bottom aggregate is the same as the original aggregate, except that
// the bottom aggregate has converted the DISTINCT aggregate to a group by clause.
final List<AggregateCall> bottomAggregateCalls = new ArrayList<>();
for (AggregateCall aggCall : originalAggCalls) {
// Project the column corresponding to the distinct aggregate. Project
// as-is all the non-distinct aggregates
if (!aggCall.isDistinct()) {
final AggregateCall newCall =
AggregateCall.create(aggCall.getAggregation(), false,
aggCall.isApproximate(), aggCall.getArgList(), -1,
ImmutableBitSet.of(bottomGroupSet).cardinality(),
relBuilder.peek(), null, aggCall.name);
bottomAggregateCalls.add(newCall); // depends on control dependency: [if], data = [none]
}
}
// Generate the aggregate B (see the reference example above)
relBuilder.push(
aggregate.copy(
aggregate.getTraitSet(), relBuilder.build(),
false, ImmutableBitSet.of(bottomGroupSet), null, bottomAggregateCalls));
// Add aggregate A (see the reference example above), the top aggregate
// to handle the rest of the aggregation that the bottom aggregate hasn't handled
final List<AggregateCall> topAggregateCalls = com.google.common.collect.Lists.newArrayList();
// Use the remapped arguments for the (non)distinct aggregate calls
int nonDistinctAggCallProcessedSoFar = 0;
for (AggregateCall aggCall : originalAggCalls) {
final AggregateCall newCall;
if (aggCall.isDistinct()) {
List<Integer> newArgList = new ArrayList<>();
for (int arg : aggCall.getArgList()) {
newArgList.add(bottomGroupSet.headSet(arg).size()); // depends on control dependency: [for], data = [arg]
}
newCall =
AggregateCall.create(aggCall.getAggregation(),
false,
aggCall.isApproximate(),
newArgList,
-1,
originalGroupSet.cardinality(),
relBuilder.peek(),
aggCall.getType(),
aggCall.name); // depends on control dependency: [if], data = [none]
} else {
// If aggregate B had a COUNT aggregate call the corresponding aggregate at
// aggregate A must be SUM. For other aggregates, it remains the same.
final List<Integer> newArgs =
com.google.common.collect.Lists.newArrayList(
bottomGroupSet.size() + nonDistinctAggCallProcessedSoFar);
if (aggCall.getAggregation().getKind() == SqlKind.COUNT) {
newCall =
AggregateCall.create(new SqlSumEmptyIsZeroAggFunction(), false,
aggCall.isApproximate(), newArgs, -1,
originalGroupSet.cardinality(), relBuilder.peek(),
aggCall.getType(), aggCall.getName()); // depends on control dependency: [if], data = [none]
} else {
newCall =
AggregateCall.create(aggCall.getAggregation(), false,
aggCall.isApproximate(), newArgs, -1,
originalGroupSet.cardinality(),
relBuilder.peek(), aggCall.getType(), aggCall.name); // depends on control dependency: [if], data = [none]
}
nonDistinctAggCallProcessedSoFar++; // depends on control dependency: [if], data = [none]
}
topAggregateCalls.add(newCall); // depends on control dependency: [for], data = [none]
}
// Populate the group-by keys with the remapped arguments for aggregate A
// The top groupset is basically an identity (first X fields of aggregate B's
// output), minus the distinct aggCall's input.
final Set<Integer> topGroupSet = new HashSet<>();
int groupSetToAdd = 0;
for (int bottomGroup : bottomGroupSet) {
if (originalGroupSet.get(bottomGroup)) {
topGroupSet.add(groupSetToAdd); // depends on control dependency: [if], data = [none]
}
groupSetToAdd++; // depends on control dependency: [for], data = [none]
}
relBuilder.push(
aggregate.copy(aggregate.getTraitSet(),
relBuilder.build(), aggregate.indicator,
ImmutableBitSet.of(topGroupSet), null, topAggregateCalls));
return relBuilder;
} } |
public class class_name {
private boolean inferTemplatedTypesForCall(Node n, FunctionType fnType, FlowScope scope) {
ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap().getTemplateKeys();
if (keys.isEmpty()) {
return false;
}
// Try to infer the template types
Map<TemplateType, JSType> rawInferrence = inferTemplateTypesFromParameters(fnType, n, scope);
Map<TemplateType, JSType> inferred = Maps.newIdentityHashMap();
for (TemplateType key : keys) {
JSType type = rawInferrence.get(key);
if (type == null) {
type = unknownType;
}
inferred.put(key, type);
}
// Try to infer the template types using the type transformations
Map<TemplateType, JSType> typeTransformations =
evaluateTypeTransformations(keys, inferred, scope);
if (typeTransformations != null) {
inferred.putAll(typeTransformations);
}
// Replace all template types. If we couldn't find a replacement, we
// replace it with UNKNOWN.
TemplateTypeReplacer replacer = new TemplateTypeReplacer(registry, inferred);
Node callTarget = n.getFirstChild();
FunctionType replacementFnType = fnType.visit(replacer).toMaybeFunctionType();
checkNotNull(replacementFnType);
callTarget.setJSType(replacementFnType);
n.setJSType(replacementFnType.getReturnType());
return replacer.madeChanges;
} } | public class class_name {
private boolean inferTemplatedTypesForCall(Node n, FunctionType fnType, FlowScope scope) {
ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap().getTemplateKeys();
if (keys.isEmpty()) {
return false; // depends on control dependency: [if], data = [none]
}
// Try to infer the template types
Map<TemplateType, JSType> rawInferrence = inferTemplateTypesFromParameters(fnType, n, scope);
Map<TemplateType, JSType> inferred = Maps.newIdentityHashMap();
for (TemplateType key : keys) {
JSType type = rawInferrence.get(key);
if (type == null) {
type = unknownType; // depends on control dependency: [if], data = [none]
}
inferred.put(key, type); // depends on control dependency: [for], data = [key]
}
// Try to infer the template types using the type transformations
Map<TemplateType, JSType> typeTransformations =
evaluateTypeTransformations(keys, inferred, scope);
if (typeTransformations != null) {
inferred.putAll(typeTransformations); // depends on control dependency: [if], data = [(typeTransformations]
}
// Replace all template types. If we couldn't find a replacement, we
// replace it with UNKNOWN.
TemplateTypeReplacer replacer = new TemplateTypeReplacer(registry, inferred);
Node callTarget = n.getFirstChild();
FunctionType replacementFnType = fnType.visit(replacer).toMaybeFunctionType();
checkNotNull(replacementFnType);
callTarget.setJSType(replacementFnType);
n.setJSType(replacementFnType.getReturnType());
return replacer.madeChanges;
} } |
public class class_name {
public final void setRollbackFor(Class<? extends Throwable>... exceptions) {
if (ArrayUtils.isNotEmpty(exceptions)) {
if (rollbackFor == null) {
rollbackFor = new HashSet<>();
}
rollbackFor.addAll(Arrays.asList(exceptions));
}
} } | public class class_name {
public final void setRollbackFor(Class<? extends Throwable>... exceptions) {
if (ArrayUtils.isNotEmpty(exceptions)) {
if (rollbackFor == null) {
rollbackFor = new HashSet<>(); // depends on control dependency: [if], data = [none]
}
rollbackFor.addAll(Arrays.asList(exceptions)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public CmsJspImageBean createRatioVariation(String ratioStr) {
CmsJspImageBean result = null;
try {
int i = ratioStr.indexOf('-');
if (i > 0) {
ratioStr = ratioStr.replace(',', '.');
double ratioW = Double.valueOf(ratioStr.substring(0, i)).doubleValue();
double ratioH = Double.valueOf(ratioStr.substring(i + 1)).doubleValue();
int targetWidth, targetHeight;
double ratioFactorW = getScaler().getWidth() / ratioW;
targetWidth = getScaler().getWidth();
targetHeight = (int)Math.round(ratioH * ratioFactorW);
if (targetHeight > getScaler().getHeight()) {
double ratioFactorH = getScaler().getHeight() / ratioH;
targetWidth = (int)Math.round(ratioW * ratioFactorH);
targetHeight = getScaler().getHeight();
}
CmsImageScaler targetScaler = createVariation(
getWidth(),
getHeight(),
getBaseScaler(),
targetWidth,
targetHeight,
getQuality());
if (targetScaler != null) {
result = createVariation(targetScaler);
result.m_ratio = ratioStr;
result.m_ratioHeightPercentage = calcRatioHeightPercentage(ratioW, ratioH);
}
}
} catch (NumberFormatException e) {
if (LOG.isWarnEnabled()) {
LOG.warn(String.format("Illegal ratio format: '%s' not usable for image scaling", ratioStr));
}
}
return result;
} } | public class class_name {
public CmsJspImageBean createRatioVariation(String ratioStr) {
CmsJspImageBean result = null;
try {
int i = ratioStr.indexOf('-');
if (i > 0) {
ratioStr = ratioStr.replace(',', '.'); // depends on control dependency: [if], data = [none]
double ratioW = Double.valueOf(ratioStr.substring(0, i)).doubleValue();
double ratioH = Double.valueOf(ratioStr.substring(i + 1)).doubleValue();
int targetWidth, targetHeight;
double ratioFactorW = getScaler().getWidth() / ratioW;
targetWidth = getScaler().getWidth(); // depends on control dependency: [if], data = [none]
targetHeight = (int)Math.round(ratioH * ratioFactorW); // depends on control dependency: [if], data = [(i]
if (targetHeight > getScaler().getHeight()) {
double ratioFactorH = getScaler().getHeight() / ratioH;
targetWidth = (int)Math.round(ratioW * ratioFactorH); // depends on control dependency: [if], data = [none]
targetHeight = getScaler().getHeight(); // depends on control dependency: [if], data = [none]
}
CmsImageScaler targetScaler = createVariation(
getWidth(),
getHeight(),
getBaseScaler(),
targetWidth,
targetHeight,
getQuality());
if (targetScaler != null) {
result = createVariation(targetScaler); // depends on control dependency: [if], data = [(targetScaler]
result.m_ratio = ratioStr; // depends on control dependency: [if], data = [none]
result.m_ratioHeightPercentage = calcRatioHeightPercentage(ratioW, ratioH); // depends on control dependency: [if], data = [none]
}
}
} catch (NumberFormatException e) {
if (LOG.isWarnEnabled()) {
LOG.warn(String.format("Illegal ratio format: '%s' not usable for image scaling", ratioStr)); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
public TreeSet<HtmlParameter> getCookieParams() {
TreeSet<HtmlParameter> set = new TreeSet<>();
Vector<String> cookies = getHeaders(HttpHeader.SET_COOKIE);
if (cookies != null) {
Iterator<String> it = cookies.iterator();
while (it.hasNext()) {
set.add(new HtmlParameter(it.next()));
}
}
Vector<String> cookies2 = getHeaders(HttpHeader.SET_COOKIE2);
if (cookies2 != null) {
Iterator<String> it = cookies2.iterator();
while (it.hasNext()) {
set.add(new HtmlParameter(it.next()));
}
}
return set;
} } | public class class_name {
public TreeSet<HtmlParameter> getCookieParams() {
TreeSet<HtmlParameter> set = new TreeSet<>();
Vector<String> cookies = getHeaders(HttpHeader.SET_COOKIE);
if (cookies != null) {
Iterator<String> it = cookies.iterator();
while (it.hasNext()) {
set.add(new HtmlParameter(it.next()));
// depends on control dependency: [while], data = [none]
}
}
Vector<String> cookies2 = getHeaders(HttpHeader.SET_COOKIE2);
if (cookies2 != null) {
Iterator<String> it = cookies2.iterator();
while (it.hasNext()) {
set.add(new HtmlParameter(it.next()));
// depends on control dependency: [while], data = [none]
}
}
return set;
} } |
public class class_name {
public void show(ViewGroup parent){
if(mState == STATE_SHOWING || mState == STATE_DISMISSING)
return;
if(getParent() != parent) {
if(getParent() != null)
((ViewGroup) getParent()).removeView(this);
parent.addView(this);
}
show();
} } | public class class_name {
public void show(ViewGroup parent){
if(mState == STATE_SHOWING || mState == STATE_DISMISSING)
return;
if(getParent() != parent) {
if(getParent() != null)
((ViewGroup) getParent()).removeView(this);
parent.addView(this); // depends on control dependency: [if], data = [none]
}
show();
} } |
public class class_name {
private void delete(String key, Map<String, String> params) {
final URI uri = createURI("/" + key);
final HttpRequestBuilder httpRequestBuilder = RequestUtils
.getHttpRequestBuilder(null, null, RequestOptions.BLANK, "");
final Set<Map.Entry<String, String>> entries = params.entrySet();
for (Map.Entry<String, String> entry : entries) {
httpRequestBuilder.addParam(entry.getKey(), entry.getValue());
}
httpRequestBuilder.setMethodDelete();
final HTTP.Response httpResponse = HTTP.deleteResponse(uri.toString() + "?" + httpRequestBuilder.paramString());
if (httpResponse.code() != 200) {
die("Unable to delete key", uri, key, httpResponse.code(), httpResponse.body());
}
} } | public class class_name {
private void delete(String key, Map<String, String> params) {
final URI uri = createURI("/" + key);
final HttpRequestBuilder httpRequestBuilder = RequestUtils
.getHttpRequestBuilder(null, null, RequestOptions.BLANK, "");
final Set<Map.Entry<String, String>> entries = params.entrySet();
for (Map.Entry<String, String> entry : entries) {
httpRequestBuilder.addParam(entry.getKey(), entry.getValue()); // depends on control dependency: [for], data = [entry]
}
httpRequestBuilder.setMethodDelete();
final HTTP.Response httpResponse = HTTP.deleteResponse(uri.toString() + "?" + httpRequestBuilder.paramString());
if (httpResponse.code() != 200) {
die("Unable to delete key", uri, key, httpResponse.code(), httpResponse.body()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private ThriftColumnFamilyDefinitionImpl toThriftColumnFamilyDefinition(Map<String, Object> options, ColumnFamily columnFamily) {
ThriftColumnFamilyDefinitionImpl def = new ThriftColumnFamilyDefinitionImpl();
Map<String, Object> internalOptions = Maps.newHashMap();
if (options != null)
internalOptions.putAll(options);
internalOptions.put("keyspace", getKeyspaceName());
if (columnFamily != null) {
internalOptions.put("name", columnFamily.getName());
if (!internalOptions.containsKey("comparator_type"))
internalOptions.put("comparator_type", columnFamily.getColumnSerializer().getComparatorType().getTypeName());
if (!internalOptions.containsKey("key_validation_class"))
internalOptions.put("key_validation_class", columnFamily.getKeySerializer().getComparatorType().getTypeName());
if (columnFamily.getDefaultValueSerializer() != null && !internalOptions.containsKey("default_validation_class"))
internalOptions.put("default_validation_class", columnFamily.getDefaultValueSerializer().getComparatorType().getTypeName());
}
def.setFields(internalOptions);
return def;
} } | public class class_name {
private ThriftColumnFamilyDefinitionImpl toThriftColumnFamilyDefinition(Map<String, Object> options, ColumnFamily columnFamily) {
ThriftColumnFamilyDefinitionImpl def = new ThriftColumnFamilyDefinitionImpl();
Map<String, Object> internalOptions = Maps.newHashMap();
if (options != null)
internalOptions.putAll(options);
internalOptions.put("keyspace", getKeyspaceName());
if (columnFamily != null) {
internalOptions.put("name", columnFamily.getName()); // depends on control dependency: [if], data = [none]
if (!internalOptions.containsKey("comparator_type"))
internalOptions.put("comparator_type", columnFamily.getColumnSerializer().getComparatorType().getTypeName());
if (!internalOptions.containsKey("key_validation_class"))
internalOptions.put("key_validation_class", columnFamily.getKeySerializer().getComparatorType().getTypeName());
if (columnFamily.getDefaultValueSerializer() != null && !internalOptions.containsKey("default_validation_class"))
internalOptions.put("default_validation_class", columnFamily.getDefaultValueSerializer().getComparatorType().getTypeName());
}
def.setFields(internalOptions);
return def;
} } |
public class class_name {
private void paintRows(final WDataTable table, final WebXmlRenderContext renderContext) {
XmlStringBuilder xml = renderContext.getWriter();
TableDataModel model = table.getDataModel();
xml.appendTagOpen("ui:tbody");
xml.appendAttribute("id", table.getRepeater().getId());
xml.appendClose();
if (model.getRowCount() == 0) {
xml.appendTag("ui:nodata");
xml.appendEscaped(table.getNoDataMessage());
xml.appendEndTag("ui:nodata");
} else {
// If has at least one visible col, paint the rows.
final int columnCount = table.getColumnCount();
for (int i = 0; i < columnCount; i++) {
if (table.getColumn(i).isVisible()) {
doPaintRows(table, renderContext);
break;
}
}
}
xml.appendEndTag("ui:tbody");
} } | public class class_name {
private void paintRows(final WDataTable table, final WebXmlRenderContext renderContext) {
XmlStringBuilder xml = renderContext.getWriter();
TableDataModel model = table.getDataModel();
xml.appendTagOpen("ui:tbody");
xml.appendAttribute("id", table.getRepeater().getId());
xml.appendClose();
if (model.getRowCount() == 0) {
xml.appendTag("ui:nodata"); // depends on control dependency: [if], data = [none]
xml.appendEscaped(table.getNoDataMessage()); // depends on control dependency: [if], data = [none]
xml.appendEndTag("ui:nodata"); // depends on control dependency: [if], data = [none]
} else {
// If has at least one visible col, paint the rows.
final int columnCount = table.getColumnCount();
for (int i = 0; i < columnCount; i++) {
if (table.getColumn(i).isVisible()) {
doPaintRows(table, renderContext); // depends on control dependency: [if], data = [none]
break;
}
}
}
xml.appendEndTag("ui:tbody");
} } |
public class class_name {
@Override
protected Configuration doConfigure(InputStream stream, String resourceName) throws HibernateException {
try {
ErrorLogger errorLogger = new ErrorLogger(resourceName);
SAXReader reader = xmlHelper.createSAXReader(errorLogger, getEntityResolver());
reader.setValidation(false);
Document document = reader.read(new InputSource(stream));
if (errorLogger.hasErrors()) { throw new MappingException("invalid configuration",
errorLogger.getErrors().get(0)); }
doConfigure(document);
} catch (DocumentException e) {
throw new HibernateException("Could not parse configuration: " + resourceName, e);
} finally {
try {
stream.close();
} catch (IOException ioe) {
logger.error("Could not close input stream for {}", resourceName);
}
}
return this;
} } | public class class_name {
@Override
protected Configuration doConfigure(InputStream stream, String resourceName) throws HibernateException {
try {
ErrorLogger errorLogger = new ErrorLogger(resourceName);
SAXReader reader = xmlHelper.createSAXReader(errorLogger, getEntityResolver());
reader.setValidation(false);
Document document = reader.read(new InputSource(stream));
if (errorLogger.hasErrors()) { throw new MappingException("invalid configuration",
errorLogger.getErrors().get(0)); }
doConfigure(document);
} catch (DocumentException e) {
throw new HibernateException("Could not parse configuration: " + resourceName, e);
} finally {
try {
stream.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
logger.error("Could not close input stream for {}", resourceName);
} // depends on control dependency: [catch], data = [none]
}
return this;
} } |
public class class_name {
private JobPushResult send(final RemotingServerDelegate remotingServer, int size, final TaskTrackerNode taskTrackerNode) {
final String nodeGroup = taskTrackerNode.getNodeGroup();
final String identity = taskTrackerNode.getIdentity();
JobSender.SendResult sendResult = appContext.getJobSender().send(nodeGroup, identity, size, new JobSender.SendInvoker() {
@Override
public JobSender.SendResult invoke(final List<JobPo> jobPos) {
// 发送给TaskTracker执行
JobPushRequest body = appContext.getCommandBodyWrapper().wrapper(new JobPushRequest());
body.setJobMetaList(JobDomainConverter.convert(jobPos));
RemotingCommand commandRequest = RemotingCommand.createRequestCommand(JobProtos.RequestCode.PUSH_JOB.code(), body);
// 是否分发推送任务成功
final Holder<Boolean> pushSuccess = new Holder<Boolean>(false);
final CountDownLatch latch = new CountDownLatch(1);
try {
remotingServer.invokeAsync(taskTrackerNode.getChannel().getChannel(), commandRequest, new AsyncCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
try {
RemotingCommand responseCommand = responseFuture.getResponseCommand();
if (responseCommand == null) {
LOGGER.warn("Job push failed! response command is null!");
return;
}
if (responseCommand.getCode() == JobProtos.ResponseCode.JOB_PUSH_SUCCESS.code()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Job push success! nodeGroup=" + nodeGroup + ", identity=" + identity + ", jobList=" + JSON.toJSONString(jobPos));
}
pushSuccess.set(true);
stat.incPushJobNum(jobPos.size());
} else if (responseCommand.getCode() == JobProtos.ResponseCode.NO_AVAILABLE_JOB_RUNNER.code()) {
JobPushResponse jobPushResponse = responseCommand.getBody();
if (jobPushResponse != null && CollectionUtils.isNotEmpty(jobPushResponse.getFailedJobIds())) {
// 修复任务
for (String jobId : jobPushResponse.getFailedJobIds()) {
for (JobPo jobPo : jobPos) {
if (jobId.equals(jobPo.getJobId())) {
resumeJob(jobPo);
break;
}
}
}
stat.incPushJobNum(jobPos.size() - jobPushResponse.getFailedJobIds().size());
} else {
stat.incPushJobNum(jobPos.size());
}
pushSuccess.set(true);
}
} finally {
latch.countDown();
}
}
});
} catch (RemotingSendException e) {
LOGGER.error("Remoting send error, jobPos={}", JSON.toJSONObject(jobPos), e);
return new JobSender.SendResult(false, JobPushResult.SENT_ERROR);
}
try {
latch.await(Constants.LATCH_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RequestTimeoutException(e);
}
if (!pushSuccess.get()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Job push failed! nodeGroup=" + nodeGroup + ", identity=" + identity + ", jobs=" + JSON.toJSONObject(jobPos));
}
for (JobPo jobPo : jobPos) {
resumeJob(jobPo);
}
return new JobSender.SendResult(false, JobPushResult.SENT_ERROR);
}
return new JobSender.SendResult(true, JobPushResult.SUCCESS);
}
});
return (JobPushResult) sendResult.getReturnValue();
} } | public class class_name {
private JobPushResult send(final RemotingServerDelegate remotingServer, int size, final TaskTrackerNode taskTrackerNode) {
final String nodeGroup = taskTrackerNode.getNodeGroup();
final String identity = taskTrackerNode.getIdentity();
JobSender.SendResult sendResult = appContext.getJobSender().send(nodeGroup, identity, size, new JobSender.SendInvoker() {
@Override
public JobSender.SendResult invoke(final List<JobPo> jobPos) {
// 发送给TaskTracker执行
JobPushRequest body = appContext.getCommandBodyWrapper().wrapper(new JobPushRequest());
body.setJobMetaList(JobDomainConverter.convert(jobPos));
RemotingCommand commandRequest = RemotingCommand.createRequestCommand(JobProtos.RequestCode.PUSH_JOB.code(), body);
// 是否分发推送任务成功
final Holder<Boolean> pushSuccess = new Holder<Boolean>(false);
final CountDownLatch latch = new CountDownLatch(1);
try {
remotingServer.invokeAsync(taskTrackerNode.getChannel().getChannel(), commandRequest, new AsyncCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
try {
RemotingCommand responseCommand = responseFuture.getResponseCommand();
if (responseCommand == null) {
LOGGER.warn("Job push failed! response command is null!"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (responseCommand.getCode() == JobProtos.ResponseCode.JOB_PUSH_SUCCESS.code()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Job push success! nodeGroup=" + nodeGroup + ", identity=" + identity + ", jobList=" + JSON.toJSONString(jobPos)); // depends on control dependency: [if], data = [none]
}
pushSuccess.set(true); // depends on control dependency: [if], data = [none]
stat.incPushJobNum(jobPos.size()); // depends on control dependency: [if], data = [none]
} else if (responseCommand.getCode() == JobProtos.ResponseCode.NO_AVAILABLE_JOB_RUNNER.code()) {
JobPushResponse jobPushResponse = responseCommand.getBody();
if (jobPushResponse != null && CollectionUtils.isNotEmpty(jobPushResponse.getFailedJobIds())) {
// 修复任务
for (String jobId : jobPushResponse.getFailedJobIds()) {
for (JobPo jobPo : jobPos) {
if (jobId.equals(jobPo.getJobId())) {
resumeJob(jobPo); // depends on control dependency: [if], data = [none]
break;
}
}
}
stat.incPushJobNum(jobPos.size() - jobPushResponse.getFailedJobIds().size()); // depends on control dependency: [if], data = [none]
} else {
stat.incPushJobNum(jobPos.size()); // depends on control dependency: [if], data = [none]
}
pushSuccess.set(true); // depends on control dependency: [if], data = [none]
}
} finally {
latch.countDown();
}
}
}); // depends on control dependency: [try], data = [none]
} catch (RemotingSendException e) {
LOGGER.error("Remoting send error, jobPos={}", JSON.toJSONObject(jobPos), e);
return new JobSender.SendResult(false, JobPushResult.SENT_ERROR);
} // depends on control dependency: [catch], data = [none]
try {
latch.await(Constants.LATCH_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
throw new RequestTimeoutException(e);
} // depends on control dependency: [catch], data = [none]
if (!pushSuccess.get()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Job push failed! nodeGroup=" + nodeGroup + ", identity=" + identity + ", jobs=" + JSON.toJSONObject(jobPos)); // depends on control dependency: [if], data = [none]
}
for (JobPo jobPo : jobPos) {
resumeJob(jobPo); // depends on control dependency: [for], data = [jobPo]
}
return new JobSender.SendResult(false, JobPushResult.SENT_ERROR); // depends on control dependency: [if], data = [none]
}
return new JobSender.SendResult(true, JobPushResult.SUCCESS);
}
});
return (JobPushResult) sendResult.getReturnValue();
} } |
public class class_name {
protected InferredPrototype createPrototype(QualifiedActionName id,
boolean isVarargs, FormalParameterProvider parameters) {
assert parameters != null;
final ActionParameterTypes key = new ActionParameterTypes(isVarargs, parameters.getFormalParameterCount());
final Map<ActionParameterTypes, List<InferredStandardParameter>> ip = buildSignaturesForArgDefaultValues(
id.getDeclaringType(),
key.toActionPrototype(id.getActionName()).toActionId(),
parameters, key);
final List<InferredStandardParameter> op = ip.remove(key);
final InferredPrototype proto = new DefaultInferredPrototype(
id,
parameters,
key,
op,
ip);
final String containerID = id.getContainerID();
Map<String, Map<ActionParameterTypes, InferredPrototype>> c = this.prototypes.get(containerID);
if (c == null) {
c = new TreeMap<>();
this.prototypes.put(containerID, c);
}
Map<ActionParameterTypes, InferredPrototype> list = c.get(id.getActionName());
if (list == null) {
list = new TreeMap<>();
c.put(id.getActionName(), list);
}
list.put(key, proto);
return proto;
} } | public class class_name {
protected InferredPrototype createPrototype(QualifiedActionName id,
boolean isVarargs, FormalParameterProvider parameters) {
assert parameters != null;
final ActionParameterTypes key = new ActionParameterTypes(isVarargs, parameters.getFormalParameterCount());
final Map<ActionParameterTypes, List<InferredStandardParameter>> ip = buildSignaturesForArgDefaultValues(
id.getDeclaringType(),
key.toActionPrototype(id.getActionName()).toActionId(),
parameters, key);
final List<InferredStandardParameter> op = ip.remove(key);
final InferredPrototype proto = new DefaultInferredPrototype(
id,
parameters,
key,
op,
ip);
final String containerID = id.getContainerID();
Map<String, Map<ActionParameterTypes, InferredPrototype>> c = this.prototypes.get(containerID);
if (c == null) {
c = new TreeMap<>(); // depends on control dependency: [if], data = [none]
this.prototypes.put(containerID, c); // depends on control dependency: [if], data = [(c]
}
Map<ActionParameterTypes, InferredPrototype> list = c.get(id.getActionName());
if (list == null) {
list = new TreeMap<>(); // depends on control dependency: [if], data = [none]
c.put(id.getActionName(), list); // depends on control dependency: [if], data = [none]
}
list.put(key, proto);
return proto;
} } |
public class class_name {
public java.util.List<TapeRecoveryPointInfo> getTapeRecoveryPointInfos() {
if (tapeRecoveryPointInfos == null) {
tapeRecoveryPointInfos = new com.amazonaws.internal.SdkInternalList<TapeRecoveryPointInfo>();
}
return tapeRecoveryPointInfos;
} } | public class class_name {
public java.util.List<TapeRecoveryPointInfo> getTapeRecoveryPointInfos() {
if (tapeRecoveryPointInfos == null) {
tapeRecoveryPointInfos = new com.amazonaws.internal.SdkInternalList<TapeRecoveryPointInfo>(); // depends on control dependency: [if], data = [none]
}
return tapeRecoveryPointInfos;
} } |
public class class_name {
private double eatReal() throws ParseException {
StringBuilder b = new StringBuilder();
for (; ; ) {
char t = peek();
if (Character.isDigit(t) || (t == 'e') || (t == 'E')
|| (t == '.') || (t == '-') || (t == '+')) {
b.append(getChar());
} else {
break;
}
}
try {
return Double.parseDouble(b.toString());
} catch (NumberFormatException e1) {
throw new ParseException("bad number" + e1, position);
}
} } | public class class_name {
private double eatReal() throws ParseException {
StringBuilder b = new StringBuilder();
for (; ; ) {
char t = peek();
if (Character.isDigit(t) || (t == 'e') || (t == 'E')
|| (t == '.') || (t == '-') || (t == '+')) {
b.append(getChar());
// depends on control dependency: [if], data = [none]
} else {
break;
}
}
try {
return Double.parseDouble(b.toString());
} catch (NumberFormatException e1) {
throw new ParseException("bad number" + e1, position);
}
} } |
public class class_name {
public void run(List<Variant> variantList) {
for (int i = 0; i < variantList.size(); i++) {
List<PopulationFrequency> populationFrequencies = getPopulationFrequencies(variantList.get(i));
// Update only if there are annotations for this variant. customAnnotation may be empty if the variant
// exists in the vcf but the info field does not contain any of the required attributes
if (populationFrequencies != null && populationFrequencies.size() > 0) {
VariantAnnotation variantAnnotation = variantList.get(i).getAnnotation();
if (variantAnnotation != null) {
// variantList and variantAnnotationList must contain variants in the SAME order: variantAnnotation
// at position i must correspond to variant i
variantAnnotation.setPopulationFrequencies(populationFrequencies);
}
}
}
} } | public class class_name {
public void run(List<Variant> variantList) {
for (int i = 0; i < variantList.size(); i++) {
List<PopulationFrequency> populationFrequencies = getPopulationFrequencies(variantList.get(i));
// Update only if there are annotations for this variant. customAnnotation may be empty if the variant
// exists in the vcf but the info field does not contain any of the required attributes
if (populationFrequencies != null && populationFrequencies.size() > 0) {
VariantAnnotation variantAnnotation = variantList.get(i).getAnnotation();
if (variantAnnotation != null) {
// variantList and variantAnnotationList must contain variants in the SAME order: variantAnnotation
// at position i must correspond to variant i
variantAnnotation.setPopulationFrequencies(populationFrequencies); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public static final String getDurationUnits(final String duration) {
if (duration == null || duration.isEmpty()) {
throw new IllegalArgumentException("Duration cannot be null or empty");
}
int unit = 0;
while (unit < duration.length() &&
Character.isDigit(duration.charAt(unit))) {
unit++;
}
final String units = duration.substring(unit).toLowerCase();
if (units.equals("ms") || units.equals("s") || units.equals("m") ||
units.equals("h") || units.equals("d") || units.equals("w") ||
units.equals("n") || units.equals("y")) {
return units;
}
throw new IllegalArgumentException("Invalid units in the duration: " + units);
} } | public class class_name {
public static final String getDurationUnits(final String duration) {
if (duration == null || duration.isEmpty()) {
throw new IllegalArgumentException("Duration cannot be null or empty");
}
int unit = 0;
while (unit < duration.length() &&
Character.isDigit(duration.charAt(unit))) {
unit++; // depends on control dependency: [while], data = [none]
}
final String units = duration.substring(unit).toLowerCase();
if (units.equals("ms") || units.equals("s") || units.equals("m") ||
units.equals("h") || units.equals("d") || units.equals("w") ||
units.equals("n") || units.equals("y")) {
return units; // depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException("Invalid units in the duration: " + units);
} } |
public class class_name {
public static boolean isDataClass(final Class<?> clazz) {
if (clazz == null || clazz.isPrimitive()) {
return true;
}
boolean isWrapperClass = contains(WRAPPER_CLASSES, clazz);
if (isWrapperClass) {
return true;
}
boolean isDataClass = contains(DATA_PRIMITIVE_CLASS, clazz);
if (isDataClass) {
return true;
}
return false;
} } | public class class_name {
public static boolean isDataClass(final Class<?> clazz) {
if (clazz == null || clazz.isPrimitive()) {
return true; // depends on control dependency: [if], data = [none]
}
boolean isWrapperClass = contains(WRAPPER_CLASSES, clazz);
if (isWrapperClass) {
return true; // depends on control dependency: [if], data = [none]
}
boolean isDataClass = contains(DATA_PRIMITIVE_CLASS, clazz);
if (isDataClass) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public static String toBundleName(String bundleBaseName, Locale locale) {
String baseName = bundleBaseName;
if (!isPluginResoucePath(bundleBaseName)) {
baseName = bundleBaseName.replace('.', '/');
}
if (locale == null) {
return baseName;
}
String language = locale.getLanguage();
String country = locale.getCountry();
String variant = locale.getVariant();
if (language == "" && country == "" && variant == "") {
return baseName;
}
StringBuffer sb = new StringBuffer(baseName);
sb.append('_');
if (variant != "") {
sb.append(language).append('_').append(country).append('_')
.append(variant);
} else if (country != "") {
sb.append(language).append('_').append(country);
} else {
sb.append(language);
}
return sb.toString();
} } | public class class_name {
public static String toBundleName(String bundleBaseName, Locale locale) {
String baseName = bundleBaseName;
if (!isPluginResoucePath(bundleBaseName)) {
baseName = bundleBaseName.replace('.', '/'); // depends on control dependency: [if], data = [none]
}
if (locale == null) {
return baseName; // depends on control dependency: [if], data = [none]
}
String language = locale.getLanguage();
String country = locale.getCountry();
String variant = locale.getVariant();
if (language == "" && country == "" && variant == "") {
return baseName; // depends on control dependency: [if], data = [none]
}
StringBuffer sb = new StringBuffer(baseName);
sb.append('_');
if (variant != "") {
sb.append(language).append('_').append(country).append('_')
.append(variant); // depends on control dependency: [if], data = [none]
} else if (country != "") {
sb.append(language).append('_').append(country); // depends on control dependency: [if], data = [(country]
} else {
sb.append(language); // depends on control dependency: [if], data = [none]
}
return sb.toString();
} } |
public class class_name {
@SuppressWarnings("unchecked")
void onItemClick(ItemClickEvent event) {
if (!event.isCtrlKey() && !event.isShiftKey()) {
// don't interfere with multi-selection using control key
if (event.getButton().equals(MouseButton.RIGHT) || (event.getPropertyId() == null)) {
CmsUUID itemId = (CmsUUID)event.getItemId();
Set<CmsUUID> value = (Set<CmsUUID>)getValue();
if (value == null) {
select(itemId);
} else if (!value.contains(itemId)) {
setValue(null);
select(itemId);
}
m_menu.setEntries(getMenuEntries(), (Set<CmsUUID>)getValue());
m_menu.openForTable(event, this);
} else if (event.getButton().equals(MouseButton.LEFT) && PROP_NAME.equals(event.getPropertyId())) {
Item item = event.getItem();
CmsUUID id = (CmsUUID)item.getItemProperty(PROP_ID).getValue();
m_manager.openSubView(
A_CmsWorkplaceApp.addParamToState(CmsProjectManager.PATH_NAME_FILES, "projectId", id.toString()),
true);
}
}
} } | public class class_name {
@SuppressWarnings("unchecked")
void onItemClick(ItemClickEvent event) {
if (!event.isCtrlKey() && !event.isShiftKey()) {
// don't interfere with multi-selection using control key
if (event.getButton().equals(MouseButton.RIGHT) || (event.getPropertyId() == null)) {
CmsUUID itemId = (CmsUUID)event.getItemId();
Set<CmsUUID> value = (Set<CmsUUID>)getValue();
if (value == null) {
select(itemId); // depends on control dependency: [if], data = [none]
} else if (!value.contains(itemId)) {
setValue(null); // depends on control dependency: [if], data = [none]
select(itemId); // depends on control dependency: [if], data = [none]
}
m_menu.setEntries(getMenuEntries(), (Set<CmsUUID>)getValue()); // depends on control dependency: [if], data = [none]
m_menu.openForTable(event, this); // depends on control dependency: [if], data = [none]
} else if (event.getButton().equals(MouseButton.LEFT) && PROP_NAME.equals(event.getPropertyId())) {
Item item = event.getItem();
CmsUUID id = (CmsUUID)item.getItemProperty(PROP_ID).getValue();
m_manager.openSubView(
A_CmsWorkplaceApp.addParamToState(CmsProjectManager.PATH_NAME_FILES, "projectId", id.toString()),
true); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public List<JAXBElement<Object>> get_GenericApplicationPropertyOfTextureParameterization() {
if (_GenericApplicationPropertyOfTextureParameterization == null) {
_GenericApplicationPropertyOfTextureParameterization = new ArrayList<JAXBElement<Object>>();
}
return this._GenericApplicationPropertyOfTextureParameterization;
} } | public class class_name {
public List<JAXBElement<Object>> get_GenericApplicationPropertyOfTextureParameterization() {
if (_GenericApplicationPropertyOfTextureParameterization == null) {
_GenericApplicationPropertyOfTextureParameterization = new ArrayList<JAXBElement<Object>>(); // depends on control dependency: [if], data = [none]
}
return this._GenericApplicationPropertyOfTextureParameterization;
} } |
public class class_name {
protected ArrayList<SameLengthMotifs> refinePatternsByClustering(GrammarRules grammarRules,
double[] ts, ArrayList<SameLengthMotifs> allClassifiedMotifs, double fractionTopDist) {
DistanceComputation dc = new DistanceComputation();
double[] origTS = ts;
ArrayList<SameLengthMotifs> newAllClassifiedMotifs = new ArrayList<SameLengthMotifs>();
for (SameLengthMotifs sameLenMotifs : allClassifiedMotifs) {
ArrayList<RuleInterval> arrPos = new ArrayList<RuleInterval>();
ArrayList<SAXMotif> subsequences = sameLenMotifs.getSameLenMotifs();
for (SAXMotif ss : subsequences) {
arrPos.add(ss.getPos());
}
int patternNum = arrPos.size();
if (patternNum < 2) {
continue;
}
double dt[][] = new double[patternNum][patternNum];
// Build distance matrix.
for (int i = 0; i < patternNum; i++) {
RuleInterval saxPos = arrPos.get(i);
int start1 = saxPos.getStart();
int end1 = saxPos.getEnd();
double[] ts1 = Arrays.copyOfRange(origTS, start1, end1);
for (int j = 0; j < arrPos.size(); j++) {
RuleInterval saxPos2 = arrPos.get(j);
if (dt[i][j] > 0) {
continue;
}
double d = 0;
dt[i][j] = d;
if (i == j) {
continue;
}
int start2 = saxPos2.getStart();
int end2 = saxPos2.getEnd();
double[] ts2 = Arrays.copyOfRange(origTS, start2, end2);
if (ts1.length > ts2.length)
d = dc.calcDistTSAndPattern(ts1, ts2);
else
d = dc.calcDistTSAndPattern(ts2, ts1);
// DTW dtw = new DTW(ts1, ts2);
// d = dtw.warpingDistance;
dt[i][j] = d;
}
}
String[] patternsName = new String[patternNum];
for (int i = 0; i < patternNum; i++) {
patternsName[i] = String.valueOf(i);
}
ClusteringAlgorithm alg = new DefaultClusteringAlgorithm();
Cluster cluster = alg.performClustering(dt, patternsName, new AverageLinkageStrategy());
// int minPatternPerCls = (int) (0.3 * patternNum);
// minPatternPerCls = minPatternPerCls > 0 ? minPatternPerCls : 1;
int minPatternPerCls = 1;
if (cluster.getDistance() == null) {
// System.out.print(false);
continue;
}
// TODO: refine hard coded threshold
// double cutDist = cluster.getDistance() * 0.67;
double cutDist = cluster.getDistanceValue() * fractionTopDist;
ArrayList<String[]> clusterTSIdx = findCluster(cluster, cutDist, minPatternPerCls);
while (clusterTSIdx.size() <= 0) {
cutDist += cutDist / 2;
clusterTSIdx = findCluster(cluster, cutDist, minPatternPerCls);
}
newAllClassifiedMotifs.addAll(SeparateMotifsByClustering(clusterTSIdx, sameLenMotifs));
}
return newAllClassifiedMotifs;
} } | public class class_name {
protected ArrayList<SameLengthMotifs> refinePatternsByClustering(GrammarRules grammarRules,
double[] ts, ArrayList<SameLengthMotifs> allClassifiedMotifs, double fractionTopDist) {
DistanceComputation dc = new DistanceComputation();
double[] origTS = ts;
ArrayList<SameLengthMotifs> newAllClassifiedMotifs = new ArrayList<SameLengthMotifs>();
for (SameLengthMotifs sameLenMotifs : allClassifiedMotifs) {
ArrayList<RuleInterval> arrPos = new ArrayList<RuleInterval>();
ArrayList<SAXMotif> subsequences = sameLenMotifs.getSameLenMotifs();
for (SAXMotif ss : subsequences) {
arrPos.add(ss.getPos());
// depends on control dependency: [for], data = [ss]
}
int patternNum = arrPos.size();
if (patternNum < 2) {
continue;
}
double dt[][] = new double[patternNum][patternNum];
// Build distance matrix.
for (int i = 0; i < patternNum; i++) {
RuleInterval saxPos = arrPos.get(i);
int start1 = saxPos.getStart();
int end1 = saxPos.getEnd();
double[] ts1 = Arrays.copyOfRange(origTS, start1, end1);
for (int j = 0; j < arrPos.size(); j++) {
RuleInterval saxPos2 = arrPos.get(j);
if (dt[i][j] > 0) {
continue;
}
double d = 0;
dt[i][j] = d;
// depends on control dependency: [for], data = [j]
if (i == j) {
continue;
}
int start2 = saxPos2.getStart();
int end2 = saxPos2.getEnd();
double[] ts2 = Arrays.copyOfRange(origTS, start2, end2);
if (ts1.length > ts2.length)
d = dc.calcDistTSAndPattern(ts1, ts2);
else
d = dc.calcDistTSAndPattern(ts2, ts1);
// DTW dtw = new DTW(ts1, ts2);
// d = dtw.warpingDistance;
dt[i][j] = d;
// depends on control dependency: [for], data = [j]
}
}
String[] patternsName = new String[patternNum];
for (int i = 0; i < patternNum; i++) {
patternsName[i] = String.valueOf(i);
// depends on control dependency: [for], data = [i]
}
ClusteringAlgorithm alg = new DefaultClusteringAlgorithm();
Cluster cluster = alg.performClustering(dt, patternsName, new AverageLinkageStrategy());
// int minPatternPerCls = (int) (0.3 * patternNum);
// minPatternPerCls = minPatternPerCls > 0 ? minPatternPerCls : 1;
int minPatternPerCls = 1;
if (cluster.getDistance() == null) {
// System.out.print(false);
continue;
}
// TODO: refine hard coded threshold
// double cutDist = cluster.getDistance() * 0.67;
double cutDist = cluster.getDistanceValue() * fractionTopDist;
ArrayList<String[]> clusterTSIdx = findCluster(cluster, cutDist, minPatternPerCls);
while (clusterTSIdx.size() <= 0) {
cutDist += cutDist / 2;
// depends on control dependency: [while], data = [none]
clusterTSIdx = findCluster(cluster, cutDist, minPatternPerCls);
// depends on control dependency: [while], data = [none]
}
newAllClassifiedMotifs.addAll(SeparateMotifsByClustering(clusterTSIdx, sameLenMotifs));
// depends on control dependency: [for], data = [sameLenMotifs]
}
return newAllClassifiedMotifs;
} } |
public class class_name {
protected Map<String, ClassNode> getPropertiesToEnsureConstraintsFor(final ClassNode classNode) {
final Map<String, ClassNode> fieldsToConstrain = new HashMap<String, ClassNode>();
final List<FieldNode> allFields = classNode.getFields();
for (final FieldNode field : allFields) {
if (!field.isStatic()) {
final PropertyNode property = classNode.getProperty(field.getName());
if(property != null) {
fieldsToConstrain.put(field.getName(), field.getType());
}
}
}
final Map<String, MethodNode> declaredMethodsMap = classNode.getDeclaredMethodsMap();
for (Entry<String, MethodNode> methodEntry : declaredMethodsMap.entrySet()) {
final MethodNode value = methodEntry.getValue();
if (!value.isStatic() && value.isPublic() && classNode.equals(value.getDeclaringClass()) && value.getLineNumber() > 0) {
Parameter[] parameters = value.getParameters();
if (parameters == null || parameters.length == 0) {
final String methodName = value.getName();
if (methodName.startsWith("get")) {
final ClassNode returnType = value.getReturnType();
final String restOfMethodName = methodName.substring(3);
final String propertyName = GrailsNameUtils.getPropertyName(restOfMethodName);
fieldsToConstrain.put(propertyName, returnType);
}
}
}
}
final ClassNode superClass = classNode.getSuperClass();
if (!superClass.equals(new ClassNode(Object.class))) {
fieldsToConstrain.putAll(getPropertiesToEnsureConstraintsFor(superClass));
}
return fieldsToConstrain;
} } | public class class_name {
protected Map<String, ClassNode> getPropertiesToEnsureConstraintsFor(final ClassNode classNode) {
final Map<String, ClassNode> fieldsToConstrain = new HashMap<String, ClassNode>();
final List<FieldNode> allFields = classNode.getFields();
for (final FieldNode field : allFields) {
if (!field.isStatic()) {
final PropertyNode property = classNode.getProperty(field.getName());
if(property != null) {
fieldsToConstrain.put(field.getName(), field.getType()); // depends on control dependency: [if], data = [none]
}
}
}
final Map<String, MethodNode> declaredMethodsMap = classNode.getDeclaredMethodsMap();
for (Entry<String, MethodNode> methodEntry : declaredMethodsMap.entrySet()) {
final MethodNode value = methodEntry.getValue();
if (!value.isStatic() && value.isPublic() && classNode.equals(value.getDeclaringClass()) && value.getLineNumber() > 0) {
Parameter[] parameters = value.getParameters();
if (parameters == null || parameters.length == 0) {
final String methodName = value.getName();
if (methodName.startsWith("get")) {
final ClassNode returnType = value.getReturnType();
final String restOfMethodName = methodName.substring(3);
final String propertyName = GrailsNameUtils.getPropertyName(restOfMethodName);
fieldsToConstrain.put(propertyName, returnType); // depends on control dependency: [if], data = [none]
}
}
}
}
final ClassNode superClass = classNode.getSuperClass();
if (!superClass.equals(new ClassNode(Object.class))) {
fieldsToConstrain.putAll(getPropertiesToEnsureConstraintsFor(superClass)); // depends on control dependency: [if], data = [none]
}
return fieldsToConstrain;
} } |
public class class_name {
public boolean add(String s) {
SortedSet<String> sub = headSet(s);
if (!sub.isEmpty() && s.startsWith((String)sub.last())) {
// no need to add; prefix is already present
return false;
}
boolean retVal = super.add(s);
sub = tailSet(s+"\0");
while(!sub.isEmpty() && ((String)sub.first()).startsWith(s)) {
// remove redundant entries
sub.remove(sub.first());
}
return retVal;
} } | public class class_name {
public boolean add(String s) {
SortedSet<String> sub = headSet(s);
if (!sub.isEmpty() && s.startsWith((String)sub.last())) {
// no need to add; prefix is already present
return false;
// depends on control dependency: [if], data = [none]
}
boolean retVal = super.add(s);
sub = tailSet(s+"\0");
while(!sub.isEmpty() && ((String)sub.first()).startsWith(s)) {
// remove redundant entries
sub.remove(sub.first());
// depends on control dependency: [while], data = [none]
}
return retVal;
} } |
public class class_name {
public String getUserCreatedName(CmsObject cms) {
try {
return CmsPrincipal.readPrincipalIncludingHistory(cms, getUserCreated()).getName();
} catch (CmsException e) {
return getUserCreated().toString();
}
} } | public class class_name {
public String getUserCreatedName(CmsObject cms) {
try {
return CmsPrincipal.readPrincipalIncludingHistory(cms, getUserCreated()).getName(); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
return getUserCreated().toString();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public DataResponse<List<Feature>> getRelevantStories(ObjectId componentId, String teamId, String projectId,
Optional<String> agileType) {
Component component = componentRepository.findOne(componentId);
if ((component == null) || CollectionUtils.isEmpty(component.getCollectorItems())
|| CollectionUtils
.isEmpty(component.getCollectorItems().get(CollectorType.AgileTool))
|| (component.getCollectorItems().get(CollectorType.AgileTool).get(0) == null)) {
return getEmptyLegacyDataResponse();
}
CollectorItem item = component.getCollectorItems().get(CollectorType.AgileTool).get(0);
QScopeOwner team = new QScopeOwner("team");
BooleanBuilder builder = new BooleanBuilder();
builder.and(team.collectorItemId.eq(item.getId()));
// Get teamId first from available collector item, based on component
List<Feature> relevantStories = getFeaturesForCurrentSprints(teamId, projectId, item.getCollectorId(), agileType.isPresent()? agileType.get() : null, false);
Collector collector = collectorRepository.findOne(item.getCollectorId());
return new DataResponse<>(relevantStories, collector.getLastExecuted());
} } | public class class_name {
@Override
public DataResponse<List<Feature>> getRelevantStories(ObjectId componentId, String teamId, String projectId,
Optional<String> agileType) {
Component component = componentRepository.findOne(componentId);
if ((component == null) || CollectionUtils.isEmpty(component.getCollectorItems())
|| CollectionUtils
.isEmpty(component.getCollectorItems().get(CollectorType.AgileTool))
|| (component.getCollectorItems().get(CollectorType.AgileTool).get(0) == null)) {
return getEmptyLegacyDataResponse(); // depends on control dependency: [if], data = [none]
}
CollectorItem item = component.getCollectorItems().get(CollectorType.AgileTool).get(0);
QScopeOwner team = new QScopeOwner("team");
BooleanBuilder builder = new BooleanBuilder();
builder.and(team.collectorItemId.eq(item.getId()));
// Get teamId first from available collector item, based on component
List<Feature> relevantStories = getFeaturesForCurrentSprints(teamId, projectId, item.getCollectorId(), agileType.isPresent()? agileType.get() : null, false);
Collector collector = collectorRepository.findOne(item.getCollectorId());
return new DataResponse<>(relevantStories, collector.getLastExecuted());
} } |
public class class_name {
@Implementation
protected static boolean checkBluetoothAddress(String address) {
if (address == null || address.length() != ADDRESS_LENGTH) {
return false;
}
for (int i = 0; i < ADDRESS_LENGTH; i++) {
char c = address.charAt(i);
switch (i % 3) {
case 0:
case 1:
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
// hex character, OK
break;
}
return false;
case 2:
if (c == ':') {
break; // OK
}
return false;
}
}
return true;
} } | public class class_name {
@Implementation
protected static boolean checkBluetoothAddress(String address) {
if (address == null || address.length() != ADDRESS_LENGTH) {
return false; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < ADDRESS_LENGTH; i++) {
char c = address.charAt(i);
switch (i % 3) { // depends on control dependency: [for], data = [i]
case 0:
case 1:
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
// hex character, OK
break;
}
return false;
case 2:
if (c == ':') {
break; // OK
}
return false;
}
}
return true;
} } |
public class class_name {
public static int klu_defaults(KLU_common Common)
{
if (Common == null)
{
return (FALSE) ;
}
/* parameters */
Common.tol = 0.001 ; /* pivot tolerance for diagonal */
Common.memgrow = 1.2 ; /* realloc size ratio increase for LU factors */
Common.initmem_amd = 1.2 ; /* init. mem with AMD: c*nnz(L) + n */
Common.initmem = 10 ; /* init. mem otherwise: c*nnz(A) + n */
Common.btf = TRUE ; /* use BTF pre-ordering, or not */
Common.maxwork = 0 ; /* no limit to work done by btf_order */
Common.ordering = 0 ; /* 0: AMD, 1: COLAMD, 2: user-provided P and Q,
* 3: user-provided function */
Common.scale = 2 ; /* scale: -1: none, and do not check for errors
* in the input matrix in KLU_refactor.
* 0: none, but check for errors,
* 1: sum, 2: max */
Common.halt_if_singular = TRUE ; /* quick halt if matrix is singular */
/* memory management routines */
//Common.malloc_memory = malloc ;
//Common.calloc_memory = calloc ;
//Common.free_memory = free ;
//Common.realloc_memory = realloc ;
/* user ordering function and optional argument */
Common.user_order = null ;
Common.user_data = null ;
/* statistics */
Common.status = KLU_OK ;
Common.nrealloc = 0 ;
Common.structural_rank = EMPTY ;
Common.numerical_rank = EMPTY ;
Common.noffdiag = EMPTY ;
Common.flops = EMPTY ;
Common.rcond = EMPTY ;
Common.condest = EMPTY ;
Common.rgrowth = EMPTY ;
Common.work = 0 ; /* work done by btf_order */
Common.memusage = 0 ;
Common.mempeak = 0 ;
return (TRUE) ;
} } | public class class_name {
public static int klu_defaults(KLU_common Common)
{
if (Common == null)
{
return (FALSE) ; // depends on control dependency: [if], data = [none]
}
/* parameters */
Common.tol = 0.001 ; /* pivot tolerance for diagonal */
Common.memgrow = 1.2 ; /* realloc size ratio increase for LU factors */
Common.initmem_amd = 1.2 ; /* init. mem with AMD: c*nnz(L) + n */
Common.initmem = 10 ; /* init. mem otherwise: c*nnz(A) + n */
Common.btf = TRUE ; /* use BTF pre-ordering, or not */
Common.maxwork = 0 ; /* no limit to work done by btf_order */
Common.ordering = 0 ; /* 0: AMD, 1: COLAMD, 2: user-provided P and Q,
* 3: user-provided function */
Common.scale = 2 ; /* scale: -1: none, and do not check for errors
* in the input matrix in KLU_refactor.
* 0: none, but check for errors,
* 1: sum, 2: max */
Common.halt_if_singular = TRUE ; /* quick halt if matrix is singular */
/* memory management routines */
//Common.malloc_memory = malloc ;
//Common.calloc_memory = calloc ;
//Common.free_memory = free ;
//Common.realloc_memory = realloc ;
/* user ordering function and optional argument */
Common.user_order = null ;
Common.user_data = null ;
/* statistics */
Common.status = KLU_OK ;
Common.nrealloc = 0 ;
Common.structural_rank = EMPTY ;
Common.numerical_rank = EMPTY ;
Common.noffdiag = EMPTY ;
Common.flops = EMPTY ;
Common.rcond = EMPTY ;
Common.condest = EMPTY ;
Common.rgrowth = EMPTY ;
Common.work = 0 ; /* work done by btf_order */
Common.memusage = 0 ;
Common.mempeak = 0 ;
return (TRUE) ;
} } |
public class class_name {
private void doDeployNetwork(final String name, final Message<JsonObject> message) {
// When deploying a bare network, we first attempt to load any existing
// configuration from the cluster. This ensures that we don't overwrite
// a cluster configuration. In some cases, the manager can be redeployed
// by deploying a network name.
String scontext = data.<String, String>getMap(String.format("%s.%s", cluster, name)).get(String.format("%s.%s", cluster, name));
final NetworkContext context = scontext != null ? Contexts.<NetworkContext>deserialize(new JsonObject(scontext)) : ContextBuilder.buildContext(new DefaultNetworkConfig(name), cluster);
// Simply deploy an empty network.
if (!managers.containsKey(context.address())) {
// If the network manager hasn't yet been deployed then deploy the manager
// and then update the network's configuration.
platform.deployVerticle(NetworkManager.class.getName(), new JsonObject().putString("cluster", cluster).putString("address", context.address()), 1, new Handler<AsyncResult<String>>() {
@Override
public void handle(AsyncResult<String> result) {
if (result.failed()) {
message.reply(new JsonObject().putString("status", "error").putString("message", "Failed to deploy network manager."));
} else {
// Once the manager has been deployed we can add the network name to
// the set of networks that are deployed in the cluster.
final String deploymentID = result.result();
DefaultNodeManager.this.context.execute(new Action<Void>() {
@Override
public Void perform() {
networks.add(context.name());
return null;
}
}, new Handler<AsyncResult<Void>>() {
@Override
public void handle(AsyncResult<Void> result) {
// And store the manager's deployment ID in the local managers map.
managers.put(context.address(), deploymentID);
doDeployNetwork(context, message);
}
});
}
}
});
} else {
message.reply(new JsonObject().putString("status", "ok").putObject("context", Contexts.serialize(context)));
}
} } | public class class_name {
private void doDeployNetwork(final String name, final Message<JsonObject> message) {
// When deploying a bare network, we first attempt to load any existing
// configuration from the cluster. This ensures that we don't overwrite
// a cluster configuration. In some cases, the manager can be redeployed
// by deploying a network name.
String scontext = data.<String, String>getMap(String.format("%s.%s", cluster, name)).get(String.format("%s.%s", cluster, name));
final NetworkContext context = scontext != null ? Contexts.<NetworkContext>deserialize(new JsonObject(scontext)) : ContextBuilder.buildContext(new DefaultNetworkConfig(name), cluster);
// Simply deploy an empty network.
if (!managers.containsKey(context.address())) {
// If the network manager hasn't yet been deployed then deploy the manager
// and then update the network's configuration.
platform.deployVerticle(NetworkManager.class.getName(), new JsonObject().putString("cluster", cluster).putString("address", context.address()), 1, new Handler<AsyncResult<String>>() {
@Override
public void handle(AsyncResult<String> result) {
if (result.failed()) {
message.reply(new JsonObject().putString("status", "error").putString("message", "Failed to deploy network manager.")); // depends on control dependency: [if], data = [none]
} else {
// Once the manager has been deployed we can add the network name to
// the set of networks that are deployed in the cluster.
final String deploymentID = result.result();
DefaultNodeManager.this.context.execute(new Action<Void>() {
@Override
public Void perform() {
networks.add(context.name());
return null;
}
}, new Handler<AsyncResult<Void>>() {
@Override
public void handle(AsyncResult<Void> result) {
// And store the manager's deployment ID in the local managers map.
managers.put(context.address(), deploymentID);
doDeployNetwork(context, message);
}
}); // depends on control dependency: [if], data = [none]
}
}
}); // depends on control dependency: [if], data = [none]
} else {
message.reply(new JsonObject().putString("status", "ok").putObject("context", Contexts.serialize(context))); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void killProcessGroup(String pgrpId) {
//If process tree is not alive then return immediately.
if(!ProcessTree.isProcessGroupAlive(pgrpId)) {
return;
}
String[] args = { "kill", "-9", "-"+pgrpId };
ShellCommandExecutor shexec = new ShellCommandExecutor(args);
try {
shexec.execute();
} catch (IOException e) {
LOG.warn("Error sending SIGKILL to process group "+ pgrpId + " ."+
StringUtils.stringifyException(e));
} finally {
LOG.info("Killing process group" + pgrpId + " with SIGKILL. Exit code "
+ shexec.getExitCode());
}
} } | public class class_name {
public static void killProcessGroup(String pgrpId) {
//If process tree is not alive then return immediately.
if(!ProcessTree.isProcessGroupAlive(pgrpId)) {
return; // depends on control dependency: [if], data = [none]
}
String[] args = { "kill", "-9", "-"+pgrpId };
ShellCommandExecutor shexec = new ShellCommandExecutor(args);
try {
shexec.execute(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
LOG.warn("Error sending SIGKILL to process group "+ pgrpId + " ."+
StringUtils.stringifyException(e));
} finally { // depends on control dependency: [catch], data = [none]
LOG.info("Killing process group" + pgrpId + " with SIGKILL. Exit code "
+ shexec.getExitCode());
}
} } |
public class class_name {
public Reader createScript(Charset charset) {
// Determine wether this is run-app or run-war style of runtime.
boolean warDeployed = ((Boolean) this.servletContext
.getAttribute(JawrGrailsConstant.GRAILS_WAR_DEPLOYED))
.booleanValue();
// Spring message bundle object, the same used by grails.
GrailsBundleMessageSource messageSource = new GrailsBundleMessageSource(
warDeployed);
messageSource.setFallbackToSystemLocale(control.isFallbackToSystemLocale());
messageSource.setFilters(filterList);
if (warDeployed) {
messageSource.setResourceLoader(new ServletContextResourceLoader(
this.servletContext));
}
messageSource.setBasenames(getBaseNames(warDeployed));
Properties props = messageSource.getAllMessages(locale);
return doCreateScript(props);
} } | public class class_name {
public Reader createScript(Charset charset) {
// Determine wether this is run-app or run-war style of runtime.
boolean warDeployed = ((Boolean) this.servletContext
.getAttribute(JawrGrailsConstant.GRAILS_WAR_DEPLOYED))
.booleanValue();
// Spring message bundle object, the same used by grails.
GrailsBundleMessageSource messageSource = new GrailsBundleMessageSource(
warDeployed);
messageSource.setFallbackToSystemLocale(control.isFallbackToSystemLocale());
messageSource.setFilters(filterList);
if (warDeployed) {
messageSource.setResourceLoader(new ServletContextResourceLoader(
this.servletContext)); // depends on control dependency: [if], data = [none]
}
messageSource.setBasenames(getBaseNames(warDeployed));
Properties props = messageSource.getAllMessages(locale);
return doCreateScript(props);
} } |
public class class_name {
public void marshall(TimeWindow timeWindow, ProtocolMarshaller protocolMarshaller) {
if (timeWindow == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(timeWindow.getStartTime(), STARTTIME_BINDING);
protocolMarshaller.marshall(timeWindow.getEndTime(), ENDTIME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(TimeWindow timeWindow, ProtocolMarshaller protocolMarshaller) {
if (timeWindow == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(timeWindow.getStartTime(), STARTTIME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(timeWindow.getEndTime(), ENDTIME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static Matrix grayOutCEOrig(Atom[] ca2, int rows, int cols,
CECalculator calculator, Matrix origM, int blankWindowSize,
double[] gradientPolyCoeff, double gradientExpCoeff) {
if (origM == null) {
origM = new Matrix(calculator.getMatMatrix());
}
// symmetry hack, disable main diagonal
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int diff = Math.abs(i - j);
double resetVal = getResetVal(origM.get(i, j), diff,
gradientPolyCoeff, gradientExpCoeff);
if (diff < blankWindowSize) {
origM.set(i, j, origM.get(i, j) + resetVal);
}
int diff2 = Math.abs(i - (j - ca2.length / 2)); // other side
double resetVal2 = getResetVal(origM.get(i, j), diff2,
gradientPolyCoeff, gradientExpCoeff);
if (diff2 < blankWindowSize) {
origM.set(i, j, origM.get(i, j) + resetVal2);
}
}
}
return origM;
} } | public class class_name {
public static Matrix grayOutCEOrig(Atom[] ca2, int rows, int cols,
CECalculator calculator, Matrix origM, int blankWindowSize,
double[] gradientPolyCoeff, double gradientExpCoeff) {
if (origM == null) {
origM = new Matrix(calculator.getMatMatrix()); // depends on control dependency: [if], data = [none]
}
// symmetry hack, disable main diagonal
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int diff = Math.abs(i - j);
double resetVal = getResetVal(origM.get(i, j), diff,
gradientPolyCoeff, gradientExpCoeff);
if (diff < blankWindowSize) {
origM.set(i, j, origM.get(i, j) + resetVal); // depends on control dependency: [if], data = [none]
}
int diff2 = Math.abs(i - (j - ca2.length / 2)); // other side
double resetVal2 = getResetVal(origM.get(i, j), diff2,
gradientPolyCoeff, gradientExpCoeff);
if (diff2 < blankWindowSize) {
origM.set(i, j, origM.get(i, j) + resetVal2); // depends on control dependency: [if], data = [none]
}
}
}
return origM;
} } |
public class class_name {
static boolean isChanged(Collection<RedisNodeDescription> o1, Collection<RedisNodeDescription> o2) {
if (o1.size() != o2.size()) {
return true;
}
for (RedisNodeDescription base : o2) {
if (!essentiallyEqualsTo(base, findNodeByUri(o1, base.getUri()))) {
return true;
}
}
return false;
} } | public class class_name {
static boolean isChanged(Collection<RedisNodeDescription> o1, Collection<RedisNodeDescription> o2) {
if (o1.size() != o2.size()) {
return true; // depends on control dependency: [if], data = [none]
}
for (RedisNodeDescription base : o2) {
if (!essentiallyEqualsTo(base, findNodeByUri(o1, base.getUri()))) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public <T> T get(Class<T> cls) {
T runtimeInstance = (T) runtimeServices.computeIfAbsent(cls, this::createRuntimeInstance);
if (runtimeInstance == null) {
throw new NoSuchElementException(cls.getName());
} else {
return runtimeInstance;
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public <T> T get(Class<T> cls) {
T runtimeInstance = (T) runtimeServices.computeIfAbsent(cls, this::createRuntimeInstance);
if (runtimeInstance == null) {
throw new NoSuchElementException(cls.getName());
} else {
return runtimeInstance; // depends on control dependency: [if], data = [none]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.