code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public void marshall(ServerLaunchConfiguration serverLaunchConfiguration, ProtocolMarshaller protocolMarshaller) {
if (serverLaunchConfiguration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(serverLaunchConfiguration.getServer(), SERVER_BINDING);
protocolMarshaller.marshall(serverLaunchConfiguration.getLogicalId(), LOGICALID_BINDING);
protocolMarshaller.marshall(serverLaunchConfiguration.getVpc(), VPC_BINDING);
protocolMarshaller.marshall(serverLaunchConfiguration.getSubnet(), SUBNET_BINDING);
protocolMarshaller.marshall(serverLaunchConfiguration.getSecurityGroup(), SECURITYGROUP_BINDING);
protocolMarshaller.marshall(serverLaunchConfiguration.getEc2KeyName(), EC2KEYNAME_BINDING);
protocolMarshaller.marshall(serverLaunchConfiguration.getUserData(), USERDATA_BINDING);
protocolMarshaller.marshall(serverLaunchConfiguration.getInstanceType(), INSTANCETYPE_BINDING);
protocolMarshaller.marshall(serverLaunchConfiguration.getAssociatePublicIpAddress(), ASSOCIATEPUBLICIPADDRESS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ServerLaunchConfiguration serverLaunchConfiguration, ProtocolMarshaller protocolMarshaller) {
if (serverLaunchConfiguration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(serverLaunchConfiguration.getServer(), SERVER_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(serverLaunchConfiguration.getLogicalId(), LOGICALID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(serverLaunchConfiguration.getVpc(), VPC_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(serverLaunchConfiguration.getSubnet(), SUBNET_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(serverLaunchConfiguration.getSecurityGroup(), SECURITYGROUP_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(serverLaunchConfiguration.getEc2KeyName(), EC2KEYNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(serverLaunchConfiguration.getUserData(), USERDATA_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(serverLaunchConfiguration.getInstanceType(), INSTANCETYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(serverLaunchConfiguration.getAssociatePublicIpAddress(), ASSOCIATEPUBLICIPADDRESS_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 Observable<ServiceResponse<Void>> addUsersWithServiceResponseAsync(String resourceGroupName, String labAccountName, String labName, List<String> emailAddresses) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (labAccountName == null) {
throw new IllegalArgumentException("Parameter labAccountName is required and cannot be null.");
}
if (labName == null) {
throw new IllegalArgumentException("Parameter labName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
if (emailAddresses == null) {
throw new IllegalArgumentException("Parameter emailAddresses is required and cannot be null.");
}
Validator.validate(emailAddresses);
AddUsersPayload addUsersPayload = new AddUsersPayload();
addUsersPayload.withEmailAddresses(emailAddresses);
return service.addUsers(this.client.subscriptionId(), resourceGroupName, labAccountName, labName, this.client.apiVersion(), this.client.acceptLanguage(), addUsersPayload, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = addUsersDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<Void>> addUsersWithServiceResponseAsync(String resourceGroupName, String labAccountName, String labName, List<String> emailAddresses) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (labAccountName == null) {
throw new IllegalArgumentException("Parameter labAccountName is required and cannot be null.");
}
if (labName == null) {
throw new IllegalArgumentException("Parameter labName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
if (emailAddresses == null) {
throw new IllegalArgumentException("Parameter emailAddresses is required and cannot be null.");
}
Validator.validate(emailAddresses);
AddUsersPayload addUsersPayload = new AddUsersPayload();
addUsersPayload.withEmailAddresses(emailAddresses);
return service.addUsers(this.client.subscriptionId(), resourceGroupName, labAccountName, labName, this.client.apiVersion(), this.client.acceptLanguage(), addUsersPayload, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = addUsersDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public Corpus process(@NonNull Corpus input, @NonNull ProcessorContext context) throws Exception {
Corpus corpus = input;
for (ProcessingModule processor : processors) {
logInfo("Running {0}...", processor.getClass().getSimpleName());
if( processor.getOverrideStatus() ){
corpus = processor.process(corpus, context);
logInfo("\tComplete [Recomputed]");
} else {
ProcessingState temp = processor.loadPreviousState(corpus, context);
if (temp.isLoaded()) {
logInfo("\tComplete [Loaded]");
corpus = temp.getCorpus();
} else {
corpus = processor.process(corpus, context);
logInfo("\tComplete [Computed]");
}
}
}
return corpus;
} } | public class class_name {
public Corpus process(@NonNull Corpus input, @NonNull ProcessorContext context) throws Exception {
Corpus corpus = input;
for (ProcessingModule processor : processors) {
logInfo("Running {0}...", processor.getClass().getSimpleName());
if( processor.getOverrideStatus() ){
corpus = processor.process(corpus, context); // depends on control dependency: [if], data = [none]
logInfo("\tComplete [Recomputed]"); // depends on control dependency: [if], data = [none]
} else {
ProcessingState temp = processor.loadPreviousState(corpus, context);
if (temp.isLoaded()) {
logInfo("\tComplete [Loaded]"); // depends on control dependency: [if], data = [none]
corpus = temp.getCorpus(); // depends on control dependency: [if], data = [none]
} else {
corpus = processor.process(corpus, context); // depends on control dependency: [if], data = [none]
logInfo("\tComplete [Computed]"); // depends on control dependency: [if], data = [none]
}
}
}
return corpus;
} } |
public class class_name {
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGcmPreferences(context);
final String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Logger.d("Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
final int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
final int currentVersion = GcmUtils.getAppVersion(context);
if (registeredVersion != currentVersion) {
Logger.d("App version changed.");
return "";
}
return registrationId;
} } | public class class_name {
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGcmPreferences(context);
final String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Logger.d("Registration not found."); // depends on control dependency: [if], data = [none]
return ""; // depends on control dependency: [if], data = [none]
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
final int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
final int currentVersion = GcmUtils.getAppVersion(context);
if (registeredVersion != currentVersion) {
Logger.d("App version changed."); // depends on control dependency: [if], data = [none]
return ""; // depends on control dependency: [if], data = [none]
}
return registrationId;
} } |
public class class_name {
public Object execute(final Object iThis, final OIdentifiable iCurrentRecord, final Object iCurrentResult,
final OCommandContext iContext) {
// RESOLVE VALUES USING THE CURRENT RECORD
for (int i = 0; i < configuredParameters.length; ++i) {
runtimeParameters[i] = configuredParameters[i];
if (configuredParameters[i] instanceof OSQLFilterItemField) {
runtimeParameters[i] = ((OSQLFilterItemField) configuredParameters[i]).getValue(iCurrentRecord, iCurrentResult, iContext);
} else if (configuredParameters[i] instanceof OSQLFunctionRuntime)
runtimeParameters[i] = ((OSQLFunctionRuntime) configuredParameters[i]).execute(iThis, iCurrentRecord, iCurrentResult,
iContext);
else if (configuredParameters[i] instanceof OSQLFilterItemVariable) {
runtimeParameters[i] = ((OSQLFilterItemVariable) configuredParameters[i])
.getValue(iCurrentRecord, iCurrentResult, iContext);
} else if (configuredParameters[i] instanceof OCommandSQL) {
try {
runtimeParameters[i] = ((OCommandSQL) configuredParameters[i]).setContext(iContext).execute();
} catch (OCommandExecutorNotFoundException ignore) {
// TRY WITH SIMPLE CONDITION
final String text = ((OCommandSQL) configuredParameters[i]).getText();
final OSQLPredicate pred = new OSQLPredicate(text);
runtimeParameters[i] = pred.evaluate(iCurrentRecord instanceof ORecord ? (ORecord) iCurrentRecord : null,
(ODocument) iCurrentResult, iContext);
// REPLACE ORIGINAL PARAM
configuredParameters[i] = pred;
}
} else if (configuredParameters[i] instanceof OSQLPredicate)
runtimeParameters[i] = ((OSQLPredicate) configuredParameters[i]).evaluate(iCurrentRecord.getRecord(),
(iCurrentRecord instanceof ODocument ? (ODocument) iCurrentResult : null), iContext);
else if (configuredParameters[i] instanceof String) {
if (configuredParameters[i].toString().startsWith("\"") || configuredParameters[i].toString().startsWith("'"))
runtimeParameters[i] = OIOUtils.getStringContent(configuredParameters[i]);
}
}
if (function.getMaxParams() == -1 || function.getMaxParams() > 0) {
if (runtimeParameters.length < function.getMinParams()
|| (function.getMaxParams() > -1 && runtimeParameters.length > function.getMaxParams()))
throw new OCommandExecutionException("Syntax error: function '"
+ function.getName()
+ "' needs "
+ (function.getMinParams() == function.getMaxParams() ? function.getMinParams() : function.getMinParams() + "-"
+ function.getMaxParams()) + " argument(s) while has been received " + runtimeParameters.length);
}
final Object functionResult = function.execute(iThis, iCurrentRecord, iCurrentResult, runtimeParameters, iContext);
if (functionResult instanceof OAutoConvertToRecord)
// FORCE AVOIDING TO CONVERT IN RECORD
((OAutoConvertToRecord) functionResult).setAutoConvertToRecord(false);
return transformValue(iCurrentRecord, iContext, functionResult);
} } | public class class_name {
public Object execute(final Object iThis, final OIdentifiable iCurrentRecord, final Object iCurrentResult,
final OCommandContext iContext) {
// RESOLVE VALUES USING THE CURRENT RECORD
for (int i = 0; i < configuredParameters.length; ++i) {
runtimeParameters[i] = configuredParameters[i]; // depends on control dependency: [for], data = [i]
if (configuredParameters[i] instanceof OSQLFilterItemField) {
runtimeParameters[i] = ((OSQLFilterItemField) configuredParameters[i]).getValue(iCurrentRecord, iCurrentResult, iContext); // depends on control dependency: [if], data = [none]
} else if (configuredParameters[i] instanceof OSQLFunctionRuntime)
runtimeParameters[i] = ((OSQLFunctionRuntime) configuredParameters[i]).execute(iThis, iCurrentRecord, iCurrentResult,
iContext);
else if (configuredParameters[i] instanceof OSQLFilterItemVariable) {
runtimeParameters[i] = ((OSQLFilterItemVariable) configuredParameters[i])
.getValue(iCurrentRecord, iCurrentResult, iContext); // depends on control dependency: [if], data = [none]
} else if (configuredParameters[i] instanceof OCommandSQL) {
try {
runtimeParameters[i] = ((OCommandSQL) configuredParameters[i]).setContext(iContext).execute(); // depends on control dependency: [try], data = [none]
} catch (OCommandExecutorNotFoundException ignore) {
// TRY WITH SIMPLE CONDITION
final String text = ((OCommandSQL) configuredParameters[i]).getText();
final OSQLPredicate pred = new OSQLPredicate(text);
runtimeParameters[i] = pred.evaluate(iCurrentRecord instanceof ORecord ? (ORecord) iCurrentRecord : null,
(ODocument) iCurrentResult, iContext);
// REPLACE ORIGINAL PARAM
configuredParameters[i] = pred;
} // depends on control dependency: [catch], data = [none]
} else if (configuredParameters[i] instanceof OSQLPredicate)
runtimeParameters[i] = ((OSQLPredicate) configuredParameters[i]).evaluate(iCurrentRecord.getRecord(),
(iCurrentRecord instanceof ODocument ? (ODocument) iCurrentResult : null), iContext);
else if (configuredParameters[i] instanceof String) {
if (configuredParameters[i].toString().startsWith("\"") || configuredParameters[i].toString().startsWith("'"))
runtimeParameters[i] = OIOUtils.getStringContent(configuredParameters[i]);
}
}
if (function.getMaxParams() == -1 || function.getMaxParams() > 0) {
if (runtimeParameters.length < function.getMinParams()
|| (function.getMaxParams() > -1 && runtimeParameters.length > function.getMaxParams()))
throw new OCommandExecutionException("Syntax error: function '"
+ function.getName()
+ "' needs "
+ (function.getMinParams() == function.getMaxParams() ? function.getMinParams() : function.getMinParams() + "-"
+ function.getMaxParams()) + " argument(s) while has been received " + runtimeParameters.length);
}
final Object functionResult = function.execute(iThis, iCurrentRecord, iCurrentResult, runtimeParameters, iContext);
if (functionResult instanceof OAutoConvertToRecord)
// FORCE AVOIDING TO CONVERT IN RECORD
((OAutoConvertToRecord) functionResult).setAutoConvertToRecord(false);
return transformValue(iCurrentRecord, iContext, functionResult);
} } |
public class class_name {
public void marshall(EntityRecognizerInputDataConfig entityRecognizerInputDataConfig, ProtocolMarshaller protocolMarshaller) {
if (entityRecognizerInputDataConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(entityRecognizerInputDataConfig.getEntityTypes(), ENTITYTYPES_BINDING);
protocolMarshaller.marshall(entityRecognizerInputDataConfig.getDocuments(), DOCUMENTS_BINDING);
protocolMarshaller.marshall(entityRecognizerInputDataConfig.getAnnotations(), ANNOTATIONS_BINDING);
protocolMarshaller.marshall(entityRecognizerInputDataConfig.getEntityList(), ENTITYLIST_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(EntityRecognizerInputDataConfig entityRecognizerInputDataConfig, ProtocolMarshaller protocolMarshaller) {
if (entityRecognizerInputDataConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(entityRecognizerInputDataConfig.getEntityTypes(), ENTITYTYPES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(entityRecognizerInputDataConfig.getDocuments(), DOCUMENTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(entityRecognizerInputDataConfig.getAnnotations(), ANNOTATIONS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(entityRecognizerInputDataConfig.getEntityList(), ENTITYLIST_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 Transaction findByTransactionId(String transactionId) {
EntityManager entityManager = getEntityManager();
try {
return entityManager.createQuery("SELECT t FROM io.motown.operatorapi.viewmodel.persistence.entities.Transaction AS t WHERE t.transactionId = :transactionId", Transaction.class)
.setParameter("transactionId", transactionId)
.getSingleResult();
} finally {
entityManager.close();
}
} } | public class class_name {
public Transaction findByTransactionId(String transactionId) {
EntityManager entityManager = getEntityManager();
try {
return entityManager.createQuery("SELECT t FROM io.motown.operatorapi.viewmodel.persistence.entities.Transaction AS t WHERE t.transactionId = :transactionId", Transaction.class)
.setParameter("transactionId", transactionId)
.getSingleResult(); // depends on control dependency: [try], data = [none]
} finally {
entityManager.close();
}
} } |
public class class_name {
private FutureCallback<ResultSet> wrapCallbackRow(FutureCallback<Row> callback) {
return new FutureCallback<ResultSet>() {
@Override
public void onSuccess(ResultSet result) {
try {
callback.onSuccess(result.one());
} finally {
asyncSemaphore.release();
}
}
@Override
public void onFailure(Throwable t) {
try {
callback.onFailure(t);
} finally {
asyncSemaphore.release();
}
}
};
} } | public class class_name {
private FutureCallback<ResultSet> wrapCallbackRow(FutureCallback<Row> callback) {
return new FutureCallback<ResultSet>() {
@Override
public void onSuccess(ResultSet result) {
try {
callback.onSuccess(result.one()); // depends on control dependency: [try], data = [none]
} finally {
asyncSemaphore.release();
}
}
@Override
public void onFailure(Throwable t) {
try {
callback.onFailure(t); // depends on control dependency: [try], data = [none]
} finally {
asyncSemaphore.release();
}
}
};
} } |
public class class_name {
private static void determineHandlers() {
/*
* find the handlers that we are dispatching to
*/
if (textHandler != null && !logRepositoryConfiguration.isTextEnabled())
textHandler = null ;
// Don't do this work if only text and text is not enabled (if so, it will always be null) 666241.1
if (binaryHandler != null && !logRepositoryConfiguration.isTextEnabled())
return ;
Handler[] handlers = Logger.getLogger("").getHandlers();
for (Handler handler : handlers) {
String name = handler.getClass().getName();
if (BINLOGGER_HANDLER_NAME.equals(name)) {
binaryHandler = (LogRecordHandler) handler;
} else if (TEXTLOGGER_HANDLER_NAME.equals(name)) {
textHandler = (LogRecordTextHandler) handler;
}
}
} } | public class class_name {
private static void determineHandlers() {
/*
* find the handlers that we are dispatching to
*/
if (textHandler != null && !logRepositoryConfiguration.isTextEnabled())
textHandler = null ;
// Don't do this work if only text and text is not enabled (if so, it will always be null) 666241.1
if (binaryHandler != null && !logRepositoryConfiguration.isTextEnabled())
return ;
Handler[] handlers = Logger.getLogger("").getHandlers();
for (Handler handler : handlers) {
String name = handler.getClass().getName();
if (BINLOGGER_HANDLER_NAME.equals(name)) {
binaryHandler = (LogRecordHandler) handler; // depends on control dependency: [if], data = [none]
} else if (TEXTLOGGER_HANDLER_NAME.equals(name)) {
textHandler = (LogRecordTextHandler) handler; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void commit(Object root) {
try {
XChangesBatch xUpdateControl = (XChangesBatch) UnoRuntime
.queryInterface(XChangesBatch.class, root);
xUpdateControl.commitChanges();
} catch (WrappedTargetException e) {
e.printStackTrace();
}
} } | public class class_name {
public void commit(Object root) {
try {
XChangesBatch xUpdateControl = (XChangesBatch) UnoRuntime
.queryInterface(XChangesBatch.class, root);
xUpdateControl.commitChanges(); // depends on control dependency: [try], data = [none]
} catch (WrappedTargetException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(AddCacheRequest addCacheRequest, ProtocolMarshaller protocolMarshaller) {
if (addCacheRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(addCacheRequest.getGatewayARN(), GATEWAYARN_BINDING);
protocolMarshaller.marshall(addCacheRequest.getDiskIds(), DISKIDS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(AddCacheRequest addCacheRequest, ProtocolMarshaller protocolMarshaller) {
if (addCacheRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(addCacheRequest.getGatewayARN(), GATEWAYARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(addCacheRequest.getDiskIds(), DISKIDS_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 String encode(final String input, final CsvContext context, final CsvPreference preference) {
final StringBuilder currentColumn = new StringBuilder();
final int delimiter = preference.getDelimiterChar();
final char quote = (char) preference.getQuoteChar();
final char quoteEscapeChar = (char) preference.getQuoteEscapeChar();
final String eolSymbols = preference.getEndOfLineSymbols();
final int lastCharIndex = input.length() - 1;
boolean quotesRequiredForSpecialChar = false;
boolean skipNewline = false;
for( int i = 0; i <= lastCharIndex; i++ ) {
final char c = input.charAt(i);
if( skipNewline ) {
skipNewline = false;
if( c == '\n' ) {
continue; // newline following a carriage return is skipped
}
}
if( c == delimiter ) {
quotesRequiredForSpecialChar = true;
currentColumn.append(c);
} else if( c == quote ) {
quotesRequiredForSpecialChar = true;
currentColumn.append(quoteEscapeChar);
currentColumn.append(quote);
} else if( c == '\r' ) {
quotesRequiredForSpecialChar = true;
currentColumn.append(eolSymbols);
context.setLineNumber(context.getLineNumber() + 1);
skipNewline = true;
} else if( c == '\n' ) {
quotesRequiredForSpecialChar = true;
currentColumn.append(eolSymbols);
context.setLineNumber(context.getLineNumber() + 1);
} else {
currentColumn.append(c);
}
}
final boolean quotesRequiredForMode = preference.getQuoteMode().quotesRequired(input, context, preference);
final boolean quotesRequiredForSurroundingSpaces = preference.isSurroundingSpacesNeedQuotes()
&& input.length() > 0 && (input.charAt(0) == ' ' || input.charAt(input.length() - 1) == ' ');
if( quotesRequiredForSpecialChar || quotesRequiredForMode || quotesRequiredForSurroundingSpaces ) {
currentColumn.insert(0, quote).append(quote);
}
return currentColumn.toString();
} } | public class class_name {
public String encode(final String input, final CsvContext context, final CsvPreference preference) {
final StringBuilder currentColumn = new StringBuilder();
final int delimiter = preference.getDelimiterChar();
final char quote = (char) preference.getQuoteChar();
final char quoteEscapeChar = (char) preference.getQuoteEscapeChar();
final String eolSymbols = preference.getEndOfLineSymbols();
final int lastCharIndex = input.length() - 1;
boolean quotesRequiredForSpecialChar = false;
boolean skipNewline = false;
for( int i = 0; i <= lastCharIndex; i++ ) {
final char c = input.charAt(i);
if( skipNewline ) {
skipNewline = false; // depends on control dependency: [if], data = [none]
if( c == '\n' ) {
continue; // newline following a carriage return is skipped
}
}
if( c == delimiter ) {
quotesRequiredForSpecialChar = true; // depends on control dependency: [if], data = [none]
currentColumn.append(c); // depends on control dependency: [if], data = [none]
} else if( c == quote ) {
quotesRequiredForSpecialChar = true; // depends on control dependency: [if], data = [none]
currentColumn.append(quoteEscapeChar); // depends on control dependency: [if], data = [none]
currentColumn.append(quote); // depends on control dependency: [if], data = [none]
} else if( c == '\r' ) {
quotesRequiredForSpecialChar = true; // depends on control dependency: [if], data = [none]
currentColumn.append(eolSymbols); // depends on control dependency: [if], data = [none]
context.setLineNumber(context.getLineNumber() + 1); // depends on control dependency: [if], data = [none]
skipNewline = true; // depends on control dependency: [if], data = [none]
} else if( c == '\n' ) {
quotesRequiredForSpecialChar = true; // depends on control dependency: [if], data = [none]
currentColumn.append(eolSymbols); // depends on control dependency: [if], data = [none]
context.setLineNumber(context.getLineNumber() + 1); // depends on control dependency: [if], data = [none]
} else {
currentColumn.append(c); // depends on control dependency: [if], data = [none]
}
}
final boolean quotesRequiredForMode = preference.getQuoteMode().quotesRequired(input, context, preference);
final boolean quotesRequiredForSurroundingSpaces = preference.isSurroundingSpacesNeedQuotes()
&& input.length() > 0 && (input.charAt(0) == ' ' || input.charAt(input.length() - 1) == ' ');
if( quotesRequiredForSpecialChar || quotesRequiredForMode || quotesRequiredForSurroundingSpaces ) {
currentColumn.insert(0, quote).append(quote); // depends on control dependency: [if], data = [none]
}
return currentColumn.toString();
} } |
public class class_name {
@Override
public IComplexNDArray muliColumnVector(INDArray columnVector) {
for (int i = 0; i < columns(); i++) {
getColumn(i).muli(columnVector.getScalar(i));
}
return this;
} } | public class class_name {
@Override
public IComplexNDArray muliColumnVector(INDArray columnVector) {
for (int i = 0; i < columns(); i++) {
getColumn(i).muli(columnVector.getScalar(i)); // depends on control dependency: [for], data = [i]
}
return this;
} } |
public class class_name {
private static Object toStringType(Object value) {
if (value instanceof String) {
return value;
} else if (value instanceof DataByteArray) {
byte[] buf = ((DataByteArray)value).get();
// mostly there is no need to copy.
return ByteBuffer.wrap(Arrays.copyOf(buf, buf.length));
}
return null;
} } | public class class_name {
private static Object toStringType(Object value) {
if (value instanceof String) {
return value; // depends on control dependency: [if], data = [none]
} else if (value instanceof DataByteArray) {
byte[] buf = ((DataByteArray)value).get();
// mostly there is no need to copy.
return ByteBuffer.wrap(Arrays.copyOf(buf, buf.length)); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Action(name = "Modify Instance Attribute",
outputs = {
@Output(Outputs.RETURN_CODE),
@Output(Outputs.RETURN_RESULT),
@Output(Outputs.EXCEPTION)
},
responses = {
@Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
@Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR)
}
)
public Map<String, String> execute(@Param(value = ENDPOINT, required = true) String endpoint,
@Param(value = IDENTITY, required = true) String identity,
@Param(value = CREDENTIAL, required = true, encrypted = true) String credential,
@Param(value = PROXY_HOST) String proxyHost,
@Param(value = PROXY_PORT) String proxyPort,
@Param(value = PROXY_USERNAME) String proxyUsername,
@Param(value = PROXY_PASSWORD, encrypted = true) String proxyPassword,
@Param(value = HEADERS) String headers,
@Param(value = QUERY_PARAMS) String queryParams,
@Param(value = VERSION) String version,
@Param(value = DELIMITER) String delimiter,
@Param(value = ATTRIBUTE) String attribute,
@Param(value = ATTRIBUTE_VALUE) String attributeValue,
@Param(value = BLOCK_DEVICE_MAPPING_DEVICE_NAMES_STRING) String blockDeviceMappingDeviceNamesString,
@Param(value = BLOCK_DEVICE_MAPPING_VIRTUAL_NAMES_STRING) String blockDeviceMappingVirtualNamesString,
@Param(value = DELETE_ON_TERMINATIONS_STRING) String deleteOnTerminationsString,
@Param(value = VOLUME_IDS_STRING) String volumeIdsString,
@Param(value = NO_DEVICES_STRING) String noDevicesString,
@Param(value = LOWER_CASE_DISABLE_API_TERMINATION) String disableApiTermination,
@Param(value = EBS_OPTIMIZED) String ebsOptimized,
@Param(value = ENA_SUPPORT) String enaSupport,
@Param(value = SECURITY_GROUP_IDS_STRING) String securityGroupIdsString,
@Param(value = INSTANCE_ID, required = true) String instanceId,
@Param(value = LOWER_CASE_INSTANCE_INITIATED_SHUTDOWN_BEHAVIOR) String instanceInitiatedShutdownBehavior,
@Param(value = INSTANCE_TYPE) String instanceType,
@Param(value = LOWER_CASE_KERNEL) String kernel,
@Param(value = LOWER_CASE_RAMDISK) String ramdisk,
@Param(value = SOURCE_DESTINATION_CHECK) String sourceDestinationCheck,
@Param(value = SRIOV_NET_SUPPORT) String sriovNetSupport,
@Param(value = LOWER_CASE_USER_DATA) String userData) {
try {
version = getDefaultStringInput(version, INSTANCES_DEFAULT_API_VERSION);
final CommonInputs commonInputs = new CommonInputs.Builder()
.withEndpoint(endpoint, EC2_API, EMPTY)
.withIdentity(identity)
.withCredential(credential)
.withProxyHost(proxyHost)
.withProxyPort(proxyPort)
.withProxyUsername(proxyUsername)
.withProxyPassword(proxyPassword)
.withHeaders(headers)
.withQueryParams(queryParams)
.withVersion(version)
.withDelimiter(delimiter)
.withAction(MODIFY_INSTANCE_ATTRIBUTE)
.withApiService(EC2_API)
.withRequestUri(EMPTY)
.withRequestPayload(EMPTY)
.withHttpClientMethod(HTTP_CLIENT_METHOD_GET)
.build();
final CustomInputs customInputs = new CustomInputs.Builder()
.withInstanceId(instanceId)
.withInstanceType(instanceType)
.build();
EbsInputs ebsInputs = new EbsInputs.Builder()
.withEbsOptimized(ebsOptimized)
.withBlockDeviceMappingDeviceNamesString(blockDeviceMappingDeviceNamesString)
.withBlockDeviceMappingVirtualNamesString(blockDeviceMappingVirtualNamesString)
.withDeleteOnTerminationsString(deleteOnTerminationsString)
.withVolumeIdsString(volumeIdsString)
.withNoDevicesString(noDevicesString)
.build();
IamInputs iamInputs = new IamInputs.Builder().withSecurityGroupIdsString(securityGroupIdsString).build();
InstanceInputs instanceInputs = new InstanceInputs.Builder()
.withAttribute(attribute)
.withAttributeValue(attributeValue)
.withDisableApiTermination(disableApiTermination)
.withEnaSupport(enaSupport)
.withInstanceInitiatedShutdownBehavior(instanceInitiatedShutdownBehavior)
.withKernel(kernel)
.withRamdisk(ramdisk)
.withSourceDestinationCheck(sourceDestinationCheck)
.withSriovNetSupport(sriovNetSupport)
.withUserData(userData)
.build();
return new QueryApiExecutor().execute(commonInputs, customInputs, ebsInputs, iamInputs, instanceInputs);
} catch (Exception e) {
return ExceptionProcessor.getExceptionResult(e);
}
} } | public class class_name {
@Action(name = "Modify Instance Attribute",
outputs = {
@Output(Outputs.RETURN_CODE),
@Output(Outputs.RETURN_RESULT),
@Output(Outputs.EXCEPTION)
},
responses = {
@Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
@Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR)
}
)
public Map<String, String> execute(@Param(value = ENDPOINT, required = true) String endpoint,
@Param(value = IDENTITY, required = true) String identity,
@Param(value = CREDENTIAL, required = true, encrypted = true) String credential,
@Param(value = PROXY_HOST) String proxyHost,
@Param(value = PROXY_PORT) String proxyPort,
@Param(value = PROXY_USERNAME) String proxyUsername,
@Param(value = PROXY_PASSWORD, encrypted = true) String proxyPassword,
@Param(value = HEADERS) String headers,
@Param(value = QUERY_PARAMS) String queryParams,
@Param(value = VERSION) String version,
@Param(value = DELIMITER) String delimiter,
@Param(value = ATTRIBUTE) String attribute,
@Param(value = ATTRIBUTE_VALUE) String attributeValue,
@Param(value = BLOCK_DEVICE_MAPPING_DEVICE_NAMES_STRING) String blockDeviceMappingDeviceNamesString,
@Param(value = BLOCK_DEVICE_MAPPING_VIRTUAL_NAMES_STRING) String blockDeviceMappingVirtualNamesString,
@Param(value = DELETE_ON_TERMINATIONS_STRING) String deleteOnTerminationsString,
@Param(value = VOLUME_IDS_STRING) String volumeIdsString,
@Param(value = NO_DEVICES_STRING) String noDevicesString,
@Param(value = LOWER_CASE_DISABLE_API_TERMINATION) String disableApiTermination,
@Param(value = EBS_OPTIMIZED) String ebsOptimized,
@Param(value = ENA_SUPPORT) String enaSupport,
@Param(value = SECURITY_GROUP_IDS_STRING) String securityGroupIdsString,
@Param(value = INSTANCE_ID, required = true) String instanceId,
@Param(value = LOWER_CASE_INSTANCE_INITIATED_SHUTDOWN_BEHAVIOR) String instanceInitiatedShutdownBehavior,
@Param(value = INSTANCE_TYPE) String instanceType,
@Param(value = LOWER_CASE_KERNEL) String kernel,
@Param(value = LOWER_CASE_RAMDISK) String ramdisk,
@Param(value = SOURCE_DESTINATION_CHECK) String sourceDestinationCheck,
@Param(value = SRIOV_NET_SUPPORT) String sriovNetSupport,
@Param(value = LOWER_CASE_USER_DATA) String userData) {
try {
version = getDefaultStringInput(version, INSTANCES_DEFAULT_API_VERSION); // depends on control dependency: [try], data = [none]
final CommonInputs commonInputs = new CommonInputs.Builder()
.withEndpoint(endpoint, EC2_API, EMPTY)
.withIdentity(identity)
.withCredential(credential)
.withProxyHost(proxyHost)
.withProxyPort(proxyPort)
.withProxyUsername(proxyUsername)
.withProxyPassword(proxyPassword)
.withHeaders(headers)
.withQueryParams(queryParams)
.withVersion(version)
.withDelimiter(delimiter)
.withAction(MODIFY_INSTANCE_ATTRIBUTE)
.withApiService(EC2_API)
.withRequestUri(EMPTY)
.withRequestPayload(EMPTY)
.withHttpClientMethod(HTTP_CLIENT_METHOD_GET)
.build();
final CustomInputs customInputs = new CustomInputs.Builder()
.withInstanceId(instanceId)
.withInstanceType(instanceType)
.build();
EbsInputs ebsInputs = new EbsInputs.Builder()
.withEbsOptimized(ebsOptimized)
.withBlockDeviceMappingDeviceNamesString(blockDeviceMappingDeviceNamesString)
.withBlockDeviceMappingVirtualNamesString(blockDeviceMappingVirtualNamesString)
.withDeleteOnTerminationsString(deleteOnTerminationsString)
.withVolumeIdsString(volumeIdsString)
.withNoDevicesString(noDevicesString)
.build();
IamInputs iamInputs = new IamInputs.Builder().withSecurityGroupIdsString(securityGroupIdsString).build();
InstanceInputs instanceInputs = new InstanceInputs.Builder()
.withAttribute(attribute)
.withAttributeValue(attributeValue)
.withDisableApiTermination(disableApiTermination)
.withEnaSupport(enaSupport)
.withInstanceInitiatedShutdownBehavior(instanceInitiatedShutdownBehavior)
.withKernel(kernel)
.withRamdisk(ramdisk)
.withSourceDestinationCheck(sourceDestinationCheck)
.withSriovNetSupport(sriovNetSupport)
.withUserData(userData)
.build();
return new QueryApiExecutor().execute(commonInputs, customInputs, ebsInputs, iamInputs, instanceInputs); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
return ExceptionProcessor.getExceptionResult(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static base_responses add(nitro_service client, tmformssoaction resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
tmformssoaction addresources[] = new tmformssoaction[resources.length];
for (int i=0;i<resources.length;i++){
addresources[i] = new tmformssoaction();
addresources[i].name = resources[i].name;
addresources[i].actionurl = resources[i].actionurl;
addresources[i].userfield = resources[i].userfield;
addresources[i].passwdfield = resources[i].passwdfield;
addresources[i].ssosuccessrule = resources[i].ssosuccessrule;
addresources[i].namevaluepair = resources[i].namevaluepair;
addresources[i].responsesize = resources[i].responsesize;
addresources[i].nvtype = resources[i].nvtype;
addresources[i].submitmethod = resources[i].submitmethod;
}
result = add_bulk_request(client, addresources);
}
return result;
} } | public class class_name {
public static base_responses add(nitro_service client, tmformssoaction resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
tmformssoaction addresources[] = new tmformssoaction[resources.length];
for (int i=0;i<resources.length;i++){
addresources[i] = new tmformssoaction(); // depends on control dependency: [for], data = [i]
addresources[i].name = resources[i].name; // depends on control dependency: [for], data = [i]
addresources[i].actionurl = resources[i].actionurl; // depends on control dependency: [for], data = [i]
addresources[i].userfield = resources[i].userfield; // depends on control dependency: [for], data = [i]
addresources[i].passwdfield = resources[i].passwdfield; // depends on control dependency: [for], data = [i]
addresources[i].ssosuccessrule = resources[i].ssosuccessrule; // depends on control dependency: [for], data = [i]
addresources[i].namevaluepair = resources[i].namevaluepair; // depends on control dependency: [for], data = [i]
addresources[i].responsesize = resources[i].responsesize; // depends on control dependency: [for], data = [i]
addresources[i].nvtype = resources[i].nvtype; // depends on control dependency: [for], data = [i]
addresources[i].submitmethod = resources[i].submitmethod; // depends on control dependency: [for], data = [i]
}
result = add_bulk_request(client, addresources);
}
return result;
} } |
public class class_name {
public ValueType get(final KeyType... keys) {
if (ArrayUtils.isEmpty(keys)) {
return null;
}
int keysLength = keys.length;
if (keysLength == 1) {
return get(keys[0]);
} else {
StorageComponent<KeyType, ValueType> storageComponent = this;
int lastKeyIndex = keysLength - 1;
for (int i = 0; i < lastKeyIndex; i++) {
KeyType storageComponentKey = keys[i];
storageComponent = storageComponent.getStorageComponent(storageComponentKey);
}
return storageComponent.get(keys[lastKeyIndex]);
}
} } | public class class_name {
public ValueType get(final KeyType... keys) {
if (ArrayUtils.isEmpty(keys)) {
return null; // depends on control dependency: [if], data = [none]
}
int keysLength = keys.length;
if (keysLength == 1) {
return get(keys[0]); // depends on control dependency: [if], data = [none]
} else {
StorageComponent<KeyType, ValueType> storageComponent = this;
int lastKeyIndex = keysLength - 1;
for (int i = 0; i < lastKeyIndex; i++) {
KeyType storageComponentKey = keys[i];
storageComponent = storageComponent.getStorageComponent(storageComponentKey); // depends on control dependency: [for], data = [none]
}
return storageComponent.get(keys[lastKeyIndex]); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
boolean matches(final SibRaConnectionInfo connectionInfo,
final SICoreConnection coreConnection) {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, "matches", new Object[] { connectionInfo,
coreConnection });
}
final boolean match;
if (!isValid ())
{
match = false;
}
else if (coreConnection != null) {
match = _coreConnection.isEquivalentTo(coreConnection);
} else {
match = _connectionInfo.equals(connectionInfo);
}
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.exit(this, TRACE, "matches", Boolean.valueOf(match));
}
return match;
} } | public class class_name {
boolean matches(final SibRaConnectionInfo connectionInfo,
final SICoreConnection coreConnection) {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, "matches", new Object[] { connectionInfo,
coreConnection }); // depends on control dependency: [if], data = [none]
}
final boolean match;
if (!isValid ())
{
match = false; // depends on control dependency: [if], data = [none]
}
else if (coreConnection != null) {
match = _coreConnection.isEquivalentTo(coreConnection); // depends on control dependency: [if], data = [(coreConnection]
} else {
match = _connectionInfo.equals(connectionInfo); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.exit(this, TRACE, "matches", Boolean.valueOf(match)); // depends on control dependency: [if], data = [none]
}
return match;
} } |
public class class_name {
public boolean addArray(double... integers) {
if (end + integers.length >= values.length) {
values = grow(values, (values.length + integers.length) * 2);
}
System.arraycopy(integers, 0, values, end, integers.length);
end += integers.length;
return true;
} } | public class class_name {
public boolean addArray(double... integers) {
if (end + integers.length >= values.length) {
values = grow(values, (values.length + integers.length) * 2); // depends on control dependency: [if], data = [none]
}
System.arraycopy(integers, 0, values, end, integers.length);
end += integers.length;
return true;
} } |
public class class_name {
public Map<Object, Object> getDefaultProperties(ResolverWrapper resolver) {
// if no resolver is given or the list of default properties is empty then
// return an empty map
if(resolver == null || resolver.properties() == null || resolver.properties().length == 0) {
return Collections.emptyMap();
}
// get properties from the resolver annotation
DefaultProperty[] properties = resolver.properties();
// copy each property annotation into the map for later use
Map<Object, Object> propertyMap = new HashMap<>(properties.length);
for(DefaultProperty property : properties) {
// nulls and empty keys are bad
if(property.key() == null || property.key().isEmpty() || property.value() == null) {
continue;
}
// no dupes
if(propertyMap.containsKey(property.key())) {
continue;
}
// put in map
propertyMap.put(property.key(), property.value());
}
return propertyMap;
} } | public class class_name {
public Map<Object, Object> getDefaultProperties(ResolverWrapper resolver) {
// if no resolver is given or the list of default properties is empty then
// return an empty map
if(resolver == null || resolver.properties() == null || resolver.properties().length == 0) {
return Collections.emptyMap(); // depends on control dependency: [if], data = [none]
}
// get properties from the resolver annotation
DefaultProperty[] properties = resolver.properties();
// copy each property annotation into the map for later use
Map<Object, Object> propertyMap = new HashMap<>(properties.length);
for(DefaultProperty property : properties) {
// nulls and empty keys are bad
if(property.key() == null || property.key().isEmpty() || property.value() == null) {
continue;
}
// no dupes
if(propertyMap.containsKey(property.key())) {
continue;
}
// put in map
propertyMap.put(property.key(), property.value()); // depends on control dependency: [for], data = [property]
}
return propertyMap;
} } |
public class class_name {
protected HttpActionAdapter<Object, JaxRsContext> adapter(Config config) {
final HttpActionAdapter adapter;
if (config.getHttpActionAdapter() != null) {
adapter = config.getHttpActionAdapter();
} else {
adapter = JaxRsHttpActionAdapter.INSTANCE;
}
return (code, context) -> {
if (skipResponse == null || !skipResponse) {
adapter.adapt(code, context);
}
return null;
};
} } | public class class_name {
protected HttpActionAdapter<Object, JaxRsContext> adapter(Config config) {
final HttpActionAdapter adapter;
if (config.getHttpActionAdapter() != null) {
adapter = config.getHttpActionAdapter(); // depends on control dependency: [if], data = [none]
} else {
adapter = JaxRsHttpActionAdapter.INSTANCE; // depends on control dependency: [if], data = [none]
}
return (code, context) -> {
if (skipResponse == null || !skipResponse) {
adapter.adapt(code, context);
}
return null;
};
} } |
public class class_name {
@Override
protected Reader generateResource(String path, GeneratorContext context) {
Reader rd = null;
try {
List<Class<?>> excluded = new ArrayList<>();
excluded.add(ISassResourceGenerator.class);
JoinableResourceBundle bundle = context.getBundle();
rd = context.getResourceReaderHandler().getResource(bundle, path, false, excluded);
if (rd == null) {
throw new ResourceNotFoundException(path);
}
String content = IOUtils.toString(rd);
String result = compile(bundle, content, path, context);
rd = new StringReader(result);
} catch (ResourceNotFoundException | IOException e) {
throw new BundlingProcessException("Unable to generate content for resource path : '" + path + "'", e);
}
return rd;
} } | public class class_name {
@Override
protected Reader generateResource(String path, GeneratorContext context) {
Reader rd = null;
try {
List<Class<?>> excluded = new ArrayList<>(); // depends on control dependency: [try], data = [none]
excluded.add(ISassResourceGenerator.class); // depends on control dependency: [try], data = [none]
JoinableResourceBundle bundle = context.getBundle();
rd = context.getResourceReaderHandler().getResource(bundle, path, false, excluded); // depends on control dependency: [try], data = [none]
if (rd == null) {
throw new ResourceNotFoundException(path);
}
String content = IOUtils.toString(rd);
String result = compile(bundle, content, path, context);
rd = new StringReader(result); // depends on control dependency: [try], data = [none]
} catch (ResourceNotFoundException | IOException e) {
throw new BundlingProcessException("Unable to generate content for resource path : '" + path + "'", e);
} // depends on control dependency: [catch], data = [none]
return rd;
} } |
public class class_name {
public static BigMoney total(BigMoneyProvider... monies) {
MoneyUtils.checkNotNull(monies, "Money array must not be null");
if (monies.length == 0) {
throw new IllegalArgumentException("Money array must not be empty");
}
BigMoney total = of(monies[0]);
MoneyUtils.checkNotNull(total, "Money array must not contain null entries");
for (int i = 1; i < monies.length; i++) {
total = total.plus(of(monies[i]));
}
return total;
} } | public class class_name {
public static BigMoney total(BigMoneyProvider... monies) {
MoneyUtils.checkNotNull(monies, "Money array must not be null");
if (monies.length == 0) {
throw new IllegalArgumentException("Money array must not be empty");
}
BigMoney total = of(monies[0]);
MoneyUtils.checkNotNull(total, "Money array must not contain null entries");
for (int i = 1; i < monies.length; i++) {
total = total.plus(of(monies[i]));
// depends on control dependency: [for], data = [i]
}
return total;
} } |
public class class_name {
public CompletableFuture<Long> appendEntries(long index) {
raft.checkThread();
if (index == 0) {
return appendEntries();
}
if (index <= raft.getCommitIndex()) {
return CompletableFuture.completedFuture(index);
}
// If there are no other stateful servers in the cluster, immediately commit the index.
if (raft.getCluster().getActiveMemberStates().isEmpty() && raft.getCluster().getPassiveMemberStates().isEmpty()) {
long previousCommitIndex = raft.getCommitIndex();
raft.setCommitIndex(index);
completeCommits(previousCommitIndex, index);
return CompletableFuture.completedFuture(index);
}
// If there are no other active members in the cluster, update the commit index and complete the commit.
// The updated commit index will be sent to passive/reserve members on heartbeats.
else if (raft.getCluster().getActiveMemberStates().isEmpty()) {
long previousCommitIndex = raft.getCommitIndex();
raft.setCommitIndex(index);
completeCommits(previousCommitIndex, index);
return CompletableFuture.completedFuture(index);
}
// Only send entry-specific AppendRequests to active members of the cluster.
return appendFutures.computeIfAbsent(index, i -> {
for (RaftMemberContext member : raft.getCluster().getActiveMemberStates()) {
appendEntries(member);
}
return new CompletableFuture<>();
});
} } | public class class_name {
public CompletableFuture<Long> appendEntries(long index) {
raft.checkThread();
if (index == 0) {
return appendEntries(); // depends on control dependency: [if], data = [none]
}
if (index <= raft.getCommitIndex()) {
return CompletableFuture.completedFuture(index); // depends on control dependency: [if], data = [(index]
}
// If there are no other stateful servers in the cluster, immediately commit the index.
if (raft.getCluster().getActiveMemberStates().isEmpty() && raft.getCluster().getPassiveMemberStates().isEmpty()) {
long previousCommitIndex = raft.getCommitIndex();
raft.setCommitIndex(index); // depends on control dependency: [if], data = [none]
completeCommits(previousCommitIndex, index); // depends on control dependency: [if], data = [none]
return CompletableFuture.completedFuture(index); // depends on control dependency: [if], data = [none]
}
// If there are no other active members in the cluster, update the commit index and complete the commit.
// The updated commit index will be sent to passive/reserve members on heartbeats.
else if (raft.getCluster().getActiveMemberStates().isEmpty()) {
long previousCommitIndex = raft.getCommitIndex();
raft.setCommitIndex(index); // depends on control dependency: [if], data = [none]
completeCommits(previousCommitIndex, index); // depends on control dependency: [if], data = [none]
return CompletableFuture.completedFuture(index); // depends on control dependency: [if], data = [none]
}
// Only send entry-specific AppendRequests to active members of the cluster.
return appendFutures.computeIfAbsent(index, i -> {
for (RaftMemberContext member : raft.getCluster().getActiveMemberStates()) {
appendEntries(member);
}
return new CompletableFuture<>();
});
} } |
public class class_name {
public void displayPage (final int page, boolean forceRefresh)
{
if (_page == page && !forceRefresh) {
return; // NOOP!
}
// Display the now loading widget, if necessary.
configureLoadingNavi(_controls, 0, _infoCol);
_page = Math.max(page, 0);
final boolean overQuery = (_model.getItemCount() < 0);
final int count = _resultsPerPage;
final int start = _resultsPerPage * page;
_model.doFetchRows(start, overQuery ? (count + 1) : count, new AsyncCallback<List<T>>() {
public void onSuccess (List<T> result) {
if (overQuery) {
// if we requested 1 item too many, see if we got it
if (result.size() < (count + 1)) {
// no: this is the last batch of items, woohoo
_lastItem = start + result.size();
} else {
// yes: strip it before anybody else gets to see it
result.remove(count);
_lastItem = -1;
}
} else {
// a valid item count should be available at this point
_lastItem = _model.getItemCount();
}
displayResults(start, count, result);
}
public void onFailure (Throwable caught) {
reportFailure(caught);
}
});
} } | public class class_name {
public void displayPage (final int page, boolean forceRefresh)
{
if (_page == page && !forceRefresh) {
return; // NOOP! // depends on control dependency: [if], data = [none]
}
// Display the now loading widget, if necessary.
configureLoadingNavi(_controls, 0, _infoCol);
_page = Math.max(page, 0);
final boolean overQuery = (_model.getItemCount() < 0);
final int count = _resultsPerPage;
final int start = _resultsPerPage * page;
_model.doFetchRows(start, overQuery ? (count + 1) : count, new AsyncCallback<List<T>>() {
public void onSuccess (List<T> result) {
if (overQuery) {
// if we requested 1 item too many, see if we got it
if (result.size() < (count + 1)) {
// no: this is the last batch of items, woohoo
_lastItem = start + result.size(); // depends on control dependency: [if], data = [none]
} else {
// yes: strip it before anybody else gets to see it
result.remove(count); // depends on control dependency: [if], data = [none]
_lastItem = -1; // depends on control dependency: [if], data = [none]
}
} else {
// a valid item count should be available at this point
_lastItem = _model.getItemCount(); // depends on control dependency: [if], data = [none]
}
displayResults(start, count, result);
}
public void onFailure (Throwable caught) {
reportFailure(caught);
}
});
} } |
public class class_name {
private TemplateImpl load(String path, ParserRuleContext errCtx) {
path = Paths.resolvePath(currentEnvironment.path, path);
try {
return (TemplateImpl) engine.load(path);
}
catch (IOException | ParseException e) {
throw new ExecutionException("error importing " + path, e, getLocation(errCtx));
}
} } | public class class_name {
private TemplateImpl load(String path, ParserRuleContext errCtx) {
path = Paths.resolvePath(currentEnvironment.path, path);
try {
return (TemplateImpl) engine.load(path); // depends on control dependency: [try], data = [none]
}
catch (IOException | ParseException e) {
throw new ExecutionException("error importing " + path, e, getLocation(errCtx));
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void removeSink(VehicleDataSink sink) {
if(sink != null) {
mSinks.remove(sink);
sink.stop();
}
} } | public class class_name {
public void removeSink(VehicleDataSink sink) {
if(sink != null) {
mSinks.remove(sink); // depends on control dependency: [if], data = [(sink]
sink.stop(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected void fireLabelProviderChanged(
final LabelProviderChangedEvent event)
{
Object[] listeners = fListeners.getListeners();
for (int i = 0; i < listeners.length; ++i)
{
final ILabelProviderListener l = (ILabelProviderListener) listeners[i];
SafeRunner.run(new SafeRunnable()
{
public void run()
{
l.labelProviderChanged(event);
}
});
}
} } | public class class_name {
protected void fireLabelProviderChanged(
final LabelProviderChangedEvent event)
{
Object[] listeners = fListeners.getListeners();
for (int i = 0; i < listeners.length; ++i)
{
final ILabelProviderListener l = (ILabelProviderListener) listeners[i];
SafeRunner.run(new SafeRunnable()
{
public void run()
{
l.labelProviderChanged(event);
}
}); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
protected String getReturnType(ExecutableMethod method) {
Class returnType = method.getReturnType().getType();
if (Publishers.isSingle(returnType) || Publishers.isConvertibleToPublisher(returnType)) {
Argument[] typeParams = method.getReturnType().getTypeParameters();
if (typeParams.length > 0) {
returnType = typeParams[0].getType();
}
}
return returnType.getName();
} } | public class class_name {
protected String getReturnType(ExecutableMethod method) {
Class returnType = method.getReturnType().getType();
if (Publishers.isSingle(returnType) || Publishers.isConvertibleToPublisher(returnType)) {
Argument[] typeParams = method.getReturnType().getTypeParameters();
if (typeParams.length > 0) {
returnType = typeParams[0].getType(); // depends on control dependency: [if], data = [none]
}
}
return returnType.getName();
} } |
public class class_name {
protected void update() {
if(conHandler.shouldStop()) {
Utils.closeQuietly(this);
return;
}
String line;
try {
line = reader.readLine();
} catch(SocketTimeoutException ex) {
// Check if the socket has timed out
if(!dataConnections.isEmpty() && (System.currentTimeMillis() - lastUpdate) >= timeout) {
Utils.closeQuietly(this);
}
return;
} catch(IOException ex) {
return;
}
if(line == null) {
Utils.closeQuietly(this);
return;
}
if(line.isEmpty()) return;
process(line);
} } | public class class_name {
protected void update() {
if(conHandler.shouldStop()) {
Utils.closeQuietly(this); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
String line;
try {
line = reader.readLine(); // depends on control dependency: [try], data = [none]
} catch(SocketTimeoutException ex) {
// Check if the socket has timed out
if(!dataConnections.isEmpty() && (System.currentTimeMillis() - lastUpdate) >= timeout) {
Utils.closeQuietly(this); // depends on control dependency: [if], data = [none]
}
return;
} catch(IOException ex) { // depends on control dependency: [catch], data = [none]
return;
} // depends on control dependency: [catch], data = [none]
if(line == null) {
Utils.closeQuietly(this); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if(line.isEmpty()) return;
process(line);
} } |
public class class_name {
public ComputeNodeDisableSchedulingOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null;
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate);
}
return this;
} } | public class class_name {
public ComputeNodeDisableSchedulingOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null; // depends on control dependency: [if], data = [none]
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate); // depends on control dependency: [if], data = [(ocpDate]
}
return this;
} } |
public class class_name {
private void initDesktopDriver() {
// super.init();
setServices();
setPrefsPaths();
// Start Opera if it is not already running
// If the Opera Binary isn't set we are assuming Opera is up and we
// can ask it for the location of itself
if (settings.getBinary() == null && !settings.noRestart()) {
String operaPath = getOperaPath();
logger.fine("OperaBinaryLocation retrieved from Opera: " + operaPath);
if (operaPath.length() > 0) {
settings.setBinary(new File(operaPath));
// Now create the OperaLauncherRunner that we have the binary path
runner = new OperaLauncherRunner(settings);
// Quit and wait for opera to quit properly
try {
getScopeServices().quit(runner);
} catch (IOException e) {
throw new WebDriverException(e);
}
// Delete the profile to start the first test with a clean profile
if (!profileUtils.deleteProfile()) {
logger.severe("Could not delete profile");
}
// Work around stop and restart Opera so the Launcher has control of it now
// Initialising the services will start Opera if the OperaLauncherRunner is
// setup correctly
startOpera();
}
}
} } | public class class_name {
private void initDesktopDriver() {
// super.init();
setServices();
setPrefsPaths();
// Start Opera if it is not already running
// If the Opera Binary isn't set we are assuming Opera is up and we
// can ask it for the location of itself
if (settings.getBinary() == null && !settings.noRestart()) {
String operaPath = getOperaPath();
logger.fine("OperaBinaryLocation retrieved from Opera: " + operaPath); // depends on control dependency: [if], data = [none]
if (operaPath.length() > 0) {
settings.setBinary(new File(operaPath)); // depends on control dependency: [if], data = [none]
// Now create the OperaLauncherRunner that we have the binary path
runner = new OperaLauncherRunner(settings); // depends on control dependency: [if], data = [none]
// Quit and wait for opera to quit properly
try {
getScopeServices().quit(runner); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new WebDriverException(e);
} // depends on control dependency: [catch], data = [none]
// Delete the profile to start the first test with a clean profile
if (!profileUtils.deleteProfile()) {
logger.severe("Could not delete profile"); // depends on control dependency: [if], data = [none]
}
// Work around stop and restart Opera so the Launcher has control of it now
// Initialising the services will start Opera if the OperaLauncherRunner is
// setup correctly
startOpera(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void getDistributedObjects(Collection<DistributedObject> result) {
Collection<DistributedObjectFuture> futures = proxies.values();
for (DistributedObjectFuture future : futures) {
if (!future.isSetAndInitialized()) {
continue;
}
try {
DistributedObject object = future.get();
result.add(object);
} catch (Throwable ignored) {
// ignore if proxy creation failed
ignore(ignored);
}
}
} } | public class class_name {
public void getDistributedObjects(Collection<DistributedObject> result) {
Collection<DistributedObjectFuture> futures = proxies.values();
for (DistributedObjectFuture future : futures) {
if (!future.isSetAndInitialized()) {
continue;
}
try {
DistributedObject object = future.get();
result.add(object); // depends on control dependency: [try], data = [none]
} catch (Throwable ignored) {
// ignore if proxy creation failed
ignore(ignored);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public PBKey getPBKey()
{
if (pbKey == null)
{
this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());
}
return pbKey;
} } | public class class_name {
public PBKey getPBKey()
{
if (pbKey == null)
{
this.pbKey = new PBKey(this.getJcdAlias(), this.getUserName(), this.getPassWord());
// depends on control dependency: [if], data = [none]
}
return pbKey;
} } |
public class class_name {
public static String encode(Color color) {
StringBuffer buffer = new StringBuffer("#");
if (color.getRed() < 16) {
buffer.append('0');
}
buffer.append(Integer.toString(color.getRed(), 16));
if (color.getGreen() < 16) {
buffer.append('0');
}
buffer.append(Integer.toString(color.getGreen(), 16));
if (color.getBlue() < 16) {
buffer.append('0');
}
buffer.append(Integer.toString(color.getBlue(), 16));
return buffer.toString();
} } | public class class_name {
public static String encode(Color color) {
StringBuffer buffer = new StringBuffer("#");
if (color.getRed() < 16) {
buffer.append('0'); // depends on control dependency: [if], data = [none]
}
buffer.append(Integer.toString(color.getRed(), 16));
if (color.getGreen() < 16) {
buffer.append('0'); // depends on control dependency: [if], data = [none]
}
buffer.append(Integer.toString(color.getGreen(), 16));
if (color.getBlue() < 16) {
buffer.append('0'); // depends on control dependency: [if], data = [none]
}
buffer.append(Integer.toString(color.getBlue(), 16));
return buffer.toString();
} } |
public class class_name {
protected TextEdit getDeclarationTextEdit(String newName, ResourceSet resourceSet) {
final EObject object = resourceSet.getEObject(this.uriProvider.apply(resourceSet), true);
if (object instanceof SarlScript) {
final ITextRegion region = getOriginalPackageRegion((SarlScript) object);
if (region != null) {
return new ReplaceEdit(region.getOffset(), region.getLength(), newName);
}
}
throw new RefactoringException("SARL script not loaded."); //$NON-NLS-1$
} } | public class class_name {
protected TextEdit getDeclarationTextEdit(String newName, ResourceSet resourceSet) {
final EObject object = resourceSet.getEObject(this.uriProvider.apply(resourceSet), true);
if (object instanceof SarlScript) {
final ITextRegion region = getOriginalPackageRegion((SarlScript) object);
if (region != null) {
return new ReplaceEdit(region.getOffset(), region.getLength(), newName); // depends on control dependency: [if], data = [(region]
}
}
throw new RefactoringException("SARL script not loaded."); //$NON-NLS-1$
} } |
public class class_name {
protected EntityDescFactory createEntityDescFactory() {
Class<?> superclass = null;
if (entityConfig.getSuperclassName() != null) {
superclass = forName(entityConfig.getSuperclassName(), "superclassName");
}
return globalFactory.createEntityDescFactory(
entityConfig.getPackageName(),
superclass,
entityPropertyDescFactory,
entityConfig.getNamingType() == null
? NamingType.NONE
: entityConfig.getNamingType().convertToEnum(),
entityConfig.getOriginalStatesPropertyName(),
entityConfig.isShowCatalogName(),
entityConfig.isShowSchemaName(),
entityConfig.isShowTableName(),
entityConfig.isShowDbComment(),
entityConfig.isUseAccessor(),
entityConfig.isUseListener());
} } | public class class_name {
protected EntityDescFactory createEntityDescFactory() {
Class<?> superclass = null;
if (entityConfig.getSuperclassName() != null) {
superclass = forName(entityConfig.getSuperclassName(), "superclassName"); // depends on control dependency: [if], data = [(entityConfig.getSuperclassName()]
}
return globalFactory.createEntityDescFactory(
entityConfig.getPackageName(),
superclass,
entityPropertyDescFactory,
entityConfig.getNamingType() == null
? NamingType.NONE
: entityConfig.getNamingType().convertToEnum(),
entityConfig.getOriginalStatesPropertyName(),
entityConfig.isShowCatalogName(),
entityConfig.isShowSchemaName(),
entityConfig.isShowTableName(),
entityConfig.isShowDbComment(),
entityConfig.isUseAccessor(),
entityConfig.isUseListener());
} } |
public class class_name {
@Pure
public boolean containsPoint(Point2D<?, ?> point, int groupIndex) {
final int grpCount = getGroupCount();
if (groupIndex < 0) {
throw new IndexOutOfBoundsException(groupIndex + "<0"); //$NON-NLS-1$
}
if (groupIndex > grpCount) {
throw new IndexOutOfBoundsException(groupIndex + ">" + grpCount); //$NON-NLS-1$
}
if (point == null) {
return false;
}
for (int i = 0; i < getPointCountInGroup(groupIndex); ++i) {
final Point2d cur = getPointAt(groupIndex, i);
if (cur.epsilonEquals(point, MapElementConstants.POINT_FUSION_DISTANCE)) {
return true;
}
}
return false;
} } | public class class_name {
@Pure
public boolean containsPoint(Point2D<?, ?> point, int groupIndex) {
final int grpCount = getGroupCount();
if (groupIndex < 0) {
throw new IndexOutOfBoundsException(groupIndex + "<0"); //$NON-NLS-1$
}
if (groupIndex > grpCount) {
throw new IndexOutOfBoundsException(groupIndex + ">" + grpCount); //$NON-NLS-1$
}
if (point == null) {
return false; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < getPointCountInGroup(groupIndex); ++i) {
final Point2d cur = getPointAt(groupIndex, i);
if (cur.epsilonEquals(point, MapElementConstants.POINT_FUSION_DISTANCE)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
private static CompilerPass runInSerial(
final Collection<CompilerPass> passes) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
for (CompilerPass pass : passes) {
pass.process(externs, root);
}
}
};
} } | public class class_name {
private static CompilerPass runInSerial(
final Collection<CompilerPass> passes) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
for (CompilerPass pass : passes) {
pass.process(externs, root); // depends on control dependency: [for], data = [pass]
}
}
};
} } |
public class class_name {
public boolean remove(Node<E> e) {
mPutLock.lock();
mPollLock.lock();
try {
if (e == null)
return false;
if (e.mRemoved)
return false;
if (mSize.get() == 0)
return false;
if (e == mTail) {
removeTail();
return true;
}
if (e == mHead.mNext) {
removeHead();
return true;
}
if (mSize.get() < 3)
return false;
if (e.mPrev == null || e.mNext == null)
return false;
e.mPrev.mNext = e.mNext;
e.mNext.mPrev = e.mPrev;
e.mRemoved = true;
mSize.decrementAndGet();
mNodePool.returnNode(e);
return true;
}
finally {
mPollLock.unlock();
mPutLock.unlock();
}
} } | public class class_name {
public boolean remove(Node<E> e) {
mPutLock.lock();
mPollLock.lock();
try {
if (e == null)
return false;
if (e.mRemoved)
return false;
if (mSize.get() == 0)
return false;
if (e == mTail) {
removeTail(); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
if (e == mHead.mNext) {
removeHead(); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
if (mSize.get() < 3)
return false;
if (e.mPrev == null || e.mNext == null)
return false;
e.mPrev.mNext = e.mNext; // depends on control dependency: [try], data = [none]
e.mNext.mPrev = e.mPrev; // depends on control dependency: [try], data = [none]
e.mRemoved = true; // depends on control dependency: [try], data = [none]
mSize.decrementAndGet(); // depends on control dependency: [try], data = [none]
mNodePool.returnNode(e); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
}
finally {
mPollLock.unlock();
mPutLock.unlock();
}
} } |
public class class_name {
public static MimeMessage createMimeMessage(Session session, String from, String[] to, String subject, String content, DataSource[] attachments) {
logger.debug("Creates a mime message with {} attachments", (attachments == null) ? 0 : attachments.length);
try {
MimeMessage message = new MimeMessage(session);
if (from != null) {
message.setSender(new InternetAddress(from));
}
if (subject != null) {
message.setSubject(subject, "UTF-8");
}
if (to != null) {
for (String toAdr : to) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAdr));
}
}
if (attachments == null || attachments.length == 0) {
// Setup a plain text message
message.setContent(content, "text/plain; charset=UTF-8");
} else {
// Setup a multipart message
Multipart multipart = new MimeMultipart();
message.setContent(multipart);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(content, "text/plain; charset=UTF-8");
multipart.addBodyPart(messageBodyPart);
// Add attachments, if any
if (attachments != null) {
for (DataSource attachment : attachments) {
BodyPart attatchmentBodyPart = new MimeBodyPart();
attatchmentBodyPart.setDataHandler(new DataHandler(attachment));
attatchmentBodyPart.setFileName(attachment.getName());
multipart.addBodyPart(attatchmentBodyPart);
}
}
}
return message;
} catch (AddressException e) {
throw new RuntimeException(e);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static MimeMessage createMimeMessage(Session session, String from, String[] to, String subject, String content, DataSource[] attachments) {
logger.debug("Creates a mime message with {} attachments", (attachments == null) ? 0 : attachments.length);
try {
MimeMessage message = new MimeMessage(session);
if (from != null) {
message.setSender(new InternetAddress(from)); // depends on control dependency: [if], data = [(from]
}
if (subject != null) {
message.setSubject(subject, "UTF-8"); // depends on control dependency: [if], data = [(subject]
}
if (to != null) {
for (String toAdr : to) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAdr)); // depends on control dependency: [for], data = [toAdr]
}
}
if (attachments == null || attachments.length == 0) {
// Setup a plain text message
message.setContent(content, "text/plain; charset=UTF-8"); // depends on control dependency: [if], data = [none]
} else {
// Setup a multipart message
Multipart multipart = new MimeMultipart();
message.setContent(multipart); // depends on control dependency: [if], data = [none]
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(content, "text/plain; charset=UTF-8"); // depends on control dependency: [if], data = [none]
multipart.addBodyPart(messageBodyPart); // depends on control dependency: [if], data = [none]
// Add attachments, if any
if (attachments != null) {
for (DataSource attachment : attachments) {
BodyPart attatchmentBodyPart = new MimeBodyPart();
attatchmentBodyPart.setDataHandler(new DataHandler(attachment)); // depends on control dependency: [for], data = [attachment]
attatchmentBodyPart.setFileName(attachment.getName()); // depends on control dependency: [for], data = [attachment]
multipart.addBodyPart(attatchmentBodyPart); // depends on control dependency: [for], data = [none]
}
}
}
return message; // depends on control dependency: [try], data = [none]
} catch (AddressException e) {
throw new RuntimeException(e);
} catch (MessagingException e) { // depends on control dependency: [catch], data = [none]
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <T, X extends Throwable> Tuple3<CompletableFuture<Subscription>, Runnable, CompletableFuture<Boolean>> forEachEvent(
final Stream<T> stream, final Consumer<? super T> consumerElement, final Consumer<? super Throwable> consumerError,
final Runnable onComplete) {
final CompletableFuture<Subscription> subscription = new CompletableFuture<>();
final CompletableFuture<Boolean> streamCompleted = new CompletableFuture<>();
return tuple(subscription, () -> {
final Iterator<T> it = stream.iterator();
final Object UNSET = new Object();
Streams.stream(new Iterator<T>() {
boolean errored = false;
@Override
public boolean hasNext() {
boolean result = false;
try {
result = it.hasNext();
return result;
} catch (final Throwable t) {
consumerError.accept(t);
errored = true;
return true;
} finally {
if (!result && !errored) {
try {
onComplete.run();
} finally {
streamCompleted.complete(true);
}
}
}
}
@Override
public T next() {
try {
if (errored)
return (T) UNSET;
else {
try {
return it.next();
}catch(Throwable t){
consumerError.accept(t);
return (T) UNSET;
}
}
} finally {
errored = false;
}
}
})
.filter(t -> t != UNSET)
.forEach(consumerElement);
} , streamCompleted);
} } | public class class_name {
public static <T, X extends Throwable> Tuple3<CompletableFuture<Subscription>, Runnable, CompletableFuture<Boolean>> forEachEvent(
final Stream<T> stream, final Consumer<? super T> consumerElement, final Consumer<? super Throwable> consumerError,
final Runnable onComplete) {
final CompletableFuture<Subscription> subscription = new CompletableFuture<>();
final CompletableFuture<Boolean> streamCompleted = new CompletableFuture<>();
return tuple(subscription, () -> {
final Iterator<T> it = stream.iterator();
final Object UNSET = new Object();
Streams.stream(new Iterator<T>() {
boolean errored = false;
@Override
public boolean hasNext() {
boolean result = false;
try {
result = it.hasNext(); // depends on control dependency: [try], data = [none]
return result; // depends on control dependency: [try], data = [none]
} catch (final Throwable t) {
consumerError.accept(t);
errored = true;
return true;
} finally { // depends on control dependency: [catch], data = [none]
if (!result && !errored) {
try {
onComplete.run(); // depends on control dependency: [try], data = [none]
} finally {
streamCompleted.complete(true);
}
}
}
}
@Override
public T next() {
try {
if (errored)
return (T) UNSET;
else {
try {
return it.next(); // depends on control dependency: [try], data = [none]
}catch(Throwable t){
consumerError.accept(t);
return (T) UNSET;
} // depends on control dependency: [catch], data = [none]
}
} finally {
errored = false;
}
}
})
.filter(t -> t != UNSET)
.forEach(consumerElement);
} , streamCompleted);
} } |
public class class_name {
public void marshall(DeleteUserPoolClientRequest deleteUserPoolClientRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteUserPoolClientRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteUserPoolClientRequest.getUserPoolId(), USERPOOLID_BINDING);
protocolMarshaller.marshall(deleteUserPoolClientRequest.getClientId(), CLIENTID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DeleteUserPoolClientRequest deleteUserPoolClientRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteUserPoolClientRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteUserPoolClientRequest.getUserPoolId(), USERPOOLID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(deleteUserPoolClientRequest.getClientId(), CLIENTID_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 <T extends StatementTree> Matcher<T> previousStatement(
Matcher<StatementTree> matcher) {
return (T statement, VisitorState state) -> {
BlockTree block = state.findEnclosing(BlockTree.class);
if (block == null) {
return false;
}
List<? extends StatementTree> statements = block.getStatements();
int idx = statements.indexOf(statement);
if (idx <= 0) {
// The block wrapping us doesn't contain this statement, or doesn't contain a previous
// statement.
return false;
}
return matcher.matches(statements.get(idx - 1), state);
};
} } | public class class_name {
public static <T extends StatementTree> Matcher<T> previousStatement(
Matcher<StatementTree> matcher) {
return (T statement, VisitorState state) -> {
BlockTree block = state.findEnclosing(BlockTree.class);
if (block == null) {
return false; // depends on control dependency: [if], data = [none]
}
List<? extends StatementTree> statements = block.getStatements();
int idx = statements.indexOf(statement);
if (idx <= 0) {
// The block wrapping us doesn't contain this statement, or doesn't contain a previous
// statement.
return false; // depends on control dependency: [if], data = [none]
}
return matcher.matches(statements.get(idx - 1), state);
};
} } |
public class class_name {
private Map<Object, Object> getPackagedWarManifestAttributes() {
Map<Object, Object> manifestAttributes = null;
try {
LOGGER.debug("Using Manifest file:{}", servletContext.getResource(MANIFEST).getPath());
Manifest manifest = new Manifest(servletContext.getResourceAsStream(MANIFEST));
manifestAttributes = manifest.getMainAttributes();
} catch (Exception e) {
LOGGER.warn("Unable to read the manifest from the packaged war");
LOGGER.debug("Unable to read the manifest from the packaged", e);
}
return manifestAttributes;
} } | public class class_name {
private Map<Object, Object> getPackagedWarManifestAttributes() {
Map<Object, Object> manifestAttributes = null;
try {
LOGGER.debug("Using Manifest file:{}", servletContext.getResource(MANIFEST).getPath());
// depends on control dependency: [try], data = [none]
Manifest manifest = new Manifest(servletContext.getResourceAsStream(MANIFEST));
manifestAttributes = manifest.getMainAttributes();
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
LOGGER.warn("Unable to read the manifest from the packaged war");
LOGGER.debug("Unable to read the manifest from the packaged", e);
}
// depends on control dependency: [catch], data = [none]
return manifestAttributes;
} } |
public class class_name {
public static int indexOf(final CharSequence cs, final char searchChar, int start) {
if (cs instanceof String) {
return ((String) cs).indexOf(searchChar, start);
} else if (cs instanceof AsciiString) {
return ((AsciiString) cs).indexOf(searchChar, start);
}
if (cs == null) {
return INDEX_NOT_FOUND;
}
final int sz = cs.length();
for (int i = start < 0 ? 0 : start; i < sz; i++) {
if (cs.charAt(i) == searchChar) {
return i;
}
}
return INDEX_NOT_FOUND;
} } | public class class_name {
public static int indexOf(final CharSequence cs, final char searchChar, int start) {
if (cs instanceof String) {
return ((String) cs).indexOf(searchChar, start); // depends on control dependency: [if], data = [none]
} else if (cs instanceof AsciiString) {
return ((AsciiString) cs).indexOf(searchChar, start); // depends on control dependency: [if], data = [none]
}
if (cs == null) {
return INDEX_NOT_FOUND; // depends on control dependency: [if], data = [none]
}
final int sz = cs.length();
for (int i = start < 0 ? 0 : start; i < sz; i++) {
if (cs.charAt(i) == searchChar) {
return i; // depends on control dependency: [if], data = [none]
}
}
return INDEX_NOT_FOUND;
} } |
public class class_name {
private static String resolvePrincipal(Session session) {
String principalName = session
.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
if (principalName != null) {
return principalName;
}
SecurityContext securityContext = session
.getAttribute(SPRING_SECURITY_CONTEXT);
if (securityContext != null
&& securityContext.getAuthentication() != null) {
return securityContext.getAuthentication().getName();
}
return "";
} } | public class class_name {
private static String resolvePrincipal(Session session) {
String principalName = session
.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
if (principalName != null) {
return principalName; // depends on control dependency: [if], data = [none]
}
SecurityContext securityContext = session
.getAttribute(SPRING_SECURITY_CONTEXT);
if (securityContext != null
&& securityContext.getAuthentication() != null) {
return securityContext.getAuthentication().getName(); // depends on control dependency: [if], data = [none]
}
return "";
} } |
public class class_name {
public static void prepareX509Infrastructure(X509Metadata metadata, File serverKeyStore, File serverTrustStore, X509Log x509log) {
// make the specified folder, if necessary
File folder = serverKeyStore.getParentFile();
folder.mkdirs();
// Fathom CA certificate
File caKeyStore = new File(folder, CA_KEY_STORE);
if (!caKeyStore.exists()) {
logger.info(MessageFormat.format("Generating {0} ({1})", CA_CN, caKeyStore.getAbsolutePath()));
X509Certificate caCert = newCertificateAuthority(metadata, caKeyStore, x509log);
saveCertificate(caCert, new File(caKeyStore.getParentFile(), "ca.cer"));
}
// Fathom CRL
File caRevocationList = new File(folder, CA_REVOCATION_LIST);
if (!caRevocationList.exists()) {
logger.info(MessageFormat.format("Generating {0} CRL ({1})", CA_CN, caRevocationList.getAbsolutePath()));
newCertificateRevocationList(caRevocationList, caKeyStore, metadata.password);
x509log.log("new certificate revocation list created");
}
// create web SSL certificate signed by CA
if (!serverKeyStore.exists()) {
logger.info(MessageFormat.format("Generating SSL certificate for {0} signed by {1} ({2})", metadata.commonName, CA_CN, serverKeyStore.getAbsolutePath()));
PrivateKey caPrivateKey = getPrivateKey(CA_ALIAS, caKeyStore, metadata.password);
X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
newSSLCertificate(metadata, caPrivateKey, caCert, serverKeyStore, x509log);
}
// server certificate trust store holds trusted public certificates
if (!serverTrustStore.exists()) {
logger.info(MessageFormat.format("Importing {0} into trust store ({1})", CA_ALIAS, serverTrustStore.getAbsolutePath()));
X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
addTrustedCertificate(CA_ALIAS, caCert, serverTrustStore, metadata.password);
}
} } | public class class_name {
public static void prepareX509Infrastructure(X509Metadata metadata, File serverKeyStore, File serverTrustStore, X509Log x509log) {
// make the specified folder, if necessary
File folder = serverKeyStore.getParentFile();
folder.mkdirs();
// Fathom CA certificate
File caKeyStore = new File(folder, CA_KEY_STORE);
if (!caKeyStore.exists()) {
logger.info(MessageFormat.format("Generating {0} ({1})", CA_CN, caKeyStore.getAbsolutePath())); // depends on control dependency: [if], data = [none]
X509Certificate caCert = newCertificateAuthority(metadata, caKeyStore, x509log);
saveCertificate(caCert, new File(caKeyStore.getParentFile(), "ca.cer")); // depends on control dependency: [if], data = [none]
}
// Fathom CRL
File caRevocationList = new File(folder, CA_REVOCATION_LIST);
if (!caRevocationList.exists()) {
logger.info(MessageFormat.format("Generating {0} CRL ({1})", CA_CN, caRevocationList.getAbsolutePath())); // depends on control dependency: [if], data = [none]
newCertificateRevocationList(caRevocationList, caKeyStore, metadata.password); // depends on control dependency: [if], data = [none]
x509log.log("new certificate revocation list created"); // depends on control dependency: [if], data = [none]
}
// create web SSL certificate signed by CA
if (!serverKeyStore.exists()) {
logger.info(MessageFormat.format("Generating SSL certificate for {0} signed by {1} ({2})", metadata.commonName, CA_CN, serverKeyStore.getAbsolutePath())); // depends on control dependency: [if], data = [none]
PrivateKey caPrivateKey = getPrivateKey(CA_ALIAS, caKeyStore, metadata.password);
X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
newSSLCertificate(metadata, caPrivateKey, caCert, serverKeyStore, x509log); // depends on control dependency: [if], data = [none]
}
// server certificate trust store holds trusted public certificates
if (!serverTrustStore.exists()) {
logger.info(MessageFormat.format("Importing {0} into trust store ({1})", CA_ALIAS, serverTrustStore.getAbsolutePath())); // depends on control dependency: [if], data = [none]
X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
addTrustedCertificate(CA_ALIAS, caCert, serverTrustStore, metadata.password); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void processEvent(EventModel<?> event) {
if (!event.getSource().isCreatedFromInstance()) {
error("event: " + event + "has invalid source");
return;
}
debug("EventFired: " + event.toString() + " from " + event.getSource().getID());
submit(() -> event.lifecycleCallback(EventLifeCycle.START));
if (checkEventsControllers(event)) {
submit(() -> event.lifecycleCallback(EventLifeCycle.APPROVED));
submit(() -> event.lifecycleCallback(EventLifeCycle.RESOURCE));
List<ResourceModel> resourceList = getMain().getResourceManager().generateResources(event);
event.addResources(resourceList);
submit(() -> event.lifecycleCallback(EventLifeCycle.LISTENERS));
List<EventListenerModel> listenersTemp = event.getAllInformations().parallelStream()
.map(listeners::get)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
List<CompletableFuture> futures = listenersTemp.stream()
.map(eventListener -> submit(() -> eventListener.eventFired(event)))
.collect(Collectors.toList());
try {
timeOut(futures, 1000);
} catch (InterruptedException e) {
error("interrupted", e);
}
submit(() -> event.lifecycleCallback(EventLifeCycle.OUTPUT));
getMain().getOutputManager().passDataToOutputPlugins(event);
submit(() -> event.lifecycleCallback(EventLifeCycle.ENDED));
List<EventListenerModel> finishListenersTemp = event.getAllInformations().parallelStream()
.map(finishListeners::get)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
futures = finishListenersTemp.stream()
.map(eventListener -> submit(() -> eventListener.eventFired(event)))
.collect(Collectors.toList());
try {
timeOut(futures, 1000);
} catch (InterruptedException e) {
error("interrupted", e);
}
} else {
debug("canceling: " + event.toString() + " from " + event.getSource().getID());
submit(() -> event.lifecycleCallback(EventLifeCycle.CANCELED));
}
} } | public class class_name {
private void processEvent(EventModel<?> event) {
if (!event.getSource().isCreatedFromInstance()) {
error("event: " + event + "has invalid source"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
debug("EventFired: " + event.toString() + " from " + event.getSource().getID());
submit(() -> event.lifecycleCallback(EventLifeCycle.START));
if (checkEventsControllers(event)) {
submit(() -> event.lifecycleCallback(EventLifeCycle.APPROVED)); // depends on control dependency: [if], data = [none]
submit(() -> event.lifecycleCallback(EventLifeCycle.RESOURCE)); // depends on control dependency: [if], data = [none]
List<ResourceModel> resourceList = getMain().getResourceManager().generateResources(event);
event.addResources(resourceList); // depends on control dependency: [if], data = [none]
submit(() -> event.lifecycleCallback(EventLifeCycle.LISTENERS)); // depends on control dependency: [if], data = [none]
List<EventListenerModel> listenersTemp = event.getAllInformations().parallelStream()
.map(listeners::get)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
List<CompletableFuture> futures = listenersTemp.stream()
.map(eventListener -> submit(() -> eventListener.eventFired(event)))
.collect(Collectors.toList());
try {
timeOut(futures, 1000); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
error("interrupted", e);
} // depends on control dependency: [catch], data = [none]
submit(() -> event.lifecycleCallback(EventLifeCycle.OUTPUT)); // depends on control dependency: [if], data = [none]
getMain().getOutputManager().passDataToOutputPlugins(event); // depends on control dependency: [if], data = [none]
submit(() -> event.lifecycleCallback(EventLifeCycle.ENDED)); // depends on control dependency: [if], data = [none]
List<EventListenerModel> finishListenersTemp = event.getAllInformations().parallelStream()
.map(finishListeners::get)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
futures = finishListenersTemp.stream()
.map(eventListener -> submit(() -> eventListener.eventFired(event)))
.collect(Collectors.toList()); // depends on control dependency: [if], data = [none]
try {
timeOut(futures, 1000); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
error("interrupted", e);
} // depends on control dependency: [catch], data = [none]
} else {
debug("canceling: " + event.toString() + " from " + event.getSource().getID()); // depends on control dependency: [if], data = [none]
submit(() -> event.lifecycleCallback(EventLifeCycle.CANCELED)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void visitToken(DetailAST token) {
// Failed to load ServiceClient's class, don't validate anything.
if (this.serviceClientClass == null) {
return;
}
switch (token.getType()) {
case TokenTypes.PACKAGE_DEF:
this.extendsServiceClient = extendsServiceClient(token);
break;
case TokenTypes.CTOR_DEF:
if (this.extendsServiceClient && visibilityIsPublicOrProtected(token)) {
log(token, CONSTRUCTOR_ERROR_MESSAGE);
}
break;
case TokenTypes.METHOD_DEF:
if (this.extendsServiceClient && !this.hasStaticBuilder && methodIsStaticBuilder(token)) {
this.hasStaticBuilder = true;
}
break;
}
} } | public class class_name {
@Override
public void visitToken(DetailAST token) {
// Failed to load ServiceClient's class, don't validate anything.
if (this.serviceClientClass == null) {
return; // depends on control dependency: [if], data = [none]
}
switch (token.getType()) {
case TokenTypes.PACKAGE_DEF:
this.extendsServiceClient = extendsServiceClient(token);
break;
case TokenTypes.CTOR_DEF:
if (this.extendsServiceClient && visibilityIsPublicOrProtected(token)) {
log(token, CONSTRUCTOR_ERROR_MESSAGE); // depends on control dependency: [if], data = [none]
}
break;
case TokenTypes.METHOD_DEF:
if (this.extendsServiceClient && !this.hasStaticBuilder && methodIsStaticBuilder(token)) {
this.hasStaticBuilder = true; // depends on control dependency: [if], data = [none]
}
break;
}
} } |
public class class_name {
private static boolean turnOffClientInterface() {
// we don't expect this to ever fail, but if it does, skip to dying immediately
VoltDBInterface vdbInstance = instance();
if (vdbInstance != null) {
ClientInterface ci = vdbInstance.getClientInterface();
if (ci != null) {
if (!ci.ceaseAllPublicFacingTrafficImmediately()) {
return false;
}
}
}
return true;
} } | public class class_name {
private static boolean turnOffClientInterface() {
// we don't expect this to ever fail, but if it does, skip to dying immediately
VoltDBInterface vdbInstance = instance();
if (vdbInstance != null) {
ClientInterface ci = vdbInstance.getClientInterface();
if (ci != null) {
if (!ci.ceaseAllPublicFacingTrafficImmediately()) {
return false; // depends on control dependency: [if], data = [none]
}
}
}
return true;
} } |
public class class_name {
public void setValue(Object newValue) {
synchronized (lock) {
// Allow only once.
if (ready) {
return;
}
result = newValue;
ready = true;
if (waiters > 0) {
lock.notifyAll();
}
}
notifyListeners();
} } | public class class_name {
public void setValue(Object newValue) {
synchronized (lock) {
// Allow only once.
if (ready) {
return; // depends on control dependency: [if], data = [none]
}
result = newValue;
ready = true;
if (waiters > 0) {
lock.notifyAll(); // depends on control dependency: [if], data = [none]
}
}
notifyListeners();
} } |
public class class_name {
public long getPreviousSequenceId()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getPreviousSequenceId");
long previousSequenceID=0;
try
{
SIMPMessage msg = getSIMPMessage();
if(msg!=null)
{
previousSequenceID = msg.getMessage().getGuaranteedValueStartTick()-1;
}
}
catch (SIResourceException e)
{
// No FFDC code needed
SibTr.exception(tc, e);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getPreviousSequenceId", Long.valueOf(previousSequenceID));
return previousSequenceID;
} } | public class class_name {
public long getPreviousSequenceId()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getPreviousSequenceId");
long previousSequenceID=0;
try
{
SIMPMessage msg = getSIMPMessage();
if(msg!=null)
{
previousSequenceID = msg.getMessage().getGuaranteedValueStartTick()-1; // depends on control dependency: [if], data = [none]
}
}
catch (SIResourceException e)
{
// No FFDC code needed
SibTr.exception(tc, e);
} // depends on control dependency: [catch], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getPreviousSequenceId", Long.valueOf(previousSequenceID));
return previousSequenceID;
} } |
public class class_name {
private static Method[] getMethods(Object object) {
Method[] methods = methodCache.get(object.getClass());
if (methods == null) {
methods = object.getClass().getMethods();
methodCache.put(object.getClass(), methods);
}
return methods;
} } | public class class_name {
private static Method[] getMethods(Object object) {
Method[] methods = methodCache.get(object.getClass());
if (methods == null) {
methods = object.getClass().getMethods(); // depends on control dependency: [if], data = [none]
methodCache.put(object.getClass(), methods); // depends on control dependency: [if], data = [none]
}
return methods;
} } |
public class class_name {
public static String streamToString(InputStream is, String name, Integer numberOfLines) {
String result = null;
try {
try {
if (numberOfLines == null) {
// read complete file into string
result = new Scanner(is, FILE_ENCODING).useDelimiter("\\A").next();
} else {
// read only given number of lines
Scanner scanner = new Scanner(is, FILE_ENCODING);
int resultNrOfLines = 1;
result = "";
while (scanner.hasNext()) {
result = result + scanner.nextLine() + System.lineSeparator();
if (++resultNrOfLines > numberOfLines) {
break;
}
}
scanner.close();
if (result.isEmpty()) {
result = null;
}
}
} catch (java.util.NoSuchElementException e) {
throw new IllegalStateException("Unable to read: " + name + ". Error: " + e.getMessage(), e);
}
} finally {
try {
is.close();
} catch (IOException e) {
// what the hell?!
throw new RuntimeException("Unable to close: " + name, e);
}
}
return result;
} } | public class class_name {
public static String streamToString(InputStream is, String name, Integer numberOfLines) {
String result = null;
try {
try {
if (numberOfLines == null) {
// read complete file into string
result = new Scanner(is, FILE_ENCODING).useDelimiter("\\A").next(); // depends on control dependency: [if], data = [none]
} else {
// read only given number of lines
Scanner scanner = new Scanner(is, FILE_ENCODING);
int resultNrOfLines = 1;
result = ""; // depends on control dependency: [if], data = [none]
while (scanner.hasNext()) {
result = result + scanner.nextLine() + System.lineSeparator(); // depends on control dependency: [while], data = [none]
if (++resultNrOfLines > numberOfLines) {
break;
}
}
scanner.close(); // depends on control dependency: [if], data = [none]
if (result.isEmpty()) {
result = null; // depends on control dependency: [if], data = [none]
}
}
} catch (java.util.NoSuchElementException e) {
throw new IllegalStateException("Unable to read: " + name + ". Error: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} finally {
try {
is.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
// what the hell?!
throw new RuntimeException("Unable to close: " + name, e);
} // depends on control dependency: [catch], data = [none]
}
return result;
} } |
public class class_name {
private void signalOnSizeThresholdCrossing(long oldSize, long newSize)
{
if (signalable != null)
{
if ((oldSize >= lowWaterSizeThreshold) && (newSize < lowWaterSizeThreshold))
{
signalable.signalAll();
}
else if ((oldSize >= highWaterSizeThreshold) && (newSize < highWaterSizeThreshold))
{
signalable.signal();
}
}
} } | public class class_name {
private void signalOnSizeThresholdCrossing(long oldSize, long newSize)
{
if (signalable != null)
{
if ((oldSize >= lowWaterSizeThreshold) && (newSize < lowWaterSizeThreshold))
{
signalable.signalAll(); // depends on control dependency: [if], data = [none]
}
else if ((oldSize >= highWaterSizeThreshold) && (newSize < highWaterSizeThreshold))
{
signalable.signal(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private void installModuleMBeanServer() {
try {
Method method = ModuleLoader.class.getDeclaredMethod("installMBeanServer");
method.setAccessible(true);
method.invoke(null);
} catch (Exception e) {
SwarmMessages.MESSAGES.moduleMBeanServerNotInstalled(e);
}
} } | public class class_name {
private void installModuleMBeanServer() {
try {
Method method = ModuleLoader.class.getDeclaredMethod("installMBeanServer");
method.setAccessible(true); // depends on control dependency: [try], data = [none]
method.invoke(null); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
SwarmMessages.MESSAGES.moduleMBeanServerNotInstalled(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static File substituteExtention( File file, String newExtention ) {
String path = file.getAbsolutePath();
int lastDot = path.lastIndexOf("."); //$NON-NLS-1$
if (lastDot == -1) {
path = path + "." + newExtention; //$NON-NLS-1$
} else {
path = path.substring(0, lastDot) + "." + newExtention; //$NON-NLS-1$
}
return new File(path);
} } | public class class_name {
public static File substituteExtention( File file, String newExtention ) {
String path = file.getAbsolutePath();
int lastDot = path.lastIndexOf("."); //$NON-NLS-1$
if (lastDot == -1) {
path = path + "." + newExtention; //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
} else {
path = path.substring(0, lastDot) + "." + newExtention; //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
return new File(path);
} } |
public class class_name {
@Override
public EClass getIfcDistributionFlowElement() {
if (ifcDistributionFlowElementEClass == null) {
ifcDistributionFlowElementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(185);
}
return ifcDistributionFlowElementEClass;
} } | public class class_name {
@Override
public EClass getIfcDistributionFlowElement() {
if (ifcDistributionFlowElementEClass == null) {
ifcDistributionFlowElementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(185);
// depends on control dependency: [if], data = [none]
}
return ifcDistributionFlowElementEClass;
} } |
public class class_name {
@Override
public String getSqlWithValues() {
final StringBuilder sb = new StringBuilder();
final String statementQuery = getStatementQuery();
// iterate over the characters in the query replacing the parameter placeholders
// with the actual values
int currentParameter = 0;
for( int pos = 0; pos < statementQuery.length(); pos ++) {
char character = statementQuery.charAt(pos);
if( statementQuery.charAt(pos) == '?' && currentParameter <= parameterValues.size()) {
// replace with parameter value
Value value = parameterValues.get(currentParameter);
sb.append(value != null ? value.toString() : new Value().toString());
currentParameter++;
} else {
sb.append(character);
}
}
return sb.toString();
} } | public class class_name {
@Override
public String getSqlWithValues() {
final StringBuilder sb = new StringBuilder();
final String statementQuery = getStatementQuery();
// iterate over the characters in the query replacing the parameter placeholders
// with the actual values
int currentParameter = 0;
for( int pos = 0; pos < statementQuery.length(); pos ++) {
char character = statementQuery.charAt(pos);
if( statementQuery.charAt(pos) == '?' && currentParameter <= parameterValues.size()) {
// replace with parameter value
Value value = parameterValues.get(currentParameter);
sb.append(value != null ? value.toString() : new Value().toString()); // depends on control dependency: [if], data = [none]
currentParameter++; // depends on control dependency: [if], data = [none]
} else {
sb.append(character); // depends on control dependency: [if], data = [none]
}
}
return sb.toString();
} } |
public class class_name {
private static boolean checkCaseCanonical(final File file, String pathToTest) throws PrivilegedActionException {
// The canonical path returns the actual path on the file system so get this
String onDiskCanonicalPath = AccessController.doPrivileged(new PrivilegedExceptionAction<String>() {
/** {@inheritDoc} */
@Override
public String run() throws IOException {
return file.getCanonicalPath();
}
});
onDiskCanonicalPath = onDiskCanonicalPath.replace("\\", "/");
// The trailing / on a file name is optional so add it if this is a directory
final String expectedEnding;
if (onDiskCanonicalPath.endsWith("/")) {
if (pathToTest.endsWith("/")) {
expectedEnding = pathToTest;
} else {
expectedEnding = pathToTest + "/";
}
} else {
if (pathToTest.endsWith("/")) {
expectedEnding = pathToTest.substring(0, pathToTest.length() - 1);
} else {
expectedEnding = pathToTest;
}
}
if (expectedEnding.isEmpty()) {
// Nothing to compare so case must match
return true;
}
return onDiskCanonicalPath.endsWith(expectedEnding);
} } | public class class_name {
private static boolean checkCaseCanonical(final File file, String pathToTest) throws PrivilegedActionException {
// The canonical path returns the actual path on the file system so get this
String onDiskCanonicalPath = AccessController.doPrivileged(new PrivilegedExceptionAction<String>() {
/** {@inheritDoc} */
@Override
public String run() throws IOException {
return file.getCanonicalPath();
}
});
onDiskCanonicalPath = onDiskCanonicalPath.replace("\\", "/");
// The trailing / on a file name is optional so add it if this is a directory
final String expectedEnding;
if (onDiskCanonicalPath.endsWith("/")) {
if (pathToTest.endsWith("/")) {
expectedEnding = pathToTest; // depends on control dependency: [if], data = [none]
} else {
expectedEnding = pathToTest + "/"; // depends on control dependency: [if], data = [none]
}
} else {
if (pathToTest.endsWith("/")) {
expectedEnding = pathToTest.substring(0, pathToTest.length() - 1); // depends on control dependency: [if], data = [none]
} else {
expectedEnding = pathToTest; // depends on control dependency: [if], data = [none]
}
}
if (expectedEnding.isEmpty()) {
// Nothing to compare so case must match
return true;
}
return onDiskCanonicalPath.endsWith(expectedEnding);
} } |
public class class_name {
public E pollAccept(Object owner)
{
if (transactional)
{
E element = null;
RequeueElementWrapper<E> record = null;
// Find an element on the requeue that is free, or has already been acquired by the owner but not accepted.
// Mark the element as acquired by the owner as necessary.
if (!requeue.isEmpty())
{
for (RequeueElementWrapper<E> nextRecord : requeue)
{
if (AcquireState.Free.equals(nextRecord.state))
{
record = nextRecord;
record.state = AcquireState.Acquired;
record.owner = owner;
element = record.element;
break;
}
else if (AcquireState.Acquired.equals(nextRecord.state) && owner.equals(nextRecord.owner))
{
record = nextRecord;
element = record.element;
break;
}
}
}
// If an element cannot be found on the requeue, poll an element from the main queue, and place it onto the
// requeue.
if (record == null)
{
element = queue.poll();
}
// If no element at all can be found return null.
if (element == null)
{
return element;
}
// Check that an element was actually available on the queue before creating a new acquired record for it
// on the requeue.
if (record == null)
{
record = requeue(element, owner, AcquireState.Acquired);
}
// Accept the element and create a transaction operation to remove it upon commit or unnaccept it upon
// rollback.
record.state = AcquireState.Accepted;
txMethod.requestWriteOperation(new AcceptRecord(record));
return record.element;
}
else
{
E element;
// Find an element on the requeue that is free. Remove it and return it.
if (!requeue.isEmpty())
{
for (RequeueElementWrapper<E> nextRecord : requeue)
{
if (AcquireState.Free.equals(nextRecord.state))
{
requeue.remove(nextRecord);
requeuedElementMap.remove(nextRecord.element);
return nextRecord.element;
}
}
}
// Or poll an element from the main queue and return it.
element = queue.poll();
if (element != null)
{
decrementSizeAndCount(element);
}
return element;
}
} } | public class class_name {
public E pollAccept(Object owner)
{
if (transactional)
{
E element = null;
RequeueElementWrapper<E> record = null;
// Find an element on the requeue that is free, or has already been acquired by the owner but not accepted.
// Mark the element as acquired by the owner as necessary.
if (!requeue.isEmpty())
{
for (RequeueElementWrapper<E> nextRecord : requeue)
{
if (AcquireState.Free.equals(nextRecord.state))
{
record = nextRecord; // depends on control dependency: [if], data = [none]
record.state = AcquireState.Acquired; // depends on control dependency: [if], data = [none]
record.owner = owner; // depends on control dependency: [if], data = [none]
element = record.element; // depends on control dependency: [if], data = [none]
break;
}
else if (AcquireState.Acquired.equals(nextRecord.state) && owner.equals(nextRecord.owner))
{
record = nextRecord; // depends on control dependency: [if], data = [none]
element = record.element; // depends on control dependency: [if], data = [none]
break;
}
}
}
// If an element cannot be found on the requeue, poll an element from the main queue, and place it onto the
// requeue.
if (record == null)
{
element = queue.poll(); // depends on control dependency: [if], data = [none]
}
// If no element at all can be found return null.
if (element == null)
{
return element; // depends on control dependency: [if], data = [none]
}
// Check that an element was actually available on the queue before creating a new acquired record for it
// on the requeue.
if (record == null)
{
record = requeue(element, owner, AcquireState.Acquired); // depends on control dependency: [if], data = [none]
}
// Accept the element and create a transaction operation to remove it upon commit or unnaccept it upon
// rollback.
record.state = AcquireState.Accepted; // depends on control dependency: [if], data = [none]
txMethod.requestWriteOperation(new AcceptRecord(record)); // depends on control dependency: [if], data = [none]
return record.element; // depends on control dependency: [if], data = [none]
}
else
{
E element;
// Find an element on the requeue that is free. Remove it and return it.
if (!requeue.isEmpty())
{
for (RequeueElementWrapper<E> nextRecord : requeue)
{
if (AcquireState.Free.equals(nextRecord.state))
{
requeue.remove(nextRecord); // depends on control dependency: [if], data = [none]
requeuedElementMap.remove(nextRecord.element); // depends on control dependency: [if], data = [none]
return nextRecord.element; // depends on control dependency: [if], data = [none]
}
}
}
// Or poll an element from the main queue and return it.
element = queue.poll(); // depends on control dependency: [if], data = [none]
if (element != null)
{
decrementSizeAndCount(element); // depends on control dependency: [if], data = [(element]
}
return element; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
void changeDragViewViewAlpha() {
if (enableHorizontalAlphaEffect) {
float alpha = 1 - getHorizontalDragOffset();
if (alpha == 0) {
alpha = 1;
}
ViewHelper.setAlpha(dragView, alpha);
}
} } | public class class_name {
void changeDragViewViewAlpha() {
if (enableHorizontalAlphaEffect) {
float alpha = 1 - getHorizontalDragOffset();
if (alpha == 0) {
alpha = 1; // depends on control dependency: [if], data = [none]
}
ViewHelper.setAlpha(dragView, alpha); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void clearAccordion()
{
List<JComponent> components =
new ArrayList<JComponent>(collapsiblePanels.keySet());
for (JComponent component : components)
{
removeFromAccordion(component);
}
} } | public class class_name {
public void clearAccordion()
{
List<JComponent> components =
new ArrayList<JComponent>(collapsiblePanels.keySet());
for (JComponent component : components)
{
removeFromAccordion(component);
// depends on control dependency: [for], data = [component]
}
} } |
public class class_name {
private CmsPublishOptions getCachedOptions() {
CmsPublishOptions cache = (CmsPublishOptions)getRequest().getSession().getAttribute(
SESSION_ATTR_ADE_PUB_OPTS_CACHE);
if (cache == null) {
CmsUserSettings settings = new CmsUserSettings(getCmsObject());
cache = new CmsPublishOptions();
cache.setIncludeSiblings(settings.getDialogPublishSiblings());
getRequest().getSession().setAttribute(SESSION_ATTR_ADE_PUB_OPTS_CACHE, cache);
}
return cache;
} } | public class class_name {
private CmsPublishOptions getCachedOptions() {
CmsPublishOptions cache = (CmsPublishOptions)getRequest().getSession().getAttribute(
SESSION_ATTR_ADE_PUB_OPTS_CACHE);
if (cache == null) {
CmsUserSettings settings = new CmsUserSettings(getCmsObject());
cache = new CmsPublishOptions(); // depends on control dependency: [if], data = [none]
cache.setIncludeSiblings(settings.getDialogPublishSiblings()); // depends on control dependency: [if], data = [none]
getRequest().getSession().setAttribute(SESSION_ATTR_ADE_PUB_OPTS_CACHE, cache); // depends on control dependency: [if], data = [none]
}
return cache;
} } |
public class class_name {
@Override
public void cacheResult(List<CPRule> cpRules) {
for (CPRule cpRule : cpRules) {
if (entityCache.getResult(CPRuleModelImpl.ENTITY_CACHE_ENABLED,
CPRuleImpl.class, cpRule.getPrimaryKey()) == null) {
cacheResult(cpRule);
}
else {
cpRule.resetOriginalValues();
}
}
} } | public class class_name {
@Override
public void cacheResult(List<CPRule> cpRules) {
for (CPRule cpRule : cpRules) {
if (entityCache.getResult(CPRuleModelImpl.ENTITY_CACHE_ENABLED,
CPRuleImpl.class, cpRule.getPrimaryKey()) == null) {
cacheResult(cpRule); // depends on control dependency: [if], data = [none]
}
else {
cpRule.resetOriginalValues(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static void writeFile(File file, byte[] bytes) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(bytes);
} finally {
if (fos != null) {
fos.close();
}
}
} } | public class class_name {
public static void writeFile(File file, byte[] bytes) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(bytes);
} finally {
if (fos != null) {
fos.close(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static boolean isSDCardWritable() {
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states,
// but all we need
// to know is we can neither read nor write
mExternalStorageWriteable = false;
}
return mExternalStorageWriteable;
} } | public class class_name {
public static boolean isSDCardWritable() {
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageWriteable = true;
// depends on control dependency: [if], data = [none]
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageWriteable = false;
// depends on control dependency: [if], data = [none]
} else {
// Something else is wrong. It may be one of many other states,
// but all we need
// to know is we can neither read nor write
mExternalStorageWriteable = false;
// depends on control dependency: [if], data = [none]
}
return mExternalStorageWriteable;
} } |
public class class_name {
public static Object getEmptyValue(Type t)
{
if(byte.class.equals(t) || Byte.class.equals(t)) {
return (byte)0;
}
if(short.class.equals(t) || Short.class.equals(t)) {
return (short)0;
}
if(int.class.equals(t) || Integer.class.equals(t)) {
return (int)0;
}
if(long.class.equals(t) || Long.class.equals(t)) {
return (long)0;
}
if(float.class.equals(t) || Float.class.equals(t)) {
return (float)0;
}
if(double.class.equals(t) || Double.class.equals(t)) {
return (double)0;
}
if(Types.isBoolean(t)) {
return Boolean.valueOf(false);
}
if(Types.isCharacter(t)) {
return '\0';
}
if(String.class.equals(t)) {
return "";
}
if(Types.isDate(t)) {
return new Date();
}
if(Types.isCollection(t)) {
return Classes.newCollection(t);
}
if(Types.isArray(t)) {
Array.newInstance(((Class<?>)t).getComponentType(), 0);
}
return null;
} } | public class class_name {
public static Object getEmptyValue(Type t)
{
if(byte.class.equals(t) || Byte.class.equals(t)) {
return (byte)0;
// depends on control dependency: [if], data = [none]
}
if(short.class.equals(t) || Short.class.equals(t)) {
return (short)0;
// depends on control dependency: [if], data = [none]
}
if(int.class.equals(t) || Integer.class.equals(t)) {
return (int)0;
// depends on control dependency: [if], data = [none]
}
if(long.class.equals(t) || Long.class.equals(t)) {
return (long)0;
// depends on control dependency: [if], data = [none]
}
if(float.class.equals(t) || Float.class.equals(t)) {
return (float)0;
// depends on control dependency: [if], data = [none]
}
if(double.class.equals(t) || Double.class.equals(t)) {
return (double)0;
// depends on control dependency: [if], data = [none]
}
if(Types.isBoolean(t)) {
return Boolean.valueOf(false);
// depends on control dependency: [if], data = [none]
}
if(Types.isCharacter(t)) {
return '\0';
// depends on control dependency: [if], data = [none]
}
if(String.class.equals(t)) {
return "";
// depends on control dependency: [if], data = [none]
}
if(Types.isDate(t)) {
return new Date();
// depends on control dependency: [if], data = [none]
}
if(Types.isCollection(t)) {
return Classes.newCollection(t);
// depends on control dependency: [if], data = [none]
}
if(Types.isArray(t)) {
Array.newInstance(((Class<?>)t).getComponentType(), 0);
// depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public HttpResponse unzip() {
String contentEncoding = contentEncoding();
if (contentEncoding != null && contentEncoding().equals("gzip")) {
if (body != null) {
headerRemove(HEADER_CONTENT_ENCODING);
try {
ByteArrayInputStream in = new ByteArrayInputStream(body.getBytes(StringPool.ISO_8859_1));
GZIPInputStream gzipInputStream = new GZIPInputStream(in);
ByteArrayOutputStream out = new ByteArrayOutputStream();
StreamUtil.copy(gzipInputStream, out);
body(out.toString(StringPool.ISO_8859_1));
} catch (IOException ioex) {
throw new HttpException(ioex);
}
}
}
return this;
} } | public class class_name {
public HttpResponse unzip() {
String contentEncoding = contentEncoding();
if (contentEncoding != null && contentEncoding().equals("gzip")) {
if (body != null) {
headerRemove(HEADER_CONTENT_ENCODING); // depends on control dependency: [if], data = [none]
try {
ByteArrayInputStream in = new ByteArrayInputStream(body.getBytes(StringPool.ISO_8859_1));
GZIPInputStream gzipInputStream = new GZIPInputStream(in);
ByteArrayOutputStream out = new ByteArrayOutputStream();
StreamUtil.copy(gzipInputStream, out); // depends on control dependency: [try], data = [none]
body(out.toString(StringPool.ISO_8859_1)); // depends on control dependency: [try], data = [none]
} catch (IOException ioex) {
throw new HttpException(ioex);
} // depends on control dependency: [catch], data = [none]
}
}
return this;
} } |
public class class_name {
private void _initLogger(Map<String, ?> conf) {
boolean logEnabled = (Boolean) RythmConfigurationKey.LOG_ENABLED.getConfiguration(conf);
if (logEnabled) {
ILoggerFactory factory = RythmConfigurationKey.LOG_FACTORY_IMPL.getConfiguration(conf);
Logger.registerLoggerFactory(factory);
} else {
Logger.registerLoggerFactory(new NullLogger.Factory());
}
} } | public class class_name {
private void _initLogger(Map<String, ?> conf) {
boolean logEnabled = (Boolean) RythmConfigurationKey.LOG_ENABLED.getConfiguration(conf);
if (logEnabled) {
ILoggerFactory factory = RythmConfigurationKey.LOG_FACTORY_IMPL.getConfiguration(conf);
Logger.registerLoggerFactory(factory); // depends on control dependency: [if], data = [none]
} else {
Logger.registerLoggerFactory(new NullLogger.Factory()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void updateAfterMisfire (final ICalendar cal)
{
int instr = getMisfireInstruction ();
if (instr == ITrigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY)
return;
if (instr == MISFIRE_INSTRUCTION_SMART_POLICY)
{
instr = MISFIRE_INSTRUCTION_FIRE_ONCE_NOW;
}
if (instr == MISFIRE_INSTRUCTION_DO_NOTHING)
{
Date newFireTime = getFireTimeAfter (new Date ());
while (newFireTime != null && cal != null && !cal.isTimeIncluded (newFireTime.getTime ()))
{
newFireTime = getFireTimeAfter (newFireTime);
}
setNextFireTime (newFireTime);
}
else
if (instr == MISFIRE_INSTRUCTION_FIRE_ONCE_NOW)
{
setNextFireTime (new Date ());
}
} } | public class class_name {
@Override
public void updateAfterMisfire (final ICalendar cal)
{
int instr = getMisfireInstruction ();
if (instr == ITrigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY)
return;
if (instr == MISFIRE_INSTRUCTION_SMART_POLICY)
{
instr = MISFIRE_INSTRUCTION_FIRE_ONCE_NOW; // depends on control dependency: [if], data = [none]
}
if (instr == MISFIRE_INSTRUCTION_DO_NOTHING)
{
Date newFireTime = getFireTimeAfter (new Date ());
while (newFireTime != null && cal != null && !cal.isTimeIncluded (newFireTime.getTime ()))
{
newFireTime = getFireTimeAfter (newFireTime); // depends on control dependency: [while], data = [(newFireTime]
}
setNextFireTime (newFireTime); // depends on control dependency: [if], data = [none]
}
else
if (instr == MISFIRE_INSTRUCTION_FIRE_ONCE_NOW)
{
setNextFireTime (new Date ()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static <T> T executeIn(ClassLoader loader, Callable<T> task) throws Exception
{
if (task == null)
return null;
if (log.isLoggable(Level.FINE))
{
log.fine("ClassLoader [" + loader + "] task began.");
}
ClassLoader original = SecurityActions.getContextClassLoader();
try
{
SecurityActions.setContextClassLoader(loader);
return task.call();
}
finally
{
SecurityActions.setContextClassLoader(original);
if (log.isLoggable(Level.FINE))
{
log.fine("ClassLoader [" + loader + "] task ended.");
}
}
} } | public class class_name {
public static <T> T executeIn(ClassLoader loader, Callable<T> task) throws Exception
{
if (task == null)
return null;
if (log.isLoggable(Level.FINE))
{
log.fine("ClassLoader [" + loader + "] task began.");
}
ClassLoader original = SecurityActions.getContextClassLoader();
try
{
SecurityActions.setContextClassLoader(loader);
return task.call();
}
finally
{
SecurityActions.setContextClassLoader(original);
if (log.isLoggable(Level.FINE))
{
log.fine("ClassLoader [" + loader + "] task ended."); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private void addQueryParams(final Request request) {
if (log != null) {
request.addQueryParam("Log", log.toString());
}
if (absoluteMessageDate != null) {
request.addQueryParam("MessageDate", absoluteMessageDate.toString(Request.QUERY_STRING_DATE_FORMAT));
} else if (rangeMessageDate != null) {
request.addQueryDateRange("MessageDate", rangeMessageDate);
}
if (getPageSize() != null) {
request.addQueryParam("PageSize", Integer.toString(getPageSize()));
}
} } | public class class_name {
private void addQueryParams(final Request request) {
if (log != null) {
request.addQueryParam("Log", log.toString()); // depends on control dependency: [if], data = [none]
}
if (absoluteMessageDate != null) {
request.addQueryParam("MessageDate", absoluteMessageDate.toString(Request.QUERY_STRING_DATE_FORMAT)); // depends on control dependency: [if], data = [none]
} else if (rangeMessageDate != null) {
request.addQueryDateRange("MessageDate", rangeMessageDate); // depends on control dependency: [if], data = [none]
}
if (getPageSize() != null) {
request.addQueryParam("PageSize", Integer.toString(getPageSize())); // depends on control dependency: [if], data = [(getPageSize()]
}
} } |
public class class_name {
public void setMargin(Rectangle2D bounds, Direction... dirs)
{
for (Direction dir : dirs)
{
switch (dir)
{
case BOTTOM:
combinedTransform.transform(userBounds.getCenterX(), userBounds.getMinY(), (x,y)->
{
inverse.transform(x, y+bounds.getHeight(), this::updatePoint);
});
break;
case LEFT:
combinedTransform.transform(userBounds.getMinX(), userBounds.getCenterY(), (x,y)->
{
inverse.transform(x-bounds.getWidth(), y, this::updatePoint);
});
break;
case RIGHT:
combinedTransform.transform(userBounds.getMaxX(), userBounds.getCenterY(), (x,y)->
{
inverse.transform(x+bounds.getWidth(), y, this::updatePoint);
});
break;
case TOP:
combinedTransform.transform(userBounds.getCenterX(), userBounds.getMaxY(), (x,y)->
{
inverse.transform(x, y-bounds.getHeight(), this::updatePoint);
});
break;
}
}
} } | public class class_name {
public void setMargin(Rectangle2D bounds, Direction... dirs)
{
for (Direction dir : dirs)
{
switch (dir)
{
case BOTTOM:
combinedTransform.transform(userBounds.getCenterX(), userBounds.getMinY(), (x,y)->
{
inverse.transform(x, y+bounds.getHeight(), this::updatePoint);
});
break;
case LEFT:
combinedTransform.transform(userBounds.getMinX(), userBounds.getCenterY(), (x,y)->
{
inverse.transform(x-bounds.getWidth(), y, this::updatePoint); // depends on control dependency: [for], data = [none]
});
break;
case RIGHT:
combinedTransform.transform(userBounds.getMaxX(), userBounds.getCenterY(), (x,y)->
{
inverse.transform(x+bounds.getWidth(), y, this::updatePoint);
});
break;
case TOP:
combinedTransform.transform(userBounds.getCenterX(), userBounds.getMaxY(), (x,y)->
{
inverse.transform(x, y-bounds.getHeight(), this::updatePoint);
});
break;
}
}
} } |
public class class_name {
public String getPrintName()
{
JType []typeArgs = getActualTypeArguments();
if (typeArgs.length == 0)
return getRawClass().getPrintName();
StringBuilder cb = new StringBuilder();
cb.append(getRawClass().getPrintName());
cb.append('<');
for (int i = 0; i < typeArgs.length; i++) {
if (i != 0)
cb.append(',');
cb.append(typeArgs[i].getPrintName());
}
cb.append('>');
return cb.toString();
} } | public class class_name {
public String getPrintName()
{
JType []typeArgs = getActualTypeArguments();
if (typeArgs.length == 0)
return getRawClass().getPrintName();
StringBuilder cb = new StringBuilder();
cb.append(getRawClass().getPrintName());
cb.append('<');
for (int i = 0; i < typeArgs.length; i++) {
if (i != 0)
cb.append(',');
cb.append(typeArgs[i].getPrintName()); // depends on control dependency: [for], data = [i]
}
cb.append('>');
return cb.toString();
} } |
public class class_name {
public static String decryptByAES(final String content, final String key) {
try {
final byte[] data = Hex.decodeHex(content.toCharArray());
final KeyGenerator kgen = KeyGenerator.getInstance("AES");
final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
final SecretKey secretKey = kgen.generateKey();
final byte[] enCodeFormat = secretKey.getEncoded();
final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
final Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
final byte[] result = cipher.doFinal(data);
return new String(result, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Decrypt failed");
return null;
}
} } | public class class_name {
public static String decryptByAES(final String content, final String key) {
try {
final byte[] data = Hex.decodeHex(content.toCharArray());
final KeyGenerator kgen = KeyGenerator.getInstance("AES");
final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes()); // depends on control dependency: [try], data = [none]
kgen.init(128, secureRandom); // depends on control dependency: [try], data = [none]
final SecretKey secretKey = kgen.generateKey();
final byte[] enCodeFormat = secretKey.getEncoded();
final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
final Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec); // depends on control dependency: [try], data = [none]
final byte[] result = cipher.doFinal(data);
return new String(result, "UTF-8"); // depends on control dependency: [try], data = [none]
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Decrypt failed");
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public float z_value(Vector3 q) {
if(q==null || this.halfplane) throw new RuntimeException("*** ERR wrong parameters, can't approximate the z value ..***: "+q);
/* incase the query point is on one of the points */
if(q.x==a.x & q.y==a.y) return a.z;
if(q.x==b.x & q.y==b.y) return b.z;
if(q.x==c.x & q.y==c.y) return c.z;
/*
* plane: aX + bY + c = Z:
* 2D line: y= mX + k
*
*/
float x=0,x0 = q.x, x1 = a.x, x2=b.x, x3=c.x;
float y=0,y0 = q.y, y1 = a.y, y2=b.y, y3=c.y;
float z=0, m01=0,k01=0,m23=0,k23=0;
float r = 0;
// 0 - regular, 1-horizontal , 2-vertical.
int flag01 = 0;
if(x0!=x1) {
m01 = (y0-y1)/(x0-x1);
k01 = y0 - m01*x0;
if (m01 ==0) {
flag01 = 1;
}
} else { // 2-vertical.
flag01 = 2;//x01 = x0
}
int flag23 = 0;
if(x2!=x3) {
m23 = (y2-y3)/(x2-x3);
k23 = y2 - m23*x2;
if (m23 ==0) {
flag23 = 1;
}
}
else { // 2-vertical.
flag23 = 2;//x01 = x0
}
if (flag01 ==2 ) {
x = x0;
y = m23*x + k23;
}
else {
if(flag23==2) {
x = x2;
y = m01*x + k01;
}
else { // regular case
x=(k23-k01)/(m01-m23);
y = m01*x+k01;
}
}
if(flag23==2) {
r=(y2-y)/(y2-y3);
} else {
r=(x2-x)/(x2-x3);
}
z = b.z + (c.z-b.z)*r;
if(flag01==2) {
r=(y1-y0)/(y1-y);
} else {
r=(x1-x0)/(x1-x);
}
float qZ = a.z + (z-a.z)*r;
return qZ;
} } | public class class_name {
public float z_value(Vector3 q) {
if(q==null || this.halfplane) throw new RuntimeException("*** ERR wrong parameters, can't approximate the z value ..***: "+q);
/* incase the query point is on one of the points */
if(q.x==a.x & q.y==a.y) return a.z;
if(q.x==b.x & q.y==b.y) return b.z;
if(q.x==c.x & q.y==c.y) return c.z;
/*
* plane: aX + bY + c = Z:
* 2D line: y= mX + k
*
*/
float x=0,x0 = q.x, x1 = a.x, x2=b.x, x3=c.x;
float y=0,y0 = q.y, y1 = a.y, y2=b.y, y3=c.y;
float z=0, m01=0,k01=0,m23=0,k23=0;
float r = 0;
// 0 - regular, 1-horizontal , 2-vertical.
int flag01 = 0;
if(x0!=x1) {
m01 = (y0-y1)/(x0-x1); // depends on control dependency: [if], data = [(x0]
k01 = y0 - m01*x0; // depends on control dependency: [if], data = [none]
if (m01 ==0) {
flag01 = 1; // depends on control dependency: [if], data = [none]
}
} else { // 2-vertical.
flag01 = 2;//x01 = x0 // depends on control dependency: [if], data = [none]
}
int flag23 = 0;
if(x2!=x3) {
m23 = (y2-y3)/(x2-x3); // depends on control dependency: [if], data = [(x2]
k23 = y2 - m23*x2; // depends on control dependency: [if], data = [none]
if (m23 ==0) {
flag23 = 1; // depends on control dependency: [if], data = [none]
}
}
else { // 2-vertical.
flag23 = 2;//x01 = x0 // depends on control dependency: [if], data = [none]
}
if (flag01 ==2 ) {
x = x0; // depends on control dependency: [if], data = [none]
y = m23*x + k23; // depends on control dependency: [if], data = [none]
}
else {
if(flag23==2) {
x = x2; // depends on control dependency: [if], data = [none]
y = m01*x + k01; // depends on control dependency: [if], data = [none]
}
else { // regular case
x=(k23-k01)/(m01-m23); // depends on control dependency: [if], data = [none]
y = m01*x+k01; // depends on control dependency: [if], data = [none]
}
}
if(flag23==2) {
r=(y2-y)/(y2-y3); // depends on control dependency: [if], data = [none]
} else {
r=(x2-x)/(x2-x3); // depends on control dependency: [if], data = [none]
}
z = b.z + (c.z-b.z)*r;
if(flag01==2) {
r=(y1-y0)/(y1-y); // depends on control dependency: [if], data = [none]
} else {
r=(x1-x0)/(x1-x); // depends on control dependency: [if], data = [none]
}
float qZ = a.z + (z-a.z)*r;
return qZ;
} } |
public class class_name {
public File transform(File inputFile,
File outFile,
GlobalTransform transform) {
try {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter(outFile)));
// Read in the header for matrix file.
String line = br.readLine();
String[] rowColNonZeroCount = line.split("\\s+");
int numRows = Integer.parseInt(rowColNonZeroCount[0]);
int numCols = Integer.parseInt(rowColNonZeroCount[1]);
int numTotalNonZeros = Integer.parseInt(rowColNonZeroCount[2]);
// Write out the header for the new matrix file.
writer.printf("%d %d %d\n", numRows, numCols, numTotalNonZeros);
line = br.readLine();
// Traverse each column in the matrix.
for (int col = 0; line != null && col < numCols; ++col) {
int numNonZeros = Integer.parseInt(line);
writer.printf("%d\n", numNonZeros);
// Transform each of the non zero values for the new matrix
// file.
for (int index = 0; (line = br.readLine()) != null &&
index < numNonZeros; ++index) {
String[] rowValue = line.split("\\s+");
int row = Integer.parseInt(rowValue[0]);
double value = Double.parseDouble(rowValue[1]);
writer.printf("%d %f\n", row,
transform.transform(row, col, value));
}
}
writer.close();
} catch (IOException ioe) {
throw new IOError(ioe);
}
return outFile;
} } | public class class_name {
public File transform(File inputFile,
File outFile,
GlobalTransform transform) {
try {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter(outFile)));
// Read in the header for matrix file.
String line = br.readLine();
String[] rowColNonZeroCount = line.split("\\s+");
int numRows = Integer.parseInt(rowColNonZeroCount[0]);
int numCols = Integer.parseInt(rowColNonZeroCount[1]);
int numTotalNonZeros = Integer.parseInt(rowColNonZeroCount[2]);
// Write out the header for the new matrix file.
writer.printf("%d %d %d\n", numRows, numCols, numTotalNonZeros); // depends on control dependency: [try], data = [none]
line = br.readLine(); // depends on control dependency: [try], data = [none]
// Traverse each column in the matrix.
for (int col = 0; line != null && col < numCols; ++col) {
int numNonZeros = Integer.parseInt(line);
writer.printf("%d\n", numNonZeros); // depends on control dependency: [for], data = [none]
// Transform each of the non zero values for the new matrix
// file.
for (int index = 0; (line = br.readLine()) != null &&
index < numNonZeros; ++index) {
String[] rowValue = line.split("\\s+");
int row = Integer.parseInt(rowValue[0]);
double value = Double.parseDouble(rowValue[1]);
writer.printf("%d %f\n", row,
transform.transform(row, col, value)); // depends on control dependency: [for], data = [none]
}
}
writer.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
throw new IOError(ioe);
} // depends on control dependency: [catch], data = [none]
return outFile;
} } |
public class class_name {
private Producer<CloseableReference<CloseableImage>> newBitmapCacheGetToDecodeSequence(
Producer<EncodedImage> inputProducer) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection("ProducerSequenceFactory#newBitmapCacheGetToDecodeSequence");
}
DecodeProducer decodeProducer = mProducerFactory.newDecodeProducer(inputProducer);
Producer<CloseableReference<CloseableImage>> result =
newBitmapCacheGetToBitmapCacheSequence(decodeProducer);
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
return result;
} } | public class class_name {
private Producer<CloseableReference<CloseableImage>> newBitmapCacheGetToDecodeSequence(
Producer<EncodedImage> inputProducer) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection("ProducerSequenceFactory#newBitmapCacheGetToDecodeSequence"); // depends on control dependency: [if], data = [none]
}
DecodeProducer decodeProducer = mProducerFactory.newDecodeProducer(inputProducer);
Producer<CloseableReference<CloseableImage>> result =
newBitmapCacheGetToBitmapCacheSequence(decodeProducer);
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection(); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public EClass getIfcPresentationStyleSelect() {
if (ifcPresentationStyleSelectEClass == null) {
ifcPresentationStyleSelectEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(967);
}
return ifcPresentationStyleSelectEClass;
} } | public class class_name {
public EClass getIfcPresentationStyleSelect() {
if (ifcPresentationStyleSelectEClass == null) {
ifcPresentationStyleSelectEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(967);
// depends on control dependency: [if], data = [none]
}
return ifcPresentationStyleSelectEClass;
} } |
public class class_name {
public static ArrayList<ACL> createAcl(FailoverWatcher failoverWatcher, String znode) {
if (znode.equals("/chronos")) {
return Ids.OPEN_ACL_UNSAFE;
}
if (failoverWatcher.isZkSecure()) {
ArrayList<ACL> acls = new ArrayList<ACL>();
acls.add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE));
acls.add(new ACL(ZooDefs.Perms.ALL, new Id("sasl", failoverWatcher.getZkAdmin())));
return acls;
} else {
return Ids.OPEN_ACL_UNSAFE;
}
} } | public class class_name {
public static ArrayList<ACL> createAcl(FailoverWatcher failoverWatcher, String znode) {
if (znode.equals("/chronos")) {
return Ids.OPEN_ACL_UNSAFE; // depends on control dependency: [if], data = [none]
}
if (failoverWatcher.isZkSecure()) {
ArrayList<ACL> acls = new ArrayList<ACL>();
acls.add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE)); // depends on control dependency: [if], data = [none]
acls.add(new ACL(ZooDefs.Perms.ALL, new Id("sasl", failoverWatcher.getZkAdmin()))); // depends on control dependency: [if], data = [none]
return acls; // depends on control dependency: [if], data = [none]
} else {
return Ids.OPEN_ACL_UNSAFE; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) {
ModelNode readOps = null;
try {
readOps = cliGuiCtx.getExecutor().doCommand("/subsystem=logging:read-children-types");
} catch (CommandFormatException | IOException e) {
return false;
}
if (!readOps.get("result").isDefined()) return false;
for (ModelNode op: readOps.get("result").asList()) {
if ("log-file".equals(op.asString())) return true;
}
return false;
} } | public class class_name {
public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) {
ModelNode readOps = null;
try {
readOps = cliGuiCtx.getExecutor().doCommand("/subsystem=logging:read-children-types"); // depends on control dependency: [try], data = [none]
} catch (CommandFormatException | IOException e) {
return false;
} // depends on control dependency: [catch], data = [none]
if (!readOps.get("result").isDefined()) return false;
for (ModelNode op: readOps.get("result").asList()) {
if ("log-file".equals(op.asString())) return true;
}
return false;
} } |
public class class_name {
public ACE[] getShareSecurity(boolean resolveSids) throws IOException {
String p = url.getPath();
MsrpcShareGetInfo rpc;
DcerpcHandle handle;
ACE[] aces;
resolveDfs(null);
String server = getServerWithDfs();
rpc = new MsrpcShareGetInfo(server, tree.share);
handle = DcerpcHandle.getHandle("ncacn_np:" + server + "[\\PIPE\\srvsvc]", auth);
try {
handle.sendrecv(rpc);
if (rpc.retval != 0)
throw new SmbException(rpc.retval, true);
aces = rpc.getSecurity();
if (aces != null)
processAces(aces, resolveSids);
} finally {
try {
handle.close();
} catch(IOException ioe) {
if (log.level >= 1)
ioe.printStackTrace(log);
}
}
return aces;
} } | public class class_name {
public ACE[] getShareSecurity(boolean resolveSids) throws IOException {
String p = url.getPath();
MsrpcShareGetInfo rpc;
DcerpcHandle handle;
ACE[] aces;
resolveDfs(null);
String server = getServerWithDfs();
rpc = new MsrpcShareGetInfo(server, tree.share);
handle = DcerpcHandle.getHandle("ncacn_np:" + server + "[\\PIPE\\srvsvc]", auth);
try {
handle.sendrecv(rpc);
if (rpc.retval != 0)
throw new SmbException(rpc.retval, true);
aces = rpc.getSecurity();
if (aces != null)
processAces(aces, resolveSids);
} finally {
try {
handle.close(); // depends on control dependency: [try], data = [none]
} catch(IOException ioe) {
if (log.level >= 1)
ioe.printStackTrace(log);
} // depends on control dependency: [catch], data = [none]
}
return aces;
} } |
public class class_name {
private static String formatKey(String prjKey) {
String formatKey = prjKey;
if (prjKey.startsWith("+")) {
formatKey = prjKey.substring(1);
}
return formatKey;
} } | public class class_name {
private static String formatKey(String prjKey) {
String formatKey = prjKey;
if (prjKey.startsWith("+")) {
formatKey = prjKey.substring(1); // depends on control dependency: [if], data = [none]
}
return formatKey;
} } |
public class class_name {
public JvmAnnotationReference findAnnotation(/* @NonNull */ JvmAnnotationTarget annotationTarget, /* @NonNull */ Class<? extends Annotation> lookupType) {
// avoid creating an empty list for all given targets but check for #eIsSet first
if (annotationTarget.eIsSet(TypesPackage.Literals.JVM_ANNOTATION_TARGET__ANNOTATIONS)) {
for(JvmAnnotationReference annotation: annotationTarget.getAnnotations()) {
JvmAnnotationType annotationType = annotation.getAnnotation();
if (annotationType != null && lookupType.getCanonicalName().equals(annotationType.getQualifiedName())) {
return annotation;
}
}
}
return null;
} } | public class class_name {
public JvmAnnotationReference findAnnotation(/* @NonNull */ JvmAnnotationTarget annotationTarget, /* @NonNull */ Class<? extends Annotation> lookupType) {
// avoid creating an empty list for all given targets but check for #eIsSet first
if (annotationTarget.eIsSet(TypesPackage.Literals.JVM_ANNOTATION_TARGET__ANNOTATIONS)) {
for(JvmAnnotationReference annotation: annotationTarget.getAnnotations()) {
JvmAnnotationType annotationType = annotation.getAnnotation();
if (annotationType != null && lookupType.getCanonicalName().equals(annotationType.getQualifiedName())) {
return annotation; // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
private Function<HttpRequestContext, String> createPathSubstitution(final String param, final AbstractMethod am) {
int from = 0;
int segment = -1;
// Get the path from resource then from the method
Path[] annotations = new Path[] { am.getResource().getAnnotation(Path.class), am.getAnnotation(Path.class) };
for (Path annotation : annotations) {
if (annotation == null) {
continue;
}
int index = getSubstitutionIndex(param, annotation.value());
if (index >= 0) {
segment = from + index;
} else {
from += -index;
}
}
if (segment == -1) {
throw new IllegalArgumentException("Param not found in path: " + param);
}
final int validatedSegment = segment;
return new Function<HttpRequestContext, String>() {
@Override
public String apply(HttpRequestContext request) {
return request.getPathSegments().get(validatedSegment).getPath();
}
};
} } | public class class_name {
private Function<HttpRequestContext, String> createPathSubstitution(final String param, final AbstractMethod am) {
int from = 0;
int segment = -1;
// Get the path from resource then from the method
Path[] annotations = new Path[] { am.getResource().getAnnotation(Path.class), am.getAnnotation(Path.class) };
for (Path annotation : annotations) {
if (annotation == null) {
continue;
}
int index = getSubstitutionIndex(param, annotation.value());
if (index >= 0) {
segment = from + index; // depends on control dependency: [if], data = [none]
} else {
from += -index; // depends on control dependency: [if], data = [none]
}
}
if (segment == -1) {
throw new IllegalArgumentException("Param not found in path: " + param);
}
final int validatedSegment = segment;
return new Function<HttpRequestContext, String>() {
@Override
public String apply(HttpRequestContext request) {
return request.getPathSegments().get(validatedSegment).getPath();
}
};
} } |
public class class_name {
@Override
protected boolean i_updateRow(Connection conn,
String table,
String[] columns,
String[] values,
String uniqueColumn,
boolean[] numeric) throws SQLException {
// prepare update statement
StringBuilder sql = new StringBuilder(64);
sql.append("UPDATE ").append(table).append(" SET ");
boolean needComma = false;
for (int i = 0; i < columns.length; i++) {
if (!columns[i].equals(uniqueColumn)) {
if (needComma) {
sql.append(", ");
} else {
needComma = true;
}
sql.append(columns[i] + " = ");
if (values[i] == null) {
sql.append("NULL");
} else {
sql.append('?');
}
}
}
sql.append(" WHERE ");
sql.append(uniqueColumn);
sql.append(" = ?");
if (logger.isDebugEnabled()) {
logger.debug("About to execute: " + sql.toString());
}
PreparedStatement stmt = conn.prepareStatement(sql.toString());
try {
// populate values
int varIndex = 0;
for (int i = 0; i < columns.length; i++) {
if (!columns[i].equals(uniqueColumn) && values[i] != null) {
varIndex++;
if (numeric != null && numeric[i]) {
setNumeric(stmt, varIndex, columns[i], values[i]);
} else {
stmt.setString(varIndex, values[i]);
}
}
}
varIndex++;
stmt
.setString(varIndex, getSelector(columns,
values,
uniqueColumn));
// execute and return true if existing row was updated
return stmt.executeUpdate() > 0;
} finally {
closeStatement(stmt);
}
} } | public class class_name {
@Override
protected boolean i_updateRow(Connection conn,
String table,
String[] columns,
String[] values,
String uniqueColumn,
boolean[] numeric) throws SQLException {
// prepare update statement
StringBuilder sql = new StringBuilder(64);
sql.append("UPDATE ").append(table).append(" SET ");
boolean needComma = false;
for (int i = 0; i < columns.length; i++) {
if (!columns[i].equals(uniqueColumn)) {
if (needComma) {
sql.append(", "); // depends on control dependency: [if], data = [none]
} else {
needComma = true; // depends on control dependency: [if], data = [none]
}
sql.append(columns[i] + " = ");
if (values[i] == null) {
sql.append("NULL"); // depends on control dependency: [if], data = [none]
} else {
sql.append('?'); // depends on control dependency: [if], data = [none]
}
}
}
sql.append(" WHERE ");
sql.append(uniqueColumn);
sql.append(" = ?");
if (logger.isDebugEnabled()) {
logger.debug("About to execute: " + sql.toString());
}
PreparedStatement stmt = conn.prepareStatement(sql.toString());
try {
// populate values
int varIndex = 0;
for (int i = 0; i < columns.length; i++) {
if (!columns[i].equals(uniqueColumn) && values[i] != null) {
varIndex++;
if (numeric != null && numeric[i]) {
setNumeric(stmt, varIndex, columns[i], values[i]);
} else {
stmt.setString(varIndex, values[i]);
}
}
}
varIndex++;
stmt
.setString(varIndex, getSelector(columns,
values,
uniqueColumn));
// execute and return true if existing row was updated
return stmt.executeUpdate() > 0;
} finally {
closeStatement(stmt);
}
} } |
public class class_name {
public boolean safeToMoveBefore(Node source,
AbstractMotionEnvironment environment,
Node destination) {
checkNotNull(locationAbstraction);
checkArgument(!nodeHasAncestor(destination, source));
// It is always safe to move pure code.
if (isPure(source)) {
return true;
}
// Don't currently support interprocedural analysis
if (nodeHasCall(source)) {
return false;
}
LocationSummary sourceLocationSummary =
locationAbstraction.calculateLocationSummary(source);
EffectLocation sourceModSet = sourceLocationSummary.getModSet();
// If the source has side effects, then we require that the source
// is executed exactly as many times as the destination.
if (!sourceModSet.isEmpty() &&
!nodesHaveSameControlFlow(source, destination)) {
return false;
}
EffectLocation sourceRefSet = sourceLocationSummary.getRefSet();
Set<Node> environmentNodes = environment.calculateEnvironment();
for (Node environmentNode : environmentNodes) {
if (nodeHasCall(environmentNode)) {
return false;
}
}
LocationSummary environmentLocationSummary =
locationAbstraction.calculateLocationSummary(environmentNodes);
EffectLocation environmentModSet = environmentLocationSummary.getModSet();
EffectLocation environmentRefSet = environmentLocationSummary.getRefSet();
// If MOD(environment) intersects REF(source) then moving the
// source across the environment could cause the source
// to read an incorrect value.
// If REF(environment) intersects MOD(source) then moving the
// source across the environment could cause the environment
// to read an incorrect value.
// If MOD(environment) intersects MOD(source) then moving the
// source across the environment could cause some later code that reads
// a modified location to get an incorrect value.
return !environmentModSet.intersectsLocation(sourceRefSet)
&& !environmentRefSet.intersectsLocation(sourceModSet)
&& !environmentModSet.intersectsLocation(sourceModSet);
} } | public class class_name {
public boolean safeToMoveBefore(Node source,
AbstractMotionEnvironment environment,
Node destination) {
checkNotNull(locationAbstraction);
checkArgument(!nodeHasAncestor(destination, source));
// It is always safe to move pure code.
if (isPure(source)) {
return true; // depends on control dependency: [if], data = [none]
}
// Don't currently support interprocedural analysis
if (nodeHasCall(source)) {
return false; // depends on control dependency: [if], data = [none]
}
LocationSummary sourceLocationSummary =
locationAbstraction.calculateLocationSummary(source);
EffectLocation sourceModSet = sourceLocationSummary.getModSet();
// If the source has side effects, then we require that the source
// is executed exactly as many times as the destination.
if (!sourceModSet.isEmpty() &&
!nodesHaveSameControlFlow(source, destination)) {
return false; // depends on control dependency: [if], data = [none]
}
EffectLocation sourceRefSet = sourceLocationSummary.getRefSet();
Set<Node> environmentNodes = environment.calculateEnvironment();
for (Node environmentNode : environmentNodes) {
if (nodeHasCall(environmentNode)) {
return false; // depends on control dependency: [if], data = [none]
}
}
LocationSummary environmentLocationSummary =
locationAbstraction.calculateLocationSummary(environmentNodes);
EffectLocation environmentModSet = environmentLocationSummary.getModSet();
EffectLocation environmentRefSet = environmentLocationSummary.getRefSet();
// If MOD(environment) intersects REF(source) then moving the
// source across the environment could cause the source
// to read an incorrect value.
// If REF(environment) intersects MOD(source) then moving the
// source across the environment could cause the environment
// to read an incorrect value.
// If MOD(environment) intersects MOD(source) then moving the
// source across the environment could cause some later code that reads
// a modified location to get an incorrect value.
return !environmentModSet.intersectsLocation(sourceRefSet)
&& !environmentRefSet.intersectsLocation(sourceModSet)
&& !environmentModSet.intersectsLocation(sourceModSet);
} } |
public class class_name {
Stream<String> writeTimeGauge(TimeGauge timeGauge) {
Double value = timeGauge.value(getBaseTimeUnit());
if (Double.isFinite(value)) {
return Stream.of(writeMetric(timeGauge.getId(), config().clock().wallTime(), value));
}
return Stream.empty();
} } | public class class_name {
Stream<String> writeTimeGauge(TimeGauge timeGauge) {
Double value = timeGauge.value(getBaseTimeUnit());
if (Double.isFinite(value)) {
return Stream.of(writeMetric(timeGauge.getId(), config().clock().wallTime(), value)); // depends on control dependency: [if], data = [none]
}
return Stream.empty();
} } |
public class class_name {
public void bind(final StringProperty property, String key) {
String value = prefs.get(validateKey(key), null);
if (value != null) {
property.set(value);
}
property.addListener(o -> prefs.put(key, property.getValue()));
} } | public class class_name {
public void bind(final StringProperty property, String key) {
String value = prefs.get(validateKey(key), null);
if (value != null) {
property.set(value); // depends on control dependency: [if], data = [(value]
}
property.addListener(o -> prefs.put(key, property.getValue()));
} } |
public class class_name {
@Override
public CommerceAccount fetchByPrimaryKey(Serializable primaryKey) {
Serializable serializable = entityCache.getResult(CommerceAccountModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountImpl.class, primaryKey);
if (serializable == nullModel) {
return null;
}
CommerceAccount commerceAccount = (CommerceAccount)serializable;
if (commerceAccount == null) {
Session session = null;
try {
session = openSession();
commerceAccount = (CommerceAccount)session.get(CommerceAccountImpl.class,
primaryKey);
if (commerceAccount != null) {
cacheResult(commerceAccount);
}
else {
entityCache.putResult(CommerceAccountModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountImpl.class, primaryKey, nullModel);
}
}
catch (Exception e) {
entityCache.removeResult(CommerceAccountModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountImpl.class, primaryKey);
throw processException(e);
}
finally {
closeSession(session);
}
}
return commerceAccount;
} } | public class class_name {
@Override
public CommerceAccount fetchByPrimaryKey(Serializable primaryKey) {
Serializable serializable = entityCache.getResult(CommerceAccountModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountImpl.class, primaryKey);
if (serializable == nullModel) {
return null; // depends on control dependency: [if], data = [none]
}
CommerceAccount commerceAccount = (CommerceAccount)serializable;
if (commerceAccount == null) {
Session session = null;
try {
session = openSession(); // depends on control dependency: [try], data = [none]
commerceAccount = (CommerceAccount)session.get(CommerceAccountImpl.class,
primaryKey); // depends on control dependency: [try], data = [none]
if (commerceAccount != null) {
cacheResult(commerceAccount); // depends on control dependency: [if], data = [(commerceAccount]
}
else {
entityCache.putResult(CommerceAccountModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountImpl.class, primaryKey, nullModel); // depends on control dependency: [if], data = [none]
}
}
catch (Exception e) {
entityCache.removeResult(CommerceAccountModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountImpl.class, primaryKey);
throw processException(e);
} // depends on control dependency: [catch], data = [none]
finally {
closeSession(session);
}
}
return commerceAccount;
} } |
public class class_name {
public boolean isSupported(DateTimeFieldType type) {
if (type == null) {
return false;
}
return type.getField(getChronology()).isSupported();
} } | public class class_name {
public boolean isSupported(DateTimeFieldType type) {
if (type == null) {
return false; // depends on control dependency: [if], data = [none]
}
return type.getField(getChronology()).isSupported();
} } |
public class class_name {
void setIsIndeterminate(boolean isIndeterminate) {
if (mIsIndeterminate != isIndeterminate) {
mIsIndeterminate = isIndeterminate;
mInputAdapter.setIndeterminate(isIndeterminate);
notifyDataSetChanged();
}
} } | public class class_name {
void setIsIndeterminate(boolean isIndeterminate) {
if (mIsIndeterminate != isIndeterminate) {
mIsIndeterminate = isIndeterminate; // depends on control dependency: [if], data = [none]
mInputAdapter.setIndeterminate(isIndeterminate); // depends on control dependency: [if], data = [isIndeterminate)]
notifyDataSetChanged(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private String buildClassPath()
{
String classPath = null;//_classPath;
if (classPath != null) {
return classPath;
}
if (classPath == null && _loader instanceof DynamicClassLoader) {
classPath = ((DynamicClassLoader) _loader).getClassPath();
}
else { // if (true || _loader instanceof URLClassLoader) {
StringBuilder sb = new StringBuilder();
sb.append(CauchoUtil.getClassPath());
if (_loader != null)
buildClassPath(sb, _loader);
classPath = sb.toString();
}
//else if (classPath == null)
//classPath = CauchoSystem.getClassPath();
String srcDirName = getSourceDirName();
String classDirName = getClassDirName();
char sep = CauchoUtil.getPathSeparatorChar();
if (_extraClassPath != null)
classPath = classPath + sep + _extraClassPath;
// Adding the srcDir lets javac and jikes find source files
if (! srcDirName.equals(classDirName))
classPath = srcDirName + sep + classPath;
classPath = classDirName + sep + classPath;
return classPath;
} } | public class class_name {
private String buildClassPath()
{
String classPath = null;//_classPath;
if (classPath != null) {
return classPath; // depends on control dependency: [if], data = [none]
}
if (classPath == null && _loader instanceof DynamicClassLoader) {
classPath = ((DynamicClassLoader) _loader).getClassPath(); // depends on control dependency: [if], data = [none]
}
else { // if (true || _loader instanceof URLClassLoader) {
StringBuilder sb = new StringBuilder();
sb.append(CauchoUtil.getClassPath()); // depends on control dependency: [if], data = [none]
if (_loader != null)
buildClassPath(sb, _loader);
classPath = sb.toString(); // depends on control dependency: [if], data = [none]
}
//else if (classPath == null)
//classPath = CauchoSystem.getClassPath();
String srcDirName = getSourceDirName();
String classDirName = getClassDirName();
char sep = CauchoUtil.getPathSeparatorChar();
if (_extraClassPath != null)
classPath = classPath + sep + _extraClassPath;
// Adding the srcDir lets javac and jikes find source files
if (! srcDirName.equals(classDirName))
classPath = srcDirName + sep + classPath;
classPath = classDirName + sep + classPath;
return classPath;
} } |
public class class_name {
public void progress() {
count++;
if (count % period == 0 && LOG.isInfoEnabled()) {
final double percent = 100 * (count / (double) totalIterations);
final long tock = System.currentTimeMillis();
final long timeInterval = tock - tick;
final long linesPerSec = (count - prevCount) * 1000 / timeInterval;
tick = tock;
prevCount = count;
final int etaSeconds = (int) ((totalIterations - count) / linesPerSec);
final long hours = SECONDS.toHours(etaSeconds);
final long minutes = SECONDS.toMinutes(etaSeconds - HOURS.toSeconds(hours));
final long seconds = SECONDS.toSeconds(etaSeconds - MINUTES.toSeconds(minutes));
LOG.info(String.format("[%3.0f%%] Completed %d iterations of %d total input. %d iters/s. ETA %02d:%02d:%02d",
percent, count, totalIterations, linesPerSec, hours, minutes, seconds));
}
} } | public class class_name {
public void progress() {
count++;
if (count % period == 0 && LOG.isInfoEnabled()) {
final double percent = 100 * (count / (double) totalIterations);
final long tock = System.currentTimeMillis();
final long timeInterval = tock - tick;
final long linesPerSec = (count - prevCount) * 1000 / timeInterval;
tick = tock; // depends on control dependency: [if], data = [none]
prevCount = count; // depends on control dependency: [if], data = [none]
final int etaSeconds = (int) ((totalIterations - count) / linesPerSec);
final long hours = SECONDS.toHours(etaSeconds);
final long minutes = SECONDS.toMinutes(etaSeconds - HOURS.toSeconds(hours));
final long seconds = SECONDS.toSeconds(etaSeconds - MINUTES.toSeconds(minutes));
LOG.info(String.format("[%3.0f%%] Completed %d iterations of %d total input. %d iters/s. ETA %02d:%02d:%02d",
percent, count, totalIterations, linesPerSec, hours, minutes, seconds)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setMax(int max) {
mMax = max;
if (mMax <= mMin) {
setMin(mMax - 1);
}
updateKeyboardRange();
mSeekBarDrawable.setNumSegments(mMax - mMin);
if (mValue < mMin || mValue > mMax) {
setProgress(mValue);
} else {
updateThumbPosForScale(-1);
}
} } | public class class_name {
public void setMax(int max) {
mMax = max;
if (mMax <= mMin) {
setMin(mMax - 1); // depends on control dependency: [if], data = [(mMax]
}
updateKeyboardRange();
mSeekBarDrawable.setNumSegments(mMax - mMin);
if (mValue < mMin || mValue > mMax) {
setProgress(mValue); // depends on control dependency: [if], data = [none]
} else {
updateThumbPosForScale(-1); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static BigDecimal log(BigDecimal x, MathContext mathContext) {
checkMathContext(mathContext);
if (x.signum() <= 0) {
throw new ArithmeticException("Illegal log(x) for x <= 0: x = " + x);
}
if (x.compareTo(ONE) == 0) {
return ZERO;
}
BigDecimal result;
switch (x.compareTo(TEN)) {
case 0:
result = logTen(mathContext);
break;
case 1:
result = logUsingExponent(x, mathContext);
break;
default :
result = logUsingTwoThree(x, mathContext);
}
return round(result, mathContext);
} } | public class class_name {
public static BigDecimal log(BigDecimal x, MathContext mathContext) {
checkMathContext(mathContext);
if (x.signum() <= 0) {
throw new ArithmeticException("Illegal log(x) for x <= 0: x = " + x);
}
if (x.compareTo(ONE) == 0) {
return ZERO; // depends on control dependency: [if], data = [none]
}
BigDecimal result;
switch (x.compareTo(TEN)) {
case 0:
result = logTen(mathContext);
break;
case 1:
result = logUsingExponent(x, mathContext);
break;
default :
result = logUsingTwoThree(x, mathContext);
}
return round(result, mathContext);
} } |
public class class_name {
private int getLineNumber(int pc) {
LineNumberTable lnt = getMethod().getLineNumberTable();
if (lnt == null) {
return pc;
}
LineNumber[] lns = lnt.getLineNumberTable();
if (lns == null) {
return pc;
}
if (pc > lns[lns.length - 1].getStartPC()) {
return lns[lns.length - 1].getLineNumber();
}
int lo = 0;
int hi = lns.length - 2;
int mid = 0;
while (lo <= hi) {
mid = (lo + hi) >>> 1;
if (pc < lns[mid].getStartPC()) {
hi = mid - 1;
} else if (pc >= lns[mid + 1].getStartPC()) {
lo = mid + 1;
} else {
break;
}
}
return lns[mid].getLineNumber();
} } | public class class_name {
private int getLineNumber(int pc) {
LineNumberTable lnt = getMethod().getLineNumberTable();
if (lnt == null) {
return pc; // depends on control dependency: [if], data = [none]
}
LineNumber[] lns = lnt.getLineNumberTable();
if (lns == null) {
return pc; // depends on control dependency: [if], data = [none]
}
if (pc > lns[lns.length - 1].getStartPC()) {
return lns[lns.length - 1].getLineNumber(); // depends on control dependency: [if], data = [none]
}
int lo = 0;
int hi = lns.length - 2;
int mid = 0;
while (lo <= hi) {
mid = (lo + hi) >>> 1; // depends on control dependency: [while], data = [(lo]
if (pc < lns[mid].getStartPC()) {
hi = mid - 1; // depends on control dependency: [if], data = [none]
} else if (pc >= lns[mid + 1].getStartPC()) {
lo = mid + 1; // depends on control dependency: [if], data = [none]
} else {
break;
}
}
return lns[mid].getLineNumber();
} } |
public class class_name {
private ValueMember[] getValueMembersForTypeCode() {
LocalContained[] c = _contents(DefinitionKind.dk_ValueMember, false);
ValueMember[] vms = new ValueMember[c.length];
for (int i = 0; i < c.length; ++i) {
ValueMemberDefImpl vmdi = (ValueMemberDefImpl) c[i];
vms[i] = new ValueMember(vmdi.name(),
null, // ignore id
null, // ignore defined_in
null, // ignore version
vmdi.type(),
null, // ignore type_def
vmdi.access());
}
return vms;
} } | public class class_name {
private ValueMember[] getValueMembersForTypeCode() {
LocalContained[] c = _contents(DefinitionKind.dk_ValueMember, false);
ValueMember[] vms = new ValueMember[c.length];
for (int i = 0; i < c.length; ++i) {
ValueMemberDefImpl vmdi = (ValueMemberDefImpl) c[i];
vms[i] = new ValueMember(vmdi.name(),
null, // ignore id
null, // ignore defined_in
null, // ignore version
vmdi.type(),
null, // ignore type_def
vmdi.access()); // depends on control dependency: [for], data = [i]
}
return vms;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.