code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
String assertion() {
String assertion = assertionForEmailAndSite(email, getRemoteURL());
if (assertion == null) {
Log.w(TAG, "PersonaAuthorizer<%s> no assertion found for: %s", email, getRemoteURL());
return null;
}
Map<String, Object> result = parseAssertion(assertion);
if (result == null || isAssertionExpired(result)) {
Log.w(TAG, "PersonaAuthorizer<%s> assertion invalid or expired: %s", email, assertion);
return null;
}
return assertion;
} } | public class class_name {
String assertion() {
String assertion = assertionForEmailAndSite(email, getRemoteURL());
if (assertion == null) {
Log.w(TAG, "PersonaAuthorizer<%s> no assertion found for: %s", email, getRemoteURL()); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
Map<String, Object> result = parseAssertion(assertion);
if (result == null || isAssertionExpired(result)) {
Log.w(TAG, "PersonaAuthorizer<%s> assertion invalid or expired: %s", email, assertion); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
return assertion;
} } |
public class class_name {
public PStm findStatement(ClassListInterpreter classes, File file,
int lineno)
{
for (SClassDefinition c : classes)
{
if (c.getName().getLocation().getFile().equals(file))
{
PStm stmt = findStatement(c, lineno);
if (stmt != null)
{
return stmt;
}
}
}
return null;
} } | public class class_name {
public PStm findStatement(ClassListInterpreter classes, File file,
int lineno)
{
for (SClassDefinition c : classes)
{
if (c.getName().getLocation().getFile().equals(file))
{
PStm stmt = findStatement(c, lineno);
if (stmt != null)
{
return stmt; // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
public void setZone(DateTimeZone newZone) {
newZone = DateTimeUtils.getZone(newZone);
Chronology chrono = getChronology();
if (chrono.getZone() != newZone) {
setChronology(chrono.withZone(newZone)); // set via this class not super
}
} } | public class class_name {
public void setZone(DateTimeZone newZone) {
newZone = DateTimeUtils.getZone(newZone);
Chronology chrono = getChronology();
if (chrono.getZone() != newZone) {
setChronology(chrono.withZone(newZone)); // set via this class not super // depends on control dependency: [if], data = [newZone)]
}
} } |
public class class_name {
public void abortExternalTx(TransactionImpl odmgTrans)
{
if (log.isDebugEnabled()) log.debug("abortExternTransaction was called");
if (odmgTrans == null) return;
TxBuffer buf = (TxBuffer) txRepository.get();
Transaction extTx = buf != null ? buf.getExternTx() : null;
try
{
if (extTx != null && extTx.getStatus() == Status.STATUS_ACTIVE)
{
if(log.isDebugEnabled())
{
log.debug("Set extern transaction to rollback");
}
extTx.setRollbackOnly();
}
}
catch (Exception ignore)
{
}
txRepository.set(null);
} } | public class class_name {
public void abortExternalTx(TransactionImpl odmgTrans)
{
if (log.isDebugEnabled()) log.debug("abortExternTransaction was called");
if (odmgTrans == null) return;
TxBuffer buf = (TxBuffer) txRepository.get();
Transaction extTx = buf != null ? buf.getExternTx() : null;
try
{
if (extTx != null && extTx.getStatus() == Status.STATUS_ACTIVE)
{
if(log.isDebugEnabled())
{
log.debug("Set extern transaction to rollback");
// depends on control dependency: [if], data = [none]
}
extTx.setRollbackOnly();
// depends on control dependency: [if], data = [none]
}
}
catch (Exception ignore)
{
}
// depends on control dependency: [catch], data = [none]
txRepository.set(null);
} } |
public class class_name {
@Override
public JobReport mergerReports(JobReport... jobReports) {
List<Long> startTimes = new ArrayList<>();
List<Long> endTimes = new ArrayList<>();
List<String> jobNames = new ArrayList<>();
JobParameters parameters = new JobParameters();
JobMetrics metrics = new JobMetrics();
JobReport finalJobReport = new JobReport();
finalJobReport.setParameters(parameters);
finalJobReport.setMetrics(metrics);
finalJobReport.setStatus(JobStatus.COMPLETED);
for (JobReport jobReport : jobReports) {
startTimes.add(jobReport.getMetrics().getStartTime());
endTimes.add(jobReport.getMetrics().getEndTime());
calculateReadRecords(finalJobReport, jobReport);
calculateWrittenRecords(finalJobReport, jobReport);
calculateFilteredRecords(finalJobReport, jobReport);
calculateErrorRecords(finalJobReport, jobReport);
setStatus(finalJobReport, jobReport);
jobNames.add(jobReport.getJobName());
finalJobReport.setSystemProperties(jobReport.getSystemProperties()); // works unless partial jobs are run in different JVMs..
}
//merge results
finalJobReport.getMetrics().setStartTime(Collections.min(startTimes));
finalJobReport.getMetrics().setEndTime(Collections.max(endTimes));
// set name
finalJobReport.setJobName(concatenate(jobNames));
return finalJobReport;
} } | public class class_name {
@Override
public JobReport mergerReports(JobReport... jobReports) {
List<Long> startTimes = new ArrayList<>();
List<Long> endTimes = new ArrayList<>();
List<String> jobNames = new ArrayList<>();
JobParameters parameters = new JobParameters();
JobMetrics metrics = new JobMetrics();
JobReport finalJobReport = new JobReport();
finalJobReport.setParameters(parameters);
finalJobReport.setMetrics(metrics);
finalJobReport.setStatus(JobStatus.COMPLETED);
for (JobReport jobReport : jobReports) {
startTimes.add(jobReport.getMetrics().getStartTime()); // depends on control dependency: [for], data = [jobReport]
endTimes.add(jobReport.getMetrics().getEndTime()); // depends on control dependency: [for], data = [jobReport]
calculateReadRecords(finalJobReport, jobReport); // depends on control dependency: [for], data = [jobReport]
calculateWrittenRecords(finalJobReport, jobReport); // depends on control dependency: [for], data = [jobReport]
calculateFilteredRecords(finalJobReport, jobReport); // depends on control dependency: [for], data = [jobReport]
calculateErrorRecords(finalJobReport, jobReport); // depends on control dependency: [for], data = [jobReport]
setStatus(finalJobReport, jobReport); // depends on control dependency: [for], data = [jobReport]
jobNames.add(jobReport.getJobName()); // depends on control dependency: [for], data = [jobReport]
finalJobReport.setSystemProperties(jobReport.getSystemProperties()); // works unless partial jobs are run in different JVMs.. // depends on control dependency: [for], data = [jobReport]
}
//merge results
finalJobReport.getMetrics().setStartTime(Collections.min(startTimes));
finalJobReport.getMetrics().setEndTime(Collections.max(endTimes));
// set name
finalJobReport.setJobName(concatenate(jobNames));
return finalJobReport;
} } |
public class class_name {
void initializeLocals() {
if (localsInitialized) {
throw new AssertionError();
}
localsInitialized = true;
int reg = 0;
for (Local<?> local : locals) {
reg += local.initialize(reg);
}
int firstParamReg = reg;
List<Insn> moveParameterInstructions = new ArrayList<Insn>();
for (Local<?> local : parameters) {
CstInteger paramConstant = CstInteger.make(reg - firstParamReg);
reg += local.initialize(reg);
moveParameterInstructions.add(new PlainCstInsn(Rops.opMoveParam(local.type.ropType),
sourcePosition, local.spec(), RegisterSpecList.EMPTY, paramConstant));
}
labels.get(0).instructions.addAll(0, moveParameterInstructions);
} } | public class class_name {
void initializeLocals() {
if (localsInitialized) {
throw new AssertionError();
}
localsInitialized = true;
int reg = 0;
for (Local<?> local : locals) {
reg += local.initialize(reg); // depends on control dependency: [for], data = [local]
}
int firstParamReg = reg;
List<Insn> moveParameterInstructions = new ArrayList<Insn>();
for (Local<?> local : parameters) {
CstInteger paramConstant = CstInteger.make(reg - firstParamReg);
reg += local.initialize(reg); // depends on control dependency: [for], data = [local]
moveParameterInstructions.add(new PlainCstInsn(Rops.opMoveParam(local.type.ropType),
sourcePosition, local.spec(), RegisterSpecList.EMPTY, paramConstant)); // depends on control dependency: [for], data = [local]
}
labels.get(0).instructions.addAll(0, moveParameterInstructions);
} } |
public class class_name {
protected Drawable boundToHotspot(final Drawable marker, HotspotPlace hotspot) {
if (hotspot == null) {
hotspot = HotspotPlace.BOTTOM_CENTER;
}
final int markerWidth = marker.getIntrinsicWidth();
final int markerHeight = marker.getIntrinsicHeight();
final int offsetX;
final int offsetY;
switch(hotspot) {
default:
case NONE:
case LEFT_CENTER:
case UPPER_LEFT_CORNER:
case LOWER_LEFT_CORNER:
offsetX = 0;
break;
case CENTER:
case BOTTOM_CENTER:
case TOP_CENTER:
offsetX = -markerWidth / 2;
break;
case RIGHT_CENTER:
case UPPER_RIGHT_CORNER:
case LOWER_RIGHT_CORNER:
offsetX = -markerWidth;
break;
}
switch (hotspot) {
default:
case NONE:
case TOP_CENTER:
case UPPER_LEFT_CORNER:
case UPPER_RIGHT_CORNER:
offsetY = 0;
break;
case CENTER:
case RIGHT_CENTER:
case LEFT_CENTER:
offsetY = -markerHeight / 2;
break;
case BOTTOM_CENTER:
case LOWER_RIGHT_CORNER:
case LOWER_LEFT_CORNER:
offsetY = -markerHeight;
break;
}
marker.setBounds(offsetX, offsetY, offsetX + markerWidth, offsetY + markerHeight);
return marker;
} } | public class class_name {
protected Drawable boundToHotspot(final Drawable marker, HotspotPlace hotspot) {
if (hotspot == null) {
hotspot = HotspotPlace.BOTTOM_CENTER; // depends on control dependency: [if], data = [none]
}
final int markerWidth = marker.getIntrinsicWidth();
final int markerHeight = marker.getIntrinsicHeight();
final int offsetX;
final int offsetY;
switch(hotspot) {
default:
case NONE:
case LEFT_CENTER:
case UPPER_LEFT_CORNER:
case LOWER_LEFT_CORNER:
offsetX = 0;
break;
case CENTER:
case BOTTOM_CENTER:
case TOP_CENTER:
offsetX = -markerWidth / 2;
break;
case RIGHT_CENTER:
case UPPER_RIGHT_CORNER:
case LOWER_RIGHT_CORNER:
offsetX = -markerWidth;
break;
}
switch (hotspot) {
default:
case NONE:
case TOP_CENTER:
case UPPER_LEFT_CORNER:
case UPPER_RIGHT_CORNER:
offsetY = 0;
break;
case CENTER:
case RIGHT_CENTER:
case LEFT_CENTER:
offsetY = -markerHeight / 2;
break;
case BOTTOM_CENTER:
case LOWER_RIGHT_CORNER:
case LOWER_LEFT_CORNER:
offsetY = -markerHeight;
break;
}
marker.setBounds(offsetX, offsetY, offsetX + markerWidth, offsetY + markerHeight);
return marker;
} } |
public class class_name {
@Override
public synchronized void onNext(final RuntimeStart startTime) {
if (this.isPidNotWritten()) {
final long pid = OSUtils.getPID();
final File outfile = new File(PID_FILE_NAME);
LOG.log(Level.FINEST, "Storing pid `" + pid + "` in file " + outfile.getAbsolutePath());
try (final PrintWriter p = new PrintWriter(PID_FILE_NAME, "UTF-8")) {
p.write(String.valueOf(pid));
p.write("\n");
} catch (final FileNotFoundException | UnsupportedEncodingException e) {
LOG.log(Level.WARNING, "Unable to create PID file.", e);
}
this.pidIsWritten = true;
} else {
LOG.log(Level.FINEST, "PID already written.");
}
} } | public class class_name {
@Override
public synchronized void onNext(final RuntimeStart startTime) {
if (this.isPidNotWritten()) {
final long pid = OSUtils.getPID();
final File outfile = new File(PID_FILE_NAME);
LOG.log(Level.FINEST, "Storing pid `" + pid + "` in file " + outfile.getAbsolutePath()); // depends on control dependency: [if], data = [none]
try (final PrintWriter p = new PrintWriter(PID_FILE_NAME, "UTF-8")) {
p.write(String.valueOf(pid));
p.write("\n"); // depends on control dependency: [if], data = [none]
} catch (final FileNotFoundException | UnsupportedEncodingException e) {
LOG.log(Level.WARNING, "Unable to create PID file.", e);
}
this.pidIsWritten = true;
} else {
LOG.log(Level.FINEST, "PID already written.");
}
} } |
public class class_name {
public static String toBinary(final byte[] pBytes) {
String ret = null;
if (pBytes != null && pBytes.length > 0) {
BigInteger val = new BigInteger(bytesToStringNoSpace(pBytes), HEXA);
StringBuilder build = new StringBuilder(val.toString(2));
// left pad with 0 to fit byte size
for (int i = build.length(); i < pBytes.length * BitUtils.BYTE_SIZE; i++) {
build.insert(0, 0);
}
ret = build.toString();
}
return ret;
} } | public class class_name {
public static String toBinary(final byte[] pBytes) {
String ret = null;
if (pBytes != null && pBytes.length > 0) {
BigInteger val = new BigInteger(bytesToStringNoSpace(pBytes), HEXA);
StringBuilder build = new StringBuilder(val.toString(2));
// left pad with 0 to fit byte size
for (int i = build.length(); i < pBytes.length * BitUtils.BYTE_SIZE; i++) {
build.insert(0, 0);
// depends on control dependency: [for], data = [none]
}
ret = build.toString();
// depends on control dependency: [if], data = [none]
}
return ret;
} } |
public class class_name {
public String getRepository()
{
if (repository == null)
{
try
{
return repositoryService.getCurrentRepository().getConfiguration().getName();
}
catch (RepositoryException e)
{
throw new RuntimeException("Can not get current repository and repository name was not configured", e);
}
}
else
{
return repository;
}
} } | public class class_name {
public String getRepository()
{
if (repository == null)
{
try
{
return repositoryService.getCurrentRepository().getConfiguration().getName(); // depends on control dependency: [try], data = [none]
}
catch (RepositoryException e)
{
throw new RuntimeException("Can not get current repository and repository name was not configured", e);
} // depends on control dependency: [catch], data = [none]
}
else
{
return repository; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private Record parseResponse(InputStream response) throws StageException {
Record record = null;
if (conf.httpMethod == HttpMethod.HEAD) {
// Head will have no body so can't be parsed. Return an empty record.
record = getContext().createRecord("");
record.set(Field.create(new HashMap()));
} else if (response != null) {
try (DataParser parser = parserFactory.getParser("", response, "0")) {
// A response may only contain a single record, so we only parse it once.
record = parser.parse();
if (conf.dataFormat == DataFormat.TEXT) {
// Output is placed in a field "/text" so we remove it here.
record.set(record.get("/text"));
}
} catch (IOException | DataParserException e) {
errorRecordHandler.onError(Errors.HTTP_00, e.toString(), e);
}
}
return record;
} } | public class class_name {
private Record parseResponse(InputStream response) throws StageException {
Record record = null;
if (conf.httpMethod == HttpMethod.HEAD) {
// Head will have no body so can't be parsed. Return an empty record.
record = getContext().createRecord("");
record.set(Field.create(new HashMap()));
} else if (response != null) {
try (DataParser parser = parserFactory.getParser("", response, "0")) {
// A response may only contain a single record, so we only parse it once.
record = parser.parse();
if (conf.dataFormat == DataFormat.TEXT) {
// Output is placed in a field "/text" so we remove it here.
record.set(record.get("/text")); // depends on control dependency: [if], data = [none]
}
} catch (IOException | DataParserException e) {
errorRecordHandler.onError(Errors.HTTP_00, e.toString(), e);
}
}
return record;
} } |
public class class_name {
public void clear() {
if (m_handlerRegistration != null) {
m_handlerRegistration.removeHandler();
m_handlerRegistration = null;
}
m_changeListeners.clear();
m_scopeValues.clear();
m_observerdEntity = null;
} } | public class class_name {
public void clear() {
if (m_handlerRegistration != null) {
m_handlerRegistration.removeHandler();
// depends on control dependency: [if], data = [none]
m_handlerRegistration = null;
// depends on control dependency: [if], data = [none]
}
m_changeListeners.clear();
m_scopeValues.clear();
m_observerdEntity = null;
} } |
public class class_name {
protected void populateObjectMetadata(HttpResponse response, ObjectMetadata metadata) {
for (Entry<String, String> header : response.getHeaders().entrySet()) {
String key = header.getKey();
if (StringUtils.beginsWithIgnoreCase(key, Headers.S3_USER_METADATA_PREFIX)) {
key = key.substring(Headers.S3_USER_METADATA_PREFIX.length());
metadata.addUserMetadata(key, header.getValue());
} else if (ignoredHeaders.contains(key)) {
// ignore...
} else if (key.equalsIgnoreCase(Headers.LAST_MODIFIED)) {
try {
metadata.setHeader(key, ServiceUtils.parseRfc822Date(header.getValue()));
} catch (Exception pe) {
log.warn("Unable to parse last modified date: " + header.getValue(), pe);
}
} else if (key.equalsIgnoreCase(Headers.CONTENT_LENGTH)) {
try {
metadata.setHeader(key, Long.parseLong(header.getValue()));
} catch (NumberFormatException nfe) {
throw new SdkClientException(
"Unable to parse content length. Header 'Content-Length' has corrupted data" + nfe.getMessage(), nfe);
}
} else if (key.equalsIgnoreCase(Headers.ETAG)) {
metadata.setHeader(key, ServiceUtils.removeQuotes(header.getValue()));
} else if (key.equalsIgnoreCase(Headers.EXPIRES)) {
try {
metadata.setHttpExpiresDate(DateUtils.parseRFC822Date(header.getValue()));
} catch (Exception pe) {
log.warn("Unable to parse http expiration date: " + header.getValue(), pe);
}
} else if (key.equalsIgnoreCase(Headers.EXPIRATION)) {
new ObjectExpirationHeaderHandler<ObjectMetadata>().handle(metadata, response);
} else if (key.equalsIgnoreCase(Headers.RESTORE)) {
new ObjectRestoreHeaderHandler<ObjectRestoreResult>().handle(metadata, response);
} else if (key.equalsIgnoreCase(Headers.IBM_TRANSITION)) {
new ObjectTransitionHeaderHandler<ObjectTransitionResult>().handle(metadata, response);
metadata.setHeader(key, header.getValue());
} else if (key.equalsIgnoreCase(Headers.REQUESTER_CHARGED_HEADER)) {
new S3RequesterChargedHeaderHandler<S3RequesterChargedResult>().handle(metadata, response);
} else if (key.equalsIgnoreCase(Headers.S3_PARTS_COUNT)) {
try {
metadata.setHeader(key, Integer.parseInt(header.getValue()));
} catch (NumberFormatException nfe) {
throw new SdkClientException(
"Unable to parse part count. Header x-amz-mp-parts-count has corrupted data" + nfe.getMessage(), nfe);
}
} else if (key.equalsIgnoreCase(Headers.RETENTION_EXPIRATION_DATE)) {
try {
metadata.setRetentionExpirationDate(ServiceUtils.parseRfc822Date(header.getValue()));
} catch (Exception pe) {
log.warn("Unable to parse retention expiration date: " + header.getValue(), pe);
}
} else if (key.equalsIgnoreCase(Headers.RETENTION_LEGAL_HOLD_COUNT)) {
try {
metadata.setRetentionLegalHoldCount(Integer.parseInt(header.getValue()));
} catch (NumberFormatException nfe) {
log.warn("Unable to parse legal hold count: " + header.getValue(), nfe);
}
} else if (key.equalsIgnoreCase(Headers.RETENTION_PERIOD)) {
try {
metadata.setRetentionPeriod(Long.parseLong(header.getValue()));
} catch (NumberFormatException nfe) {
log.warn("Unable to parse retention period: " + header.getValue(), nfe);
}
} else {
metadata.setHeader(key, header.getValue());
}
}
} } | public class class_name {
protected void populateObjectMetadata(HttpResponse response, ObjectMetadata metadata) {
for (Entry<String, String> header : response.getHeaders().entrySet()) {
String key = header.getKey();
if (StringUtils.beginsWithIgnoreCase(key, Headers.S3_USER_METADATA_PREFIX)) {
key = key.substring(Headers.S3_USER_METADATA_PREFIX.length()); // depends on control dependency: [if], data = [none]
metadata.addUserMetadata(key, header.getValue()); // depends on control dependency: [if], data = [none]
} else if (ignoredHeaders.contains(key)) {
// ignore...
} else if (key.equalsIgnoreCase(Headers.LAST_MODIFIED)) {
try {
metadata.setHeader(key, ServiceUtils.parseRfc822Date(header.getValue())); // depends on control dependency: [try], data = [none]
} catch (Exception pe) {
log.warn("Unable to parse last modified date: " + header.getValue(), pe);
} // depends on control dependency: [catch], data = [none]
} else if (key.equalsIgnoreCase(Headers.CONTENT_LENGTH)) {
try {
metadata.setHeader(key, Long.parseLong(header.getValue())); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException nfe) {
throw new SdkClientException(
"Unable to parse content length. Header 'Content-Length' has corrupted data" + nfe.getMessage(), nfe);
} // depends on control dependency: [catch], data = [none]
} else if (key.equalsIgnoreCase(Headers.ETAG)) {
metadata.setHeader(key, ServiceUtils.removeQuotes(header.getValue())); // depends on control dependency: [if], data = [none]
} else if (key.equalsIgnoreCase(Headers.EXPIRES)) {
try {
metadata.setHttpExpiresDate(DateUtils.parseRFC822Date(header.getValue())); // depends on control dependency: [try], data = [none]
} catch (Exception pe) {
log.warn("Unable to parse http expiration date: " + header.getValue(), pe);
} // depends on control dependency: [catch], data = [none]
} else if (key.equalsIgnoreCase(Headers.EXPIRATION)) {
new ObjectExpirationHeaderHandler<ObjectMetadata>().handle(metadata, response); // depends on control dependency: [if], data = [none]
} else if (key.equalsIgnoreCase(Headers.RESTORE)) {
new ObjectRestoreHeaderHandler<ObjectRestoreResult>().handle(metadata, response); // depends on control dependency: [if], data = [none]
} else if (key.equalsIgnoreCase(Headers.IBM_TRANSITION)) {
new ObjectTransitionHeaderHandler<ObjectTransitionResult>().handle(metadata, response); // depends on control dependency: [if], data = [none]
metadata.setHeader(key, header.getValue()); // depends on control dependency: [if], data = [none]
} else if (key.equalsIgnoreCase(Headers.REQUESTER_CHARGED_HEADER)) {
new S3RequesterChargedHeaderHandler<S3RequesterChargedResult>().handle(metadata, response); // depends on control dependency: [if], data = [none]
} else if (key.equalsIgnoreCase(Headers.S3_PARTS_COUNT)) {
try {
metadata.setHeader(key, Integer.parseInt(header.getValue())); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException nfe) {
throw new SdkClientException(
"Unable to parse part count. Header x-amz-mp-parts-count has corrupted data" + nfe.getMessage(), nfe);
} // depends on control dependency: [catch], data = [none]
} else if (key.equalsIgnoreCase(Headers.RETENTION_EXPIRATION_DATE)) {
try {
metadata.setRetentionExpirationDate(ServiceUtils.parseRfc822Date(header.getValue())); // depends on control dependency: [try], data = [none]
} catch (Exception pe) {
log.warn("Unable to parse retention expiration date: " + header.getValue(), pe);
} // depends on control dependency: [catch], data = [none]
} else if (key.equalsIgnoreCase(Headers.RETENTION_LEGAL_HOLD_COUNT)) {
try {
metadata.setRetentionLegalHoldCount(Integer.parseInt(header.getValue())); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException nfe) {
log.warn("Unable to parse legal hold count: " + header.getValue(), nfe);
} // depends on control dependency: [catch], data = [none]
} else if (key.equalsIgnoreCase(Headers.RETENTION_PERIOD)) {
try {
metadata.setRetentionPeriod(Long.parseLong(header.getValue())); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException nfe) {
log.warn("Unable to parse retention period: " + header.getValue(), nfe);
} // depends on control dependency: [catch], data = [none]
} else {
metadata.setHeader(key, header.getValue()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
public JSONObject toJsonObject() throws JSONException {
JSONObject returnVal = new JSONObject();
//Template Name...
if(this.getTemplateName() != null)
{
returnVal.put(JSONMapping.TEMPLATE_NAME,
this.getTemplateName());
}
//Template Description...
if(this.getTemplateDescription() != null)
{
returnVal.put(JSONMapping.TEMPLATE_DESCRIPTION,
this.getTemplateDescription());
}
//Template Comment...
if(this.getTemplateComment() != null)
{
returnVal.put(JSONMapping.TEMPLATE_COMMENT,
this.getTemplateComment());
}
//Forms and Fields...
if(this.getFormsAndFields() != null && !this.getFormsAndFields().isEmpty())
{
JSONArray jsonArray = new JSONArray();
for(Form form : this.getFormsAndFields())
{
jsonArray.put(form.toJsonObject());
}
returnVal.put(JSONMapping.FORMS_AND_FIELDS, jsonArray);
}
//User Queries...
if(this.getUserQueries() != null && !this.getUserQueries().isEmpty())
{
JSONArray jsonArray = new JSONArray();
for(UserQuery userQuery : this.getUserQueries())
{
jsonArray.put(userQuery.toJsonObject());
}
returnVal.put(JSONMapping.USER_QUERIES, jsonArray);
}
//Flows...
if(this.getFlows() != null && !this.getFlows().isEmpty())
{
JSONArray jsonArray = new JSONArray();
for(Flow flow : this.getFlows())
{
jsonArray.put(flow.toJsonObject());
}
returnVal.put(JSONMapping.FLOWS, jsonArray);
}
//Third Party Libraries...
if(this.getThirdPartyLibraries() != null &&
!this.getThirdPartyLibraries().isEmpty())
{
JSONArray jsonArray = new JSONArray();
for(ThirdPartyLibrary thirdPartyLibrary : this.getThirdPartyLibraries())
{
jsonArray.put(thirdPartyLibrary.toJsonObject());
}
returnVal.put(JSONMapping.THIRD_PARTY_LIBRARIES, jsonArray);
}
//User Fields...
if(this.getUserFields() != null && !this.getUserFields().isEmpty())
{
JSONArray jsonArray = new JSONArray();
for(Field field : this.getUserFields())
{
jsonArray.put(field.toJsonObject());
}
returnVal.put(JSONMapping.USER_FIELDS, jsonArray);
}
//Route Fields...
if(this.getRouteFields() != null && !this.getRouteFields().isEmpty())
{
JSONArray fieldsArr = new JSONArray();
for(Field toAdd :this.getRouteFields())
{
fieldsArr.put(toAdd.toJsonObject());
}
returnVal.put(JSONMapping.ROUTE_FIELDS, fieldsArr);
}
//Global Fields...
if(this.getGlobalFields() != null && !this.getGlobalFields().isEmpty())
{
JSONArray fieldsArr = new JSONArray();
for(Field toAdd :this.getGlobalFields())
{
fieldsArr.put(toAdd.toJsonObject());
}
returnVal.put(JSONMapping.GLOBAL_FIELDS, fieldsArr);
}
return returnVal;
} } | public class class_name {
@Override
public JSONObject toJsonObject() throws JSONException {
JSONObject returnVal = new JSONObject();
//Template Name...
if(this.getTemplateName() != null)
{
returnVal.put(JSONMapping.TEMPLATE_NAME,
this.getTemplateName());
}
//Template Description...
if(this.getTemplateDescription() != null)
{
returnVal.put(JSONMapping.TEMPLATE_DESCRIPTION,
this.getTemplateDescription());
}
//Template Comment...
if(this.getTemplateComment() != null)
{
returnVal.put(JSONMapping.TEMPLATE_COMMENT,
this.getTemplateComment());
}
//Forms and Fields...
if(this.getFormsAndFields() != null && !this.getFormsAndFields().isEmpty())
{
JSONArray jsonArray = new JSONArray();
for(Form form : this.getFormsAndFields())
{
jsonArray.put(form.toJsonObject()); // depends on control dependency: [for], data = [form]
}
returnVal.put(JSONMapping.FORMS_AND_FIELDS, jsonArray);
}
//User Queries...
if(this.getUserQueries() != null && !this.getUserQueries().isEmpty())
{
JSONArray jsonArray = new JSONArray();
for(UserQuery userQuery : this.getUserQueries())
{
jsonArray.put(userQuery.toJsonObject());
}
returnVal.put(JSONMapping.USER_QUERIES, jsonArray);
}
//Flows...
if(this.getFlows() != null && !this.getFlows().isEmpty())
{
JSONArray jsonArray = new JSONArray();
for(Flow flow : this.getFlows())
{
jsonArray.put(flow.toJsonObject());
}
returnVal.put(JSONMapping.FLOWS, jsonArray);
}
//Third Party Libraries...
if(this.getThirdPartyLibraries() != null &&
!this.getThirdPartyLibraries().isEmpty())
{
JSONArray jsonArray = new JSONArray();
for(ThirdPartyLibrary thirdPartyLibrary : this.getThirdPartyLibraries())
{
jsonArray.put(thirdPartyLibrary.toJsonObject());
}
returnVal.put(JSONMapping.THIRD_PARTY_LIBRARIES, jsonArray);
}
//User Fields...
if(this.getUserFields() != null && !this.getUserFields().isEmpty())
{
JSONArray jsonArray = new JSONArray();
for(Field field : this.getUserFields())
{
jsonArray.put(field.toJsonObject());
}
returnVal.put(JSONMapping.USER_FIELDS, jsonArray);
}
//Route Fields...
if(this.getRouteFields() != null && !this.getRouteFields().isEmpty())
{
JSONArray fieldsArr = new JSONArray();
for(Field toAdd :this.getRouteFields())
{
fieldsArr.put(toAdd.toJsonObject());
}
returnVal.put(JSONMapping.ROUTE_FIELDS, fieldsArr);
}
//Global Fields...
if(this.getGlobalFields() != null && !this.getGlobalFields().isEmpty())
{
JSONArray fieldsArr = new JSONArray();
for(Field toAdd :this.getGlobalFields())
{
fieldsArr.put(toAdd.toJsonObject());
}
returnVal.put(JSONMapping.GLOBAL_FIELDS, fieldsArr);
}
return returnVal;
} } |
public class class_name {
public void convertGeometryFromEnuToWgs84( Geometry geometryEnu ) {
Coordinate[] coordinates = geometryEnu.getCoordinates();
for( int i = 0; i < coordinates.length; i++ ) {
Coordinate wgs84 = enuToWgs84(coordinates[i]);
coordinates[i].x = wgs84.x;
coordinates[i].y = wgs84.y;
coordinates[i].z = wgs84.z;
}
} } | public class class_name {
public void convertGeometryFromEnuToWgs84( Geometry geometryEnu ) {
Coordinate[] coordinates = geometryEnu.getCoordinates();
for( int i = 0; i < coordinates.length; i++ ) {
Coordinate wgs84 = enuToWgs84(coordinates[i]);
coordinates[i].x = wgs84.x; // depends on control dependency: [for], data = [i]
coordinates[i].y = wgs84.y; // depends on control dependency: [for], data = [i]
coordinates[i].z = wgs84.z; // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
public void setTextOrientation(final TextOrientation ORIENTATION) {
if (null == textOrientation) {
_textOrientation = ORIENTATION;
redraw();
} else {
textOrientation.set(ORIENTATION);
}
} } | public class class_name {
public void setTextOrientation(final TextOrientation ORIENTATION) {
if (null == textOrientation) {
_textOrientation = ORIENTATION; // depends on control dependency: [if], data = [none]
redraw(); // depends on control dependency: [if], data = [none]
} else {
textOrientation.set(ORIENTATION); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setKeyword(java.util.Collection<KeywordFilter> keyword) {
if (keyword == null) {
this.keyword = null;
return;
}
this.keyword = new java.util.ArrayList<KeywordFilter>(keyword);
} } | public class class_name {
public void setKeyword(java.util.Collection<KeywordFilter> keyword) {
if (keyword == null) {
this.keyword = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.keyword = new java.util.ArrayList<KeywordFilter>(keyword);
} } |
public class class_name {
private void cloneTransitionPath(MDAGNode pivotConfluenceNode, String transitionStringToPivotNode, String str)
{
MDAGNode lastTargetNode = pivotConfluenceNode.transition(str); //Will store the last node which was used as the base of a cloning operation
MDAGNode lastClonedNode = null; //Will store the last cloned node
char lastTransitionLabelChar = '\0'; //Will store the char which labels the _transition to lastTargetNode from its parent node in the prefixString's _transition path
//Loop backwards through the indices of str, using each as a boundary to create substrings of str of decreasing length
//which will be used to _transition to, and duplicate the nodes in the _transition path of str from pivotConfluenceNode.
for (int i = str.length(); i >= 0; i--)
{
String currentTransitionString = (i > 0 ? str.substring(0, i) : null);
MDAGNode currentTargetNode = (i > 0 ? pivotConfluenceNode.transition(currentTransitionString) : pivotConfluenceNode);
MDAGNode clonedNode;
if (i == 0) //if we have reached pivotConfluenceNode
{
//Clone pivotConfluenceNode in a way that reassigns the _transition of its parent node (in transitionStringToConfluenceNode's path) to the clone.
String transitionStringToPivotNodeParent = transitionStringToPivotNode.substring(0, transitionStringToPivotNode.length() - 1);
char parentTransitionLabelChar = transitionStringToPivotNode.charAt(transitionStringToPivotNode.length() - 1);
clonedNode = pivotConfluenceNode.clone(sourceNode.transition(transitionStringToPivotNodeParent), parentTransitionLabelChar);
/////
}
else
clonedNode = currentTargetNode.clone(); //simply clone curentTargetNode
transitionCount += clonedNode.getOutgoingTransitionCount();
//If this isn't the first node we've cloned, reassign clonedNode's _transition labeled
//with the lastTransitionChar (which points to the last targetNode) to the last clone.
if (lastClonedNode != null)
{
clonedNode.reassignOutgoingTransition(lastTransitionLabelChar, lastTargetNode, lastClonedNode);
lastTargetNode = currentTargetNode;
}
//Store clonedNode and the char which labels the _transition between the node it was cloned from (currentTargetNode) and THAT node's parent.
//These will be used to establish an equivalent _transition to clonedNode from the next clone to be created (it's clone parent).
lastClonedNode = clonedNode;
lastTransitionLabelChar = (i > 0 ? str.charAt(i - 1) : '\0');
/////
}
/////
} } | public class class_name {
private void cloneTransitionPath(MDAGNode pivotConfluenceNode, String transitionStringToPivotNode, String str)
{
MDAGNode lastTargetNode = pivotConfluenceNode.transition(str); //Will store the last node which was used as the base of a cloning operation
MDAGNode lastClonedNode = null; //Will store the last cloned node
char lastTransitionLabelChar = '\0'; //Will store the char which labels the _transition to lastTargetNode from its parent node in the prefixString's _transition path
//Loop backwards through the indices of str, using each as a boundary to create substrings of str of decreasing length
//which will be used to _transition to, and duplicate the nodes in the _transition path of str from pivotConfluenceNode.
for (int i = str.length(); i >= 0; i--)
{
String currentTransitionString = (i > 0 ? str.substring(0, i) : null);
MDAGNode currentTargetNode = (i > 0 ? pivotConfluenceNode.transition(currentTransitionString) : pivotConfluenceNode);
MDAGNode clonedNode;
if (i == 0) //if we have reached pivotConfluenceNode
{
//Clone pivotConfluenceNode in a way that reassigns the _transition of its parent node (in transitionStringToConfluenceNode's path) to the clone.
String transitionStringToPivotNodeParent = transitionStringToPivotNode.substring(0, transitionStringToPivotNode.length() - 1);
char parentTransitionLabelChar = transitionStringToPivotNode.charAt(transitionStringToPivotNode.length() - 1);
clonedNode = pivotConfluenceNode.clone(sourceNode.transition(transitionStringToPivotNodeParent), parentTransitionLabelChar); // depends on control dependency: [if], data = [none]
/////
}
else
clonedNode = currentTargetNode.clone(); //simply clone curentTargetNode
transitionCount += clonedNode.getOutgoingTransitionCount(); // depends on control dependency: [for], data = [none]
//If this isn't the first node we've cloned, reassign clonedNode's _transition labeled
//with the lastTransitionChar (which points to the last targetNode) to the last clone.
if (lastClonedNode != null)
{
clonedNode.reassignOutgoingTransition(lastTransitionLabelChar, lastTargetNode, lastClonedNode); // depends on control dependency: [if], data = [none]
lastTargetNode = currentTargetNode; // depends on control dependency: [if], data = [none]
}
//Store clonedNode and the char which labels the _transition between the node it was cloned from (currentTargetNode) and THAT node's parent.
//These will be used to establish an equivalent _transition to clonedNode from the next clone to be created (it's clone parent).
lastClonedNode = clonedNode; // depends on control dependency: [for], data = [none]
lastTransitionLabelChar = (i > 0 ? str.charAt(i - 1) : '\0'); // depends on control dependency: [for], data = [i]
/////
}
/////
} } |
public class class_name {
private boolean canStay(VM vm) {
Mapping m = rp.getSourceModel().getMapping();
if (m.isRunning(vm)) {
int curPos = rp.getNode(m.getVMLocation(vm));
if (!rp.getVMAction(vm).getDSlice().getHoster().contains(curPos)) {
return false;
}
IStateInt[] loads = load(curPos);
return loadWith(curPos, loads, vm) <= 1.0;
}
return false;
} } | public class class_name {
private boolean canStay(VM vm) {
Mapping m = rp.getSourceModel().getMapping();
if (m.isRunning(vm)) {
int curPos = rp.getNode(m.getVMLocation(vm));
if (!rp.getVMAction(vm).getDSlice().getHoster().contains(curPos)) {
return false; // depends on control dependency: [if], data = [none]
}
IStateInt[] loads = load(curPos);
return loadWith(curPos, loads, vm) <= 1.0; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public <OUT> DataStreamSource<OUT> fromCollection(Collection<OUT> data) {
Preconditions.checkNotNull(data, "Collection must not be null");
if (data.isEmpty()) {
throw new IllegalArgumentException("Collection must not be empty");
}
OUT first = data.iterator().next();
if (first == null) {
throw new IllegalArgumentException("Collection must not contain null elements");
}
TypeInformation<OUT> typeInfo;
try {
typeInfo = TypeExtractor.getForObject(first);
}
catch (Exception e) {
throw new RuntimeException("Could not create TypeInformation for type " + first.getClass()
+ "; please specify the TypeInformation manually via "
+ "StreamExecutionEnvironment#fromElements(Collection, TypeInformation)", e);
}
return fromCollection(data, typeInfo);
} } | public class class_name {
public <OUT> DataStreamSource<OUT> fromCollection(Collection<OUT> data) {
Preconditions.checkNotNull(data, "Collection must not be null");
if (data.isEmpty()) {
throw new IllegalArgumentException("Collection must not be empty");
}
OUT first = data.iterator().next();
if (first == null) {
throw new IllegalArgumentException("Collection must not contain null elements");
}
TypeInformation<OUT> typeInfo;
try {
typeInfo = TypeExtractor.getForObject(first); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
throw new RuntimeException("Could not create TypeInformation for type " + first.getClass()
+ "; please specify the TypeInformation manually via "
+ "StreamExecutionEnvironment#fromElements(Collection, TypeInformation)", e);
} // depends on control dependency: [catch], data = [none]
return fromCollection(data, typeInfo);
} } |
public class class_name {
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription);
break;
}
}
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
if (subscriberMethod.sticky) {
if (eventInheritance) {
// Existing sticky events of all subclasses of eventType have to be considered.
// Note: Iterating over all events may be inefficient with lots of sticky events,
// thus data structure should be changed to allow a more efficient lookup
// (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
for (Map.Entry<Class<?>, Object> entry : entries) {
Class<?> candidateEventType = entry.getKey();
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} } | public class class_name {
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription); // depends on control dependency: [if], data = [(i]
break;
}
}
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>(); // depends on control dependency: [if], data = [none]
typesBySubscriber.put(subscriber, subscribedEvents); // depends on control dependency: [if], data = [none]
}
subscribedEvents.add(eventType);
if (subscriberMethod.sticky) {
if (eventInheritance) {
// Existing sticky events of all subclasses of eventType have to be considered.
// Note: Iterating over all events may be inefficient with lots of sticky events,
// thus data structure should be changed to allow a more efficient lookup
// (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
for (Map.Entry<Class<?>, Object> entry : entries) {
Class<?> candidateEventType = entry.getKey();
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSubscription, stickyEvent); // depends on control dependency: [if], data = [none]
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void marshall(AssociateAdminAccountRequest associateAdminAccountRequest, ProtocolMarshaller protocolMarshaller) {
if (associateAdminAccountRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(associateAdminAccountRequest.getAdminAccount(), ADMINACCOUNT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(AssociateAdminAccountRequest associateAdminAccountRequest, ProtocolMarshaller protocolMarshaller) {
if (associateAdminAccountRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(associateAdminAccountRequest.getAdminAccount(), ADMINACCOUNT_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 HtmlPolicyBuilder allowElements(
ElementPolicy policy, String... elementNames) {
invalidateCompiledState();
for (String elementName : elementNames) {
elementName = HtmlLexer.canonicalName(elementName);
ElementPolicy newPolicy = ElementPolicy.Util.join(
elPolicies.get(elementName), policy);
// Don't remove if newPolicy is the always reject policy since we want
// that to infect later allowElement calls for this particular element
// name. rejects should have higher priority than allows.
elPolicies.put(elementName, newPolicy);
if (!textContainers.containsKey(elementName)) {
if (METADATA.canContainPlainText(METADATA.indexForName(elementName))) {
textContainers.put(elementName, true);
}
}
}
return this;
} } | public class class_name {
public HtmlPolicyBuilder allowElements(
ElementPolicy policy, String... elementNames) {
invalidateCompiledState();
for (String elementName : elementNames) {
elementName = HtmlLexer.canonicalName(elementName); // depends on control dependency: [for], data = [elementName]
ElementPolicy newPolicy = ElementPolicy.Util.join(
elPolicies.get(elementName), policy);
// Don't remove if newPolicy is the always reject policy since we want
// that to infect later allowElement calls for this particular element
// name. rejects should have higher priority than allows.
elPolicies.put(elementName, newPolicy); // depends on control dependency: [for], data = [elementName]
if (!textContainers.containsKey(elementName)) {
if (METADATA.canContainPlainText(METADATA.indexForName(elementName))) {
textContainers.put(elementName, true); // depends on control dependency: [if], data = [none]
}
}
}
return this;
} } |
public class class_name {
public String[] getAllTemplateNames(boolean recurse)
throws IOException {
if (mTemplateProviderMap == null) {
synchronized (this) {
mTemplateProviderMap = new HashMap<String, CompilationProvider>();
for (CompilationProvider provider : mCompilationProviders) {
String[] templates = provider.getKnownTemplateNames(recurse);
for (String template : templates) {
if (!mTemplateProviderMap.containsKey(template)) {
mTemplateProviderMap.put(template, provider);
}
}
}
}
}
return mTemplateProviderMap.keySet().toArray(
new String[mTemplateProviderMap.size()]);
} } | public class class_name {
public String[] getAllTemplateNames(boolean recurse)
throws IOException {
if (mTemplateProviderMap == null) {
synchronized (this) {
mTemplateProviderMap = new HashMap<String, CompilationProvider>();
for (CompilationProvider provider : mCompilationProviders) {
String[] templates = provider.getKnownTemplateNames(recurse);
for (String template : templates) {
if (!mTemplateProviderMap.containsKey(template)) {
mTemplateProviderMap.put(template, provider); // depends on control dependency: [if], data = [none]
}
}
}
}
}
return mTemplateProviderMap.keySet().toArray(
new String[mTemplateProviderMap.size()]);
} } |
public class class_name {
public static MapBounds adjustBoundsToScaleAndMapSize(
final GenericMapAttributeValues mapValues,
final Rectangle paintArea,
final MapBounds bounds,
final double dpi) {
MapBounds newBounds = bounds;
if (mapValues.isUseNearestScale()) {
newBounds = newBounds.adjustBoundsToNearestScale(
mapValues.getZoomLevels(),
mapValues.getZoomSnapTolerance(),
mapValues.getZoomLevelSnapStrategy(),
mapValues.getZoomSnapGeodetic(),
paintArea, dpi);
}
newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));
if (mapValues.isUseAdjustBounds()) {
newBounds = newBounds.adjustedEnvelope(paintArea);
}
return newBounds;
} } | public class class_name {
public static MapBounds adjustBoundsToScaleAndMapSize(
final GenericMapAttributeValues mapValues,
final Rectangle paintArea,
final MapBounds bounds,
final double dpi) {
MapBounds newBounds = bounds;
if (mapValues.isUseNearestScale()) {
newBounds = newBounds.adjustBoundsToNearestScale(
mapValues.getZoomLevels(),
mapValues.getZoomSnapTolerance(),
mapValues.getZoomLevelSnapStrategy(),
mapValues.getZoomSnapGeodetic(),
paintArea, dpi); // depends on control dependency: [if], data = [none]
}
newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));
if (mapValues.isUseAdjustBounds()) {
newBounds = newBounds.adjustedEnvelope(paintArea); // depends on control dependency: [if], data = [none]
}
return newBounds;
} } |
public class class_name {
public static Boolean xor(Boolean... bools)
{
Parameters.checkCondition(bools.length > 0);
boolean xor = false;
for (Boolean bool : bools) {
if (bool) {
if (xor) {
return FALSE;
} else {
xor = true;
}
}
}
return xor ? TRUE : FALSE;
} } | public class class_name {
public static Boolean xor(Boolean... bools)
{
Parameters.checkCondition(bools.length > 0);
boolean xor = false;
for (Boolean bool : bools) {
if (bool) {
if (xor) {
return FALSE; // depends on control dependency: [if], data = [none]
} else {
xor = true; // depends on control dependency: [if], data = [none]
}
}
}
return xor ? TRUE : FALSE;
} } |
public class class_name {
@Override
public short getShort(final int index) {
boundsCheck(index, Bits.SHORT_SIZE_IN_BYTES);
short bits = MEM.getShort(byteArray, addressOffset + index);
if (NATIVE_BYTE_ORDER != PROTOCOL_BYTE_ORDER) {
bits = Short.reverseBytes(bits);
}
return bits;
} } | public class class_name {
@Override
public short getShort(final int index) {
boundsCheck(index, Bits.SHORT_SIZE_IN_BYTES);
short bits = MEM.getShort(byteArray, addressOffset + index);
if (NATIVE_BYTE_ORDER != PROTOCOL_BYTE_ORDER) {
bits = Short.reverseBytes(bits); // depends on control dependency: [if], data = [none]
}
return bits;
} } |
public class class_name {
public boolean isDeprecated(Class<?> clazz) {
// check if class is marked as deprecated
if (clazz.getAnnotation(Deprecated.class) != null) {
return true;
}
// check if super class is deprecated
Class<?> superClass = clazz.getSuperclass();
if (superClass != null) {
return isDeprecated(superClass);
}
// check if interfaces are deprecated
for (Class<?> iface : clazz.getInterfaces()) {
return isDeprecated(iface);
}
// not deprecated
return false;
} } | public class class_name {
public boolean isDeprecated(Class<?> clazz) {
// check if class is marked as deprecated
if (clazz.getAnnotation(Deprecated.class) != null) {
return true; // depends on control dependency: [if], data = [none]
}
// check if super class is deprecated
Class<?> superClass = clazz.getSuperclass();
if (superClass != null) {
return isDeprecated(superClass); // depends on control dependency: [if], data = [(superClass]
}
// check if interfaces are deprecated
for (Class<?> iface : clazz.getInterfaces()) {
return isDeprecated(iface); // depends on control dependency: [for], data = [iface]
}
// not deprecated
return false;
} } |
public class class_name {
private String convertOutputToHtml(String content) {
if (content.length() == 0) {
return "";
}
StringBuilder buffer = new StringBuilder();
for (String line : content.split("\n")) {
buffer.append(CmsEncoder.escapeXml(line) + "<br>");
}
return buffer.toString();
} } | public class class_name {
private String convertOutputToHtml(String content) {
if (content.length() == 0) {
return ""; // depends on control dependency: [if], data = [none]
}
StringBuilder buffer = new StringBuilder();
for (String line : content.split("\n")) {
buffer.append(CmsEncoder.escapeXml(line) + "<br>"); // depends on control dependency: [for], data = [line]
}
return buffer.toString();
} } |
public class class_name {
@Override
public void deleteUnpackedWAR(StandardContext standardContext)
{
File unpackDir = new File(standardHost.getAppBase(), standardContext.getPath().substring(1));
if (unpackDir.exists())
{
ExpandWar.deleteDir(unpackDir);
}
} } | public class class_name {
@Override
public void deleteUnpackedWAR(StandardContext standardContext)
{
File unpackDir = new File(standardHost.getAppBase(), standardContext.getPath().substring(1));
if (unpackDir.exists())
{
ExpandWar.deleteDir(unpackDir); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String replaceObjectNameParameters (String pattern, MBeanLocationParameterSource parameterSource) {
Matcher matcher = replaceParamPattern.matcher(pattern);
StringBuffer result = new StringBuffer();
while ( matcher.find() ) {
String name = matcher.group("paramName");
String value = parameterSource.getParameter(name);
if ( value != null ) {
matcher.appendReplacement(result, value);
} else {
matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group()));
}
}
matcher.appendTail(result);
return result.toString();
} } | public class class_name {
public String replaceObjectNameParameters (String pattern, MBeanLocationParameterSource parameterSource) {
Matcher matcher = replaceParamPattern.matcher(pattern);
StringBuffer result = new StringBuffer();
while ( matcher.find() ) {
String name = matcher.group("paramName");
String value = parameterSource.getParameter(name);
if ( value != null ) {
matcher.appendReplacement(result, value); // depends on control dependency: [if], data = [none]
} else {
matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group())); // depends on control dependency: [if], data = [none]
}
}
matcher.appendTail(result);
return result.toString();
} } |
public class class_name {
public Query rewrite(IndexReader reader) throws IOException {
MoreLikeThis more = new MoreLikeThis(reader);
more.setAnalyzer(analyzer);
more.setFieldNames(new String[]{FieldNames.FULLTEXT});
more.setMinWordLen(4);
Query similarityQuery = null;
TermDocs td = reader.termDocs(new Term(FieldNames.UUID, uuid));
try {
if (td.next()) {
similarityQuery = more.like(td.doc());
}
} finally {
td.close();
}
if (similarityQuery != null) {
return similarityQuery.rewrite(reader);
} else {
// return dummy query that never matches
return new BooleanQuery();
}
} } | public class class_name {
public Query rewrite(IndexReader reader) throws IOException {
MoreLikeThis more = new MoreLikeThis(reader);
more.setAnalyzer(analyzer);
more.setFieldNames(new String[]{FieldNames.FULLTEXT});
more.setMinWordLen(4);
Query similarityQuery = null;
TermDocs td = reader.termDocs(new Term(FieldNames.UUID, uuid));
try {
if (td.next()) {
similarityQuery = more.like(td.doc()); // depends on control dependency: [if], data = [none]
}
} finally {
td.close();
}
if (similarityQuery != null) {
return similarityQuery.rewrite(reader);
} else {
// return dummy query that never matches
return new BooleanQuery();
}
} } |
public class class_name {
public static String computeNewTitleProperty(String name) {
String title = name;
int lastDot = title.lastIndexOf('.');
// check the mime type for the file extension
if ((lastDot > 0) && (lastDot < (title.length() - 1))) {
// remove suffix for Title and NavPos property
title = title.substring(0, lastDot);
}
return title;
} } | public class class_name {
public static String computeNewTitleProperty(String name) {
String title = name;
int lastDot = title.lastIndexOf('.');
// check the mime type for the file extension
if ((lastDot > 0) && (lastDot < (title.length() - 1))) {
// remove suffix for Title and NavPos property
title = title.substring(0, lastDot); // depends on control dependency: [if], data = [none]
}
return title;
} } |
public class class_name {
@Override
public Long dbSize(byte[] pattern) {
long dbSize = 0L;
Jedis jedis = getJedis();
try {
ScanParams params = new ScanParams();
params.count(count);
params.match(pattern);
byte[] cursor = ScanParams.SCAN_POINTER_START_BINARY;
ScanResult<byte[]> scanResult;
do {
scanResult = jedis.scan(cursor, params);
List<byte[]> results = scanResult.getResult();
for (byte[] result : results) {
dbSize++;
}
cursor = scanResult.getCursorAsBytes();
} while (scanResult.getStringCursor().compareTo(ScanParams.SCAN_POINTER_START) > 0);
} finally {
jedis.close();
}
return dbSize;
} } | public class class_name {
@Override
public Long dbSize(byte[] pattern) {
long dbSize = 0L;
Jedis jedis = getJedis();
try {
ScanParams params = new ScanParams();
params.count(count); // depends on control dependency: [try], data = [none]
params.match(pattern); // depends on control dependency: [try], data = [none]
byte[] cursor = ScanParams.SCAN_POINTER_START_BINARY;
ScanResult<byte[]> scanResult;
do {
scanResult = jedis.scan(cursor, params);
List<byte[]> results = scanResult.getResult();
for (byte[] result : results) {
dbSize++; // depends on control dependency: [for], data = [none]
}
cursor = scanResult.getCursorAsBytes();
} while (scanResult.getStringCursor().compareTo(ScanParams.SCAN_POINTER_START) > 0);
} finally {
jedis.close();
}
return dbSize;
} } |
public class class_name {
protected BaseFeatureData selectFeatures(IDataSet dataSet)
{
ChiSquareFeatureExtractor chiSquareFeatureExtractor = new ChiSquareFeatureExtractor();
logger.start("使用卡方检测选择特征中...");
//FeatureStats对象包含文档中所有特征及其统计信息
BaseFeatureData featureData = chiSquareFeatureExtractor.extractBasicFeatureData(dataSet); //执行统计
//我们传入这些统计信息到特征选择算法中,得到特征与其分值
Map<Integer, Double> selectedFeatures = chiSquareFeatureExtractor.chi_square(featureData);
//从统计数据中删掉无用的特征并重建特征映射表
int[][] featureCategoryJointCount = new int[selectedFeatures.size()][];
featureData.wordIdTrie = new BinTrie<Integer>();
String[] wordIdArray = dataSet.getLexicon().getWordIdArray();
int p = -1;
for (Integer feature : selectedFeatures.keySet())
{
featureCategoryJointCount[++p] = featureData.featureCategoryJointCount[feature];
featureData.wordIdTrie.put(wordIdArray[feature], p);
}
logger.finish(",选中特征数:%d / %d = %.2f%%\n", featureCategoryJointCount.length,
featureData.featureCategoryJointCount.length,
featureCategoryJointCount.length / (double)featureData.featureCategoryJointCount.length * 100.);
featureData.featureCategoryJointCount = featureCategoryJointCount;
return featureData;
} } | public class class_name {
protected BaseFeatureData selectFeatures(IDataSet dataSet)
{
ChiSquareFeatureExtractor chiSquareFeatureExtractor = new ChiSquareFeatureExtractor();
logger.start("使用卡方检测选择特征中...");
//FeatureStats对象包含文档中所有特征及其统计信息
BaseFeatureData featureData = chiSquareFeatureExtractor.extractBasicFeatureData(dataSet); //执行统计
//我们传入这些统计信息到特征选择算法中,得到特征与其分值
Map<Integer, Double> selectedFeatures = chiSquareFeatureExtractor.chi_square(featureData);
//从统计数据中删掉无用的特征并重建特征映射表
int[][] featureCategoryJointCount = new int[selectedFeatures.size()][];
featureData.wordIdTrie = new BinTrie<Integer>();
String[] wordIdArray = dataSet.getLexicon().getWordIdArray();
int p = -1;
for (Integer feature : selectedFeatures.keySet())
{
featureCategoryJointCount[++p] = featureData.featureCategoryJointCount[feature]; // depends on control dependency: [for], data = [feature]
featureData.wordIdTrie.put(wordIdArray[feature], p); // depends on control dependency: [for], data = [feature]
}
logger.finish(",选中特征数:%d / %d = %.2f%%\n", featureCategoryJointCount.length,
featureData.featureCategoryJointCount.length,
featureCategoryJointCount.length / (double)featureData.featureCategoryJointCount.length * 100.);
featureData.featureCategoryJointCount = featureCategoryJointCount;
return featureData;
} } |
public class class_name {
public String getRawJobHistory(QualifiedJobId jobId) throws IOException {
String historyData = null;
byte[] rowKey = idConv.toBytes(jobId);
Get get = new Get(rowKey);
get.addColumn(Constants.RAW_FAM_BYTES, Constants.JOBHISTORY_COL_BYTES);
Table rawTable = null;
try {
rawTable = hbaseConnection
.getTable(TableName.valueOf(Constants.HISTORY_RAW_TABLE));
Result result = rawTable.get(get);
if (result != null && !result.isEmpty()) {
historyData = Bytes.toString(result.getValue(Constants.RAW_FAM_BYTES,
Constants.JOBHISTORY_COL_BYTES));
}
} finally {
if (rawTable != null) {
rawTable.close();
}
}
return historyData;
} } | public class class_name {
public String getRawJobHistory(QualifiedJobId jobId) throws IOException {
String historyData = null;
byte[] rowKey = idConv.toBytes(jobId);
Get get = new Get(rowKey);
get.addColumn(Constants.RAW_FAM_BYTES, Constants.JOBHISTORY_COL_BYTES);
Table rawTable = null;
try {
rawTable = hbaseConnection
.getTable(TableName.valueOf(Constants.HISTORY_RAW_TABLE));
Result result = rawTable.get(get);
if (result != null && !result.isEmpty()) {
historyData = Bytes.toString(result.getValue(Constants.RAW_FAM_BYTES,
Constants.JOBHISTORY_COL_BYTES)); // depends on control dependency: [if], data = [(result]
}
} finally {
if (rawTable != null) {
rawTable.close(); // depends on control dependency: [if], data = [none]
}
}
return historyData;
} } |
public class class_name {
public static INDArray amax(INDArray x, INDArray y, INDArray z, int... dimensions) {
if(dimensions == null || dimensions.length == 0) {
validateShapesNoDimCase(x,y,z);
return Nd4j.getExecutioner().exec(new AMax(x,y,z));
}
return Nd4j.getExecutioner().exec(new BroadcastAMax(x,y,z,dimensions));
} } | public class class_name {
public static INDArray amax(INDArray x, INDArray y, INDArray z, int... dimensions) {
if(dimensions == null || dimensions.length == 0) {
validateShapesNoDimCase(x,y,z); // depends on control dependency: [if], data = [none]
return Nd4j.getExecutioner().exec(new AMax(x,y,z)); // depends on control dependency: [if], data = [none]
}
return Nd4j.getExecutioner().exec(new BroadcastAMax(x,y,z,dimensions));
} } |
public class class_name {
public static Object toResultCheckIfNull(Object value, String desc) {
if (value == null) {
if (desc.length() == 1) {
switch (desc.charAt(0)) {
case 'I':
return DEFAULT_INT;
case 'B':
return DEFAULT_BYTE;
case 'C':
return DEFAULT_CHAR;
case 'S':
return DEFAULT_SHORT;
case 'J':
return DEFAULT_LONG;
case 'F':
return DEFAULT_FLOAT;
case 'D':
return DEFAULT_DOUBLE;
case 'Z':
return Boolean.FALSE;
default:
throw new IllegalStateException("Invalid primitive descriptor " + desc);
}
}
else {
return null;
}
}
else {
return value;
}
} } | public class class_name {
public static Object toResultCheckIfNull(Object value, String desc) {
if (value == null) {
if (desc.length() == 1) {
switch (desc.charAt(0)) {
case 'I':
return DEFAULT_INT;
case 'B':
return DEFAULT_BYTE;
case 'C':
return DEFAULT_CHAR;
case 'S':
return DEFAULT_SHORT;
case 'J':
return DEFAULT_LONG;
case 'F':
return DEFAULT_FLOAT;
case 'D':
return DEFAULT_DOUBLE;
case 'Z':
return Boolean.FALSE;
default:
throw new IllegalStateException("Invalid primitive descriptor " + desc);
}
}
else {
return null; // depends on control dependency: [if], data = [none]
}
}
else {
return value; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean isEventStream() {
boolean isEventStream = false;
if (!getResponseHeader().isEmpty()) {
isEventStream = getResponseHeader().hasContentType("text/event-stream");
} else {
// response not available
// is request for event-stream?
String acceptHeader = getRequestHeader().getHeader("Accept");
if (acceptHeader != null && acceptHeader.equals("text/event-stream")) {
// request is for an SSE stream
isEventStream = true;
}
}
return isEventStream;
} } | public class class_name {
public boolean isEventStream() {
boolean isEventStream = false;
if (!getResponseHeader().isEmpty()) {
isEventStream = getResponseHeader().hasContentType("text/event-stream");
// depends on control dependency: [if], data = [none]
} else {
// response not available
// is request for event-stream?
String acceptHeader = getRequestHeader().getHeader("Accept");
if (acceptHeader != null && acceptHeader.equals("text/event-stream")) {
// request is for an SSE stream
isEventStream = true;
// depends on control dependency: [if], data = [none]
}
}
return isEventStream;
} } |
public class class_name {
public static void setLong(MemorySegment[] segments, int offset, long value) {
if (inFirstSegment(segments, offset, 8)) {
segments[0].putLong(offset, value);
} else {
setLongMultiSegments(segments, offset, value);
}
} } | public class class_name {
public static void setLong(MemorySegment[] segments, int offset, long value) {
if (inFirstSegment(segments, offset, 8)) {
segments[0].putLong(offset, value); // depends on control dependency: [if], data = [none]
} else {
setLongMultiSegments(segments, offset, value); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void removeOverlaps(Collection<TermOccurrence> referenceSet, Collection<TermOccurrence> occurrenceSet) {
Iterator<TermOccurrence> it = occurrenceSet.iterator();
while(it.hasNext()) {
TermOccurrence occ = it.next();
for(TermOccurrence refOcc:referenceSet) {
if(occ.getSourceDocument().equals(refOcc.getSourceDocument())
&& areOffsetsOverlapping(occ, refOcc)) {
it.remove();
break;
}
}
}
} } | public class class_name {
public static void removeOverlaps(Collection<TermOccurrence> referenceSet, Collection<TermOccurrence> occurrenceSet) {
Iterator<TermOccurrence> it = occurrenceSet.iterator();
while(it.hasNext()) {
TermOccurrence occ = it.next();
for(TermOccurrence refOcc:referenceSet) {
if(occ.getSourceDocument().equals(refOcc.getSourceDocument())
&& areOffsetsOverlapping(occ, refOcc)) {
it.remove(); // depends on control dependency: [if], data = [none]
break;
}
}
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static <T> T getByNameAndType(Object object, String fieldName, Class<T> expectedFieldType) {
Field foundField = findSingleFieldUsingStrategy(new FieldNameAndTypeMatcherStrategy(fieldName,
expectedFieldType), object, true, getType(object));
try {
return (T) foundField.get(object);
} catch (IllegalAccessException e) {
throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public static <T> T getByNameAndType(Object object, String fieldName, Class<T> expectedFieldType) {
Field foundField = findSingleFieldUsingStrategy(new FieldNameAndTypeMatcherStrategy(fieldName,
expectedFieldType), object, true, getType(object));
try {
return (T) foundField.get(object); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException e) {
throw new RuntimeException("Internal error: Failed to get field in method getInternalState.", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void doStartPlaying()
{
if (currentContainer!=null)
{
doStopPlaying();
if (currentContainer instanceof ModContainer)
{
System.out.println(((ModContainer) currentContainer).getCurrentMod().toString());
}
Mixer mixer = createNewMixer();
mixer.setExportFile(wavFileName);
playerThread = new PlayThread(mixer, this);
playerThread.start();
}
} } | public class class_name {
private void doStartPlaying()
{
if (currentContainer!=null)
{
doStopPlaying(); // depends on control dependency: [if], data = [none]
if (currentContainer instanceof ModContainer)
{
System.out.println(((ModContainer) currentContainer).getCurrentMod().toString()); // depends on control dependency: [if], data = [none]
}
Mixer mixer = createNewMixer();
mixer.setExportFile(wavFileName); // depends on control dependency: [if], data = [none]
playerThread = new PlayThread(mixer, this); // depends on control dependency: [if], data = [none]
playerThread.start(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setFilePaths(Path... filePaths) {
if (!supportsMultiPaths() && filePaths.length > 1) {
throw new UnsupportedOperationException(
"Multiple paths are not supported by this FileInputFormat.");
}
if (filePaths.length < 1) {
throw new IllegalArgumentException("At least one file path must be specified.");
}
if (filePaths.length == 1) {
// set for backwards compatibility
this.filePath = filePaths[0];
} else {
// clear file path in case it had been set before
this.filePath = null;
}
this.filePaths = filePaths;
} } | public class class_name {
public void setFilePaths(Path... filePaths) {
if (!supportsMultiPaths() && filePaths.length > 1) {
throw new UnsupportedOperationException(
"Multiple paths are not supported by this FileInputFormat.");
}
if (filePaths.length < 1) {
throw new IllegalArgumentException("At least one file path must be specified.");
}
if (filePaths.length == 1) {
// set for backwards compatibility
this.filePath = filePaths[0]; // depends on control dependency: [if], data = [none]
} else {
// clear file path in case it had been set before
this.filePath = null; // depends on control dependency: [if], data = [none]
}
this.filePaths = filePaths;
} } |
public class class_name {
public static String inspect(Annotation a) {
final int begin = 40, after = 50;
try {
JCas jCas = a.getCAS().getJCas();
String text = jCas.getDocumentText();
StringBuilder sb = new StringBuilder();
if (a.getBegin() - begin < 0) {
for (int i = 0; i < (begin - a.getBegin()); i++) {
sb.append(' ');
}
sb.append(text.substring(0, a.getBegin()));
} else {
sb.append(text.substring(a.getBegin() - begin, a.getBegin()));
}
sb.append('{');
sb.append(a.getCoveredText());
sb.append('}');
if (a.getEnd() < text.length()) {
sb.append(text.substring(a.getEnd(),
Math.min(a.getEnd() + after, text.length())));
}
sb.append("[pmid:" + getHeaderIntDocId(jCas) + ", " + a.getBegin()
+ ":" + a.getEnd() + "]");
return sb.toString();
} catch (Throwable e) {
e.printStackTrace();
return "";
}
} } | public class class_name {
public static String inspect(Annotation a) {
final int begin = 40, after = 50;
try {
JCas jCas = a.getCAS().getJCas();
String text = jCas.getDocumentText();
StringBuilder sb = new StringBuilder();
if (a.getBegin() - begin < 0) {
for (int i = 0; i < (begin - a.getBegin()); i++) {
sb.append(' '); // depends on control dependency: [for], data = [none]
}
sb.append(text.substring(0, a.getBegin())); // depends on control dependency: [if], data = [none]
} else {
sb.append(text.substring(a.getBegin() - begin, a.getBegin())); // depends on control dependency: [if], data = [(a.getBegin() - begin]
}
sb.append('{'); // depends on control dependency: [try], data = [none]
sb.append(a.getCoveredText()); // depends on control dependency: [try], data = [none]
sb.append('}'); // depends on control dependency: [try], data = [none]
if (a.getEnd() < text.length()) {
sb.append(text.substring(a.getEnd(),
Math.min(a.getEnd() + after, text.length()))); // depends on control dependency: [if], data = [(a.getEnd()]
}
sb.append("[pmid:" + getHeaderIntDocId(jCas) + ", " + a.getBegin()
+ ":" + a.getEnd() + "]"); // depends on control dependency: [try], data = [none]
return sb.toString(); // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
e.printStackTrace();
return "";
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
static List<Long> fixupShortcuts(List<Long> path, NavMeshQuery navQuery) {
if (path.size() < 3) {
return path;
}
// Get connected polygons
List<Long> neis = new ArrayList<>();
Result<Tupple2<MeshTile, Poly>> tileAndPoly = navQuery.getAttachedNavMesh().getTileAndPolyByRef(path.get(0));
if (tileAndPoly.failed()) {
return path;
}
MeshTile tile = tileAndPoly.result.first;
Poly poly = tileAndPoly.result.second;
for (int k = poly.firstLink; k != NavMesh.DT_NULL_LINK; k = tile.links.get(k).next) {
Link link = tile.links.get(k);
if (link.ref != 0) {
neis.add(link.ref);
}
}
// If any of the neighbour polygons is within the next few polygons
// in the path, short cut to that polygon directly.
int maxLookAhead = 6;
int cut = 0;
for (int i = Math.min(maxLookAhead, path.size()) - 1; i > 1 && cut == 0; i--) {
for (int j = 0; j < neis.size(); j++) {
if (path.get(i).longValue() == neis.get(j).longValue()) {
cut = i;
break;
}
}
}
if (cut > 1) {
List<Long> shortcut = new ArrayList<>();
shortcut.add(path.get(0));
shortcut.addAll(path.subList(cut, path.size()));
return shortcut;
}
return path;
} } | public class class_name {
static List<Long> fixupShortcuts(List<Long> path, NavMeshQuery navQuery) {
if (path.size() < 3) {
return path; // depends on control dependency: [if], data = [none]
}
// Get connected polygons
List<Long> neis = new ArrayList<>();
Result<Tupple2<MeshTile, Poly>> tileAndPoly = navQuery.getAttachedNavMesh().getTileAndPolyByRef(path.get(0));
if (tileAndPoly.failed()) {
return path; // depends on control dependency: [if], data = [none]
}
MeshTile tile = tileAndPoly.result.first;
Poly poly = tileAndPoly.result.second;
for (int k = poly.firstLink; k != NavMesh.DT_NULL_LINK; k = tile.links.get(k).next) {
Link link = tile.links.get(k);
if (link.ref != 0) {
neis.add(link.ref); // depends on control dependency: [if], data = [(link.ref]
}
}
// If any of the neighbour polygons is within the next few polygons
// in the path, short cut to that polygon directly.
int maxLookAhead = 6;
int cut = 0;
for (int i = Math.min(maxLookAhead, path.size()) - 1; i > 1 && cut == 0; i--) {
for (int j = 0; j < neis.size(); j++) {
if (path.get(i).longValue() == neis.get(j).longValue()) {
cut = i; // depends on control dependency: [if], data = [none]
break;
}
}
}
if (cut > 1) {
List<Long> shortcut = new ArrayList<>();
shortcut.add(path.get(0)); // depends on control dependency: [if], data = [none]
shortcut.addAll(path.subList(cut, path.size())); // depends on control dependency: [if], data = [(cut]
return shortcut; // depends on control dependency: [if], data = [none]
}
return path;
} } |
public class class_name {
public SeleniumAssert hasSize(Integer size) {
if (actual instanceof PreviousWebElements) {
Integers.instance().assertEqual(info, ((PreviousWebElements) actual).getPreviousWebElements().size(), size);
}
return this;
} } | public class class_name {
public SeleniumAssert hasSize(Integer size) {
if (actual instanceof PreviousWebElements) {
Integers.instance().assertEqual(info, ((PreviousWebElements) actual).getPreviousWebElements().size(), size); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public static TypePath fromString(final String typePath) {
if (typePath == null || typePath.length() == 0) {
return null;
}
int n = typePath.length();
ByteVector out = new ByteVector(n);
out.putByte(0);
for (int i = 0; i < n;) {
char c = typePath.charAt(i++);
if (c == '[') {
out.put11(ARRAY_ELEMENT, 0);
} else if (c == '.') {
out.put11(INNER_TYPE, 0);
} else if (c == '*') {
out.put11(WILDCARD_BOUND, 0);
} else if (c >= '0' && c <= '9') {
int typeArg = c - '0';
while (i < n && (c = typePath.charAt(i)) >= '0' && c <= '9') {
typeArg = typeArg * 10 + c - '0';
i += 1;
}
out.put11(TYPE_ARGUMENT, typeArg);
}
}
out.data[0] = (byte) (out.length / 2);
return new TypePath(out.data, 0);
} } | public class class_name {
public static TypePath fromString(final String typePath) {
if (typePath == null || typePath.length() == 0) {
return null; // depends on control dependency: [if], data = [none]
}
int n = typePath.length();
ByteVector out = new ByteVector(n);
out.putByte(0);
for (int i = 0; i < n;) {
char c = typePath.charAt(i++);
if (c == '[') {
out.put11(ARRAY_ELEMENT, 0); // depends on control dependency: [if], data = [none]
} else if (c == '.') {
out.put11(INNER_TYPE, 0); // depends on control dependency: [if], data = [none]
} else if (c == '*') {
out.put11(WILDCARD_BOUND, 0); // depends on control dependency: [if], data = [none]
} else if (c >= '0' && c <= '9') {
int typeArg = c - '0';
while (i < n && (c = typePath.charAt(i)) >= '0' && c <= '9') {
typeArg = typeArg * 10 + c - '0'; // depends on control dependency: [while], data = [none]
i += 1; // depends on control dependency: [while], data = [none]
}
out.put11(TYPE_ARGUMENT, typeArg); // depends on control dependency: [if], data = [none]
}
}
out.data[0] = (byte) (out.length / 2);
return new TypePath(out.data, 0);
} } |
public class class_name {
@Override
public void update(Object entry) {
Assert.notNull(entry, "Entry must not be null");
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Updating entry - %s$1", entry));
}
Name originalId = odm.getId(entry);
Name calculatedId = odm.getCalculatedId(entry);
if(originalId != null && calculatedId != null && !originalId.equals(calculatedId)) {
// The DN has changed - remove the original entry and bind the new one
// (because other data may have changed as well
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Calculated DN of %s; of entry %s differs from explicitly specified one; %s - moving",
calculatedId, entry, originalId));
}
unbind(originalId);
DirContextAdapter context = new DirContextAdapter(calculatedId);
odm.mapToLdapDataEntry(entry, context);
bind(context);
odm.setId(entry, calculatedId);
} else {
// DN is the same, just modify the attributes
Name id = originalId;
if(id == null) {
id = calculatedId;
odm.setId(entry, calculatedId);
}
Assert.notNull(id, String.format("Unable to determine id for entry %s", entry.toString()));
DirContextOperations context = lookupContext(id);
odm.mapToLdapDataEntry(entry, context);
modifyAttributes(context);
}
} } | public class class_name {
@Override
public void update(Object entry) {
Assert.notNull(entry, "Entry must not be null");
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Updating entry - %s$1", entry)); // depends on control dependency: [if], data = [none]
}
Name originalId = odm.getId(entry);
Name calculatedId = odm.getCalculatedId(entry);
if(originalId != null && calculatedId != null && !originalId.equals(calculatedId)) {
// The DN has changed - remove the original entry and bind the new one
// (because other data may have changed as well
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Calculated DN of %s; of entry %s differs from explicitly specified one; %s - moving",
calculatedId, entry, originalId)); // depends on control dependency: [if], data = [none]
}
unbind(originalId); // depends on control dependency: [if], data = [(originalId]
DirContextAdapter context = new DirContextAdapter(calculatedId);
odm.mapToLdapDataEntry(entry, context); // depends on control dependency: [if], data = [none]
bind(context); // depends on control dependency: [if], data = [none]
odm.setId(entry, calculatedId); // depends on control dependency: [if], data = [none]
} else {
// DN is the same, just modify the attributes
Name id = originalId;
if(id == null) {
id = calculatedId; // depends on control dependency: [if], data = [none]
odm.setId(entry, calculatedId); // depends on control dependency: [if], data = [none]
}
Assert.notNull(id, String.format("Unable to determine id for entry %s", entry.toString())); // depends on control dependency: [if], data = [none]
DirContextOperations context = lookupContext(id);
odm.mapToLdapDataEntry(entry, context); // depends on control dependency: [if], data = [none]
modifyAttributes(context); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static Observable<List<File>> createFilesFromClipData(final Context context,
final ClipData clipData, final MimeMap mimeTypeMap) {
return Observable.defer(new Func0<Observable<List<File>>>() {
@Override
public Observable<List<File>> call() {
int numOfUris = clipData.getItemCount();
List<File> filesRetrieved = new ArrayList<>(numOfUris);
for (int i = 0; i < numOfUris; i++) {
Uri data = clipData.getItemAt(i).getUri();
if (data != null) {
try {
filesRetrieved.add(fileFromUri(context, data, mimeTypeMap));
} catch (Exception e) {
logError(e);
return Observable.error(e);
}
}
}
return Observable.just(filesRetrieved);
}
});
} } | public class class_name {
private static Observable<List<File>> createFilesFromClipData(final Context context,
final ClipData clipData, final MimeMap mimeTypeMap) {
return Observable.defer(new Func0<Observable<List<File>>>() {
@Override
public Observable<List<File>> call() {
int numOfUris = clipData.getItemCount();
List<File> filesRetrieved = new ArrayList<>(numOfUris);
for (int i = 0; i < numOfUris; i++) {
Uri data = clipData.getItemAt(i).getUri();
if (data != null) {
try {
filesRetrieved.add(fileFromUri(context, data, mimeTypeMap)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logError(e);
return Observable.error(e);
} // depends on control dependency: [catch], data = [none]
}
}
return Observable.just(filesRetrieved);
}
});
} } |
public class class_name {
public Observable<ServiceResponse<DnsNameAvailabilityResultInner>> checkDnsNameAvailabilityWithServiceResponseAsync(String location, String domainNameLabel) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (this.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.subscriptionId() is required and cannot be null.");
}
if (domainNameLabel == null) {
throw new IllegalArgumentException("Parameter domainNameLabel is required and cannot be null.");
}
final String apiVersion = "2018-04-01";
return service.checkDnsNameAvailability(location, this.subscriptionId(), domainNameLabel, apiVersion, this.acceptLanguage(), this.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<DnsNameAvailabilityResultInner>>>() {
@Override
public Observable<ServiceResponse<DnsNameAvailabilityResultInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<DnsNameAvailabilityResultInner> clientResponse = checkDnsNameAvailabilityDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<DnsNameAvailabilityResultInner>> checkDnsNameAvailabilityWithServiceResponseAsync(String location, String domainNameLabel) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (this.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.subscriptionId() is required and cannot be null.");
}
if (domainNameLabel == null) {
throw new IllegalArgumentException("Parameter domainNameLabel is required and cannot be null.");
}
final String apiVersion = "2018-04-01";
return service.checkDnsNameAvailability(location, this.subscriptionId(), domainNameLabel, apiVersion, this.acceptLanguage(), this.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<DnsNameAvailabilityResultInner>>>() {
@Override
public Observable<ServiceResponse<DnsNameAvailabilityResultInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<DnsNameAvailabilityResultInner> clientResponse = checkDnsNameAvailabilityDelegate(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 {
@Override
public ImageSource apply(ImageSource source) {
if (radius != 0) {
if (source.isGrayscale()) {
return applyGrayscale(source, radius);
} else {
return applyRGB(source, radius);
}
} else {
if (source.isGrayscale()) {
return applyGrayscale(source, kernel);
} else {
return applyRGB(source, kernel);
}
}
} } | public class class_name {
@Override
public ImageSource apply(ImageSource source) {
if (radius != 0) {
if (source.isGrayscale()) {
return applyGrayscale(source, radius);
// depends on control dependency: [if], data = [none]
} else {
return applyRGB(source, radius);
// depends on control dependency: [if], data = [none]
}
} else {
if (source.isGrayscale()) {
return applyGrayscale(source, kernel);
// depends on control dependency: [if], data = [none]
} else {
return applyRGB(source, kernel);
// depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private boolean setupManyNesting() {
BeanAttributeInformation parentAttribute = null;
BeanAttributeInformation idAttribute = null;
BeanInformation beanInformation = BeanInformation.get(idField.getType());
for (String attributeName : beanInformation.getAttributeNames()) {
BeanAttributeInformation attribute = beanInformation.getAttribute(attributeName);
if (attribute.getAnnotation(JsonApiRelationId.class).isPresent()) {
PreconditionUtil.verify(parentAttribute == null,
"nested identifiers can only have a single @JsonApiRelationId annotated field, got multiple for %s",
beanInformation.getImplementationClass());
parentAttribute = attribute;
} else if (attribute.getAnnotation(JsonApiId.class).isPresent()) {
PreconditionUtil.verify(idAttribute == null,
"nested identifiers can only one attribute being annotated with @JsonApiId, got multiple for %s",
beanInformation.getImplementationClass());
idAttribute = attribute;
}
}
if (parentAttribute != null || idAttribute != null) {
if (!shouldBeNested()) {
LOGGER.warn("add @JsonApiResource(nested=true) to {} to mark it as being nested, in the future automatic discovery based on the id will be removed",
implementationClass);
}
PreconditionUtil.verify(idAttribute != null,
"nested identifiers must have attribute annotated with @JsonApiId, got none for %s",
beanInformation.getImplementationClass());
PreconditionUtil.verify(parentAttribute != null,
"nested identifiers must have attribute annotated with @JsonApiRelationId, got none for %s",
beanInformation.getImplementationClass());
String relationshipName = parentAttribute.getName().substring(0, parentAttribute.getName().length() - 2);
// accessors for nested and parent id, able to deal with both resources and identifiers as parameters
this.parentIdAccessor = new NestedIdAccessor(parentAttribute);
this.childIdAccessor = new NestedIdAccessor(idAttribute);
// check whether parentField is duplicated in ID. This can be a valid use case if the nested identifier is considered
// an add-on to an existing object.
String parentName = parentAttribute.getName();
Optional<ResourceField> optParentField = relationshipFields.stream().filter(it -> it.hasIdField() && it.getIdName().equals(parentName)).findFirst();
if (optParentField.isPresent()) {
parentField = optParentField.get();
} else {
PreconditionUtil.verify(parentAttribute.getName().endsWith("Id"),
"nested identifier must have @JsonApiRelationId field being named with a 'Id' suffix or match in name with a @JsonApiRelationId annotated field on the resource, got %s for %s",
parentAttribute.getName(), beanInformation.getImplementationClass());
parentField = findRelationshipFieldByName(relationshipName);
PreconditionUtil.verify(parentField != null,
"naming of relationship to parent resource and relationship identifier within resource identifier must "
+ "match, not found for %s of %s",
parentAttribute.getName(), implementationClass);
((ResourceFieldImpl) parentField).setIdField(parentAttribute.getName(), parentAttribute.getImplementationClass(), parentIdAccessor);
}
return true;
}
return false;
} } | public class class_name {
private boolean setupManyNesting() {
BeanAttributeInformation parentAttribute = null;
BeanAttributeInformation idAttribute = null;
BeanInformation beanInformation = BeanInformation.get(idField.getType());
for (String attributeName : beanInformation.getAttributeNames()) {
BeanAttributeInformation attribute = beanInformation.getAttribute(attributeName);
if (attribute.getAnnotation(JsonApiRelationId.class).isPresent()) {
PreconditionUtil.verify(parentAttribute == null,
"nested identifiers can only have a single @JsonApiRelationId annotated field, got multiple for %s",
beanInformation.getImplementationClass()); // depends on control dependency: [if], data = [none]
parentAttribute = attribute; // depends on control dependency: [if], data = [none]
} else if (attribute.getAnnotation(JsonApiId.class).isPresent()) {
PreconditionUtil.verify(idAttribute == null,
"nested identifiers can only one attribute being annotated with @JsonApiId, got multiple for %s",
beanInformation.getImplementationClass()); // depends on control dependency: [if], data = [none]
idAttribute = attribute; // depends on control dependency: [if], data = [none]
}
}
if (parentAttribute != null || idAttribute != null) {
if (!shouldBeNested()) {
LOGGER.warn("add @JsonApiResource(nested=true) to {} to mark it as being nested, in the future automatic discovery based on the id will be removed",
implementationClass); // depends on control dependency: [if], data = [none]
}
PreconditionUtil.verify(idAttribute != null,
"nested identifiers must have attribute annotated with @JsonApiId, got none for %s",
beanInformation.getImplementationClass()); // depends on control dependency: [if], data = [none]
PreconditionUtil.verify(parentAttribute != null,
"nested identifiers must have attribute annotated with @JsonApiRelationId, got none for %s",
beanInformation.getImplementationClass()); // depends on control dependency: [if], data = [(parentAttribute]
String relationshipName = parentAttribute.getName().substring(0, parentAttribute.getName().length() - 2);
// accessors for nested and parent id, able to deal with both resources and identifiers as parameters
this.parentIdAccessor = new NestedIdAccessor(parentAttribute); // depends on control dependency: [if], data = [(parentAttribute]
this.childIdAccessor = new NestedIdAccessor(idAttribute); // depends on control dependency: [if], data = [none]
// check whether parentField is duplicated in ID. This can be a valid use case if the nested identifier is considered
// an add-on to an existing object.
String parentName = parentAttribute.getName();
Optional<ResourceField> optParentField = relationshipFields.stream().filter(it -> it.hasIdField() && it.getIdName().equals(parentName)).findFirst();
if (optParentField.isPresent()) {
parentField = optParentField.get(); // depends on control dependency: [if], data = [none]
} else {
PreconditionUtil.verify(parentAttribute.getName().endsWith("Id"),
"nested identifier must have @JsonApiRelationId field being named with a 'Id' suffix or match in name with a @JsonApiRelationId annotated field on the resource, got %s for %s",
parentAttribute.getName(), beanInformation.getImplementationClass()); // depends on control dependency: [if], data = [none]
parentField = findRelationshipFieldByName(relationshipName); // depends on control dependency: [if], data = [none]
PreconditionUtil.verify(parentField != null,
"naming of relationship to parent resource and relationship identifier within resource identifier must "
+ "match, not found for %s of %s",
parentAttribute.getName(), implementationClass); // depends on control dependency: [if], data = [none]
((ResourceFieldImpl) parentField).setIdField(parentAttribute.getName(), parentAttribute.getImplementationClass(), parentIdAccessor); // depends on control dependency: [if], data = [none]
}
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Override
public void addRemoteRepo(MavenRemoteRepository repository) {
Builder builder = new Builder(repository.getId(), repository.getType(), repository.getUrl());
builder.setPolicy(new RepositoryPolicy(true, repository.getUpdatePolicy() == null ? null : repository
.getUpdatePolicy().apiValue(), repository.getChecksumPolicy() == null ? null : repository
.getChecksumPolicy().apiValue()));
for (RemoteRepository r : this.additionalRemoteRepositories) {
if (r.getId().equals(repository.getId())) {
this.additionalRemoteRepositories.remove(r);
}
}
this.additionalRemoteRepositories.add(builder.build());
} } | public class class_name {
@Override
public void addRemoteRepo(MavenRemoteRepository repository) {
Builder builder = new Builder(repository.getId(), repository.getType(), repository.getUrl());
builder.setPolicy(new RepositoryPolicy(true, repository.getUpdatePolicy() == null ? null : repository
.getUpdatePolicy().apiValue(), repository.getChecksumPolicy() == null ? null : repository
.getChecksumPolicy().apiValue()));
for (RemoteRepository r : this.additionalRemoteRepositories) {
if (r.getId().equals(repository.getId())) {
this.additionalRemoteRepositories.remove(r); // depends on control dependency: [if], data = [none]
}
}
this.additionalRemoteRepositories.add(builder.build());
} } |
public class class_name {
public void marshall(SetUserMFAPreferenceRequest setUserMFAPreferenceRequest, ProtocolMarshaller protocolMarshaller) {
if (setUserMFAPreferenceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(setUserMFAPreferenceRequest.getSMSMfaSettings(), SMSMFASETTINGS_BINDING);
protocolMarshaller.marshall(setUserMFAPreferenceRequest.getSoftwareTokenMfaSettings(), SOFTWARETOKENMFASETTINGS_BINDING);
protocolMarshaller.marshall(setUserMFAPreferenceRequest.getAccessToken(), ACCESSTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(SetUserMFAPreferenceRequest setUserMFAPreferenceRequest, ProtocolMarshaller protocolMarshaller) {
if (setUserMFAPreferenceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(setUserMFAPreferenceRequest.getSMSMfaSettings(), SMSMFASETTINGS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(setUserMFAPreferenceRequest.getSoftwareTokenMfaSettings(), SOFTWARETOKENMFASETTINGS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(setUserMFAPreferenceRequest.getAccessToken(), ACCESSTOKEN_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 String[] union(String[] arr1, String[] arr2) {
Set<String> set = new HashSet<String>();
for (String str : arr1) {
set.add(str);
}
for (String str : arr2) {
set.add(str);
}
String[] result = {};
return set.toArray(result);
} } | public class class_name {
public static String[] union(String[] arr1, String[] arr2) {
Set<String> set = new HashSet<String>();
for (String str : arr1) {
set.add(str); // depends on control dependency: [for], data = [str]
}
for (String str : arr2) {
set.add(str); // depends on control dependency: [for], data = [str]
}
String[] result = {};
return set.toArray(result);
} } |
public class class_name {
private static String normalizeDomain(String value) {
if (value.startsWith(".")) {
return value.substring(1);
}
return value.toLowerCase();
} } | public class class_name {
private static String normalizeDomain(String value) {
if (value.startsWith(".")) {
return value.substring(1); // depends on control dependency: [if], data = [none]
}
return value.toLowerCase();
} } |
public class class_name {
public Color getColorAt(float p) {
if (p <= 0) {
return ((Step) steps.get(0)).col;
}
if (p > 1) {
return ((Step) steps.get(steps.size()-1)).col;
}
for (int i=1;i<steps.size();i++) {
Step prev = ((Step) steps.get(i-1));
Step current = ((Step) steps.get(i));
if (p <= current.location) {
float dis = current.location - prev.location;
p -= prev.location;
float v = p / dis;
Color c = new Color(1,1,1,1);
c.a = (prev.col.a * (1 - v)) + (current.col.a * (v));
c.r = (prev.col.r * (1 - v)) + (current.col.r * (v));
c.g = (prev.col.g * (1 - v)) + (current.col.g * (v));
c.b = (prev.col.b * (1 - v)) + (current.col.b * (v));
return c;
}
}
// shouldn't ever happen
return Color.black;
} } | public class class_name {
public Color getColorAt(float p) {
if (p <= 0) {
return ((Step) steps.get(0)).col;
// depends on control dependency: [if], data = [none]
}
if (p > 1) {
return ((Step) steps.get(steps.size()-1)).col;
// depends on control dependency: [if], data = [1)]
}
for (int i=1;i<steps.size();i++) {
Step prev = ((Step) steps.get(i-1));
Step current = ((Step) steps.get(i));
if (p <= current.location) {
float dis = current.location - prev.location;
p -= prev.location;
// depends on control dependency: [if], data = [none]
float v = p / dis;
Color c = new Color(1,1,1,1);
c.a = (prev.col.a * (1 - v)) + (current.col.a * (v));
// depends on control dependency: [if], data = [(p]
c.r = (prev.col.r * (1 - v)) + (current.col.r * (v));
// depends on control dependency: [if], data = [(p]
c.g = (prev.col.g * (1 - v)) + (current.col.g * (v));
// depends on control dependency: [if], data = [(p]
c.b = (prev.col.b * (1 - v)) + (current.col.b * (v));
// depends on control dependency: [if], data = [(p]
return c;
// depends on control dependency: [if], data = [none]
}
}
// shouldn't ever happen
return Color.black;
} } |
public class class_name {
public static OptionElement findByName(List<OptionElement> options, String name) {
checkNotNull(options, "options");
checkNotNull(name, "name");
OptionElement found = null;
for (OptionElement option : options) {
if (option.name().equals(name)) {
if (found != null) {
throw new IllegalStateException("Multiple options match name: " + name);
}
found = option;
}
}
return found;
} } | public class class_name {
public static OptionElement findByName(List<OptionElement> options, String name) {
checkNotNull(options, "options");
checkNotNull(name, "name");
OptionElement found = null;
for (OptionElement option : options) {
if (option.name().equals(name)) {
if (found != null) {
throw new IllegalStateException("Multiple options match name: " + name);
}
found = option; // depends on control dependency: [if], data = [none]
}
}
return found;
} } |
public class class_name {
public void addDeployedArtifact(ResourceDefinitionEntity deployedArtifact) {
if (deployedArtifacts == null) {
deployedArtifacts = new HashMap<Class<?>, List>();
}
Class<?> clazz = deployedArtifact.getClass();
List artifacts = deployedArtifacts.get(clazz);
if (artifacts == null) {
artifacts = new ArrayList();
deployedArtifacts.put(clazz, artifacts);
}
artifacts.add(deployedArtifact);
} } | public class class_name {
public void addDeployedArtifact(ResourceDefinitionEntity deployedArtifact) {
if (deployedArtifacts == null) {
deployedArtifacts = new HashMap<Class<?>, List>(); // depends on control dependency: [if], data = [none]
}
Class<?> clazz = deployedArtifact.getClass();
List artifacts = deployedArtifacts.get(clazz);
if (artifacts == null) {
artifacts = new ArrayList(); // depends on control dependency: [if], data = [none]
deployedArtifacts.put(clazz, artifacts); // depends on control dependency: [if], data = [none]
}
artifacts.add(deployedArtifact);
} } |
public class class_name {
protected List<CmsUUID> parseResources(String resources) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(resources)) {
return Collections.emptyList();
} else {
List<CmsUUID> result = new ArrayList<CmsUUID>();
String[] resArray = resources.trim().split(";");
for (int i = 0; i < resArray.length; i++) {
result.add(new CmsUUID(resArray[i]));
}
return result;
}
} } | public class class_name {
protected List<CmsUUID> parseResources(String resources) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(resources)) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
} else {
List<CmsUUID> result = new ArrayList<CmsUUID>();
String[] resArray = resources.trim().split(";");
for (int i = 0; i < resArray.length; i++) {
result.add(new CmsUUID(resArray[i])); // depends on control dependency: [for], data = [i]
}
return result; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private EntityType buildEntityType(SessionFactory sessionFactory, String entityName) {
EntityType entityType = (EntityType) entityTypes.get(entityName);
if (null == entityType) {
ClassMetadata cm = sessionFactory.getClassMetadata(entityName);
if (null == cm) {
logger.error("Cannot find ClassMetadata for {}", entityName);
return null;
}
entityType = new EntityType(cm.getEntityName(), cm.getMappedClass(), cm.getIdentifierPropertyName(),
new IdentifierType(cm.getIdentifierType().getReturnedClass()));
entityTypes.put(cm.getEntityName(), entityType);
Map<String, Type> propertyTypes = entityType.getPropertyTypes();
String[] ps = cm.getPropertyNames();
for (int i = 0; i < ps.length; i++) {
org.hibernate.type.Type type = cm.getPropertyType(ps[i]);
if (type.isEntityType()) {
propertyTypes.put(ps[i], buildEntityType(sessionFactory, type.getName()));
} else if (type.isComponentType()) {
propertyTypes.put(ps[i], buildComponentType(sessionFactory, entityName, ps[i]));
} else if (type.isCollectionType()) {
propertyTypes.put(ps[i],
buildCollectionType(sessionFactory, defaultCollectionClass(type), entityName + "." + ps[i]));
}
}
}
return entityType;
} } | public class class_name {
private EntityType buildEntityType(SessionFactory sessionFactory, String entityName) {
EntityType entityType = (EntityType) entityTypes.get(entityName);
if (null == entityType) {
ClassMetadata cm = sessionFactory.getClassMetadata(entityName);
if (null == cm) {
logger.error("Cannot find ClassMetadata for {}", entityName); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
entityType = new EntityType(cm.getEntityName(), cm.getMappedClass(), cm.getIdentifierPropertyName(),
new IdentifierType(cm.getIdentifierType().getReturnedClass())); // depends on control dependency: [if], data = [none]
entityTypes.put(cm.getEntityName(), entityType); // depends on control dependency: [if], data = [entityType)]
Map<String, Type> propertyTypes = entityType.getPropertyTypes();
String[] ps = cm.getPropertyNames();
for (int i = 0; i < ps.length; i++) {
org.hibernate.type.Type type = cm.getPropertyType(ps[i]);
if (type.isEntityType()) {
propertyTypes.put(ps[i], buildEntityType(sessionFactory, type.getName())); // depends on control dependency: [if], data = [none]
} else if (type.isComponentType()) {
propertyTypes.put(ps[i], buildComponentType(sessionFactory, entityName, ps[i])); // depends on control dependency: [if], data = [none]
} else if (type.isCollectionType()) {
propertyTypes.put(ps[i],
buildCollectionType(sessionFactory, defaultCollectionClass(type), entityName + "." + ps[i])); // depends on control dependency: [if], data = [none]
}
}
}
return entityType;
} } |
public class class_name {
public static void main(String[] args) throws Exception {
Options options = new Options();
HelpFormatter hf = new HelpFormatter();
hf.setWidth(100);
options.addOption(
Option.builder("i")
.argName("in_path")
.longOpt("input-file")
.hasArg()
.required()
.desc("path to target jar/aar file")
.build());
options.addOption(
Option.builder("p")
.argName("pkg_name")
.longOpt("package")
.hasArg()
.desc("qualified package name")
.build());
options.addOption(
Option.builder("o")
.argName("out_path")
.longOpt("output-file")
.hasArg()
.required()
.desc("path to processed jar/aar file")
.build());
options.addOption(
Option.builder("h")
.argName("help")
.longOpt("help")
.desc("print usage information")
.build());
options.addOption(
Option.builder("d")
.argName("debug")
.longOpt("debug")
.desc("print debug information")
.build());
options.addOption(
Option.builder("v").argName("verbose").longOpt("verbose").desc("set verbosity").build());
try {
CommandLine line = new DefaultParser().parse(options, args);
if (line.hasOption('h')) {
hf.printHelp(appName, options, true);
return;
}
String jarPath = line.getOptionValue('i');
String pkgName = line.getOptionValue('p', "");
String outPath = line.getOptionValue('o');
boolean debug = line.hasOption('d');
boolean verbose = line.hasOption('v');
if (!pkgName.isEmpty()) {
pkgName = "L" + pkgName.replaceAll("\\.", "/");
}
DefinitelyDerefedParamsDriver.run(jarPath, pkgName, outPath, debug, verbose);
if (!new File(outPath).exists()) {
System.out.println("Could not write jar file: " + outPath);
}
} catch (ParseException pe) {
hf.printHelp(appName, options, true);
}
} } | public class class_name {
public static void main(String[] args) throws Exception {
Options options = new Options();
HelpFormatter hf = new HelpFormatter();
hf.setWidth(100);
options.addOption(
Option.builder("i")
.argName("in_path")
.longOpt("input-file")
.hasArg()
.required()
.desc("path to target jar/aar file")
.build());
options.addOption(
Option.builder("p")
.argName("pkg_name")
.longOpt("package")
.hasArg()
.desc("qualified package name")
.build());
options.addOption(
Option.builder("o")
.argName("out_path")
.longOpt("output-file")
.hasArg()
.required()
.desc("path to processed jar/aar file")
.build());
options.addOption(
Option.builder("h")
.argName("help")
.longOpt("help")
.desc("print usage information")
.build());
options.addOption(
Option.builder("d")
.argName("debug")
.longOpt("debug")
.desc("print debug information")
.build());
options.addOption(
Option.builder("v").argName("verbose").longOpt("verbose").desc("set verbosity").build());
try {
CommandLine line = new DefaultParser().parse(options, args);
if (line.hasOption('h')) {
hf.printHelp(appName, options, true); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
String jarPath = line.getOptionValue('i');
String pkgName = line.getOptionValue('p', "");
String outPath = line.getOptionValue('o');
boolean debug = line.hasOption('d');
boolean verbose = line.hasOption('v');
if (!pkgName.isEmpty()) {
pkgName = "L" + pkgName.replaceAll("\\.", "/"); // depends on control dependency: [if], data = [none]
}
DefinitelyDerefedParamsDriver.run(jarPath, pkgName, outPath, debug, verbose);
if (!new File(outPath).exists()) {
System.out.println("Could not write jar file: " + outPath);
}
} catch (ParseException pe) {
hf.printHelp(appName, options, true);
}
} } |
public class class_name {
@Override
public String url(Object string)
{
// TODO: Introduce a xwiki-commons-url module and move this code in it so that we can share it with
// platform's XWikiServletURLFactory and functional test TestUtils class.
String encodedURL = null;
if (string != null) {
try {
encodedURL = URLEncoder.encode(String.valueOf(string), "UTF-8");
} catch (UnsupportedEncodingException e) {
// Should not happen (UTF-8 is always available)
throw new RuntimeException("Missing charset [UTF-8]", e);
}
// The previous call will convert " " into "+" (and "+" into "%2B") so we need to convert "+" into "%20"
// It's ok since %20 is allowed in both the URL path and the query string (and anchor).
encodedURL = encodedURL.replaceAll("\\+", "%20");
}
return encodedURL;
} } | public class class_name {
@Override
public String url(Object string)
{
// TODO: Introduce a xwiki-commons-url module and move this code in it so that we can share it with
// platform's XWikiServletURLFactory and functional test TestUtils class.
String encodedURL = null;
if (string != null) {
try {
encodedURL = URLEncoder.encode(String.valueOf(string), "UTF-8"); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
// Should not happen (UTF-8 is always available)
throw new RuntimeException("Missing charset [UTF-8]", e);
} // depends on control dependency: [catch], data = [none]
// The previous call will convert " " into "+" (and "+" into "%2B") so we need to convert "+" into "%20"
// It's ok since %20 is allowed in both the URL path and the query string (and anchor).
encodedURL = encodedURL.replaceAll("\\+", "%20"); // depends on control dependency: [if], data = [none]
}
return encodedURL;
} } |
public class class_name {
public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions)
{
if (strCommand.equalsIgnoreCase(MenuConstants.FORMDETAIL))
{ // Make sure if the use wants to select a record to re-connect the selection
Record targetRecord = null;
int iMode = ScreenConstants.DETAIL_MODE;
OnSelectHandler listener = (OnSelectHandler)this.getMainRecord().getListener(OnSelectHandler.class);
if (listener != null)
{
targetRecord = listener.getRecordToSync();
this.getMainRecord().removeListener(listener, false);
iMode = iMode | ScreenConstants.SELECT_MODE;
}
BasePanel screen = this.onForm(null, iMode, true, iCommandOptions, null);
if (targetRecord != null)
screen.setSelectQuery(targetRecord, false);
return true;
}
else
return super.doCommand(strCommand, sourceSField, iCommandOptions);
} } | public class class_name {
public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions)
{
if (strCommand.equalsIgnoreCase(MenuConstants.FORMDETAIL))
{ // Make sure if the use wants to select a record to re-connect the selection
Record targetRecord = null;
int iMode = ScreenConstants.DETAIL_MODE;
OnSelectHandler listener = (OnSelectHandler)this.getMainRecord().getListener(OnSelectHandler.class);
if (listener != null)
{
targetRecord = listener.getRecordToSync(); // depends on control dependency: [if], data = [none]
this.getMainRecord().removeListener(listener, false); // depends on control dependency: [if], data = [(listener]
iMode = iMode | ScreenConstants.SELECT_MODE; // depends on control dependency: [if], data = [none]
}
BasePanel screen = this.onForm(null, iMode, true, iCommandOptions, null);
if (targetRecord != null)
screen.setSelectQuery(targetRecord, false);
return true; // depends on control dependency: [if], data = [none]
}
else
return super.doCommand(strCommand, sourceSField, iCommandOptions);
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static <X> TypeInformation<X> parse(String infoString) {
try {
if (infoString == null) {
throw new IllegalArgumentException("String is null.");
}
String clearedString = infoString.replaceAll("\\s", "");
if (clearedString.length() == 0) {
throw new IllegalArgumentException("String must not be empty.");
}
return (TypeInformation<X>) parse(new StringBuilder(clearedString));
} catch (Exception e) {
throw new IllegalArgumentException("String could not be parsed: " + e.getMessage());
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public static <X> TypeInformation<X> parse(String infoString) {
try {
if (infoString == null) {
throw new IllegalArgumentException("String is null.");
}
String clearedString = infoString.replaceAll("\\s", "");
if (clearedString.length() == 0) {
throw new IllegalArgumentException("String must not be empty.");
}
return (TypeInformation<X>) parse(new StringBuilder(clearedString)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new IllegalArgumentException("String could not be parsed: " + e.getMessage());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void printErrors(final List<Span> falsePositives,
final List<Span> falseNegatives, final String doc) {
this.printStream.println("False positives: {");
for (final Span span : falsePositives) {
this.printStream.println(span.getCoveredText(doc));
}
this.printStream.println("} False negatives: {");
for (final Span span : falseNegatives) {
this.printStream.println(span.getCoveredText(doc));
}
this.printStream.println("}\n");
} } | public class class_name {
private void printErrors(final List<Span> falsePositives,
final List<Span> falseNegatives, final String doc) {
this.printStream.println("False positives: {");
for (final Span span : falsePositives) {
this.printStream.println(span.getCoveredText(doc)); // depends on control dependency: [for], data = [span]
}
this.printStream.println("} False negatives: {");
for (final Span span : falseNegatives) {
this.printStream.println(span.getCoveredText(doc)); // depends on control dependency: [for], data = [span]
}
this.printStream.println("}\n");
} } |
public class class_name {
private void initInternalListener(Context context) {
mInternalListener = new PlaybackListener() {
@Override
protected void onPlay(SoundCloudTrack track) {
super.onPlay(track);
mState = STATE_PLAYING;
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onPlayerPlay(track, mPlayerPlaylist.getCurrentTrackIndex());
}
}
@Override
protected void onPause() {
super.onPause();
mState = STATE_PAUSED;
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onPlayerPause();
}
}
@Override
protected void onPlayerDestroyed() {
super.onPlayerDestroyed();
mState = STATE_STOPPED;
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onPlayerDestroyed();
}
if (mDestroyDelayed) {
CheerleaderPlayer.this.destroy();
}
}
@Override
protected void onSeekTo(int milli) {
super.onSeekTo(milli);
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onPlayerSeekTo(milli);
}
}
@Override
protected void onBufferingStarted() {
super.onBufferingStarted();
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onBufferingStarted();
}
}
@Override
protected void onBufferingEnded() {
super.onBufferingEnded();
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onBufferingEnded();
}
}
@Override
protected void onProgressChanged(int milli) {
super.onProgressChanged(milli);
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onProgressChanged(milli);
}
}
};
PlaybackService.registerListener(context, mInternalListener);
} } | public class class_name {
private void initInternalListener(Context context) {
mInternalListener = new PlaybackListener() {
@Override
protected void onPlay(SoundCloudTrack track) {
super.onPlay(track);
mState = STATE_PLAYING;
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onPlayerPlay(track, mPlayerPlaylist.getCurrentTrackIndex()); // depends on control dependency: [for], data = [listener]
}
}
@Override
protected void onPause() {
super.onPause();
mState = STATE_PAUSED;
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onPlayerPause(); // depends on control dependency: [for], data = [listener]
}
}
@Override
protected void onPlayerDestroyed() {
super.onPlayerDestroyed();
mState = STATE_STOPPED;
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onPlayerDestroyed(); // depends on control dependency: [for], data = [listener]
}
if (mDestroyDelayed) {
CheerleaderPlayer.this.destroy(); // depends on control dependency: [if], data = [none]
}
}
@Override
protected void onSeekTo(int milli) {
super.onSeekTo(milli);
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onPlayerSeekTo(milli); // depends on control dependency: [for], data = [listener]
}
}
@Override
protected void onBufferingStarted() {
super.onBufferingStarted();
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onBufferingStarted(); // depends on control dependency: [for], data = [listener]
}
}
@Override
protected void onBufferingEnded() {
super.onBufferingEnded();
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onBufferingEnded(); // depends on control dependency: [for], data = [listener]
}
}
@Override
protected void onProgressChanged(int milli) {
super.onProgressChanged(milli);
for (CheerleaderPlayerListener listener : mCheerleaderPlayerListeners) {
listener.onProgressChanged(milli); // depends on control dependency: [for], data = [listener]
}
}
};
PlaybackService.registerListener(context, mInternalListener);
} } |
public class class_name {
public static ManagedObjectReference[] createMORs(ManagedObject[] mos) {
if (mos == null) {
throw new IllegalArgumentException();
}
ManagedObjectReference[] mors = new ManagedObjectReference[mos.length];
for (int i = 0; i < mos.length; i++) {
mors[i] = mos[i].getMOR();
}
return mors;
} } | public class class_name {
public static ManagedObjectReference[] createMORs(ManagedObject[] mos) {
if (mos == null) {
throw new IllegalArgumentException();
}
ManagedObjectReference[] mors = new ManagedObjectReference[mos.length];
for (int i = 0; i < mos.length; i++) {
mors[i] = mos[i].getMOR();
// depends on control dependency: [for], data = [i]
}
return mors;
} } |
public class class_name {
private static List<Object> processMultiBulkReply(final RedisInputStream is) {
int num = Integer.parseInt(is.readLine());
log.trace("[RedisProtocol] Reply multi-bulk-reply. *{}", num);
if (num == -1) {
return null;
}
List<Object> ret = new ArrayList<Object>(num);
for (int i = 0; i < num; i++) {
try {
ret.add(process(is));
} catch (JedisDataException e) {
ret.add(e);
}
}
return ret;
} } | public class class_name {
private static List<Object> processMultiBulkReply(final RedisInputStream is) {
int num = Integer.parseInt(is.readLine());
log.trace("[RedisProtocol] Reply multi-bulk-reply. *{}", num);
if (num == -1) {
return null; // depends on control dependency: [if], data = [none]
}
List<Object> ret = new ArrayList<Object>(num);
for (int i = 0; i < num; i++) {
try {
ret.add(process(is)); // depends on control dependency: [try], data = [none]
} catch (JedisDataException e) {
ret.add(e);
} // depends on control dependency: [catch], data = [none]
}
return ret;
} } |
public class class_name {
@SuppressWarnings({ "unchecked", "rawtypes" })
private StringBuffer getAllPublishedInterfaces(ServletContext servletContext) {
StringBuffer sb = new StringBuffer();
// List all containers to find all DWR interfaces
List<Container> containers = ContainerUtil.getAllPublishedContainers(servletContext);
for(Iterator<Container> it = containers.iterator();it.hasNext();) {
Container container = (Container) it.next();
// The creatormanager holds the list of beans
CreatorManager ctManager = (CreatorManager) container.getBean(CreatorManager.class.getName());
if(null != ctManager) {
// The remoter builds interface scripts.
Remoter remoter = (Remoter) container.getBean(Remoter.class.getName());
String path = getPathReplacementString(container);
boolean debugMode = ctManager.isDebug();
Collection creators = null;
if(!(ctManager instanceof DefaultCreatorManager)) {
if(!debugMode)
LOGGER.warn("The current creatormanager is a custom implementation ["
+ ctManager.getClass().getName()
+ "]. Debug mode is off, so the mapping dwr:_** is likely to trigger a SecurityException." +
" Attempting to get all published creators..." );
creators = ctManager.getCreatorNames();
}
else {
DefaultCreatorManager dfCreator = (DefaultCreatorManager) ctManager;
try
{
dfCreator.setDebug(true);
creators = ctManager.getCreatorNames();
}
finally{
// restore debug mode no matter what
dfCreator.setDebug(debugMode);
}
}
for(Iterator<String> names = creators.iterator();names.hasNext();) {
String script = remoter.generateInterfaceScript(names.next(), path);
// Must remove the engine init script to avoid unneeded duplication
script = removeEngineInit(script);
sb.append(script);
}
}
}
return sb;
} } | public class class_name {
@SuppressWarnings({ "unchecked", "rawtypes" })
private StringBuffer getAllPublishedInterfaces(ServletContext servletContext) {
StringBuffer sb = new StringBuffer();
// List all containers to find all DWR interfaces
List<Container> containers = ContainerUtil.getAllPublishedContainers(servletContext);
for(Iterator<Container> it = containers.iterator();it.hasNext();) {
Container container = (Container) it.next();
// The creatormanager holds the list of beans
CreatorManager ctManager = (CreatorManager) container.getBean(CreatorManager.class.getName());
if(null != ctManager) {
// The remoter builds interface scripts.
Remoter remoter = (Remoter) container.getBean(Remoter.class.getName());
String path = getPathReplacementString(container);
boolean debugMode = ctManager.isDebug();
Collection creators = null;
if(!(ctManager instanceof DefaultCreatorManager)) {
if(!debugMode)
LOGGER.warn("The current creatormanager is a custom implementation ["
+ ctManager.getClass().getName()
+ "]. Debug mode is off, so the mapping dwr:_** is likely to trigger a SecurityException." +
" Attempting to get all published creators..." );
creators = ctManager.getCreatorNames(); // depends on control dependency: [if], data = [none]
}
else {
DefaultCreatorManager dfCreator = (DefaultCreatorManager) ctManager;
try
{
dfCreator.setDebug(true); // depends on control dependency: [try], data = [none]
creators = ctManager.getCreatorNames(); // depends on control dependency: [try], data = [none]
}
finally{
// restore debug mode no matter what
dfCreator.setDebug(debugMode);
}
}
for(Iterator<String> names = creators.iterator();names.hasNext();) {
String script = remoter.generateInterfaceScript(names.next(), path);
// Must remove the engine init script to avoid unneeded duplication
script = removeEngineInit(script); // depends on control dependency: [for], data = [none]
sb.append(script); // depends on control dependency: [for], data = [none]
}
}
}
return sb;
} } |
public class class_name {
public void formatLine(String line, PrintWriter writer)
{
processingState.setLine(line);
processingState.pwriter = writer;
processingState = processingState.formatState.formatPartialLine(processingState);
while (!processingState.isDoneWithLine())
{
processingState = processingState.formatState.formatPartialLine(processingState);
}
} } | public class class_name {
public void formatLine(String line, PrintWriter writer)
{
processingState.setLine(line);
processingState.pwriter = writer;
processingState = processingState.formatState.formatPartialLine(processingState);
while (!processingState.isDoneWithLine())
{
processingState = processingState.formatState.formatPartialLine(processingState);
// depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
Constraint getLimitConstraint() {
Constraint result = null;
for (Constraint constraint : getConstraints()) {
if (constraint.getConstraintType() == Constraint.LIMIT) {
// We're assuming only one LIMIT constraint at the moment
result = constraint;
break;
}
}
return result;
} } | public class class_name {
Constraint getLimitConstraint() {
Constraint result = null;
for (Constraint constraint : getConstraints()) {
if (constraint.getConstraintType() == Constraint.LIMIT) {
// We're assuming only one LIMIT constraint at the moment
result = constraint; // depends on control dependency: [if], data = [none]
break;
}
}
return result;
} } |
public class class_name {
public static void generateMutations(long seq, TxLog txLog, Consumer<Mutation> consumer) {
Map<Bytes, Mutation> mutationMap = new HashMap<>();
for (LogEntry le : txLog.getLogEntries()) {
LogEntry.Operation op = le.getOp();
Column col = le.getColumn();
byte[] cf = col.getFamily().toArray();
byte[] cq = col.getQualifier().toArray();
byte[] cv = col.getVisibility().toArray();
if (op.equals(LogEntry.Operation.DELETE) || op.equals(LogEntry.Operation.SET)) {
Mutation m = mutationMap.computeIfAbsent(le.getRow(), k -> new Mutation(k.toArray()));
if (op.equals(LogEntry.Operation.DELETE)) {
if (col.isVisibilitySet()) {
m.putDelete(cf, cq, new ColumnVisibility(cv), seq);
} else {
m.putDelete(cf, cq, seq);
}
} else {
if (col.isVisibilitySet()) {
m.put(cf, cq, new ColumnVisibility(cv), seq, le.getValue().toArray());
} else {
m.put(cf, cq, seq, le.getValue().toArray());
}
}
}
}
mutationMap.values().forEach(consumer);
} } | public class class_name {
public static void generateMutations(long seq, TxLog txLog, Consumer<Mutation> consumer) {
Map<Bytes, Mutation> mutationMap = new HashMap<>();
for (LogEntry le : txLog.getLogEntries()) {
LogEntry.Operation op = le.getOp();
Column col = le.getColumn();
byte[] cf = col.getFamily().toArray();
byte[] cq = col.getQualifier().toArray();
byte[] cv = col.getVisibility().toArray();
if (op.equals(LogEntry.Operation.DELETE) || op.equals(LogEntry.Operation.SET)) {
Mutation m = mutationMap.computeIfAbsent(le.getRow(), k -> new Mutation(k.toArray()));
if (op.equals(LogEntry.Operation.DELETE)) {
if (col.isVisibilitySet()) {
m.putDelete(cf, cq, new ColumnVisibility(cv), seq); // depends on control dependency: [if], data = [none]
} else {
m.putDelete(cf, cq, seq); // depends on control dependency: [if], data = [none]
}
} else {
if (col.isVisibilitySet()) {
m.put(cf, cq, new ColumnVisibility(cv), seq, le.getValue().toArray()); // depends on control dependency: [if], data = [none]
} else {
m.put(cf, cq, seq, le.getValue().toArray()); // depends on control dependency: [if], data = [none]
}
}
}
}
mutationMap.values().forEach(consumer);
} } |
public class class_name {
public static int asIntExactly(Number number) {
Class clazz = number.getClass();
if (isLongRepresentableExceptLong(clazz)) {
return number.intValue();
} else if (clazz == Long.class) {
int intValue = number.intValue();
if (number.longValue() == (long) intValue) {
return intValue;
}
} else if (isDoubleRepresentable(clazz)) {
int intValue = number.intValue();
if (equalDoubles(number.doubleValue(), (double) intValue)) {
return intValue;
}
}
throw new IllegalArgumentException("Can't represent " + number + " as int exactly");
} } | public class class_name {
public static int asIntExactly(Number number) {
Class clazz = number.getClass();
if (isLongRepresentableExceptLong(clazz)) {
return number.intValue(); // depends on control dependency: [if], data = [none]
} else if (clazz == Long.class) {
int intValue = number.intValue();
if (number.longValue() == (long) intValue) {
return intValue; // depends on control dependency: [if], data = [none]
}
} else if (isDoubleRepresentable(clazz)) {
int intValue = number.intValue();
if (equalDoubles(number.doubleValue(), (double) intValue)) {
return intValue; // depends on control dependency: [if], data = [none]
}
}
throw new IllegalArgumentException("Can't represent " + number + " as int exactly");
} } |
public class class_name {
protected boolean needsUpdating(CmsSetupDb dbCon, String tablename) throws SQLException {
System.out.println(new Exception().getStackTrace()[0].toString());
boolean result = true;
String query = readQuery(QUERY_DESCRIBE_TABLE);
Map<String, String> replacer = new HashMap<String, String>();
replacer.put(REPLACEMENT_TABLENAME, tablename);
CmsSetupDBWrapper db = null;
try {
db = dbCon.executeSqlStatement(query, replacer);
while (db.getResultSet().next()) {
String fieldname = db.getResultSet().getString("Field");
if (fieldname.equals(COLUMN_PROJECT_ID) || fieldname.equals(COLUMN_PROJECT_LASTMODIFIED)) {
try {
String fieldtype = db.getResultSet().getString("Type");
// If the type is varchar then no update needs to be done.
if (fieldtype.indexOf("varchar") > 0) {
return false;
}
} catch (SQLException e) {
result = true;
}
}
}
} finally {
if (db != null) {
db.close();
}
}
return result;
} } | public class class_name {
protected boolean needsUpdating(CmsSetupDb dbCon, String tablename) throws SQLException {
System.out.println(new Exception().getStackTrace()[0].toString());
boolean result = true;
String query = readQuery(QUERY_DESCRIBE_TABLE);
Map<String, String> replacer = new HashMap<String, String>();
replacer.put(REPLACEMENT_TABLENAME, tablename);
CmsSetupDBWrapper db = null;
try {
db = dbCon.executeSqlStatement(query, replacer);
while (db.getResultSet().next()) {
String fieldname = db.getResultSet().getString("Field");
if (fieldname.equals(COLUMN_PROJECT_ID) || fieldname.equals(COLUMN_PROJECT_LASTMODIFIED)) {
try {
String fieldtype = db.getResultSet().getString("Type");
// If the type is varchar then no update needs to be done.
if (fieldtype.indexOf("varchar") > 0) {
return false; // depends on control dependency: [if], data = [none]
}
} catch (SQLException e) {
result = true;
} // depends on control dependency: [catch], data = [none]
}
}
} finally {
if (db != null) {
db.close(); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public String getNameInClass(boolean shortenPackages, boolean useJVMMethodName, boolean hash, boolean omitMethodName) {
// Convert to "nice" representation
StringBuilder result = new StringBuilder();
if (!omitMethodName) {
if (useJVMMethodName) {
result.append(getMethodName());
} else {
result.append(getJavaSourceMethodName());
}
}
result.append('(');
// append args
SignatureConverter converter = new SignatureConverter(methodSig);
if (converter.getFirst() != '(') {
throw new IllegalStateException("bad method signature " + methodSig);
}
converter.skip();
boolean needsComma = false;
while (converter.getFirst() != ')') {
if (needsComma) {
if (hash) {
result.append(",");
} else {
result.append(", ");
}
}
if (shortenPackages) {
result.append(removePackageName(converter.parseNext()));
} else {
result.append(converter.parseNext());
}
needsComma = true;
}
converter.skip();
result.append(')');
return result.toString();
} } | public class class_name {
public String getNameInClass(boolean shortenPackages, boolean useJVMMethodName, boolean hash, boolean omitMethodName) {
// Convert to "nice" representation
StringBuilder result = new StringBuilder();
if (!omitMethodName) {
if (useJVMMethodName) {
result.append(getMethodName()); // depends on control dependency: [if], data = [none]
} else {
result.append(getJavaSourceMethodName()); // depends on control dependency: [if], data = [none]
}
}
result.append('(');
// append args
SignatureConverter converter = new SignatureConverter(methodSig);
if (converter.getFirst() != '(') {
throw new IllegalStateException("bad method signature " + methodSig);
}
converter.skip();
boolean needsComma = false;
while (converter.getFirst() != ')') {
if (needsComma) {
if (hash) {
result.append(","); // depends on control dependency: [if], data = [none]
} else {
result.append(", "); // depends on control dependency: [if], data = [none]
}
}
if (shortenPackages) {
result.append(removePackageName(converter.parseNext())); // depends on control dependency: [if], data = [none]
} else {
result.append(converter.parseNext()); // depends on control dependency: [if], data = [none]
}
needsComma = true; // depends on control dependency: [while], data = [none]
}
converter.skip();
result.append(')');
return result.toString();
} } |
public class class_name {
public void close() {
if (this.m_stream != null) {
try {
this.m_stream.close();
this.m_stream = null;
} catch (IOException e) {
logger.warn("Error closing stream", e);
}
}
} } | public class class_name {
public void close() {
if (this.m_stream != null) {
try {
this.m_stream.close(); // depends on control dependency: [try], data = [none]
this.m_stream = null; // depends on control dependency: [try], data = [none]
} catch (IOException e) {
logger.warn("Error closing stream", e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public EEnum getIfcAnalysisTheoryTypeEnum() {
if (ifcAnalysisTheoryTypeEnumEEnum == null) {
ifcAnalysisTheoryTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(780);
}
return ifcAnalysisTheoryTypeEnumEEnum;
} } | public class class_name {
public EEnum getIfcAnalysisTheoryTypeEnum() {
if (ifcAnalysisTheoryTypeEnumEEnum == null) {
ifcAnalysisTheoryTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(780);
// depends on control dependency: [if], data = [none]
}
return ifcAnalysisTheoryTypeEnumEEnum;
} } |
public class class_name {
public Map<String, String> read(final String... nameMapping) throws IOException {
if( nameMapping == null ) {
throw new NullPointerException("nameMapping should not be null");
}
if( readRow() ) {
final Map<String, String> destination = new HashMap<String, String>();
Util.filterListToMap(destination, nameMapping, getColumns());
return destination;
}
return null; // EOF
} } | public class class_name {
public Map<String, String> read(final String... nameMapping) throws IOException {
if( nameMapping == null ) {
throw new NullPointerException("nameMapping should not be null");
}
if( readRow() ) {
final Map<String, String> destination = new HashMap<String, String>();
Util.filterListToMap(destination, nameMapping, getColumns()); // depends on control dependency: [if], data = [none]
return destination; // depends on control dependency: [if], data = [none]
}
return null; // EOF
} } |
public class class_name {
public void startTracking() {
if (isTracking) {
return;
}
if (this.session == null) {
addBroadcastReceiver();
}
// if the session is not null, then add the callback to it right away
if (getSession() != null) {
getSession().addCallback(callback);
}
isTracking = true;
} } | public class class_name {
public void startTracking() {
if (isTracking) {
return; // depends on control dependency: [if], data = [none]
}
if (this.session == null) {
addBroadcastReceiver(); // depends on control dependency: [if], data = [none]
}
// if the session is not null, then add the callback to it right away
if (getSession() != null) {
getSession().addCallback(callback); // depends on control dependency: [if], data = [none]
}
isTracking = true;
} } |
public class class_name {
@Override
public Result<Void> cacheClear(AuthzTrans trans, String cname) {
TimeTaken tt = trans.start(CACHE_CLEAR + cname, Env.SUB|Env.ALWAYS);
try {
return service.cacheClear(trans,cname);
} catch (Exception e) {
trans.error().log(e,IN,CACHE_CLEAR);
return Result.err(e);
} finally {
tt.done();
}
} } | public class class_name {
@Override
public Result<Void> cacheClear(AuthzTrans trans, String cname) {
TimeTaken tt = trans.start(CACHE_CLEAR + cname, Env.SUB|Env.ALWAYS);
try {
return service.cacheClear(trans,cname);
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
trans.error().log(e,IN,CACHE_CLEAR);
return Result.err(e);
} finally {
// depends on control dependency: [catch], data = [none]
tt.done();
}
} } |
public class class_name {
public static List<Kontonummer> getKontonummerListForRegisternummer(String registernummer, int length) {
KontonummerValidator.validateRegisternummerSyntax(registernummer);
final class RegisternummerKontonrDigitGenerator extends KontonummerDigitGenerator {
private final String registerNr;
RegisternummerKontonrDigitGenerator(String registerNr) {
this.registerNr = registerNr;
}
@Override
String generateKontonummer() {
StringBuilder kontonrBuffer = new StringBuilder(LENGTH);
for (int i = 0; i < LENGTH;) {
if (i == REGISTERNUMMER_START_DIGIT) {
kontonrBuffer.append(registerNr);
i += registerNr.length();
} else {
kontonrBuffer.append((int) (Math.random() * 10));
i++;
}
}
return kontonrBuffer.toString();
}
}
return getKontonummerListUsingGenerator(new RegisternummerKontonrDigitGenerator(registernummer), length);
} } | public class class_name {
public static List<Kontonummer> getKontonummerListForRegisternummer(String registernummer, int length) {
KontonummerValidator.validateRegisternummerSyntax(registernummer);
final class RegisternummerKontonrDigitGenerator extends KontonummerDigitGenerator {
private final String registerNr;
RegisternummerKontonrDigitGenerator(String registerNr) {
this.registerNr = registerNr;
}
@Override
String generateKontonummer() {
StringBuilder kontonrBuffer = new StringBuilder(LENGTH);
for (int i = 0; i < LENGTH;) {
if (i == REGISTERNUMMER_START_DIGIT) {
kontonrBuffer.append(registerNr);
// depends on control dependency: [if], data = [none]
i += registerNr.length();
// depends on control dependency: [if], data = [none]
} else {
kontonrBuffer.append((int) (Math.random() * 10));
// depends on control dependency: [if], data = [(i]
i++;
// depends on control dependency: [if], data = [none]
}
}
return kontonrBuffer.toString();
}
}
return getKontonummerListUsingGenerator(new RegisternummerKontonrDigitGenerator(registernummer), length);
} } |
public class class_name {
public void marshall(LinuxParameters linuxParameters, ProtocolMarshaller protocolMarshaller) {
if (linuxParameters == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(linuxParameters.getCapabilities(), CAPABILITIES_BINDING);
protocolMarshaller.marshall(linuxParameters.getDevices(), DEVICES_BINDING);
protocolMarshaller.marshall(linuxParameters.getInitProcessEnabled(), INITPROCESSENABLED_BINDING);
protocolMarshaller.marshall(linuxParameters.getSharedMemorySize(), SHAREDMEMORYSIZE_BINDING);
protocolMarshaller.marshall(linuxParameters.getTmpfs(), TMPFS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(LinuxParameters linuxParameters, ProtocolMarshaller protocolMarshaller) {
if (linuxParameters == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(linuxParameters.getCapabilities(), CAPABILITIES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(linuxParameters.getDevices(), DEVICES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(linuxParameters.getInitProcessEnabled(), INITPROCESSENABLED_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(linuxParameters.getSharedMemorySize(), SHAREDMEMORYSIZE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(linuxParameters.getTmpfs(), TMPFS_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 {
Map<String, Integer> getPrefixesIds(String field, List<String> prefixes) {
LinkedHashMap<String, Long> refs = getPrefixRefs(field);
if (refs != null) {
List<String> list = new ArrayList<>(refs.keySet());
Map<String, Integer> result = new HashMap<>();
for (String prefix : prefixes) {
int id = list.indexOf(prefix);
if (id >= 0) {
result.put(prefix, id + 1);
}
}
return result;
} else {
return null;
}
} } | public class class_name {
Map<String, Integer> getPrefixesIds(String field, List<String> prefixes) {
LinkedHashMap<String, Long> refs = getPrefixRefs(field);
if (refs != null) {
List<String> list = new ArrayList<>(refs.keySet());
Map<String, Integer> result = new HashMap<>();
for (String prefix : prefixes) {
int id = list.indexOf(prefix);
if (id >= 0) {
result.put(prefix, id + 1); // depends on control dependency: [if], data = [none]
}
}
return result; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static int[] addToSortedIntArray(int[] a, int value) {
if(a == null || a.length == 0) {
return new int[] {value};
}
int insertionPoint = -java.util.Arrays.binarySearch(a, value) - 1;
if(insertionPoint < 0) {
throw new IllegalArgumentException(String.format("Element %d already exists in array", value));
}
int[] array = new int[a.length + 1];
if(insertionPoint > 0) {
System.arraycopy(a, 0, array, 0, insertionPoint);
}
array[insertionPoint] = value;
if(insertionPoint < a.length) {
System.arraycopy(a, insertionPoint, array, insertionPoint + 1, array.length - insertionPoint - 1);
}
return array;
} } | public class class_name {
public static int[] addToSortedIntArray(int[] a, int value) {
if(a == null || a.length == 0) {
return new int[] {value}; // depends on control dependency: [if], data = [none]
}
int insertionPoint = -java.util.Arrays.binarySearch(a, value) - 1;
if(insertionPoint < 0) {
throw new IllegalArgumentException(String.format("Element %d already exists in array", value));
}
int[] array = new int[a.length + 1];
if(insertionPoint > 0) {
System.arraycopy(a, 0, array, 0, insertionPoint); // depends on control dependency: [if], data = [none]
}
array[insertionPoint] = value;
if(insertionPoint < a.length) {
System.arraycopy(a, insertionPoint, array, insertionPoint + 1, array.length - insertionPoint - 1); // depends on control dependency: [if], data = [none]
}
return array;
} } |
public class class_name {
public void setPermittedAddresses(List<DomainMatcher> addrs) {
if (addrs == null || addrs.isEmpty()) {
((HierarchicalConfiguration) getConfig()).clearTree(ADDRESS_KEY);
this.permittedAddresses = Collections.emptyList();
this.permittedAddressesEnabled = Collections.emptyList();
return;
}
this.permittedAddresses = new ArrayList<>(addrs);
((HierarchicalConfiguration) getConfig()).clearTree(ADDRESS_KEY);
int size = addrs.size();
ArrayList<DomainMatcher> enabledAddrs = new ArrayList<>(size);
for (int i = 0; i < size; ++i) {
String elementBaseKey = ADDRESS_KEY + "(" + i + ").";
DomainMatcher addr = addrs.get(i);
getConfig().setProperty(elementBaseKey + ADDRESS_VALUE_KEY, addr.getValue());
getConfig().setProperty(elementBaseKey + ADDRESS_REGEX_KEY, addr.isRegex());
getConfig().setProperty(elementBaseKey + ADDRESS_ENABLED_KEY, addr.isEnabled());
if (addr.isEnabled()) {
enabledAddrs.add(addr);
}
}
enabledAddrs.trimToSize();
this.permittedAddressesEnabled = enabledAddrs;
} } | public class class_name {
public void setPermittedAddresses(List<DomainMatcher> addrs) {
if (addrs == null || addrs.isEmpty()) {
((HierarchicalConfiguration) getConfig()).clearTree(ADDRESS_KEY);
// depends on control dependency: [if], data = [none]
this.permittedAddresses = Collections.emptyList();
// depends on control dependency: [if], data = [none]
this.permittedAddressesEnabled = Collections.emptyList();
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
this.permittedAddresses = new ArrayList<>(addrs);
((HierarchicalConfiguration) getConfig()).clearTree(ADDRESS_KEY);
int size = addrs.size();
ArrayList<DomainMatcher> enabledAddrs = new ArrayList<>(size);
for (int i = 0; i < size; ++i) {
String elementBaseKey = ADDRESS_KEY + "(" + i + ").";
DomainMatcher addr = addrs.get(i);
getConfig().setProperty(elementBaseKey + ADDRESS_VALUE_KEY, addr.getValue());
// depends on control dependency: [for], data = [none]
getConfig().setProperty(elementBaseKey + ADDRESS_REGEX_KEY, addr.isRegex());
// depends on control dependency: [for], data = [none]
getConfig().setProperty(elementBaseKey + ADDRESS_ENABLED_KEY, addr.isEnabled());
// depends on control dependency: [for], data = [none]
if (addr.isEnabled()) {
enabledAddrs.add(addr);
// depends on control dependency: [if], data = [none]
}
}
enabledAddrs.trimToSize();
this.permittedAddressesEnabled = enabledAddrs;
} } |
public class class_name {
public void setUsers(java.util.Collection<UserMetadata> users) {
if (users == null) {
this.users = null;
return;
}
this.users = new java.util.ArrayList<UserMetadata>(users);
} } | public class class_name {
public void setUsers(java.util.Collection<UserMetadata> users) {
if (users == null) {
this.users = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.users = new java.util.ArrayList<UserMetadata>(users);
} } |
public class class_name {
@Override
public void removeByCPInstanceUuid(String CPInstanceUuid) {
for (CommerceWishListItem commerceWishListItem : findByCPInstanceUuid(
CPInstanceUuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceWishListItem);
}
} } | public class class_name {
@Override
public void removeByCPInstanceUuid(String CPInstanceUuid) {
for (CommerceWishListItem commerceWishListItem : findByCPInstanceUuid(
CPInstanceUuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceWishListItem); // depends on control dependency: [for], data = [commerceWishListItem]
}
} } |
public class class_name {
private static boolean hasAlwaysDeniedPermission(Source source, String... deniedPermissions) {
for (String permission : deniedPermissions) {
if (!source.isShowRationalePermission(permission)) {
return true;
}
}
return false;
} } | public class class_name {
private static boolean hasAlwaysDeniedPermission(Source source, String... deniedPermissions) {
for (String permission : deniedPermissions) {
if (!source.isShowRationalePermission(permission)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
protected ModifiableRule retrieveModifiableOverriden() {
ModifiableRule overridenRule = null;
//use local var to prevent potential concurent cleanup
SipSession session = getSession();
if (session != null && session.getServletContext() != null) {
String overridenRuleStr = session.getServletContext().getInitParameter(SYS_HDR_MOD_OVERRIDE);
if (overridenRuleStr != null)
{
overridenRule = ModifiableRule.valueOf(overridenRuleStr);
}
}
return overridenRule;
} } | public class class_name {
protected ModifiableRule retrieveModifiableOverriden() {
ModifiableRule overridenRule = null;
//use local var to prevent potential concurent cleanup
SipSession session = getSession();
if (session != null && session.getServletContext() != null) {
String overridenRuleStr = session.getServletContext().getInitParameter(SYS_HDR_MOD_OVERRIDE);
if (overridenRuleStr != null)
{
overridenRule = ModifiableRule.valueOf(overridenRuleStr); // depends on control dependency: [if], data = [(overridenRuleStr]
}
}
return overridenRule;
} } |
public class class_name {
public static <IN, OUT> List<OUT> create(IN[] arr, Creator<IN, OUT> creator) {
if (arr == null) {
return null;
}
ArrayList<OUT> list = new ArrayList<>(arr.length);
for (IN value : arr) {
OUT item = value == null ? null : creator.create(value);
if (item != null) {
list.add(item);
}
}
return list;
} } | public class class_name {
public static <IN, OUT> List<OUT> create(IN[] arr, Creator<IN, OUT> creator) {
if (arr == null) {
return null; // depends on control dependency: [if], data = [none]
}
ArrayList<OUT> list = new ArrayList<>(arr.length);
for (IN value : arr) {
OUT item = value == null ? null : creator.create(value);
if (item != null) {
list.add(item); // depends on control dependency: [if], data = [(item]
}
}
return list;
} } |
public class class_name {
public void calculateGisModelDwgPolylines() {
for( int i = 0; i < dwgObjects.size(); i++ ) {
DwgObject pol = (DwgObject) dwgObjects.get(i);
if (pol instanceof DwgPolyline2D) {
int flags = ((DwgPolyline2D) pol).getFlags();
int firstHandle = ((DwgPolyline2D) pol).getFirstVertexHandle();
int lastHandle = ((DwgPolyline2D) pol).getLastVertexHandle();
Vector pts = new Vector();
Vector bulges = new Vector();
double[] pt = new double[3];
for( int j = 0; j < dwgObjects.size(); j++ ) {
DwgObject firstVertex = (DwgObject) dwgObjects.get(j);
if (firstVertex instanceof DwgVertex2D) {
int vertexHandle = firstVertex.getHandle();
if (vertexHandle == firstHandle) {
int k = 0;
while( true ) {
DwgObject vertex = (DwgObject) dwgObjects.get(j + k);
int vHandle = vertex.getHandle();
if (vertex instanceof DwgVertex2D) {
pt = ((DwgVertex2D) vertex).getPoint();
pts.add(new Point2D.Double(pt[0], pt[1]));
double bulge = ((DwgVertex2D) vertex).getBulge();
bulges.add(new Double(bulge));
k++;
if (vHandle == lastHandle && vertex instanceof DwgVertex2D) {
break;
}
} else if (vertex instanceof DwgSeqend) {
break;
}
}
}
}
}
if (pts.size() > 0) {
Point2D[] newPts = new Point2D[pts.size()];
if ((flags & 0x1) == 0x1) {
newPts = new Point2D[pts.size() + 1];
for( int j = 0; j < pts.size(); j++ ) {
newPts[j] = (Point2D) pts.get(j);
}
newPts[pts.size()] = (Point2D) pts.get(0);
bulges.add(new Double(0));
} else {
for( int j = 0; j < pts.size(); j++ ) {
newPts[j] = (Point2D) pts.get(j);
}
}
double[] bs = new double[bulges.size()];
for( int j = 0; j < bulges.size(); j++ ) {
bs[j] = ((Double) bulges.get(j)).doubleValue();
}
((DwgPolyline2D) pol).setBulges(bs);
Point2D[] points = GisModelCurveCalculator.calculateGisModelBulge(newPts, bs);
((DwgPolyline2D) pol).setPts(points);
} else {
// System.out.println("Encontrada polil�nea sin puntos ...");
// TODO: No se debe mandar nunca una polil�nea sin puntos, si esto
// ocurre es porque existe un error que hay que corregir ...
}
} else if (pol instanceof DwgPolyline3D) {
int closedFlags = ((DwgPolyline3D) pol).getClosedFlags();
int firstHandle = ((DwgPolyline3D) pol).getFirstVertexHandle();
int lastHandle = ((DwgPolyline3D) pol).getLastVertexHandle();
Vector pts = new Vector();
double[] pt = new double[3];
for( int j = 0; j < dwgObjects.size(); j++ ) {
DwgObject firstVertex = (DwgObject) dwgObjects.get(j);
if (firstVertex instanceof DwgVertex3D) {
int vertexHandle = firstVertex.getHandle();
if (vertexHandle == firstHandle) {
int k = 0;
while( true ) {
DwgObject vertex = (DwgObject) dwgObjects.get(j + k);
int vHandle = vertex.getHandle();
if (vertex instanceof DwgVertex3D) {
pt = ((DwgVertex3D) vertex).getPoint();
pts.add(new double[]{pt[0], pt[1], pt[2]});
k++;
if (vHandle == lastHandle && vertex instanceof DwgVertex3D) {
break;
}
} else if (vertex instanceof DwgSeqend) {
break;
}
}
}
}
}
if (pts.size() > 0) {
double[][] newPts = new double[pts.size()][3];
if ((closedFlags & 0x1) == 0x1) {
newPts = new double[pts.size() + 1][3];
for( int j = 0; j < pts.size(); j++ ) {
newPts[j][0] = ((double[]) pts.get(j))[0];
newPts[j][1] = ((double[]) pts.get(j))[1];
newPts[j][2] = ((double[]) pts.get(j))[2];
}
newPts[pts.size()][0] = ((double[]) pts.get(0))[0];
newPts[pts.size()][1] = ((double[]) pts.get(0))[1];
newPts[pts.size()][2] = ((double[]) pts.get(0))[2];
} else {
for( int j = 0; j < pts.size(); j++ ) {
newPts[j][0] = ((double[]) pts.get(j))[0];
newPts[j][1] = ((double[]) pts.get(j))[1];
newPts[j][2] = ((double[]) pts.get(j))[2];
}
}
((DwgPolyline3D) pol).setPts(newPts);
} else {
// System.out.println("Encontrada polil�nea sin puntos ...");
// TODO: No se debe mandar nunca una polil�nea sin puntos, si esto
// ocurre es porque existe un error que hay que corregir ...
}
} else if (pol instanceof DwgLwPolyline && ((DwgLwPolyline) pol).getVertices() != null) {
int flags = ((DwgLwPolyline) pol).getFlag();
Point2D[] pts = ((DwgLwPolyline) pol).getVertices();
double[] bulges = ((DwgLwPolyline) pol).getBulges();
Point2D[] newPts = new Point2D[pts.length];
double[] newBulges = new double[bulges.length];
// TODO: Aqu� pueden existir casos no contemplados ...
// System.out.println("flags = " + flags);
if (flags == 512 || flags == 776 || flags == 768) {
newPts = new Point2D[pts.length + 1];
newBulges = new double[bulges.length + 1];
for( int j = 0; j < pts.length; j++ ) {
newPts[j] = (Point2D) pts[j];
}
newPts[pts.length] = (Point2D) pts[0];
newBulges[pts.length] = 0;
} else {
for( int j = 0; j < pts.length; j++ ) {
newPts[j] = (Point2D) pts[j];
}
}
if (pts.length > 0) {
((DwgLwPolyline) pol).setBulges(newBulges);
Point2D[] points = GisModelCurveCalculator.calculateGisModelBulge(newPts,
newBulges);
((DwgLwPolyline) pol).setVertices(points);
} else {
// System.out.println("Encontrada polil�nea sin puntos ...");
// TODO: No se debe mandar nunca una polil�nea sin puntos, si esto
// ocurre es porque existe un error que hay que corregir ...
}
}
}
} } | public class class_name {
public void calculateGisModelDwgPolylines() {
for( int i = 0; i < dwgObjects.size(); i++ ) {
DwgObject pol = (DwgObject) dwgObjects.get(i);
if (pol instanceof DwgPolyline2D) {
int flags = ((DwgPolyline2D) pol).getFlags();
int firstHandle = ((DwgPolyline2D) pol).getFirstVertexHandle();
int lastHandle = ((DwgPolyline2D) pol).getLastVertexHandle();
Vector pts = new Vector();
Vector bulges = new Vector();
double[] pt = new double[3];
for( int j = 0; j < dwgObjects.size(); j++ ) {
DwgObject firstVertex = (DwgObject) dwgObjects.get(j);
if (firstVertex instanceof DwgVertex2D) {
int vertexHandle = firstVertex.getHandle();
if (vertexHandle == firstHandle) {
int k = 0;
while( true ) {
DwgObject vertex = (DwgObject) dwgObjects.get(j + k);
int vHandle = vertex.getHandle();
if (vertex instanceof DwgVertex2D) {
pt = ((DwgVertex2D) vertex).getPoint(); // depends on control dependency: [if], data = [none]
pts.add(new Point2D.Double(pt[0], pt[1])); // depends on control dependency: [if], data = [none]
double bulge = ((DwgVertex2D) vertex).getBulge();
bulges.add(new Double(bulge)); // depends on control dependency: [if], data = [none]
k++; // depends on control dependency: [if], data = [none]
if (vHandle == lastHandle && vertex instanceof DwgVertex2D) {
break;
}
} else if (vertex instanceof DwgSeqend) {
break;
}
}
}
}
}
if (pts.size() > 0) {
Point2D[] newPts = new Point2D[pts.size()];
if ((flags & 0x1) == 0x1) {
newPts = new Point2D[pts.size() + 1]; // depends on control dependency: [if], data = [none]
for( int j = 0; j < pts.size(); j++ ) {
newPts[j] = (Point2D) pts.get(j); // depends on control dependency: [for], data = [j]
}
newPts[pts.size()] = (Point2D) pts.get(0); // depends on control dependency: [if], data = [none]
bulges.add(new Double(0)); // depends on control dependency: [if], data = [none]
} else {
for( int j = 0; j < pts.size(); j++ ) {
newPts[j] = (Point2D) pts.get(j); // depends on control dependency: [for], data = [j]
}
}
double[] bs = new double[bulges.size()];
for( int j = 0; j < bulges.size(); j++ ) {
bs[j] = ((Double) bulges.get(j)).doubleValue(); // depends on control dependency: [for], data = [j]
}
((DwgPolyline2D) pol).setBulges(bs); // depends on control dependency: [if], data = [none]
Point2D[] points = GisModelCurveCalculator.calculateGisModelBulge(newPts, bs);
((DwgPolyline2D) pol).setPts(points); // depends on control dependency: [if], data = [none]
} else {
// System.out.println("Encontrada polil�nea sin puntos ...");
// TODO: No se debe mandar nunca una polil�nea sin puntos, si esto
// ocurre es porque existe un error que hay que corregir ...
}
} else if (pol instanceof DwgPolyline3D) {
int closedFlags = ((DwgPolyline3D) pol).getClosedFlags();
int firstHandle = ((DwgPolyline3D) pol).getFirstVertexHandle();
int lastHandle = ((DwgPolyline3D) pol).getLastVertexHandle();
Vector pts = new Vector();
double[] pt = new double[3];
for( int j = 0; j < dwgObjects.size(); j++ ) {
DwgObject firstVertex = (DwgObject) dwgObjects.get(j);
if (firstVertex instanceof DwgVertex3D) {
int vertexHandle = firstVertex.getHandle();
if (vertexHandle == firstHandle) {
int k = 0;
while( true ) {
DwgObject vertex = (DwgObject) dwgObjects.get(j + k);
int vHandle = vertex.getHandle();
if (vertex instanceof DwgVertex3D) {
pt = ((DwgVertex3D) vertex).getPoint(); // depends on control dependency: [if], data = [none]
pts.add(new double[]{pt[0], pt[1], pt[2]}); // depends on control dependency: [if], data = [none]
k++; // depends on control dependency: [if], data = [none]
if (vHandle == lastHandle && vertex instanceof DwgVertex3D) {
break;
}
} else if (vertex instanceof DwgSeqend) {
break;
}
}
}
}
}
if (pts.size() > 0) {
double[][] newPts = new double[pts.size()][3];
if ((closedFlags & 0x1) == 0x1) {
newPts = new double[pts.size() + 1][3]; // depends on control dependency: [if], data = [none]
for( int j = 0; j < pts.size(); j++ ) {
newPts[j][0] = ((double[]) pts.get(j))[0]; // depends on control dependency: [for], data = [j]
newPts[j][1] = ((double[]) pts.get(j))[1]; // depends on control dependency: [for], data = [j]
newPts[j][2] = ((double[]) pts.get(j))[2]; // depends on control dependency: [for], data = [j]
}
newPts[pts.size()][0] = ((double[]) pts.get(0))[0]; // depends on control dependency: [if], data = [none]
newPts[pts.size()][1] = ((double[]) pts.get(0))[1]; // depends on control dependency: [if], data = [none]
newPts[pts.size()][2] = ((double[]) pts.get(0))[2]; // depends on control dependency: [if], data = [none]
} else {
for( int j = 0; j < pts.size(); j++ ) {
newPts[j][0] = ((double[]) pts.get(j))[0]; // depends on control dependency: [for], data = [j]
newPts[j][1] = ((double[]) pts.get(j))[1]; // depends on control dependency: [for], data = [j]
newPts[j][2] = ((double[]) pts.get(j))[2]; // depends on control dependency: [for], data = [j]
}
}
((DwgPolyline3D) pol).setPts(newPts); // depends on control dependency: [if], data = [none]
} else {
// System.out.println("Encontrada polil�nea sin puntos ...");
// TODO: No se debe mandar nunca una polil�nea sin puntos, si esto
// ocurre es porque existe un error que hay que corregir ...
}
} else if (pol instanceof DwgLwPolyline && ((DwgLwPolyline) pol).getVertices() != null) {
int flags = ((DwgLwPolyline) pol).getFlag();
Point2D[] pts = ((DwgLwPolyline) pol).getVertices();
double[] bulges = ((DwgLwPolyline) pol).getBulges();
Point2D[] newPts = new Point2D[pts.length];
double[] newBulges = new double[bulges.length];
// TODO: Aqu� pueden existir casos no contemplados ...
// System.out.println("flags = " + flags);
if (flags == 512 || flags == 776 || flags == 768) {
newPts = new Point2D[pts.length + 1]; // depends on control dependency: [if], data = [none]
newBulges = new double[bulges.length + 1]; // depends on control dependency: [if], data = [none]
for( int j = 0; j < pts.length; j++ ) {
newPts[j] = (Point2D) pts[j]; // depends on control dependency: [for], data = [j]
}
newPts[pts.length] = (Point2D) pts[0]; // depends on control dependency: [if], data = [none]
newBulges[pts.length] = 0; // depends on control dependency: [if], data = [none]
} else {
for( int j = 0; j < pts.length; j++ ) {
newPts[j] = (Point2D) pts[j]; // depends on control dependency: [for], data = [j]
}
}
if (pts.length > 0) {
((DwgLwPolyline) pol).setBulges(newBulges); // depends on control dependency: [if], data = [none]
Point2D[] points = GisModelCurveCalculator.calculateGisModelBulge(newPts,
newBulges);
((DwgLwPolyline) pol).setVertices(points); // depends on control dependency: [if], data = [none]
} else {
// System.out.println("Encontrada polil�nea sin puntos ...");
// TODO: No se debe mandar nunca una polil�nea sin puntos, si esto
// ocurre es porque existe un error que hay que corregir ...
}
}
}
} } |
public class class_name {
@Override
public void store(BinaryEntry entry) {
try {
ByteString key = getRiakKey(entry);
ByteString value = ByteString.copyFrom(entry.getBinaryValue().toByteArray());
client.store(new RiakObject(bucket, key, value));
}
catch (IOException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
@Override
public void store(BinaryEntry entry) {
try {
ByteString key = getRiakKey(entry);
ByteString value = ByteString.copyFrom(entry.getBinaryValue().toByteArray());
client.store(new RiakObject(bucket, key, value)); // depends on control dependency: [try], data = [none]
}
catch (IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public int getTransactionTimeout() {
for (TransactionSettingsProvider s : _serverWideConfigProvider.getTransactionSettingsProviders().services()) {
if (s.isActive()) {
final GlobalTransactionSettings gts = s.getGlobalTransactionSettings();
if (gts != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "Found a GlobalTransactionSettings");
return gts.getTransactionTimeout();
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "No GlobalTransactionSettings on this thread");
}
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "Found the TransactionSettingsProvider but it was inactive");
}
}
return -1;
} } | public class class_name {
@Override
public int getTransactionTimeout() {
for (TransactionSettingsProvider s : _serverWideConfigProvider.getTransactionSettingsProviders().services()) {
if (s.isActive()) {
final GlobalTransactionSettings gts = s.getGlobalTransactionSettings();
if (gts != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "Found a GlobalTransactionSettings");
return gts.getTransactionTimeout(); // depends on control dependency: [if], data = [none]
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "No GlobalTransactionSettings on this thread");
}
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "Found the TransactionSettingsProvider but it was inactive");
}
}
return -1;
} } |
public class class_name {
@Override
public void notifyListeners(GerritEvent event) {
if (event instanceof CommentAdded) {
if (ignoreEvent((CommentAdded)event)) {
logger.trace("CommentAdded ignored");
return;
}
}
for (GerritEventListener listener : gerritEventListeners) {
try {
notifyListener(listener, event);
} catch (Exception ex) {
logger.error("When notifying listener: {} about event: {}", listener, event);
logger.error("Notify-error: ", ex);
}
}
} } | public class class_name {
@Override
public void notifyListeners(GerritEvent event) {
if (event instanceof CommentAdded) {
if (ignoreEvent((CommentAdded)event)) {
logger.trace("CommentAdded ignored"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
for (GerritEventListener listener : gerritEventListeners) {
try {
notifyListener(listener, event); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
logger.error("When notifying listener: {} about event: {}", listener, event);
logger.error("Notify-error: ", ex);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
@Override
protected void informSynchronizations(boolean isCompleting)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "informSynchronizations: isCompleting="+isCompleting);
ensureActive();
boolean shouldContinue = true;
if (_state == Completed && _interposedSynchronizations != null)
{
for (int i = 0; i < _interposedSynchronizations.size() && shouldContinue; i++)
{
final Synchronization sync = _interposedSynchronizations.get(i);
shouldContinue = driveSynchronization(sync);
}
}
if (_syncs != null)
{
for (int i = 0; i < _syncs.size() && shouldContinue; i++) // d128178 size can grow
{
Synchronization sync = _syncs.get(i);
shouldContinue = driveSynchronization(sync);
}
}
if (_state == Running && _interposedSynchronizations != null)
{
for (int i = 0; i < _interposedSynchronizations.size() && shouldContinue; i++)
{
final Synchronization sync = _interposedSynchronizations.get(i);
shouldContinue = driveSynchronization(sync);
}
}
// Defect 126930
//
// Drive signals on ContainerSynchronization
//
if (_containerSync != null)
{
if (_state == Running)
{
_containerSync.setCompleting(isCompleting);
// Don't drive the container's synchronization if a failure
// in a 'normal' synchronization driven above has resulted
// in the LTC being marked rollback only.
if (!_rollbackOnly)
{
try /* @PK08578A*/
{ /* @PK08578A*/
_containerSync.beforeCompletion();
} /* @PK08578A*/
catch (Throwable t) /* @PK08578A*/
{ /* @PK08578A*/
FFDCFilter.processException(t, "com.ibm.tx.ltc.embeddable.impl.EmbeddableLocalTranCoordImpl.informSynchronizations", "257", this); /* @PK08578A*/
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "ContainerSync threw an exception during beforeCompletion", t); /* @PK08578A*/
setRollbackOnly(); /* @PK08578A*/
} /* @PK08578A*/
}
}
// if not really completing (mid-AS checkpoint or reset) delay this signal
else if (isCompleting && (_state == Completed))
{
_containerSync.setCompleting(isCompleting);
try /* @PK08578A*/
{ /* @PK08578A*/
if (_outcomeRollback)
{
_containerSync.afterCompletion(javax.transaction.Status.STATUS_ROLLEDBACK);
}
else
{
_containerSync.afterCompletion(javax.transaction.Status.STATUS_COMMITTED);
}
} /* @PK08578A*/
catch (Throwable t) /* @PK08578A*/
{ /* @PK08578A*/
FFDCFilter.processException(t, "com.ibm.tx.ltc.embeddable.impl.EmbeddableLocalTranCoordImpl.informSynchronizations", "281", this); /* @PK08578A*/
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "ContainerSync threw an exception during afterCompletion", t); /* @PK08578A*/
} /* @PK08578A*/
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "informSynchronizations");
} } | public class class_name {
@Override
protected void informSynchronizations(boolean isCompleting)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "informSynchronizations: isCompleting="+isCompleting);
ensureActive();
boolean shouldContinue = true;
if (_state == Completed && _interposedSynchronizations != null)
{
for (int i = 0; i < _interposedSynchronizations.size() && shouldContinue; i++)
{
final Synchronization sync = _interposedSynchronizations.get(i);
shouldContinue = driveSynchronization(sync); // depends on control dependency: [for], data = [none]
}
}
if (_syncs != null)
{
for (int i = 0; i < _syncs.size() && shouldContinue; i++) // d128178 size can grow
{
Synchronization sync = _syncs.get(i);
shouldContinue = driveSynchronization(sync); // depends on control dependency: [for], data = [none]
}
}
if (_state == Running && _interposedSynchronizations != null)
{
for (int i = 0; i < _interposedSynchronizations.size() && shouldContinue; i++)
{
final Synchronization sync = _interposedSynchronizations.get(i);
shouldContinue = driveSynchronization(sync); // depends on control dependency: [for], data = [none]
}
}
// Defect 126930
//
// Drive signals on ContainerSynchronization
//
if (_containerSync != null)
{
if (_state == Running)
{
_containerSync.setCompleting(isCompleting); // depends on control dependency: [if], data = [none]
// Don't drive the container's synchronization if a failure
// in a 'normal' synchronization driven above has resulted
// in the LTC being marked rollback only.
if (!_rollbackOnly)
{
try /* @PK08578A*/
{ /* @PK08578A*/
_containerSync.beforeCompletion(); // depends on control dependency: [try], data = [none]
} /* @PK08578A*/
catch (Throwable t) /* @PK08578A*/
{ /* @PK08578A*/
FFDCFilter.processException(t, "com.ibm.tx.ltc.embeddable.impl.EmbeddableLocalTranCoordImpl.informSynchronizations", "257", this); /* @PK08578A*/
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "ContainerSync threw an exception during beforeCompletion", t); /* @PK08578A*/
setRollbackOnly(); /* @PK08578A*/
} /* @PK08578A*/ // depends on control dependency: [catch], data = [none]
}
}
// if not really completing (mid-AS checkpoint or reset) delay this signal
else if (isCompleting && (_state == Completed))
{
_containerSync.setCompleting(isCompleting); // depends on control dependency: [if], data = [none]
try /* @PK08578A*/
{ /* @PK08578A*/
if (_outcomeRollback)
{
_containerSync.afterCompletion(javax.transaction.Status.STATUS_ROLLEDBACK); // depends on control dependency: [if], data = [none]
}
else
{
_containerSync.afterCompletion(javax.transaction.Status.STATUS_COMMITTED); // depends on control dependency: [if], data = [none]
}
} /* @PK08578A*/
catch (Throwable t) /* @PK08578A*/
{ /* @PK08578A*/
FFDCFilter.processException(t, "com.ibm.tx.ltc.embeddable.impl.EmbeddableLocalTranCoordImpl.informSynchronizations", "281", this); /* @PK08578A*/
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "ContainerSync threw an exception during afterCompletion", t); /* @PK08578A*/
} /* @PK08578A*/ // depends on control dependency: [catch], data = [none]
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "informSynchronizations");
} } |
public class class_name {
public String readUTF8(final int offset, final char[] charBuffer) {
int constantPoolEntryIndex = readUnsignedShort(offset);
if (offset == 0 || constantPoolEntryIndex == 0) {
return null;
}
return readUtf(constantPoolEntryIndex, charBuffer);
} } | public class class_name {
public String readUTF8(final int offset, final char[] charBuffer) {
int constantPoolEntryIndex = readUnsignedShort(offset);
if (offset == 0 || constantPoolEntryIndex == 0) {
return null; // depends on control dependency: [if], data = [none]
}
return readUtf(constantPoolEntryIndex, charBuffer);
} } |
public class class_name {
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
final Resource resource = context.createResource(PathAddress.EMPTY_ADDRESS);
final ModelNode model = resource.getModel();
for (SimpleAttributeDefinition atr : ALL_ATTRIBUTES) {
atr.validateAndSet(operation, model);
}
recordCapabilitiesAndRequirements(context, resource, ALL_ATTRIBUTES);
boolean stepCompleted = false;
if (context.isNormalServer()) {
final boolean enabled = SCAN_ENABLED.resolveModelAttribute(context, operation).asBoolean();
final boolean bootTimeScan = context.isBooting() && enabled;
final String path = DeploymentScannerDefinition.PATH.resolveModelAttribute(context, operation).asString();
final ModelNode relativeToNode = RELATIVE_TO.resolveModelAttribute(context, operation);
final String relativeTo = relativeToNode.isDefined() ? relativeToNode.asString() : null;
final boolean autoDeployZip = AUTO_DEPLOY_ZIPPED.resolveModelAttribute(context, operation).asBoolean();
final boolean autoDeployExp = AUTO_DEPLOY_EXPLODED.resolveModelAttribute(context, operation).asBoolean();
final boolean autoDeployXml = AUTO_DEPLOY_XML.resolveModelAttribute(context, operation).asBoolean();
final long deploymentTimeout = DEPLOYMENT_TIMEOUT.resolveModelAttribute(context, operation).asLong();
final int scanInterval = SCAN_INTERVAL.resolveModelAttribute(context, operation).asInt();
final boolean rollback = RUNTIME_FAILURE_CAUSES_ROLLBACK.resolveModelAttribute(context, operation).asBoolean();
final ScheduledExecutorService scheduledExecutorService = createScannerExecutorService();
final FileSystemDeploymentService bootTimeScanner;
if (bootTimeScan) {
final String pathName = pathManager.resolveRelativePathEntry(path, relativeTo);
File relativePath = null;
if (relativeTo != null) {
relativePath = new File(pathManager.getPathEntry(relativeTo).resolvePath());
}
PathAddress ownerAddress = context.getCurrentAddress();
bootTimeScanner = new FileSystemDeploymentService(ownerAddress, relativeTo, new File(pathName), relativePath, null, scheduledExecutorService,
(ControlledProcessStateService) context.getServiceRegistry(false).getService(ControlledProcessStateService.SERVICE_NAME).getValue());
bootTimeScanner.setAutoDeployExplodedContent(autoDeployExp);
bootTimeScanner.setAutoDeployZippedContent(autoDeployZip);
bootTimeScanner.setAutoDeployXMLContent(autoDeployXml);
bootTimeScanner.setDeploymentTimeout(deploymentTimeout);
bootTimeScanner.setScanInterval(scanInterval);
bootTimeScanner.setRuntimeFailureCausesRollback(rollback);
} else {
bootTimeScanner = null;
}
context.addStep(new OperationStepHandler() {
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
performRuntime(context, operation, model, scheduledExecutorService, bootTimeScanner);
// We count on the context's automatic service removal on rollback
context.completeStep(OperationContext.ResultHandler.NOOP_RESULT_HANDLER);
}
}, OperationContext.Stage.RUNTIME);
if (bootTimeScan) {
final AtomicReference<ModelNode> deploymentOperation = new AtomicReference<ModelNode>();
final AtomicReference<ModelNode> deploymentResults = new AtomicReference<ModelNode>(new ModelNode());
final CountDownLatch scanDoneLatch = new CountDownLatch(1);
final CountDownLatch deploymentDoneLatch = new CountDownLatch(1);
final DeploymentOperations deploymentOps = new BootTimeScannerDeployment(deploymentOperation, deploymentDoneLatch, deploymentResults, scanDoneLatch);
scheduledExecutorService.submit(new Runnable() {
@Override
public void run() {
try {
bootTimeScanner.bootTimeScan(deploymentOps);
} catch (Throwable t){
DeploymentScannerLogger.ROOT_LOGGER.initialScanFailed(t);
} finally {
scanDoneLatch.countDown();
}
}
});
boolean interrupted = false;
boolean asyncCountDown = false;
try {
scanDoneLatch.await();
final ModelNode op = deploymentOperation.get();
if (op != null) {
final ModelNode result = new ModelNode();
final PathAddress opPath = PathAddress.pathAddress(op.get(OP_ADDR));
final OperationStepHandler handler = context.getRootResourceRegistration().getOperationHandler(opPath, op.get(OP).asString());
context.addStep(result, op, handler, OperationContext.Stage.MODEL);
stepCompleted = true;
context.completeStep(new OperationContext.ResultHandler() {
@Override
public void handleResult(OperationContext.ResultAction resultAction, OperationContext context, ModelNode operation) {
try {
deploymentResults.set(result);
} finally {
deploymentDoneLatch.countDown();
}
}
});
asyncCountDown = true;
} else {
stepCompleted = true;
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
} catch (InterruptedException e) {
interrupted = true;
throw new RuntimeException(e);
} finally {
if (!asyncCountDown) {
deploymentDoneLatch.countDown();
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
}
if (!stepCompleted) {
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
} } | public class class_name {
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
final Resource resource = context.createResource(PathAddress.EMPTY_ADDRESS);
final ModelNode model = resource.getModel();
for (SimpleAttributeDefinition atr : ALL_ATTRIBUTES) {
atr.validateAndSet(operation, model);
}
recordCapabilitiesAndRequirements(context, resource, ALL_ATTRIBUTES);
boolean stepCompleted = false;
if (context.isNormalServer()) {
final boolean enabled = SCAN_ENABLED.resolveModelAttribute(context, operation).asBoolean();
final boolean bootTimeScan = context.isBooting() && enabled;
final String path = DeploymentScannerDefinition.PATH.resolveModelAttribute(context, operation).asString();
final ModelNode relativeToNode = RELATIVE_TO.resolveModelAttribute(context, operation);
final String relativeTo = relativeToNode.isDefined() ? relativeToNode.asString() : null;
final boolean autoDeployZip = AUTO_DEPLOY_ZIPPED.resolveModelAttribute(context, operation).asBoolean();
final boolean autoDeployExp = AUTO_DEPLOY_EXPLODED.resolveModelAttribute(context, operation).asBoolean();
final boolean autoDeployXml = AUTO_DEPLOY_XML.resolveModelAttribute(context, operation).asBoolean();
final long deploymentTimeout = DEPLOYMENT_TIMEOUT.resolveModelAttribute(context, operation).asLong();
final int scanInterval = SCAN_INTERVAL.resolveModelAttribute(context, operation).asInt();
final boolean rollback = RUNTIME_FAILURE_CAUSES_ROLLBACK.resolveModelAttribute(context, operation).asBoolean();
final ScheduledExecutorService scheduledExecutorService = createScannerExecutorService();
final FileSystemDeploymentService bootTimeScanner;
if (bootTimeScan) {
final String pathName = pathManager.resolveRelativePathEntry(path, relativeTo);
File relativePath = null;
if (relativeTo != null) {
relativePath = new File(pathManager.getPathEntry(relativeTo).resolvePath()); // depends on control dependency: [if], data = [(relativeTo]
}
PathAddress ownerAddress = context.getCurrentAddress();
bootTimeScanner = new FileSystemDeploymentService(ownerAddress, relativeTo, new File(pathName), relativePath, null, scheduledExecutorService,
(ControlledProcessStateService) context.getServiceRegistry(false).getService(ControlledProcessStateService.SERVICE_NAME).getValue()); // depends on control dependency: [if], data = [none]
bootTimeScanner.setAutoDeployExplodedContent(autoDeployExp); // depends on control dependency: [if], data = [none]
bootTimeScanner.setAutoDeployZippedContent(autoDeployZip); // depends on control dependency: [if], data = [none]
bootTimeScanner.setAutoDeployXMLContent(autoDeployXml); // depends on control dependency: [if], data = [none]
bootTimeScanner.setDeploymentTimeout(deploymentTimeout); // depends on control dependency: [if], data = [none]
bootTimeScanner.setScanInterval(scanInterval); // depends on control dependency: [if], data = [none]
bootTimeScanner.setRuntimeFailureCausesRollback(rollback); // depends on control dependency: [if], data = [none]
} else {
bootTimeScanner = null; // depends on control dependency: [if], data = [none]
}
context.addStep(new OperationStepHandler() {
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
performRuntime(context, operation, model, scheduledExecutorService, bootTimeScanner);
// We count on the context's automatic service removal on rollback
context.completeStep(OperationContext.ResultHandler.NOOP_RESULT_HANDLER);
}
}, OperationContext.Stage.RUNTIME);
if (bootTimeScan) {
final AtomicReference<ModelNode> deploymentOperation = new AtomicReference<ModelNode>();
final AtomicReference<ModelNode> deploymentResults = new AtomicReference<ModelNode>(new ModelNode());
final CountDownLatch scanDoneLatch = new CountDownLatch(1);
final CountDownLatch deploymentDoneLatch = new CountDownLatch(1);
final DeploymentOperations deploymentOps = new BootTimeScannerDeployment(deploymentOperation, deploymentDoneLatch, deploymentResults, scanDoneLatch);
scheduledExecutorService.submit(new Runnable() {
@Override
public void run() {
try {
bootTimeScanner.bootTimeScan(deploymentOps); // depends on control dependency: [try], data = [none]
} catch (Throwable t){
DeploymentScannerLogger.ROOT_LOGGER.initialScanFailed(t);
} finally { // depends on control dependency: [catch], data = [none]
scanDoneLatch.countDown();
}
}
}); // depends on control dependency: [if], data = [none]
boolean interrupted = false;
boolean asyncCountDown = false;
try {
scanDoneLatch.await(); // depends on control dependency: [try], data = [none]
final ModelNode op = deploymentOperation.get();
if (op != null) {
final ModelNode result = new ModelNode();
final PathAddress opPath = PathAddress.pathAddress(op.get(OP_ADDR));
final OperationStepHandler handler = context.getRootResourceRegistration().getOperationHandler(opPath, op.get(OP).asString());
context.addStep(result, op, handler, OperationContext.Stage.MODEL); // depends on control dependency: [if], data = [none]
stepCompleted = true; // depends on control dependency: [if], data = [none]
context.completeStep(new OperationContext.ResultHandler() {
@Override
public void handleResult(OperationContext.ResultAction resultAction, OperationContext context, ModelNode operation) {
try {
deploymentResults.set(result); // depends on control dependency: [try], data = [none]
} finally {
deploymentDoneLatch.countDown();
}
}
}); // depends on control dependency: [if], data = [none]
asyncCountDown = true; // depends on control dependency: [if], data = [none]
} else {
stepCompleted = true; // depends on control dependency: [if], data = [none]
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); // depends on control dependency: [if], data = [none]
}
} catch (InterruptedException e) {
interrupted = true;
throw new RuntimeException(e);
} finally { // depends on control dependency: [catch], data = [none]
if (!asyncCountDown) {
deploymentDoneLatch.countDown(); // depends on control dependency: [if], data = [none]
}
if (interrupted) {
Thread.currentThread().interrupt(); // depends on control dependency: [if], data = [none]
}
}
}
}
if (!stepCompleted) {
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
} } |
public class class_name {
public boolean sendMessage(WebSocketMessage<?> message) {
boolean sentSuccessfully = false;
if (sessions.isEmpty()) {
LOG.warn("No Web Socket session exists - message cannot be sent");
}
for (WebSocketSession session : sessions.values()) {
if (session != null && session.isOpen()) {
try {
session.sendMessage(message);
sentSuccessfully = true;
} catch (IOException e) {
LOG.error(String.format("(%s) error sending message", session.getId()), e);
}
}
}
return sentSuccessfully;
} } | public class class_name {
public boolean sendMessage(WebSocketMessage<?> message) {
boolean sentSuccessfully = false;
if (sessions.isEmpty()) {
LOG.warn("No Web Socket session exists - message cannot be sent"); // depends on control dependency: [if], data = [none]
}
for (WebSocketSession session : sessions.values()) {
if (session != null && session.isOpen()) {
try {
session.sendMessage(message); // depends on control dependency: [try], data = [none]
sentSuccessfully = true; // depends on control dependency: [try], data = [none]
} catch (IOException e) {
LOG.error(String.format("(%s) error sending message", session.getId()), e);
} // depends on control dependency: [catch], data = [none]
}
}
return sentSuccessfully;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.