code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private Block convertToDeepTree(Block sourceTree, String iconName)
{
XDOM targetTree = new XDOM(Collections.<Block>emptyList());
Block pointer = targetTree;
for (Block block : sourceTree.getChildren()) {
pointer.addChild(block);
pointer = block;
}
// Add an image block as the last block
pointer.addChild(new ImageBlock(new ResourceReference(iconName, ResourceType.ICON), true));
return targetTree;
} } | public class class_name {
private Block convertToDeepTree(Block sourceTree, String iconName)
{
XDOM targetTree = new XDOM(Collections.<Block>emptyList());
Block pointer = targetTree;
for (Block block : sourceTree.getChildren()) {
pointer.addChild(block); // depends on control dependency: [for], data = [block]
pointer = block; // depends on control dependency: [for], data = [block]
}
// Add an image block as the last block
pointer.addChild(new ImageBlock(new ResourceReference(iconName, ResourceType.ICON), true));
return targetTree;
} } |
public class class_name {
@NotNull
private BoundStatement createBoundStatement(@NotNull PreparedStatement prepare, @NotNull V entity, @NotNull List<ColumnMetadata> columns) {
BoundStatement boundStatement = new BoundStatement(prepare);
boundStatement.setConsistencyLevel(getEntityMetadata().getWriteConsistencyLevel());
for (int i = 0; i < columns.size(); i++) {
ColumnMetadata column = columns.get(i);
Object value = column.readValue(entity);
boundStatement.setBytesUnsafe(i, column.serialize(value));
}
return boundStatement;
} } | public class class_name {
@NotNull
private BoundStatement createBoundStatement(@NotNull PreparedStatement prepare, @NotNull V entity, @NotNull List<ColumnMetadata> columns) {
BoundStatement boundStatement = new BoundStatement(prepare);
boundStatement.setConsistencyLevel(getEntityMetadata().getWriteConsistencyLevel());
for (int i = 0; i < columns.size(); i++) {
ColumnMetadata column = columns.get(i);
Object value = column.readValue(entity);
boundStatement.setBytesUnsafe(i, column.serialize(value)); // depends on control dependency: [for], data = [i]
}
return boundStatement;
} } |
public class class_name {
public static ChartData initChartDataFromXSSFChart(final String chartId,
final XSSFChart chart, final XSSFWorkbook wb) {
ThemesTable themeTable = wb.getStylesSource().getTheme();
ChartData chartData = new ChartData();
XSSFRichTextString chartTitle = chart.getTitle();
if (chartTitle != null) {
chartData.setTitle(chartTitle.toString());
}
CTChart ctChart = chart.getCTChart();
ChartType chartType = ChartUtility.getChartType(ctChart);
if (chartType == null) {
throw new IllegalChartException("Unknown chart type");
}
chartData.setBgColor(
ColorUtility.getBgColor(ctChart.getPlotArea(), themeTable));
chartData.setId(chartId);
chartData.setType(chartType);
List<CTCatAx> ctCatAxList = ctChart.getPlotArea().getCatAxList();
if ((ctCatAxList != null) && (!ctCatAxList.isEmpty())) {
chartData.setCatAx(new ChartAxis(ctCatAxList.get(0)));
}
List<CTValAx> ctValAxList = ctChart.getPlotArea().getValAxList();
if ((ctValAxList != null) && (!ctValAxList.isEmpty())) {
chartData.setValAx(new ChartAxis(ctValAxList.get(0)));
}
ChartObject ctObj = chartType.createChartObject();
if (ctObj == null) {
throw new IllegalChartException("Cannot create chart object.");
}
setUpChartData(chartData, ctChart, themeTable, ctObj);
return chartData;
} } | public class class_name {
public static ChartData initChartDataFromXSSFChart(final String chartId,
final XSSFChart chart, final XSSFWorkbook wb) {
ThemesTable themeTable = wb.getStylesSource().getTheme();
ChartData chartData = new ChartData();
XSSFRichTextString chartTitle = chart.getTitle();
if (chartTitle != null) {
chartData.setTitle(chartTitle.toString());
// depends on control dependency: [if], data = [(chartTitle]
}
CTChart ctChart = chart.getCTChart();
ChartType chartType = ChartUtility.getChartType(ctChart);
if (chartType == null) {
throw new IllegalChartException("Unknown chart type");
}
chartData.setBgColor(
ColorUtility.getBgColor(ctChart.getPlotArea(), themeTable));
chartData.setId(chartId);
chartData.setType(chartType);
List<CTCatAx> ctCatAxList = ctChart.getPlotArea().getCatAxList();
if ((ctCatAxList != null) && (!ctCatAxList.isEmpty())) {
chartData.setCatAx(new ChartAxis(ctCatAxList.get(0)));
// depends on control dependency: [if], data = [none]
}
List<CTValAx> ctValAxList = ctChart.getPlotArea().getValAxList();
if ((ctValAxList != null) && (!ctValAxList.isEmpty())) {
chartData.setValAx(new ChartAxis(ctValAxList.get(0)));
// depends on control dependency: [if], data = [none]
}
ChartObject ctObj = chartType.createChartObject();
if (ctObj == null) {
throw new IllegalChartException("Cannot create chart object.");
}
setUpChartData(chartData, ctChart, themeTable, ctObj);
return chartData;
} } |
public class class_name {
@Override
public void queueEnvelope(Envelope envelope) {
// The sequence number of the envelope to be queued
final int sequenceNumber = envelope.getSequenceNumber();
synchronized (this.queuedEnvelopes) {
if (this.destroyCalled) {
final Buffer buffer = envelope.getBuffer();
if (buffer != null) {
buffer.recycleBuffer();
}
return;
}
final int expectedSequenceNumber = this.lastReceivedEnvelope + 1;
if (sequenceNumber != expectedSequenceNumber) {
// This is a problem, now we are actually missing some data
reportIOException(new IOException("Expected data packet " + expectedSequenceNumber + " but received " + sequenceNumber));
// notify that something (an exception) is available
notifyGateThatInputIsAvailable();
if (LOG.isDebugEnabled()) {
LOG.debug("Input channel " + this.toString() + " expected envelope " + expectedSequenceNumber
+ " but received " + sequenceNumber);
}
// rescue the buffer
final Buffer buffer = envelope.getBuffer();
if (buffer != null) {
buffer.recycleBuffer();
}
} else {
this.queuedEnvelopes.add(envelope);
this.lastReceivedEnvelope = sequenceNumber;
this.lastSourceID = envelope.getSource();
// Notify the channel about the new data. notify as much as there is (buffer plus once per event)
if (envelope.getBuffer() != null) {
notifyGateThatInputIsAvailable();
}
List<? extends AbstractEvent> events = envelope.deserializeEvents();
if (events != null) {
for (int i = 0; i < events.size(); i++) {
notifyGateThatInputIsAvailable();
}
}
}
}
} } | public class class_name {
@Override
public void queueEnvelope(Envelope envelope) {
// The sequence number of the envelope to be queued
final int sequenceNumber = envelope.getSequenceNumber();
synchronized (this.queuedEnvelopes) {
if (this.destroyCalled) {
final Buffer buffer = envelope.getBuffer();
if (buffer != null) {
buffer.recycleBuffer(); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
final int expectedSequenceNumber = this.lastReceivedEnvelope + 1;
if (sequenceNumber != expectedSequenceNumber) {
// This is a problem, now we are actually missing some data
reportIOException(new IOException("Expected data packet " + expectedSequenceNumber + " but received " + sequenceNumber)); // depends on control dependency: [if], data = [none]
// notify that something (an exception) is available
notifyGateThatInputIsAvailable(); // depends on control dependency: [if], data = [none]
if (LOG.isDebugEnabled()) {
LOG.debug("Input channel " + this.toString() + " expected envelope " + expectedSequenceNumber
+ " but received " + sequenceNumber); // depends on control dependency: [if], data = [none]
}
// rescue the buffer
final Buffer buffer = envelope.getBuffer();
if (buffer != null) {
buffer.recycleBuffer(); // depends on control dependency: [if], data = [none]
}
} else {
this.queuedEnvelopes.add(envelope); // depends on control dependency: [if], data = [none]
this.lastReceivedEnvelope = sequenceNumber; // depends on control dependency: [if], data = [none]
this.lastSourceID = envelope.getSource(); // depends on control dependency: [if], data = [none]
// Notify the channel about the new data. notify as much as there is (buffer plus once per event)
if (envelope.getBuffer() != null) {
notifyGateThatInputIsAvailable(); // depends on control dependency: [if], data = [none]
}
List<? extends AbstractEvent> events = envelope.deserializeEvents(); // depends on control dependency: [if], data = [none]
if (events != null) {
for (int i = 0; i < events.size(); i++) {
notifyGateThatInputIsAvailable(); // depends on control dependency: [for], data = [none]
}
}
}
}
} } |
public class class_name {
private boolean getWeightRanges(long lowerLimit, long upperLimit) {
assert(lowerLimit != 0);
assert(upperLimit != 0);
/* get the lengths of the limits */
int lowerLength=lengthOfWeight(lowerLimit);
int upperLength=lengthOfWeight(upperLimit);
// printf("length of lower limit 0x%08lx is %ld\n", lowerLimit, lowerLength);
// printf("length of upper limit 0x%08lx is %ld\n", upperLimit, upperLength);
assert(lowerLength>=middleLength);
// Permit upperLength<middleLength: The upper limit for secondaries is 0x10000.
if(lowerLimit>=upperLimit) {
// printf("error: no space between lower & upper limits\n");
return false;
}
/* check that neither is a prefix of the other */
if(lowerLength<upperLength) {
if(lowerLimit==truncateWeight(upperLimit, lowerLength)) {
// printf("error: lower limit 0x%08lx is a prefix of upper limit 0x%08lx\n", lowerLimit, upperLimit);
return false;
}
}
/* if the upper limit is a prefix of the lower limit then the earlier test lowerLimit>=upperLimit has caught it */
WeightRange[] lower = new WeightRange[5]; /* [0] and [1] are not used - this simplifies indexing */
WeightRange middle = new WeightRange();
WeightRange[] upper = new WeightRange[5];
/*
* With the limit lengths of 1..4, there are up to 7 ranges for allocation:
* range minimum length
* lower[4] 4
* lower[3] 3
* lower[2] 2
* middle 1
* upper[2] 2
* upper[3] 3
* upper[4] 4
*
* We are now going to calculate up to 7 ranges.
* Some of them will typically overlap, so we will then have to merge and eliminate ranges.
*/
long weight=lowerLimit;
for(int length=lowerLength; length>middleLength; --length) {
int trail=getWeightTrail(weight, length);
if(trail<maxBytes[length]) {
lower[length] = new WeightRange();
lower[length].start=incWeightTrail(weight, length);
lower[length].end=setWeightTrail(weight, length, maxBytes[length]);
lower[length].length=length;
lower[length].count=maxBytes[length]-trail;
}
weight=truncateWeight(weight, length-1);
}
if(weight<0xff000000L) {
middle.start=incWeightTrail(weight, middleLength);
} else {
// Prevent overflow for primary lead byte FF
// which would yield a middle range starting at 0.
middle.start=0xffffffffL; // no middle range
}
weight=upperLimit;
for(int length=upperLength; length>middleLength; --length) {
int trail=getWeightTrail(weight, length);
if(trail>minBytes[length]) {
upper[length] = new WeightRange();
upper[length].start=setWeightTrail(weight, length, minBytes[length]);
upper[length].end=decWeightTrail(weight, length);
upper[length].length=length;
upper[length].count=trail-minBytes[length];
}
weight=truncateWeight(weight, length-1);
}
middle.end=decWeightTrail(weight, middleLength);
/* set the middle range */
middle.length=middleLength;
if(middle.end>=middle.start) {
middle.count=(int)((middle.end-middle.start)>>(8*(4-middleLength)))+1;
} else {
/* no middle range, eliminate overlaps */
for(int length=4; length>middleLength; --length) {
if(lower[length] != null && upper[length] != null &&
lower[length].count>0 && upper[length].count>0) {
// Note: The lowerEnd and upperStart weights are versions of
// lowerLimit and upperLimit (which are lowerLimit<upperLimit),
// truncated (still less-or-equal)
// and then with their last bytes changed to the
// maxByte (for lowerEnd) or minByte (for upperStart).
final long lowerEnd=lower[length].end;
final long upperStart=upper[length].start;
boolean merged=false;
if(lowerEnd>upperStart) {
// These two lower and upper ranges collide.
// Since lowerLimit<upperLimit and lowerEnd and upperStart
// are versions with only their last bytes modified
// (and following ones removed/reset to 0),
// lowerEnd>upperStart is only possible
// if the leading bytes are equal
// and lastByte(lowerEnd)>lastByte(upperStart).
assert(truncateWeight(lowerEnd, length-1)==
truncateWeight(upperStart, length-1));
// Intersect these two ranges.
lower[length].end=upper[length].end;
lower[length].count=
getWeightTrail(lower[length].end, length)-
getWeightTrail(lower[length].start, length)+1;
// count might be <=0 in which case there is no room,
// and the range-collecting code below will ignore this range.
merged=true;
} else if(lowerEnd==upperStart) {
// Not possible, unless minByte==maxByte which is not allowed.
assert(minBytes[length]<maxBytes[length]);
} else /* lowerEnd<upperStart */ {
if(incWeight(lowerEnd, length)==upperStart) {
// Merge adjacent ranges.
lower[length].end=upper[length].end;
lower[length].count+=upper[length].count; // might be >countBytes
merged=true;
}
}
if(merged) {
// Remove all shorter ranges.
// There was no room available for them between the ranges we just merged.
upper[length].count=0;
while(--length>middleLength) {
lower[length]=upper[length]=null;
}
break;
}
}
}
}
/* print ranges
for(int length=4; length>=2; --length) {
if(lower[length].count>0) {
printf("lower[%ld] .start=0x%08lx .end=0x%08lx .count=%ld\n", length, lower[length].start, lower[length].end, lower[length].count);
}
}
if(middle.count>0) {
printf("middle .start=0x%08lx .end=0x%08lx .count=%ld\n", middle.start, middle.end, middle.count);
}
for(int length=2; length<=4; ++length) {
if(upper[length].count>0) {
printf("upper[%ld] .start=0x%08lx .end=0x%08lx .count=%ld\n", length, upper[length].start, upper[length].end, upper[length].count);
}
} */
/* copy the ranges, shortest first, into the result array */
rangeCount=0;
if(middle.count>0) {
ranges[0] = middle;
rangeCount=1;
}
for(int length=middleLength+1; length<=4; ++length) {
/* copy upper first so that later the middle range is more likely the first one to use */
if(upper[length] != null && upper[length].count>0) {
ranges[rangeCount++]=upper[length];
}
if(lower[length] != null && lower[length].count>0) {
ranges[rangeCount++]=lower[length];
}
}
return rangeCount>0;
} } | public class class_name {
private boolean getWeightRanges(long lowerLimit, long upperLimit) {
assert(lowerLimit != 0);
assert(upperLimit != 0);
/* get the lengths of the limits */
int lowerLength=lengthOfWeight(lowerLimit);
int upperLength=lengthOfWeight(upperLimit);
// printf("length of lower limit 0x%08lx is %ld\n", lowerLimit, lowerLength);
// printf("length of upper limit 0x%08lx is %ld\n", upperLimit, upperLength);
assert(lowerLength>=middleLength);
// Permit upperLength<middleLength: The upper limit for secondaries is 0x10000.
if(lowerLimit>=upperLimit) {
// printf("error: no space between lower & upper limits\n");
return false; // depends on control dependency: [if], data = [none]
}
/* check that neither is a prefix of the other */
if(lowerLength<upperLength) {
if(lowerLimit==truncateWeight(upperLimit, lowerLength)) {
// printf("error: lower limit 0x%08lx is a prefix of upper limit 0x%08lx\n", lowerLimit, upperLimit);
return false; // depends on control dependency: [if], data = [none]
}
}
/* if the upper limit is a prefix of the lower limit then the earlier test lowerLimit>=upperLimit has caught it */
WeightRange[] lower = new WeightRange[5]; /* [0] and [1] are not used - this simplifies indexing */
WeightRange middle = new WeightRange();
WeightRange[] upper = new WeightRange[5];
/*
* With the limit lengths of 1..4, there are up to 7 ranges for allocation:
* range minimum length
* lower[4] 4
* lower[3] 3
* lower[2] 2
* middle 1
* upper[2] 2
* upper[3] 3
* upper[4] 4
*
* We are now going to calculate up to 7 ranges.
* Some of them will typically overlap, so we will then have to merge and eliminate ranges.
*/
long weight=lowerLimit;
for(int length=lowerLength; length>middleLength; --length) {
int trail=getWeightTrail(weight, length);
if(trail<maxBytes[length]) {
lower[length] = new WeightRange(); // depends on control dependency: [if], data = [none]
lower[length].start=incWeightTrail(weight, length); // depends on control dependency: [if], data = [none]
lower[length].end=setWeightTrail(weight, length, maxBytes[length]); // depends on control dependency: [if], data = [maxBytes[length])]
lower[length].length=length; // depends on control dependency: [if], data = [none]
lower[length].count=maxBytes[length]-trail; // depends on control dependency: [if], data = [none]
}
weight=truncateWeight(weight, length-1); // depends on control dependency: [for], data = [length]
}
if(weight<0xff000000L) {
middle.start=incWeightTrail(weight, middleLength); // depends on control dependency: [if], data = [(weight]
} else {
// Prevent overflow for primary lead byte FF
// which would yield a middle range starting at 0.
middle.start=0xffffffffL; // no middle range // depends on control dependency: [if], data = [none]
}
weight=upperLimit;
for(int length=upperLength; length>middleLength; --length) {
int trail=getWeightTrail(weight, length);
if(trail>minBytes[length]) {
upper[length] = new WeightRange(); // depends on control dependency: [if], data = [none]
upper[length].start=setWeightTrail(weight, length, minBytes[length]); // depends on control dependency: [if], data = [minBytes[length])]
upper[length].end=decWeightTrail(weight, length); // depends on control dependency: [if], data = [none]
upper[length].length=length; // depends on control dependency: [if], data = [none]
upper[length].count=trail-minBytes[length]; // depends on control dependency: [if], data = [none]
}
weight=truncateWeight(weight, length-1); // depends on control dependency: [for], data = [length]
}
middle.end=decWeightTrail(weight, middleLength);
/* set the middle range */
middle.length=middleLength;
if(middle.end>=middle.start) {
middle.count=(int)((middle.end-middle.start)>>(8*(4-middleLength)))+1; // depends on control dependency: [if], data = [(middle.end]
} else {
/* no middle range, eliminate overlaps */
for(int length=4; length>middleLength; --length) {
if(lower[length] != null && upper[length] != null &&
lower[length].count>0 && upper[length].count>0) {
// Note: The lowerEnd and upperStart weights are versions of
// lowerLimit and upperLimit (which are lowerLimit<upperLimit),
// truncated (still less-or-equal)
// and then with their last bytes changed to the
// maxByte (for lowerEnd) or minByte (for upperStart).
final long lowerEnd=lower[length].end;
final long upperStart=upper[length].start;
boolean merged=false;
if(lowerEnd>upperStart) {
// These two lower and upper ranges collide.
// Since lowerLimit<upperLimit and lowerEnd and upperStart
// are versions with only their last bytes modified
// (and following ones removed/reset to 0),
// lowerEnd>upperStart is only possible
// if the leading bytes are equal
// and lastByte(lowerEnd)>lastByte(upperStart).
assert(truncateWeight(lowerEnd, length-1)==
truncateWeight(upperStart, length-1)); // depends on control dependency: [if], data = [(lowerEnd]
// Intersect these two ranges.
lower[length].end=upper[length].end; // depends on control dependency: [if], data = [none]
lower[length].count=
getWeightTrail(lower[length].end, length)-
getWeightTrail(lower[length].start, length)+1; // depends on control dependency: [if], data = [none]
// count might be <=0 in which case there is no room,
// and the range-collecting code below will ignore this range.
merged=true; // depends on control dependency: [if], data = [none]
} else if(lowerEnd==upperStart) {
// Not possible, unless minByte==maxByte which is not allowed.
assert(minBytes[length]<maxBytes[length]); // depends on control dependency: [if], data = [none]
} else /* lowerEnd<upperStart */ {
if(incWeight(lowerEnd, length)==upperStart) {
// Merge adjacent ranges.
lower[length].end=upper[length].end; // depends on control dependency: [if], data = [none]
lower[length].count+=upper[length].count; // might be >countBytes // depends on control dependency: [if], data = [none]
merged=true; // depends on control dependency: [if], data = [none]
}
}
if(merged) {
// Remove all shorter ranges.
// There was no room available for them between the ranges we just merged.
upper[length].count=0; // depends on control dependency: [if], data = [none]
while(--length>middleLength) {
lower[length]=upper[length]=null; // depends on control dependency: [while], data = [none]
}
break;
}
}
}
}
/* print ranges
for(int length=4; length>=2; --length) {
if(lower[length].count>0) {
printf("lower[%ld] .start=0x%08lx .end=0x%08lx .count=%ld\n", length, lower[length].start, lower[length].end, lower[length].count);
}
}
if(middle.count>0) {
printf("middle .start=0x%08lx .end=0x%08lx .count=%ld\n", middle.start, middle.end, middle.count);
}
for(int length=2; length<=4; ++length) {
if(upper[length].count>0) {
printf("upper[%ld] .start=0x%08lx .end=0x%08lx .count=%ld\n", length, upper[length].start, upper[length].end, upper[length].count);
}
} */
/* copy the ranges, shortest first, into the result array */
rangeCount=0;
if(middle.count>0) {
ranges[0] = middle; // depends on control dependency: [if], data = [none]
rangeCount=1; // depends on control dependency: [if], data = [none]
}
for(int length=middleLength+1; length<=4; ++length) {
/* copy upper first so that later the middle range is more likely the first one to use */
if(upper[length] != null && upper[length].count>0) {
ranges[rangeCount++]=upper[length]; // depends on control dependency: [if], data = [none]
}
if(lower[length] != null && lower[length].count>0) {
ranges[rangeCount++]=lower[length]; // depends on control dependency: [if], data = [none]
}
}
return rangeCount>0;
} } |
public class class_name {
public static String[] toStringArray(final Object array) {
final int length = Array.getLength(array);
final String[] result = new String[length];
for (int i = 0; i < length; i++) {
result[i] = Array.get(array, i).toString();
}
return result;
} } | public class class_name {
public static String[] toStringArray(final Object array) {
final int length = Array.getLength(array);
final String[] result = new String[length];
for (int i = 0; i < length; i++) {
result[i] = Array.get(array, i).toString(); // depends on control dependency: [for], data = [i]
}
return result;
} } |
public class class_name {
public static <T> List<T> getList(final Cursor cursor, final Class<T> klass) {
try {
return getObjectsFromCursor(cursor, klass);
} catch (final Exception e) {
Logger.ex(e);
return null;
}
} } | public class class_name {
public static <T> List<T> getList(final Cursor cursor, final Class<T> klass) {
try {
return getObjectsFromCursor(cursor, klass); // depends on control dependency: [try], data = [none]
} catch (final Exception e) {
Logger.ex(e);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public com.google.cloud.datalabeling.v1beta1.LabelImagePolylineOperationMetadataOrBuilder
getImagePolylineDetailsOrBuilder() {
if (detailsCase_ == 12) {
return (com.google.cloud.datalabeling.v1beta1.LabelImagePolylineOperationMetadata) details_;
}
return com.google.cloud.datalabeling.v1beta1.LabelImagePolylineOperationMetadata
.getDefaultInstance();
} } | public class class_name {
public com.google.cloud.datalabeling.v1beta1.LabelImagePolylineOperationMetadataOrBuilder
getImagePolylineDetailsOrBuilder() {
if (detailsCase_ == 12) {
return (com.google.cloud.datalabeling.v1beta1.LabelImagePolylineOperationMetadata) details_; // depends on control dependency: [if], data = [none]
}
return com.google.cloud.datalabeling.v1beta1.LabelImagePolylineOperationMetadata
.getDefaultInstance();
} } |
public class class_name {
void linkLast(final E e) {
final E l = last;
last = e;
if (l == null) {
first = e;
} else {
setNext(l, e);
setPrevious(e, l);
}
} } | public class class_name {
void linkLast(final E e) {
final E l = last;
last = e;
if (l == null) {
first = e; // depends on control dependency: [if], data = [none]
} else {
setNext(l, e); // depends on control dependency: [if], data = [(l]
setPrevious(e, l); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Table sortOn(String... columnNames) {
Sort key = null;
List<String> names = columnNames().stream().map(String::toUpperCase).collect(toList());
for (String columnName : columnNames) {
Sort.Order order = Sort.Order.ASCEND;
if (!names.contains(columnName.toUpperCase())) {
// the column name has been annotated with a prefix.
// get the prefix which could be - or +
String prefix = columnName.substring(0, 1);
// remove - prefix so provided name matches actual column name
columnName = columnName.substring(1, columnName.length());
order = getOrder(prefix);
}
if (key == null) { // key will be null the first time through
key = first(columnName, order);
} else {
key.next(columnName, order);
}
}
return sortOn(key);
} } | public class class_name {
public Table sortOn(String... columnNames) {
Sort key = null;
List<String> names = columnNames().stream().map(String::toUpperCase).collect(toList());
for (String columnName : columnNames) {
Sort.Order order = Sort.Order.ASCEND;
if (!names.contains(columnName.toUpperCase())) {
// the column name has been annotated with a prefix.
// get the prefix which could be - or +
String prefix = columnName.substring(0, 1);
// remove - prefix so provided name matches actual column name
columnName = columnName.substring(1, columnName.length()); // depends on control dependency: [if], data = [none]
order = getOrder(prefix); // depends on control dependency: [if], data = [none]
}
if (key == null) { // key will be null the first time through
key = first(columnName, order); // depends on control dependency: [if], data = [none]
} else {
key.next(columnName, order); // depends on control dependency: [if], data = [none]
}
}
return sortOn(key);
} } |
public class class_name {
public void setOffset(int newOffset) {
if (0 < newOffset && newOffset < string_.length()) {
int offset = newOffset;
do {
char c = string_.charAt(offset);
if (!rbc_.isUnsafe(c) ||
(Character.isHighSurrogate(c) && !rbc_.isUnsafe(string_.codePointAt(offset)))) {
break;
}
// Back up to before this unsafe character.
--offset;
} while (offset > 0);
if (offset < newOffset) {
// We might have backed up more than necessary.
// For example, contractions "ch" and "cu" make both 'h' and 'u' unsafe,
// but for text "chu" setOffset(2) should remain at 2
// although we initially back up to offset 0.
// Find the last safe offset no greater than newOffset by iterating forward.
int lastSafeOffset = offset;
do {
iter_.resetToOffset(lastSafeOffset);
do {
iter_.nextCE();
} while ((offset = iter_.getOffset()) == lastSafeOffset);
if (offset <= newOffset) {
lastSafeOffset = offset;
}
} while (offset < newOffset);
newOffset = lastSafeOffset;
}
}
iter_.resetToOffset(newOffset);
otherHalf_ = 0;
dir_ = 1;
} } | public class class_name {
public void setOffset(int newOffset) {
if (0 < newOffset && newOffset < string_.length()) {
int offset = newOffset;
do {
char c = string_.charAt(offset);
if (!rbc_.isUnsafe(c) ||
(Character.isHighSurrogate(c) && !rbc_.isUnsafe(string_.codePointAt(offset)))) {
break;
}
// Back up to before this unsafe character.
--offset;
} while (offset > 0);
if (offset < newOffset) {
// We might have backed up more than necessary.
// For example, contractions "ch" and "cu" make both 'h' and 'u' unsafe,
// but for text "chu" setOffset(2) should remain at 2
// although we initially back up to offset 0.
// Find the last safe offset no greater than newOffset by iterating forward.
int lastSafeOffset = offset;
do {
iter_.resetToOffset(lastSafeOffset);
do {
iter_.nextCE();
} while ((offset = iter_.getOffset()) == lastSafeOffset);
if (offset <= newOffset) {
lastSafeOffset = offset; // depends on control dependency: [if], data = [none]
}
} while (offset < newOffset);
newOffset = lastSafeOffset; // depends on control dependency: [if], data = [none]
}
}
iter_.resetToOffset(newOffset);
otherHalf_ = 0;
dir_ = 1;
} } |
public class class_name {
@Override
public void add(IPermission[] perms) throws AuthorizationException {
if (perms.length > 0) {
try {
primAdd(perms);
} catch (Exception ex) {
log.error("Exception adding permissions " + Arrays.toString(perms), ex);
throw new AuthorizationException(ex);
}
}
} } | public class class_name {
@Override
public void add(IPermission[] perms) throws AuthorizationException {
if (perms.length > 0) {
try {
primAdd(perms); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
log.error("Exception adding permissions " + Arrays.toString(perms), ex);
throw new AuthorizationException(ex);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public void cleanup() {
cleanupLock.lock();
try {
// Clean up the write interface.
if (null != writeInterface) {
this.writeInterface.close();
this.writeInterface = null;
}
// Clean up the read interface.
if (null != readInterface) {
this.readInterface.close();
this.readInterface = null;
}
// Clean up the SSL engine.
if (null != getSSLEngine()) {
//If the channel has already processed the stop signal, it is too late to try and send the write handshake
if (this.sslChannel.getstop0Called() == true) {
this.connected = false;
}
SSLUtils.shutDownSSLEngine(this, isInbound, this.connected);
this.sslEngine = null;
}
// mark that we have disconnected
this.connected = false;
} finally {
cleanupLock.unlock();
}
} } | public class class_name {
public void cleanup() {
cleanupLock.lock();
try {
// Clean up the write interface.
if (null != writeInterface) {
this.writeInterface.close(); // depends on control dependency: [if], data = [none]
this.writeInterface = null; // depends on control dependency: [if], data = [none]
}
// Clean up the read interface.
if (null != readInterface) {
this.readInterface.close(); // depends on control dependency: [if], data = [none]
this.readInterface = null; // depends on control dependency: [if], data = [none]
}
// Clean up the SSL engine.
if (null != getSSLEngine()) {
//If the channel has already processed the stop signal, it is too late to try and send the write handshake
if (this.sslChannel.getstop0Called() == true) {
this.connected = false; // depends on control dependency: [if], data = [none]
}
SSLUtils.shutDownSSLEngine(this, isInbound, this.connected); // depends on control dependency: [if], data = [none]
this.sslEngine = null; // depends on control dependency: [if], data = [none]
}
// mark that we have disconnected
this.connected = false; // depends on control dependency: [try], data = [none]
} finally {
cleanupLock.unlock();
}
} } |
public class class_name {
public void onReceive(Object message) {
// Start all workers
if (message instanceof RequestToBatchSenderAsstManager) {
// clear responseMap
RequestToBatchSenderAsstManager request = (RequestToBatchSenderAsstManager) message;
originalManager = getSender();
taskId = request.getTaskId();
asstManagerRetryIntervalMillis = request
.getAsstManagerRetryIntervalMillis();
// assumption: at least 12
taskIdTrim = taskId.length() <= 12 ? taskId
: taskId.substring(taskId.length() - 12,
taskId.length());
workers = request.getWorkers();
maxConcurrencyAdjusted = request.getMaxConcurrency();
requestTotalCount = workers.size();
sendMessageUntilStopCount(maxConcurrencyAdjusted);
// if not completed; will schedule a continue send msg
if (processedWorkerCount < requestTotalCount) {
waitAndRetry();
return;
} else {
logger.info("Now finished sending all needed messages. Done job of ASST Manager at "
+ PcDateUtils.getNowDateTimeStrStandard());
return;
}
} else if (message instanceof ContinueToSendToBatchSenderAsstManager) {
// now reaching the end; have processed all of them, just waiting
// the response to come back
int notProcessedNodeCount = requestTotalCount
- processedWorkerCount;
if (notProcessedNodeCount <= 0) {
logger.info("!Finished sending all msg in ASST MANAGER at "
+ PcDateUtils.getNowDateTimeStrStandard()
+ " STOP doing wait and retry.");
return;
}
int extraSendCount = maxConcurrencyAdjusted
- (processedWorkerCount - responseCount);
if (extraSendCount > 0) {
logger.info("HAVE ROOM to send extra of : " + extraSendCount
+ " MSG. now Send at "
+ PcDateUtils.getNowDateTimeStrStandard());
sendMessageUntilStopCount(processedWorkerCount + extraSendCount);
waitAndRetry();
} else {
logger.info("NO ROOM to send extra. Windowns is full. extraSendCount is negative: "
+ extraSendCount
+ " reschedule now at "
+ PcDateUtils.getNowDateTimeStrStandard());
waitAndRetry();
}
} else if (message instanceof ResponseCountToBatchSenderAsstManager) {
responseCount = ((ResponseCountToBatchSenderAsstManager) message)
.getResponseCount();
logger.debug("RECV IN batchSenderAsstManager FROM ExecutionManager responseCount: "
+ responseCount);
}
} } | public class class_name {
public void onReceive(Object message) {
// Start all workers
if (message instanceof RequestToBatchSenderAsstManager) {
// clear responseMap
RequestToBatchSenderAsstManager request = (RequestToBatchSenderAsstManager) message;
originalManager = getSender(); // depends on control dependency: [if], data = [none]
taskId = request.getTaskId(); // depends on control dependency: [if], data = [none]
asstManagerRetryIntervalMillis = request
.getAsstManagerRetryIntervalMillis(); // depends on control dependency: [if], data = [none]
// assumption: at least 12
taskIdTrim = taskId.length() <= 12 ? taskId
: taskId.substring(taskId.length() - 12,
taskId.length()); // depends on control dependency: [if], data = [none]
workers = request.getWorkers(); // depends on control dependency: [if], data = [none]
maxConcurrencyAdjusted = request.getMaxConcurrency(); // depends on control dependency: [if], data = [none]
requestTotalCount = workers.size(); // depends on control dependency: [if], data = [none]
sendMessageUntilStopCount(maxConcurrencyAdjusted); // depends on control dependency: [if], data = [none]
// if not completed; will schedule a continue send msg
if (processedWorkerCount < requestTotalCount) {
waitAndRetry(); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
} else {
logger.info("Now finished sending all needed messages. Done job of ASST Manager at "
+ PcDateUtils.getNowDateTimeStrStandard()); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} else if (message instanceof ContinueToSendToBatchSenderAsstManager) {
// now reaching the end; have processed all of them, just waiting
// the response to come back
int notProcessedNodeCount = requestTotalCount
- processedWorkerCount;
if (notProcessedNodeCount <= 0) {
logger.info("!Finished sending all msg in ASST MANAGER at "
+ PcDateUtils.getNowDateTimeStrStandard()
+ " STOP doing wait and retry."); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
int extraSendCount = maxConcurrencyAdjusted
- (processedWorkerCount - responseCount);
if (extraSendCount > 0) {
logger.info("HAVE ROOM to send extra of : " + extraSendCount
+ " MSG. now Send at "
+ PcDateUtils.getNowDateTimeStrStandard()); // depends on control dependency: [if], data = [none]
sendMessageUntilStopCount(processedWorkerCount + extraSendCount); // depends on control dependency: [if], data = [none]
waitAndRetry(); // depends on control dependency: [if], data = [none]
} else {
logger.info("NO ROOM to send extra. Windowns is full. extraSendCount is negative: "
+ extraSendCount
+ " reschedule now at "
+ PcDateUtils.getNowDateTimeStrStandard()); // depends on control dependency: [if], data = [none]
waitAndRetry(); // depends on control dependency: [if], data = [none]
}
} else if (message instanceof ResponseCountToBatchSenderAsstManager) {
responseCount = ((ResponseCountToBatchSenderAsstManager) message)
.getResponseCount(); // depends on control dependency: [if], data = [none]
logger.debug("RECV IN batchSenderAsstManager FROM ExecutionManager responseCount: "
+ responseCount); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void startElement(String namespaceURI, String localName, String name, Map<String, String> atts)
throws RepositoryException
{
InternalQName elementName = locationFactory.parseJCRName(name).getInternalName();
if (Constants.SV_NODE_NAME.equals(elementName))
{
// sv:node element
// node name (value of sv:name attribute)
String svName = getAttribute(atts, Constants.SV_NAME_NAME);
if (svName == null)
{
throw new RepositoryException("Missing mandatory sv:name attribute of element sv:node");
}
String svId = getAttribute(atts, Constants.EXO_ID_NAME);
if (svId == null)
{
throw new RepositoryException("Missing mandatory exo:id attribute of element sv:node");
}
ImportNodeData newNodeData;
InternalQName currentNodeName;
int nodeIndex = 1;
NodeData parentData = getParent();
if (!isFirstElementChecked)
{
if (!ROOT_NODE_NAME.equals(svName))
{
throw new RepositoryException("The first element must be root. But found '" + svName + "'");
}
isFirstElementChecked = true;
}
if (ROOT_NODE_NAME.equals(svName))
{
// remove the wrong root from the stack
tree.pop();
newNodeData = addChangesForRootNodeInitialization(parentData);
}
else
{
currentNodeName = locationFactory.parseJCRName(svName).getInternalName();
nodeIndex = getNodeIndex(parentData, currentNodeName, null);
newNodeData = new ImportNodeData(parentData, currentNodeName, nodeIndex);
newNodeData.setOrderNumber(getNextChildOrderNum(parentData));
newNodeData.setIdentifier(svId);
changesLog.add(new ItemState(newNodeData, ItemState.ADDED, true, parentData.getQPath()));
}
tree.push(newNodeData);
mapNodePropertiesInfo.put(newNodeData.getIdentifier(), new NodePropertiesInfo(newNodeData));
}
else
{
super.startElement(namespaceURI, localName, name, atts);
if (Constants.SV_PROPERTY_NAME.equals(elementName))
{
String svId = getAttribute(atts, Constants.EXO_ID_NAME);
if (svId == null)
{
throw new RepositoryException("Missing mandatory exo:id attribute of element sv:property");
}
propertyInfo.setIndentifer(svId);
}
}
} } | public class class_name {
@Override
public void startElement(String namespaceURI, String localName, String name, Map<String, String> atts)
throws RepositoryException
{
InternalQName elementName = locationFactory.parseJCRName(name).getInternalName();
if (Constants.SV_NODE_NAME.equals(elementName))
{
// sv:node element
// node name (value of sv:name attribute)
String svName = getAttribute(atts, Constants.SV_NAME_NAME);
if (svName == null)
{
throw new RepositoryException("Missing mandatory sv:name attribute of element sv:node");
}
String svId = getAttribute(atts, Constants.EXO_ID_NAME);
if (svId == null)
{
throw new RepositoryException("Missing mandatory exo:id attribute of element sv:node");
}
ImportNodeData newNodeData;
InternalQName currentNodeName;
int nodeIndex = 1;
NodeData parentData = getParent();
if (!isFirstElementChecked)
{
if (!ROOT_NODE_NAME.equals(svName))
{
throw new RepositoryException("The first element must be root. But found '" + svName + "'");
}
isFirstElementChecked = true; // depends on control dependency: [if], data = [none]
}
if (ROOT_NODE_NAME.equals(svName))
{
// remove the wrong root from the stack
tree.pop(); // depends on control dependency: [if], data = [none]
newNodeData = addChangesForRootNodeInitialization(parentData); // depends on control dependency: [if], data = [none]
}
else
{
currentNodeName = locationFactory.parseJCRName(svName).getInternalName(); // depends on control dependency: [if], data = [none]
nodeIndex = getNodeIndex(parentData, currentNodeName, null); // depends on control dependency: [if], data = [none]
newNodeData = new ImportNodeData(parentData, currentNodeName, nodeIndex); // depends on control dependency: [if], data = [none]
newNodeData.setOrderNumber(getNextChildOrderNum(parentData)); // depends on control dependency: [if], data = [none]
newNodeData.setIdentifier(svId); // depends on control dependency: [if], data = [none]
changesLog.add(new ItemState(newNodeData, ItemState.ADDED, true, parentData.getQPath())); // depends on control dependency: [if], data = [none]
}
tree.push(newNodeData);
mapNodePropertiesInfo.put(newNodeData.getIdentifier(), new NodePropertiesInfo(newNodeData));
}
else
{
super.startElement(namespaceURI, localName, name, atts);
if (Constants.SV_PROPERTY_NAME.equals(elementName))
{
String svId = getAttribute(atts, Constants.EXO_ID_NAME);
if (svId == null)
{
throw new RepositoryException("Missing mandatory exo:id attribute of element sv:property");
}
propertyInfo.setIndentifer(svId); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public AvailabilityZone withLoadBalancerAddresses(LoadBalancerAddress... loadBalancerAddresses) {
if (this.loadBalancerAddresses == null) {
setLoadBalancerAddresses(new java.util.ArrayList<LoadBalancerAddress>(loadBalancerAddresses.length));
}
for (LoadBalancerAddress ele : loadBalancerAddresses) {
this.loadBalancerAddresses.add(ele);
}
return this;
} } | public class class_name {
public AvailabilityZone withLoadBalancerAddresses(LoadBalancerAddress... loadBalancerAddresses) {
if (this.loadBalancerAddresses == null) {
setLoadBalancerAddresses(new java.util.ArrayList<LoadBalancerAddress>(loadBalancerAddresses.length)); // depends on control dependency: [if], data = [none]
}
for (LoadBalancerAddress ele : loadBalancerAddresses) {
this.loadBalancerAddresses.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public <T> Map<Serializable, T> get(Collection<? extends Serializable> keys) {
Map<Serializable, T> result = Maps.newHashMapWithExpectedSize(keys.size());
for (Serializable key : keys) {
T value = (T) contents.getIfPresent(key);
if (value != null) {
result.put(key, value);
}
}
if (log.isDebugEnabled() && !result.isEmpty()) {
log.debug("Level 1 cache multiple hit: {}", result.keySet());
}
return result;
} } | public class class_name {
@SuppressWarnings("unchecked")
public <T> Map<Serializable, T> get(Collection<? extends Serializable> keys) {
Map<Serializable, T> result = Maps.newHashMapWithExpectedSize(keys.size());
for (Serializable key : keys) {
T value = (T) contents.getIfPresent(key);
if (value != null) {
result.put(key, value);
// depends on control dependency: [if], data = [none]
}
}
if (log.isDebugEnabled() && !result.isEmpty()) {
log.debug("Level 1 cache multiple hit: {}", result.keySet());
// depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
private ExtensionDependency getDependency(Extension extension, String dependencyId)
{
for (ExtensionDependency dependency : extension.getDependencies()) {
if (dependency.getId().equals(dependencyId)) {
return dependency;
}
}
return null;
} } | public class class_name {
private ExtensionDependency getDependency(Extension extension, String dependencyId)
{
for (ExtensionDependency dependency : extension.getDependencies()) {
if (dependency.getId().equals(dependencyId)) {
return dependency; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public PropertyDescriptor[] getPropertyDescriptors() {
BeanInfo info = getBeanInfo();
if (info == null) {
return null;
}
PropertyDescriptor[] pds = info.getPropertyDescriptors();
getTeaToolsUtils().sortPropertyDescriptors(pds);
return pds;
} } | public class class_name {
public PropertyDescriptor[] getPropertyDescriptors() {
BeanInfo info = getBeanInfo();
if (info == null) {
return null; // depends on control dependency: [if], data = [none]
}
PropertyDescriptor[] pds = info.getPropertyDescriptors();
getTeaToolsUtils().sortPropertyDescriptors(pds);
return pds;
} } |
public class class_name {
public static Field[] getFields(Class<?> clazz, String... fieldNames) {
final List<Field> fields = new LinkedList<Field>();
for (Field field : getAllFields(clazz)) {
for (String fieldName : fieldNames) {
if (field.getName().equals(fieldName)) {
fields.add(field);
}
}
}
final Field[] fieldArray = fields.toArray(new Field[fields.size()]);
if (fieldArray.length == 0) {
throw new FieldNotFoundException(String.format(
"No fields matching the name(s) %s were found in the class hierarchy of %s.",
concatenateStrings(fieldNames), getType(clazz)));
}
return fieldArray;
} } | public class class_name {
public static Field[] getFields(Class<?> clazz, String... fieldNames) {
final List<Field> fields = new LinkedList<Field>();
for (Field field : getAllFields(clazz)) {
for (String fieldName : fieldNames) {
if (field.getName().equals(fieldName)) {
fields.add(field); // depends on control dependency: [if], data = [none]
}
}
}
final Field[] fieldArray = fields.toArray(new Field[fields.size()]);
if (fieldArray.length == 0) {
throw new FieldNotFoundException(String.format(
"No fields matching the name(s) %s were found in the class hierarchy of %s.",
concatenateStrings(fieldNames), getType(clazz)));
}
return fieldArray;
} } |
public class class_name {
public BaseGrid setFrameVisible(boolean v) {
for (int i = 0; i < axis.length; i++) {
axis[i].setGridVisible(v);
}
return this;
} } | public class class_name {
public BaseGrid setFrameVisible(boolean v) {
for (int i = 0; i < axis.length; i++) {
axis[i].setGridVisible(v); // depends on control dependency: [for], data = [i]
}
return this;
} } |
public class class_name {
@Sensitive
public static byte[] encodeCertChain(Codec codec, @Sensitive X509Certificate[] certificateChain) {
byte[] result = null;
try {
if (certificateChain != null) {
List<X509Certificate> certList = getCertChainAsListWithoutDuplicates(certificateChain);
CertificateFactory cfx = CertificateFactory.getInstance("X.509");
CertPath certPath = cfx.generateCertPath(certList);
Any any = ORB.init().create_any();
org.omg.CSI.X509CertificateChainHelper.insert(any, certPath.getEncoded());
result = codec.encode_value(any);
}
} catch (Exception e) {
// do nothing, return null
}
return result;
} } | public class class_name {
@Sensitive
public static byte[] encodeCertChain(Codec codec, @Sensitive X509Certificate[] certificateChain) {
byte[] result = null;
try {
if (certificateChain != null) {
List<X509Certificate> certList = getCertChainAsListWithoutDuplicates(certificateChain);
CertificateFactory cfx = CertificateFactory.getInstance("X.509");
CertPath certPath = cfx.generateCertPath(certList);
Any any = ORB.init().create_any();
org.omg.CSI.X509CertificateChainHelper.insert(any, certPath.getEncoded()); // depends on control dependency: [if], data = [none]
result = codec.encode_value(any); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
// do nothing, return null
} // depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
public void parseRequestStream(InputStream inputStream, String charset) throws IOException {
setLoaded();
MultipartRequestInputStream input = new MultipartRequestInputStream(inputStream);
input.readBoundary();
while (true) {
UploadFileHeader header = input.readDataHeader(charset);
if (header == null) {
break;
}
if (header.isFile == true) {
// 文件类型的表单项
String fileName = header.fileName;
if (fileName.length() > 0 && header.contentType.contains("application/x-macbinary")) {
input.skipBytes(128);
}
UploadFile newFile = new UploadFile(header, setting);
newFile.processStream(input);
putFile(header.formFieldName, newFile);
} else {
// 标准表单项
ByteArrayOutputStream fbos = new ByteArrayOutputStream(1024);
input.copy(fbos);
String value = (charset != null) ? new String(fbos.toByteArray(), charset) : new String(fbos.toByteArray());
putParameter(header.formFieldName, value);
}
input.skipBytes(1);
input.mark(1);
// read byte, but may be end of stream
int nextByte = input.read();
if (nextByte == -1 || nextByte == '-') {
input.reset();
break;
}
input.reset();
}
} } | public class class_name {
public void parseRequestStream(InputStream inputStream, String charset) throws IOException {
setLoaded();
MultipartRequestInputStream input = new MultipartRequestInputStream(inputStream);
input.readBoundary();
while (true) {
UploadFileHeader header = input.readDataHeader(charset);
if (header == null) {
break;
}
if (header.isFile == true) {
// 文件类型的表单项
String fileName = header.fileName;
if (fileName.length() > 0 && header.contentType.contains("application/x-macbinary")) {
input.skipBytes(128);
// depends on control dependency: [if], data = [none]
}
UploadFile newFile = new UploadFile(header, setting);
newFile.processStream(input);
// depends on control dependency: [if], data = [none]
putFile(header.formFieldName, newFile);
// depends on control dependency: [if], data = [none]
} else {
// 标准表单项
ByteArrayOutputStream fbos = new ByteArrayOutputStream(1024);
input.copy(fbos);
// depends on control dependency: [if], data = [none]
String value = (charset != null) ? new String(fbos.toByteArray(), charset) : new String(fbos.toByteArray());
putParameter(header.formFieldName, value);
// depends on control dependency: [if], data = [none]
}
input.skipBytes(1);
input.mark(1);
// read byte, but may be end of stream
int nextByte = input.read();
if (nextByte == -1 || nextByte == '-') {
input.reset();
// depends on control dependency: [if], data = [none]
break;
}
input.reset();
}
} } |
public class class_name {
private void indexDense(DBIDRef ref, V obj) {
double len = 0.;
for(int dim = 0, max = obj.getDimensionality(); dim < max; dim++) {
final double val = obj.doubleValue(dim);
if(val == 0. || val != val) {
continue;
}
len += val * val;
getOrCreateColumn(dim).add(val, ref);
}
length.put(ref, FastMath.sqrt(len));
} } | public class class_name {
private void indexDense(DBIDRef ref, V obj) {
double len = 0.;
for(int dim = 0, max = obj.getDimensionality(); dim < max; dim++) {
final double val = obj.doubleValue(dim);
if(val == 0. || val != val) {
continue;
}
len += val * val; // depends on control dependency: [for], data = [none]
getOrCreateColumn(dim).add(val, ref); // depends on control dependency: [for], data = [dim]
}
length.put(ref, FastMath.sqrt(len));
} } |
public class class_name {
public boolean addRenamedFile(File sourceFilePath, File destinationFilePath, int percentage) {
if (null == sourceFilePath || null == destinationFilePath) {
return false;
}
return renamedFiles.add(new CopiedOrMovedFile(sourceFilePath, destinationFilePath, percentage));
} } | public class class_name {
public boolean addRenamedFile(File sourceFilePath, File destinationFilePath, int percentage) {
if (null == sourceFilePath || null == destinationFilePath) {
return false; // depends on control dependency: [if], data = [none]
}
return renamedFiles.add(new CopiedOrMovedFile(sourceFilePath, destinationFilePath, percentage));
} } |
public class class_name {
public DescribeEndpointConfigResult withProductionVariants(ProductionVariant... productionVariants) {
if (this.productionVariants == null) {
setProductionVariants(new java.util.ArrayList<ProductionVariant>(productionVariants.length));
}
for (ProductionVariant ele : productionVariants) {
this.productionVariants.add(ele);
}
return this;
} } | public class class_name {
public DescribeEndpointConfigResult withProductionVariants(ProductionVariant... productionVariants) {
if (this.productionVariants == null) {
setProductionVariants(new java.util.ArrayList<ProductionVariant>(productionVariants.length)); // depends on control dependency: [if], data = [none]
}
for (ProductionVariant ele : productionVariants) {
this.productionVariants.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public DescribeTransitGatewayRouteTablesRequest withTransitGatewayRouteTableIds(String... transitGatewayRouteTableIds) {
if (this.transitGatewayRouteTableIds == null) {
setTransitGatewayRouteTableIds(new com.amazonaws.internal.SdkInternalList<String>(transitGatewayRouteTableIds.length));
}
for (String ele : transitGatewayRouteTableIds) {
this.transitGatewayRouteTableIds.add(ele);
}
return this;
} } | public class class_name {
public DescribeTransitGatewayRouteTablesRequest withTransitGatewayRouteTableIds(String... transitGatewayRouteTableIds) {
if (this.transitGatewayRouteTableIds == null) {
setTransitGatewayRouteTableIds(new com.amazonaws.internal.SdkInternalList<String>(transitGatewayRouteTableIds.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : transitGatewayRouteTableIds) {
this.transitGatewayRouteTableIds.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void marshall(CreateDomainEntryRequest createDomainEntryRequest, ProtocolMarshaller protocolMarshaller) {
if (createDomainEntryRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createDomainEntryRequest.getDomainName(), DOMAINNAME_BINDING);
protocolMarshaller.marshall(createDomainEntryRequest.getDomainEntry(), DOMAINENTRY_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateDomainEntryRequest createDomainEntryRequest, ProtocolMarshaller protocolMarshaller) {
if (createDomainEntryRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createDomainEntryRequest.getDomainName(), DOMAINNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createDomainEntryRequest.getDomainEntry(), DOMAINENTRY_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 {
@PUT
@Path("/{iOSID}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response updateiOSVariant(
@MultipartForm iOSApplicationUploadForm updatedForm,
@PathParam("pushAppID") String pushApplicationId,
@PathParam("iOSID") String iOSID) {
iOSVariant iOSVariant = (iOSVariant)variantService.findByVariantID(iOSID);
if (iOSVariant != null) {
// some model validation on the uploaded form
try {
validateModelClass(updatedForm);
} catch (ConstraintViolationException cve) {
// Build and return the 400 (Bad Request) response
ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations());
return builder.build();
}
// apply update:
iOSVariant.setName(updatedForm.getName());
iOSVariant.setDescription(updatedForm.getDescription());
iOSVariant.setPassphrase(updatedForm.getPassphrase());
iOSVariant.setCertificate(updatedForm.getCertificate());
iOSVariant.setProduction(updatedForm.getProduction());
// some model validation on the entity:
try {
validateModelClass(iOSVariant);
} catch (ConstraintViolationException cve) {
logger.info("Unable to update iOS Variant '{}'", iOSVariant.getVariantID());
logger.debug("Details: {}", cve);
// Build and return the 400 (Bad Request) response
ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations());
return builder.build();
}
// update performed, we now need to invalidate existing connection w/ APNs:
logger.trace("Updating iOS Variant '{}'", iOSVariant.getVariantID());
variantUpdateEventEvent.fire(new iOSVariantUpdateEvent(iOSVariant));
variantService.updateVariant(iOSVariant);
return Response.ok(iOSVariant).build();
}
return Response.status(Status.NOT_FOUND).entity("Could not find requested Variant").build();
} } | public class class_name {
@PUT
@Path("/{iOSID}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response updateiOSVariant(
@MultipartForm iOSApplicationUploadForm updatedForm,
@PathParam("pushAppID") String pushApplicationId,
@PathParam("iOSID") String iOSID) {
iOSVariant iOSVariant = (iOSVariant)variantService.findByVariantID(iOSID);
if (iOSVariant != null) {
// some model validation on the uploaded form
try {
validateModelClass(updatedForm); // depends on control dependency: [try], data = [none]
} catch (ConstraintViolationException cve) {
// Build and return the 400 (Bad Request) response
ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations());
return builder.build();
} // depends on control dependency: [catch], data = [none]
// apply update:
iOSVariant.setName(updatedForm.getName()); // depends on control dependency: [if], data = [none]
iOSVariant.setDescription(updatedForm.getDescription()); // depends on control dependency: [if], data = [none]
iOSVariant.setPassphrase(updatedForm.getPassphrase()); // depends on control dependency: [if], data = [none]
iOSVariant.setCertificate(updatedForm.getCertificate()); // depends on control dependency: [if], data = [none]
iOSVariant.setProduction(updatedForm.getProduction()); // depends on control dependency: [if], data = [none]
// some model validation on the entity:
try {
validateModelClass(iOSVariant); // depends on control dependency: [try], data = [none]
} catch (ConstraintViolationException cve) {
logger.info("Unable to update iOS Variant '{}'", iOSVariant.getVariantID());
logger.debug("Details: {}", cve);
// Build and return the 400 (Bad Request) response
ResponseBuilder builder = createBadRequestResponse(cve.getConstraintViolations());
return builder.build();
} // depends on control dependency: [catch], data = [none]
// update performed, we now need to invalidate existing connection w/ APNs:
logger.trace("Updating iOS Variant '{}'", iOSVariant.getVariantID()); // depends on control dependency: [if], data = [none]
variantUpdateEventEvent.fire(new iOSVariantUpdateEvent(iOSVariant)); // depends on control dependency: [if], data = [(iOSVariant]
variantService.updateVariant(iOSVariant); // depends on control dependency: [if], data = [(iOSVariant]
return Response.ok(iOSVariant).build(); // depends on control dependency: [if], data = [(iOSVariant]
}
return Response.status(Status.NOT_FOUND).entity("Could not find requested Variant").build();
} } |
public class class_name {
public static boolean isMacro(String input, String macroName) {
if (isMacro(input)) {
return input.substring(2, input.length() - 1).equals(macroName);
}
return false;
} } | public class class_name {
public static boolean isMacro(String input, String macroName) {
if (isMacro(input)) {
return input.substring(2, input.length() - 1).equals(macroName); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Override
protected final void onRender()
{
Iterator<? extends Component> it = renderIterator();
while (it.hasNext())
{
Component child = it.next();
if (child == null)
{
throw new IllegalStateException(
"The render iterator returned null for a child. Container: " + this.toString() +
"; Iterator=" + it.toString());
}
renderChild(child);
}
} } | public class class_name {
@Override
protected final void onRender()
{
Iterator<? extends Component> it = renderIterator();
while (it.hasNext())
{
Component child = it.next();
if (child == null)
{
throw new IllegalStateException(
"The render iterator returned null for a child. Container: " + this.toString() +
"; Iterator=" + it.toString());
}
renderChild(child); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public static void setPreferredAttributeNameForLaneCount(String name) {
final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkConstants.class);
if (prefs != null) {
if (name == null || "".equals(name) || DEFAULT_ATTR_LANE_COUNT.equalsIgnoreCase(name)) { //$NON-NLS-1$
prefs.remove("LANE_COUNT_ATTR_NAME"); //$NON-NLS-1$
} else {
prefs.put("LANE_COUNT_ATTR_NAME", name); //$NON-NLS-1$
}
}
} } | public class class_name {
public static void setPreferredAttributeNameForLaneCount(String name) {
final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkConstants.class);
if (prefs != null) {
if (name == null || "".equals(name) || DEFAULT_ATTR_LANE_COUNT.equalsIgnoreCase(name)) { //$NON-NLS-1$
prefs.remove("LANE_COUNT_ATTR_NAME"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
} else {
prefs.put("LANE_COUNT_ATTR_NAME", name); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static boolean isAllOneColor( BufferedImage image ) {
int width = image.getWidth();
int height = image.getHeight();
int previousRgb = 0;
boolean isFirst = true;
for( int x = 0; x < width; x++ ) {
for( int y = 0; y < height; y++ ) {
int rgb = image.getRGB(x, y);
if (isFirst) {
isFirst = false;
} else {
if (rgb != previousRgb) {
return false;
}
}
previousRgb = rgb;
}
}
return true;
} } | public class class_name {
public static boolean isAllOneColor( BufferedImage image ) {
int width = image.getWidth();
int height = image.getHeight();
int previousRgb = 0;
boolean isFirst = true;
for( int x = 0; x < width; x++ ) {
for( int y = 0; y < height; y++ ) {
int rgb = image.getRGB(x, y);
if (isFirst) {
isFirst = false; // depends on control dependency: [if], data = [none]
} else {
if (rgb != previousRgb) {
return false; // depends on control dependency: [if], data = [none]
}
}
previousRgb = rgb; // depends on control dependency: [for], data = [none]
}
}
return true;
} } |
public class class_name {
@Override
public final void setDefaultLocalAddresses(Iterable<? extends SocketAddress> localAddresses) {
if (localAddresses == null) {
throw new NullPointerException("localAddresses");
}
synchronized (bindLock) {
if (!boundAddresses.isEmpty()) {
throw new IllegalStateException(
"localAddress can't be set while the acceptor is bound.");
}
Collection<SocketAddress> newLocalAddresses =
new ArrayList<>();
for (SocketAddress a: localAddresses) {
checkAddressType(a);
newLocalAddresses.add(a);
}
if (newLocalAddresses.isEmpty()) {
throw new IllegalArgumentException("empty localAddresses");
}
this.defaultLocalAddresses.clear();
this.defaultLocalAddresses.addAll(newLocalAddresses);
}
} } | public class class_name {
@Override
public final void setDefaultLocalAddresses(Iterable<? extends SocketAddress> localAddresses) {
if (localAddresses == null) {
throw new NullPointerException("localAddresses");
}
synchronized (bindLock) {
if (!boundAddresses.isEmpty()) {
throw new IllegalStateException(
"localAddress can't be set while the acceptor is bound.");
}
Collection<SocketAddress> newLocalAddresses =
new ArrayList<>();
for (SocketAddress a: localAddresses) {
checkAddressType(a); // depends on control dependency: [for], data = [a]
newLocalAddresses.add(a); // depends on control dependency: [for], data = [a]
}
if (newLocalAddresses.isEmpty()) {
throw new IllegalArgumentException("empty localAddresses");
}
this.defaultLocalAddresses.clear();
this.defaultLocalAddresses.addAll(newLocalAddresses);
}
} } |
public class class_name {
public void closePath() {
if (this.numTypes<=0 ||
(this.types[this.numTypes-1]!=PathElementType.CLOSE
&&this.types[this.numTypes-1]!=PathElementType.MOVE_TO)) {
ensureSlots(true, 0);
this.types[this.numTypes++] = PathElementType.CLOSE;
}
} } | public class class_name {
public void closePath() {
if (this.numTypes<=0 ||
(this.types[this.numTypes-1]!=PathElementType.CLOSE
&&this.types[this.numTypes-1]!=PathElementType.MOVE_TO)) {
ensureSlots(true, 0); // depends on control dependency: [if], data = [none]
this.types[this.numTypes++] = PathElementType.CLOSE; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public N pop() {
try {
return stack[(--stackTop)&mask];
} finally {
// remove the reference to the element in the
// stack to prevent hanging references from living forever
stack[(stackTop&mask)] = null;
}
} } | public class class_name {
@Override
public N pop() {
try {
return stack[(--stackTop)&mask]; // depends on control dependency: [try], data = [none]
} finally {
// remove the reference to the element in the
// stack to prevent hanging references from living forever
stack[(stackTop&mask)] = null;
}
} } |
public class class_name {
public static NestedMappingInfo loadNestedMappingInformation(XML xml, Class<?> targetClass,String nestedMappingPath, Class<?> sourceClass, Class<?> destinationClass, Field configuredField){
boolean isSourceClass = targetClass == sourceClass;
NestedMappingInfo info = new NestedMappingInfo(isSourceClass);
info.setConfiguredClass(isSourceClass?destinationClass:sourceClass);
info.setConfiguredField(configuredField);
try{
Class<?> nestedClass = targetClass;
String[] nestedFields = nestedFields(nestedMappingPath);
Field field = null;
for(int i = 0; i< nestedFields.length;i++){
String nestedFieldName = nestedFields[i];
boolean elvisOperatorDefined = false;
// the safe navigation operator is not valid for the last field
if(i < nestedFields.length - 1){
String nextNestedFieldName = nestedFields[i+1];
elvisOperatorDefined = safeNavigationOperatorDefined(nextNestedFieldName);
}
// name filtering
nestedFieldName = safeNavigationOperatorFilter(nestedFieldName);
field = retrieveField(nestedClass, nestedFieldName);
if(isNull(field))
Error.inexistentField(nestedFieldName, nestedClass.getSimpleName());
// verifies if is exists a get method for this nested field
// in case of nested mapping relative to source, only get methods will be checked
// in case of nested mapping relative to destination, get and set methods will be checked
MappedField nestedField = isSourceClass ? checkGetAccessor(xml, nestedClass, field)
//TODO Nested Mapping -> in caso di avoidSet qui potremmo avere un problema
: checkAccessors(xml, nestedClass, field);
// storage information relating to the piece of path
info.addNestedField(new NestedMappedField(nestedField, nestedClass, elvisOperatorDefined));
nestedClass = field.getType();
}
}catch(MappingException e){
InvalidNestedMappingException exception = new InvalidNestedMappingException(nestedMappingPath);
exception.getMessages().put(InvalidNestedMappingException.FIELD, e.getMessage());
throw exception;
}
return info;
} } | public class class_name {
public static NestedMappingInfo loadNestedMappingInformation(XML xml, Class<?> targetClass,String nestedMappingPath, Class<?> sourceClass, Class<?> destinationClass, Field configuredField){
boolean isSourceClass = targetClass == sourceClass;
NestedMappingInfo info = new NestedMappingInfo(isSourceClass);
info.setConfiguredClass(isSourceClass?destinationClass:sourceClass);
info.setConfiguredField(configuredField);
try{
Class<?> nestedClass = targetClass;
String[] nestedFields = nestedFields(nestedMappingPath);
Field field = null;
// depends on control dependency: [try], data = [none]
for(int i = 0; i< nestedFields.length;i++){
String nestedFieldName = nestedFields[i];
boolean elvisOperatorDefined = false;
// the safe navigation operator is not valid for the last field
if(i < nestedFields.length - 1){
String nextNestedFieldName = nestedFields[i+1];
elvisOperatorDefined = safeNavigationOperatorDefined(nextNestedFieldName);
// depends on control dependency: [if], data = [none]
}
// name filtering
nestedFieldName = safeNavigationOperatorFilter(nestedFieldName);
// depends on control dependency: [for], data = [none]
field = retrieveField(nestedClass, nestedFieldName);
// depends on control dependency: [for], data = [none]
if(isNull(field))
Error.inexistentField(nestedFieldName, nestedClass.getSimpleName());
// verifies if is exists a get method for this nested field
// in case of nested mapping relative to source, only get methods will be checked
// in case of nested mapping relative to destination, get and set methods will be checked
MappedField nestedField = isSourceClass ? checkGetAccessor(xml, nestedClass, field)
//TODO Nested Mapping -> in caso di avoidSet qui potremmo avere un problema
: checkAccessors(xml, nestedClass, field);
// storage information relating to the piece of path
info.addNestedField(new NestedMappedField(nestedField, nestedClass, elvisOperatorDefined));
// depends on control dependency: [for], data = [none]
nestedClass = field.getType();
// depends on control dependency: [for], data = [none]
}
}catch(MappingException e){
InvalidNestedMappingException exception = new InvalidNestedMappingException(nestedMappingPath);
exception.getMessages().put(InvalidNestedMappingException.FIELD, e.getMessage());
throw exception;
}
// depends on control dependency: [catch], data = [none]
return info;
} } |
public class class_name {
public com.google.cloud.datalabeling.v1beta1.LabelVideoObjectDetectionOperationMetadata
getVideoObjectDetectionDetails() {
if (detailsCase_ == 6) {
return (com.google.cloud.datalabeling.v1beta1.LabelVideoObjectDetectionOperationMetadata)
details_;
}
return com.google.cloud.datalabeling.v1beta1.LabelVideoObjectDetectionOperationMetadata
.getDefaultInstance();
} } | public class class_name {
public com.google.cloud.datalabeling.v1beta1.LabelVideoObjectDetectionOperationMetadata
getVideoObjectDetectionDetails() {
if (detailsCase_ == 6) {
return (com.google.cloud.datalabeling.v1beta1.LabelVideoObjectDetectionOperationMetadata)
details_; // depends on control dependency: [if], data = [none]
}
return com.google.cloud.datalabeling.v1beta1.LabelVideoObjectDetectionOperationMetadata
.getDefaultInstance();
} } |
public class class_name {
public byte[] unsafeBitcoinSerialize() {
// 1st attempt to use a cached array.
if (payload != null) {
if (offset == 0 && length == payload.length) {
// Cached byte array is the entire message with no extras so we can return as is and avoid an array
// copy.
return payload;
}
byte[] buf = new byte[length];
System.arraycopy(payload, offset, buf, 0, length);
return buf;
}
// No cached array available so serialize parts by stream.
ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length < 32 ? 32 : length + 32);
try {
bitcoinSerializeToStream(stream);
} catch (IOException e) {
// Cannot happen, we are serializing to a memory stream.
}
if (serializer.isParseRetainMode()) {
// A free set of steak knives!
// If there happens to be a call to this method we gain an opportunity to recache
// the byte array and in this case it contains no bytes from parent messages.
// This give a dual benefit. Releasing references to the larger byte array so that it
// it is more likely to be GC'd. And preventing double serializations. E.g. calculating
// merkle root calls this method. It is will frequently happen prior to serializing the block
// which means another call to bitcoinSerialize is coming. If we didn't recache then internal
// serialization would occur a 2nd time and every subsequent time the message is serialized.
payload = stream.toByteArray();
cursor = cursor - offset;
offset = 0;
recached = true;
length = payload.length;
return payload;
}
// Record length. If this Message wasn't parsed from a byte stream it won't have length field
// set (except for static length message types). Setting it makes future streaming more efficient
// because we can preallocate the ByteArrayOutputStream buffer and avoid resizing.
byte[] buf = stream.toByteArray();
length = buf.length;
return buf;
} } | public class class_name {
public byte[] unsafeBitcoinSerialize() {
// 1st attempt to use a cached array.
if (payload != null) {
if (offset == 0 && length == payload.length) {
// Cached byte array is the entire message with no extras so we can return as is and avoid an array
// copy.
return payload; // depends on control dependency: [if], data = [none]
}
byte[] buf = new byte[length];
System.arraycopy(payload, offset, buf, 0, length); // depends on control dependency: [if], data = [(payload]
return buf; // depends on control dependency: [if], data = [none]
}
// No cached array available so serialize parts by stream.
ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length < 32 ? 32 : length + 32);
try {
bitcoinSerializeToStream(stream); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
// Cannot happen, we are serializing to a memory stream.
} // depends on control dependency: [catch], data = [none]
if (serializer.isParseRetainMode()) {
// A free set of steak knives!
// If there happens to be a call to this method we gain an opportunity to recache
// the byte array and in this case it contains no bytes from parent messages.
// This give a dual benefit. Releasing references to the larger byte array so that it
// it is more likely to be GC'd. And preventing double serializations. E.g. calculating
// merkle root calls this method. It is will frequently happen prior to serializing the block
// which means another call to bitcoinSerialize is coming. If we didn't recache then internal
// serialization would occur a 2nd time and every subsequent time the message is serialized.
payload = stream.toByteArray(); // depends on control dependency: [if], data = [none]
cursor = cursor - offset; // depends on control dependency: [if], data = [none]
offset = 0; // depends on control dependency: [if], data = [none]
recached = true; // depends on control dependency: [if], data = [none]
length = payload.length; // depends on control dependency: [if], data = [none]
return payload; // depends on control dependency: [if], data = [none]
}
// Record length. If this Message wasn't parsed from a byte stream it won't have length field
// set (except for static length message types). Setting it makes future streaming more efficient
// because we can preallocate the ByteArrayOutputStream buffer and avoid resizing.
byte[] buf = stream.toByteArray();
length = buf.length;
return buf;
} } |
public class class_name {
public static RejectedExecutionException failWithRejected(Throwable cause) {
if (cause instanceof ReactorRejectedExecutionException) {
return (RejectedExecutionException) cause;
}
return new ReactorRejectedExecutionException("Scheduler unavailable", cause);
} } | public class class_name {
public static RejectedExecutionException failWithRejected(Throwable cause) {
if (cause instanceof ReactorRejectedExecutionException) {
return (RejectedExecutionException) cause; // depends on control dependency: [if], data = [none]
}
return new ReactorRejectedExecutionException("Scheduler unavailable", cause);
} } |
public class class_name {
@Override
public int compare(int i, int j) {
final int bufferNumI = i / this.indexEntriesPerSegment;
final int segmentOffsetI = (i % this.indexEntriesPerSegment) * this.indexEntrySize;
final int bufferNumJ = j / this.indexEntriesPerSegment;
final int segmentOffsetJ = (j % this.indexEntriesPerSegment) * this.indexEntrySize;
final MemorySegment segI = this.sortIndex.get(bufferNumI);
final MemorySegment segJ = this.sortIndex.get(bufferNumJ);
int val = MemorySegment.compare(segI, segJ, segmentOffsetI + OFFSET_LEN, segmentOffsetJ + OFFSET_LEN, this.numKeyBytes);
if (val != 0 || this.normalizedKeyFullyDetermines) {
return this.useNormKeyUninverted ? val : -val;
}
final long pointerI = segI.getLong(segmentOffsetI);
final long pointerJ = segJ.getLong(segmentOffsetJ);
return compareRecords(pointerI, pointerJ);
} } | public class class_name {
@Override
public int compare(int i, int j) {
final int bufferNumI = i / this.indexEntriesPerSegment;
final int segmentOffsetI = (i % this.indexEntriesPerSegment) * this.indexEntrySize;
final int bufferNumJ = j / this.indexEntriesPerSegment;
final int segmentOffsetJ = (j % this.indexEntriesPerSegment) * this.indexEntrySize;
final MemorySegment segI = this.sortIndex.get(bufferNumI);
final MemorySegment segJ = this.sortIndex.get(bufferNumJ);
int val = MemorySegment.compare(segI, segJ, segmentOffsetI + OFFSET_LEN, segmentOffsetJ + OFFSET_LEN, this.numKeyBytes);
if (val != 0 || this.normalizedKeyFullyDetermines) {
return this.useNormKeyUninverted ? val : -val; // depends on control dependency: [if], data = [none]
}
final long pointerI = segI.getLong(segmentOffsetI);
final long pointerJ = segJ.getLong(segmentOffsetJ);
return compareRecords(pointerI, pointerJ);
} } |
public class class_name {
@Override
public void getScope(final String scopeName, final SecurityContext securityContext,
final AsyncResponse asyncResponse) {
long traceId = LoggerHelpers.traceEnter(log, "getScope");
try {
restAuthHelper.authenticateAuthorize(
getAuthorizationHeader(),
AuthResourceRepresentation.ofScope(scopeName), READ);
} catch (AuthException e) {
log.warn("Get scope for {} failed due to authentication failure.", scopeName);
asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
LoggerHelpers.traceLeave(log, "getScope", traceId);
return;
}
controllerService.getScope(scopeName)
.thenApply(scope -> {
return Response.status(Status.OK).entity(new ScopeProperty().scopeName(scope)).build();
})
.exceptionally( exception -> {
if (exception.getCause() instanceof StoreException.DataNotFoundException) {
log.warn("Scope: {} not found", scopeName);
return Response.status(Status.NOT_FOUND).build();
} else {
log.warn("getScope for {} failed with exception: {}", scopeName, exception);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}).thenApply(asyncResponse::resume)
.thenAccept(x -> LoggerHelpers.traceLeave(log, "getScope", traceId));
} } | public class class_name {
@Override
public void getScope(final String scopeName, final SecurityContext securityContext,
final AsyncResponse asyncResponse) {
long traceId = LoggerHelpers.traceEnter(log, "getScope");
try {
restAuthHelper.authenticateAuthorize(
getAuthorizationHeader(),
AuthResourceRepresentation.ofScope(scopeName), READ); // depends on control dependency: [try], data = [none]
} catch (AuthException e) {
log.warn("Get scope for {} failed due to authentication failure.", scopeName);
asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
LoggerHelpers.traceLeave(log, "getScope", traceId);
return;
} // depends on control dependency: [catch], data = [none]
controllerService.getScope(scopeName)
.thenApply(scope -> {
return Response.status(Status.OK).entity(new ScopeProperty().scopeName(scope)).build();
})
.exceptionally( exception -> {
if (exception.getCause() instanceof StoreException.DataNotFoundException) {
log.warn("Scope: {} not found", scopeName);
return Response.status(Status.NOT_FOUND).build();
} else {
log.warn("getScope for {} failed with exception: {}", scopeName, exception);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}).thenApply(asyncResponse::resume)
.thenAccept(x -> LoggerHelpers.traceLeave(log, "getScope", traceId));
} } |
public class class_name {
protected DaoResult updateOrCreate(Connection conn, T bo) {
if (bo == null) {
return new DaoResult(DaoOperationStatus.NOT_FOUND);
}
DaoResult result = update(conn, bo);
DaoOperationStatus status = result.getStatus();
if (status == DaoOperationStatus.NOT_FOUND) {
result = create(conn, bo);
}
return result;
} } | public class class_name {
protected DaoResult updateOrCreate(Connection conn, T bo) {
if (bo == null) {
return new DaoResult(DaoOperationStatus.NOT_FOUND); // depends on control dependency: [if], data = [none]
}
DaoResult result = update(conn, bo);
DaoOperationStatus status = result.getStatus();
if (status == DaoOperationStatus.NOT_FOUND) {
result = create(conn, bo); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public void teardownLocalTxContext(TxContextChange changedContext)
{
LocalTransactionCoordinator activatedLocalTx = changedContext.getActivatedLocalTx();
// If setupLocalTxContext did nothing, teardownLocalContext will do nothing
if (activatedLocalTx != null) {
// setupLocalTxContext must have swapped a different local tx context
// onto thread so suspend it now (ie. make local tx sticky)
suspendLocalTx();
stickyLocalTxTable.put(changedContext.getKey(), activatedLocalTx);
// If setupLocalTxContext suspended a local tx which was already on the thread,
// resume that context now (ie. swap back the original context)
LocalTransactionCoordinator previousLocalTx = changedContext.getSuspendedLocalTx();
if (previousLocalTx != null) {
resumeLocalTx(previousLocalTx);
}
// If setupLocalTxContext suspended a global tx which was already on the thread,
// resume that context now (ie. swap back the original context)
Transaction previousGlobalTx = changedContext.getSuspendedGlobalTx(); //LIDB1673.2.1.5
if (previousGlobalTx != null) {
try {
resumeGlobalTx(previousGlobalTx, TIMEOUT_CLOCK_START);
} catch (Exception ex) {
FFDCFilter.processException(ex, CLASS_NAME + ".teardownLocalTxContext",
"650", this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Global tx resume failed", ex);
}
}
}
} // End if setupLocalTxContext did swap contexts
} } | public class class_name {
public void teardownLocalTxContext(TxContextChange changedContext)
{
LocalTransactionCoordinator activatedLocalTx = changedContext.getActivatedLocalTx();
// If setupLocalTxContext did nothing, teardownLocalContext will do nothing
if (activatedLocalTx != null) {
// setupLocalTxContext must have swapped a different local tx context
// onto thread so suspend it now (ie. make local tx sticky)
suspendLocalTx(); // depends on control dependency: [if], data = [none]
stickyLocalTxTable.put(changedContext.getKey(), activatedLocalTx); // depends on control dependency: [if], data = [none]
// If setupLocalTxContext suspended a local tx which was already on the thread,
// resume that context now (ie. swap back the original context)
LocalTransactionCoordinator previousLocalTx = changedContext.getSuspendedLocalTx();
if (previousLocalTx != null) {
resumeLocalTx(previousLocalTx); // depends on control dependency: [if], data = [(previousLocalTx]
}
// If setupLocalTxContext suspended a global tx which was already on the thread,
// resume that context now (ie. swap back the original context)
Transaction previousGlobalTx = changedContext.getSuspendedGlobalTx(); //LIDB1673.2.1.5
if (previousGlobalTx != null) {
try {
resumeGlobalTx(previousGlobalTx, TIMEOUT_CLOCK_START); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
FFDCFilter.processException(ex, CLASS_NAME + ".teardownLocalTxContext",
"650", this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Global tx resume failed", ex); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
} // End if setupLocalTxContext did swap contexts
} } |
public class class_name {
protected boolean detectRejection(HttpServletRequest request) {
Set<?> parameterKeys = request.getParameterMap().keySet();
if ((parameterKeys.size() == 1) && (parameterKeys.contains("state"))) {
return false;
}
return parameterKeys.size() > 0
&& !parameterKeys.contains("oauth_token")
&& !parameterKeys.contains("code")
&& !parameterKeys.contains("scope");
} } | public class class_name {
protected boolean detectRejection(HttpServletRequest request) {
Set<?> parameterKeys = request.getParameterMap().keySet();
if ((parameterKeys.size() == 1) && (parameterKeys.contains("state"))) {
return false; // depends on control dependency: [if], data = [none]
}
return parameterKeys.size() > 0
&& !parameterKeys.contains("oauth_token")
&& !parameterKeys.contains("code")
&& !parameterKeys.contains("scope");
} } |
public class class_name {
public Object[] getRecordKey(int ordinal) {
Object[] results = new Object[fieldPathIndexes.length];
for (int i = 0; i < fieldPathIndexes.length; i++) {
results[i] = readValue(ordinal, i);
}
return results;
} } | public class class_name {
public Object[] getRecordKey(int ordinal) {
Object[] results = new Object[fieldPathIndexes.length];
for (int i = 0; i < fieldPathIndexes.length; i++) {
results[i] = readValue(ordinal, i); // depends on control dependency: [for], data = [i]
}
return results;
} } |
public class class_name {
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception {
if (finished) {
if (!out.isWritable(in.readableBytes())) {
// out should be EMPTY_BUFFER because we should have allocated enough space above in allocateBuffer.
throw ENCODE_FINSHED_EXCEPTION;
}
out.writeBytes(in);
return;
}
final ByteBuf buffer = this.buffer;
int length;
while ((length = in.readableBytes()) > 0) {
final int nextChunkSize = Math.min(length, buffer.writableBytes());
in.readBytes(buffer, nextChunkSize);
if (!buffer.isWritable()) {
flushBufferedData(out);
}
}
} } | public class class_name {
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception {
if (finished) {
if (!out.isWritable(in.readableBytes())) {
// out should be EMPTY_BUFFER because we should have allocated enough space above in allocateBuffer.
throw ENCODE_FINSHED_EXCEPTION;
}
out.writeBytes(in);
return;
}
final ByteBuf buffer = this.buffer;
int length;
while ((length = in.readableBytes()) > 0) {
final int nextChunkSize = Math.min(length, buffer.writableBytes());
in.readBytes(buffer, nextChunkSize);
if (!buffer.isWritable()) {
flushBufferedData(out); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public ListChannelsResult withChannelSummaries(ChannelSummary... channelSummaries) {
if (this.channelSummaries == null) {
setChannelSummaries(new java.util.ArrayList<ChannelSummary>(channelSummaries.length));
}
for (ChannelSummary ele : channelSummaries) {
this.channelSummaries.add(ele);
}
return this;
} } | public class class_name {
public ListChannelsResult withChannelSummaries(ChannelSummary... channelSummaries) {
if (this.channelSummaries == null) {
setChannelSummaries(new java.util.ArrayList<ChannelSummary>(channelSummaries.length)); // depends on control dependency: [if], data = [none]
}
for (ChannelSummary ele : channelSummaries) {
this.channelSummaries.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private Document getDocument() {
Document document = new Document();
Comment comment = new Comment(" generated on " + new Date() + " ");
document.addContent(comment);
Element rootElement = new Element(ROOT_ELEMENT_NAME);
rootElement.setAttribute(MASTER_LANGUAGE_ATTRIBUTE_NAME, getMasterLanguage());
for (Attribute attribute : additionalRootAttrs) {
// need to set the attribute like a new attribute,
// as the original one stored the parent element and cannot be set to a new parent
rootElement.setAttribute(attribute.getName(), attribute.getValue(), attribute.getNamespace());
}
// set the namespace, this makes sure that it is written into the trema node
for (Namespace namespace : additionalNamespaces) {
rootElement.addNamespaceDeclaration(namespace);
}
for (ITextNode textNode : textNodeList) {
String key = textNode.getKey();
Element textElement = new Element(TEXT_ELEMENT_NAME);
textElement.setAttribute(KEY_ATTRIBUTE_NAME, key);
String context = textNode.getContext();
Element contextElement = new Element(CONTEXT_ELEMENT_NAME);
contextElement.setText(context);
textElement.addContent(contextElement);
IValueNode[] valueNodes = textNode.getValueNodes();
for (IValueNode valueNode : valueNodes) {
Element valueElement = new Element(VALUE_ELEMENT_NAME);
valueElement.setAttribute(LANGUAGE_ATTRIBUTE_NAME, valueNode.getLanguage());
valueElement.setAttribute(STATUS_ATTRIBUTE_NAME, valueNode.getStatus().getName());
valueElement.setText(valueNode.getValue());
textElement.addContent(valueElement);
}
rootElement.addContent(textElement);
}
document.setRootElement(rootElement);
return document;
} } | public class class_name {
private Document getDocument() {
Document document = new Document();
Comment comment = new Comment(" generated on " + new Date() + " ");
document.addContent(comment);
Element rootElement = new Element(ROOT_ELEMENT_NAME);
rootElement.setAttribute(MASTER_LANGUAGE_ATTRIBUTE_NAME, getMasterLanguage());
for (Attribute attribute : additionalRootAttrs) {
// need to set the attribute like a new attribute,
// as the original one stored the parent element and cannot be set to a new parent
rootElement.setAttribute(attribute.getName(), attribute.getValue(), attribute.getNamespace()); // depends on control dependency: [for], data = [attribute]
}
// set the namespace, this makes sure that it is written into the trema node
for (Namespace namespace : additionalNamespaces) {
rootElement.addNamespaceDeclaration(namespace); // depends on control dependency: [for], data = [namespace]
}
for (ITextNode textNode : textNodeList) {
String key = textNode.getKey();
Element textElement = new Element(TEXT_ELEMENT_NAME);
textElement.setAttribute(KEY_ATTRIBUTE_NAME, key); // depends on control dependency: [for], data = [none]
String context = textNode.getContext();
Element contextElement = new Element(CONTEXT_ELEMENT_NAME);
contextElement.setText(context); // depends on control dependency: [for], data = [none]
textElement.addContent(contextElement); // depends on control dependency: [for], data = [none]
IValueNode[] valueNodes = textNode.getValueNodes();
for (IValueNode valueNode : valueNodes) {
Element valueElement = new Element(VALUE_ELEMENT_NAME);
valueElement.setAttribute(LANGUAGE_ATTRIBUTE_NAME, valueNode.getLanguage()); // depends on control dependency: [for], data = [valueNode]
valueElement.setAttribute(STATUS_ATTRIBUTE_NAME, valueNode.getStatus().getName()); // depends on control dependency: [for], data = [valueNode]
valueElement.setText(valueNode.getValue()); // depends on control dependency: [for], data = [valueNode]
textElement.addContent(valueElement); // depends on control dependency: [for], data = [none]
}
rootElement.addContent(textElement); // depends on control dependency: [for], data = [none]
}
document.setRootElement(rootElement);
return document;
} } |
public class class_name {
public String getColorString() {
StringBuffer result = new StringBuffer();
if (m_color == Simapi.COLOR_TRANSPARENT) {
result.append(COLOR_TRANSPARENT);
} else {
if (m_color.getRed() < 16) {
result.append('0');
}
result.append(Integer.toString(m_color.getRed(), 16));
if (m_color.getGreen() < 16) {
result.append('0');
}
result.append(Integer.toString(m_color.getGreen(), 16));
if (m_color.getBlue() < 16) {
result.append('0');
}
result.append(Integer.toString(m_color.getBlue(), 16));
}
return result.toString();
} } | public class class_name {
public String getColorString() {
StringBuffer result = new StringBuffer();
if (m_color == Simapi.COLOR_TRANSPARENT) {
result.append(COLOR_TRANSPARENT); // depends on control dependency: [if], data = [none]
} else {
if (m_color.getRed() < 16) {
result.append('0'); // depends on control dependency: [if], data = [none]
}
result.append(Integer.toString(m_color.getRed(), 16)); // depends on control dependency: [if], data = [(m_color]
if (m_color.getGreen() < 16) {
result.append('0'); // depends on control dependency: [if], data = [none]
}
result.append(Integer.toString(m_color.getGreen(), 16)); // depends on control dependency: [if], data = [(m_color]
if (m_color.getBlue() < 16) {
result.append('0'); // depends on control dependency: [if], data = [none]
}
result.append(Integer.toString(m_color.getBlue(), 16)); // depends on control dependency: [if], data = [(m_color]
}
return result.toString();
} } |
public class class_name {
public void validate(String path, Schema schema, Object value, List<ValidationResult> results) {
String name = path != null ? path : "value";
List<String> found = new ArrayList<String>();
for (String property : _properties) {
Object propertyValue = ObjectReader.getProperty(value, property);
if (propertyValue != null)
found.add(property);
}
if (found.size() == 0) {
results.add(new ValidationResult(path, ValidationResultType.Error, "VALUE_NULL",
name + " must have at least one property from " + _properties, _properties, null));
}
} } | public class class_name {
public void validate(String path, Schema schema, Object value, List<ValidationResult> results) {
String name = path != null ? path : "value";
List<String> found = new ArrayList<String>();
for (String property : _properties) {
Object propertyValue = ObjectReader.getProperty(value, property);
if (propertyValue != null)
found.add(property);
}
if (found.size() == 0) {
results.add(new ValidationResult(path, ValidationResultType.Error, "VALUE_NULL",
name + " must have at least one property from " + _properties, _properties, null)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void addAnimatingView(View view) {
boolean alreadyAdded = false;
if (mNumAnimatingViews > 0) {
for (int i = mAnimatingViewIndex; i < getChildCount(); ++i) {
if (getChildAt(i) == view) {
alreadyAdded = true;
break;
}
}
}
if (!alreadyAdded) {
if (mNumAnimatingViews == 0) {
mAnimatingViewIndex = getChildCount();
}
++mNumAnimatingViews;
addView(view);
}
mRecycler.unscrapView(getChildViewHolder(view));
} } | public class class_name {
private void addAnimatingView(View view) {
boolean alreadyAdded = false;
if (mNumAnimatingViews > 0) {
for (int i = mAnimatingViewIndex; i < getChildCount(); ++i) {
if (getChildAt(i) == view) {
alreadyAdded = true; // depends on control dependency: [if], data = [none]
break;
}
}
}
if (!alreadyAdded) {
if (mNumAnimatingViews == 0) {
mAnimatingViewIndex = getChildCount(); // depends on control dependency: [if], data = [none]
}
++mNumAnimatingViews; // depends on control dependency: [if], data = [none]
addView(view); // depends on control dependency: [if], data = [none]
}
mRecycler.unscrapView(getChildViewHolder(view));
} } |
public class class_name {
@Override
public boolean add(T e) {
if (elements instanceof List<?>) {
final List<T> l = (List<T>) elements;
int pos = Collections.binarySearch(l, e);
if (pos >= 0)
return false;
l.add(-(pos + 1), e);
return true;
}
return elements.add(e);
} } | public class class_name {
@Override
public boolean add(T e) {
if (elements instanceof List<?>) {
final List<T> l = (List<T>) elements;
int pos = Collections.binarySearch(l, e);
if (pos >= 0)
return false;
l.add(-(pos + 1), e);
// depends on control dependency: [if], data = [)]
return true;
// depends on control dependency: [if], data = [none]
}
return elements.add(e);
} } |
public class class_name {
public JobFlowInstancesConfig withAdditionalSlaveSecurityGroups(String... additionalSlaveSecurityGroups) {
if (this.additionalSlaveSecurityGroups == null) {
setAdditionalSlaveSecurityGroups(new com.amazonaws.internal.SdkInternalList<String>(additionalSlaveSecurityGroups.length));
}
for (String ele : additionalSlaveSecurityGroups) {
this.additionalSlaveSecurityGroups.add(ele);
}
return this;
} } | public class class_name {
public JobFlowInstancesConfig withAdditionalSlaveSecurityGroups(String... additionalSlaveSecurityGroups) {
if (this.additionalSlaveSecurityGroups == null) {
setAdditionalSlaveSecurityGroups(new com.amazonaws.internal.SdkInternalList<String>(additionalSlaveSecurityGroups.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : additionalSlaveSecurityGroups) {
this.additionalSlaveSecurityGroups.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static String getReverseRouteFast(Class<? extends Controller> clazz) {
String simpleName = clazz.getSimpleName();
if (! simpleName.endsWith("Controller")) {
throw new ControllerException("controller name must end with 'Controller' suffix");
}
String className = clazz.getName();
if (!className.startsWith(PropertiesConstants.CONTROLLER_PACKAGE)) {
throw new ControllerException("controller must be in the '"+PropertiesConstants.CONTROLLER_PACKAGE+"' package");
}
int lastDot = className.lastIndexOf('.');
if (lastDot == CONTROLLER_PACKAGE_LENGTH) {
return "/" + StringUtil.underscore(simpleName.substring(0, simpleName.length()-CONTROLLER_LENGTH));
} else {
// we know that CONTROLLER_PACKAGE_LENGTH < lastDot
String packageSuffix = className.substring(CONTROLLER_PACKAGE_LENGTH, lastDot);
packageSuffix = packageSuffix.replace('.', '/');
return new StringBuilder(packageSuffix.length() + simpleName.length())
.append(packageSuffix)
.append('/')
.append(StringUtil.underscore(simpleName.substring(0, simpleName.length()-CONTROLLER_LENGTH)))
.toString();
}
} } | public class class_name {
public static String getReverseRouteFast(Class<? extends Controller> clazz) {
String simpleName = clazz.getSimpleName();
if (! simpleName.endsWith("Controller")) {
throw new ControllerException("controller name must end with 'Controller' suffix");
}
String className = clazz.getName();
if (!className.startsWith(PropertiesConstants.CONTROLLER_PACKAGE)) {
throw new ControllerException("controller must be in the '"+PropertiesConstants.CONTROLLER_PACKAGE+"' package");
}
int lastDot = className.lastIndexOf('.');
if (lastDot == CONTROLLER_PACKAGE_LENGTH) {
return "/" + StringUtil.underscore(simpleName.substring(0, simpleName.length()-CONTROLLER_LENGTH)); // depends on control dependency: [if], data = [none]
} else {
// we know that CONTROLLER_PACKAGE_LENGTH < lastDot
String packageSuffix = className.substring(CONTROLLER_PACKAGE_LENGTH, lastDot);
packageSuffix = packageSuffix.replace('.', '/'); // depends on control dependency: [if], data = [none]
return new StringBuilder(packageSuffix.length() + simpleName.length())
.append(packageSuffix)
.append('/')
.append(StringUtil.underscore(simpleName.substring(0, simpleName.length()-CONTROLLER_LENGTH)))
.toString(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public CRLReason getRevocationReason() {
Extension ext = getExtension(PKIXExtensions.ReasonCode_Id);
if (ext == null) {
return null;
}
CRLReasonCodeExtension rcExt = (CRLReasonCodeExtension) ext;
return rcExt.getReasonCode();
} } | public class class_name {
@Override
public CRLReason getRevocationReason() {
Extension ext = getExtension(PKIXExtensions.ReasonCode_Id);
if (ext == null) {
return null; // depends on control dependency: [if], data = [none]
}
CRLReasonCodeExtension rcExt = (CRLReasonCodeExtension) ext;
return rcExt.getReasonCode();
} } |
public class class_name {
private static void money(
CLDR.Locale locale, CLDR.Currency[] currencies, String[] numbers, CurrencyFormatOptions opts) {
for (CLDR.Currency currency : currencies) {
System.out.println("Currency " + currency);
for (String num : numbers) {
BigDecimal n = new BigDecimal(num);
NumberFormatter fmt = CLDR.get().getNumberFormatter(locale);
StringBuilder buf = new StringBuilder(" ");
fmt.formatCurrency(n, currency, buf, opts);
System.out.println(buf.toString());
}
System.out.println();
}
System.out.println();
} } | public class class_name {
private static void money(
CLDR.Locale locale, CLDR.Currency[] currencies, String[] numbers, CurrencyFormatOptions opts) {
for (CLDR.Currency currency : currencies) {
System.out.println("Currency " + currency); // depends on control dependency: [for], data = [currency]
for (String num : numbers) {
BigDecimal n = new BigDecimal(num);
NumberFormatter fmt = CLDR.get().getNumberFormatter(locale);
StringBuilder buf = new StringBuilder(" ");
fmt.formatCurrency(n, currency, buf, opts); // depends on control dependency: [for], data = [none]
System.out.println(buf.toString()); // depends on control dependency: [for], data = [none]
}
System.out.println(); // depends on control dependency: [for], data = [none]
}
System.out.println();
} } |
public class class_name {
@Override
public void addHeadLine(final String type, final String aLine) {
ArrayList<String> lines = headers.get(type);
if (lines == null) {
lines = new ArrayList<>();
headers.put(type, lines);
}
lines.add(aLine);
} } | public class class_name {
@Override
public void addHeadLine(final String type, final String aLine) {
ArrayList<String> lines = headers.get(type);
if (lines == null) {
lines = new ArrayList<>(); // depends on control dependency: [if], data = [none]
headers.put(type, lines); // depends on control dependency: [if], data = [none]
}
lines.add(aLine);
} } |
public class class_name {
private String createForwardCurve(Schedule swapTenorDefinition, String forwardCurveName) {
/*
* Temporary "hack" - we try to infer index maturity codes from curve name.
*/
String indexMaturityCode = null;
if(forwardCurveName.contains("_12M") || forwardCurveName.contains("-12M") || forwardCurveName.contains(" 12M")) {
indexMaturityCode = "12M";
}
if(forwardCurveName.contains("_1M") || forwardCurveName.contains("-1M") || forwardCurveName.contains(" 1M")) {
indexMaturityCode = "1M";
}
if(forwardCurveName.contains("_6M") || forwardCurveName.contains("-6M") || forwardCurveName.contains(" 6M")) {
indexMaturityCode = "6M";
}
if(forwardCurveName.contains("_3M") || forwardCurveName.contains("-3M") || forwardCurveName.contains(" 3M")) {
indexMaturityCode = "3M";
}
if(forwardCurveName == null || forwardCurveName.isEmpty()) {
return null;
}
// Check if the curves exists, if not create it
Curve curve = model.getCurve(forwardCurveName);
Curve forwardCurve = null;
if(curve == null) {
// Create a new forward curve
if(isUseForwardCurve) {
curve = new ForwardCurveInterpolation(forwardCurveName, swapTenorDefinition.getReferenceDate(), indexMaturityCode, ForwardCurveInterpolation.InterpolationEntityForward.FORWARD, null);
}
else {
// Alternative: Model the forward curve through an underlying discount curve.
curve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(forwardCurveName, new double[] { 0.0 }, new double[] { 1.0 });
model = model.addCurves(curve);
}
}
// Check if the curve is a discount curve, if yes - create a forward curve wrapper.
if(DiscountCurve.class.isInstance(curve)) {
/*
* If the specified forward curve exits as a discount curve, we generate a forward curve
* by wrapping the discount curve and calculating the
* forward from discount factors using the formula (df(T)/df(T+Delta T) - 1) / Delta T).
*
* If no index maturity is used, the forward curve is interpreted "single curve", i.e.
* T+Delta T is always the payment.
*/
forwardCurve = new ForwardCurveFromDiscountCurve(curve.getName(), swapTenorDefinition.getReferenceDate(), indexMaturityCode);
}
else {
// Use a given forward curve
forwardCurve = curve;
}
model = model.addCurves(forwardCurve);
return forwardCurve.getName();
} } | public class class_name {
private String createForwardCurve(Schedule swapTenorDefinition, String forwardCurveName) {
/*
* Temporary "hack" - we try to infer index maturity codes from curve name.
*/
String indexMaturityCode = null;
if(forwardCurveName.contains("_12M") || forwardCurveName.contains("-12M") || forwardCurveName.contains(" 12M")) {
indexMaturityCode = "12M"; // depends on control dependency: [if], data = [none]
}
if(forwardCurveName.contains("_1M") || forwardCurveName.contains("-1M") || forwardCurveName.contains(" 1M")) {
indexMaturityCode = "1M"; // depends on control dependency: [if], data = [none]
}
if(forwardCurveName.contains("_6M") || forwardCurveName.contains("-6M") || forwardCurveName.contains(" 6M")) {
indexMaturityCode = "6M"; // depends on control dependency: [if], data = [none]
}
if(forwardCurveName.contains("_3M") || forwardCurveName.contains("-3M") || forwardCurveName.contains(" 3M")) {
indexMaturityCode = "3M"; // depends on control dependency: [if], data = [none]
}
if(forwardCurveName == null || forwardCurveName.isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
// Check if the curves exists, if not create it
Curve curve = model.getCurve(forwardCurveName);
Curve forwardCurve = null;
if(curve == null) {
// Create a new forward curve
if(isUseForwardCurve) {
curve = new ForwardCurveInterpolation(forwardCurveName, swapTenorDefinition.getReferenceDate(), indexMaturityCode, ForwardCurveInterpolation.InterpolationEntityForward.FORWARD, null); // depends on control dependency: [if], data = [none]
}
else {
// Alternative: Model the forward curve through an underlying discount curve.
curve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(forwardCurveName, new double[] { 0.0 }, new double[] { 1.0 }); // depends on control dependency: [if], data = [none]
model = model.addCurves(curve); // depends on control dependency: [if], data = [none]
}
}
// Check if the curve is a discount curve, if yes - create a forward curve wrapper.
if(DiscountCurve.class.isInstance(curve)) {
/*
* If the specified forward curve exits as a discount curve, we generate a forward curve
* by wrapping the discount curve and calculating the
* forward from discount factors using the formula (df(T)/df(T+Delta T) - 1) / Delta T).
*
* If no index maturity is used, the forward curve is interpreted "single curve", i.e.
* T+Delta T is always the payment.
*/
forwardCurve = new ForwardCurveFromDiscountCurve(curve.getName(), swapTenorDefinition.getReferenceDate(), indexMaturityCode); // depends on control dependency: [if], data = [none]
}
else {
// Use a given forward curve
forwardCurve = curve; // depends on control dependency: [if], data = [none]
}
model = model.addCurves(forwardCurve);
return forwardCurve.getName();
} } |
public class class_name {
public static String prettyUptime(int secs) {
String[][] PRETTYSECDIVIDERS = { new String[] { "s", "60" }, new String[] { "m", "60" }, new String[] { "h", "24" },
new String[] { "d", null } };
int diversize = PRETTYSECDIVIDERS.length;
LinkedList<String> tmp = new LinkedList<>();
int div = secs;
for (int i = 0; i < diversize; i++) {
if (PRETTYSECDIVIDERS[i][1] != null) {
Integer d = Integer.parseInt(PRETTYSECDIVIDERS[i][1]);
tmp.addFirst(div % d + PRETTYSECDIVIDERS[i][0]);
div = div / d;
} else {
tmp.addFirst(div + PRETTYSECDIVIDERS[i][0]);
}
if (div <= 0 ) break;
}
Joiner joiner = Joiner.on(" ");
return joiner.join(tmp);
} } | public class class_name {
public static String prettyUptime(int secs) {
String[][] PRETTYSECDIVIDERS = { new String[] { "s", "60" }, new String[] { "m", "60" }, new String[] { "h", "24" },
new String[] { "d", null } };
int diversize = PRETTYSECDIVIDERS.length;
LinkedList<String> tmp = new LinkedList<>();
int div = secs;
for (int i = 0; i < diversize; i++) {
if (PRETTYSECDIVIDERS[i][1] != null) {
Integer d = Integer.parseInt(PRETTYSECDIVIDERS[i][1]);
tmp.addFirst(div % d + PRETTYSECDIVIDERS[i][0]); // depends on control dependency: [if], data = [none]
div = div / d; // depends on control dependency: [if], data = [none]
} else {
tmp.addFirst(div + PRETTYSECDIVIDERS[i][0]); // depends on control dependency: [if], data = [none]
}
if (div <= 0 ) break;
}
Joiner joiner = Joiner.on(" ");
return joiner.join(tmp);
} } |
public class class_name {
public Optional<Boolean> getBoolean(String key) {
Objects.requireNonNull(key, Required.KEY.toString());
String value = this.values.get(key);
if (StringUtils.isNotBlank(value)) {
if (("1").equals(value)) {
return Optional.of(Boolean.TRUE);
} else if (("true").equals(value)) {
return Optional.of(Boolean.TRUE);
} else if (("false").equals(value)) {
return Optional.of(Boolean.FALSE);
} else if (("0").equals(value)) {
return Optional.of(Boolean.FALSE);
} else {
// Ignore anything else
}
}
return Optional.empty();
} } | public class class_name {
public Optional<Boolean> getBoolean(String key) {
Objects.requireNonNull(key, Required.KEY.toString());
String value = this.values.get(key);
if (StringUtils.isNotBlank(value)) {
if (("1").equals(value)) {
return Optional.of(Boolean.TRUE); // depends on control dependency: [if], data = [none]
} else if (("true").equals(value)) {
return Optional.of(Boolean.TRUE); // depends on control dependency: [if], data = [none]
} else if (("false").equals(value)) {
return Optional.of(Boolean.FALSE); // depends on control dependency: [if], data = [none]
} else if (("0").equals(value)) {
return Optional.of(Boolean.FALSE); // depends on control dependency: [if], data = [none]
} else {
// Ignore anything else
}
}
return Optional.empty();
} } |
public class class_name {
private static void writeLiteralRegex(ByteIterator input, ByteString.Output output) {
while (input.hasNext()) {
byte unquoted = input.nextByte();
if ((unquoted < 'a' || unquoted > 'z')
&& (unquoted < 'A' || unquoted > 'Z')
&& (unquoted < '0' || unquoted > '9')
&& unquoted != '_'
&&
// If this is the part of a UTF8 or Latin1 character, we need
// to copy this byte without escaping. Experimentally this is
// what works correctly with the regexp library.
(unquoted & 128) == 0) {
if (unquoted == '\0') { // Special handling for null chars.
// Note that this special handling is not strictly required for RE2,
// but this quoting is required for other regexp libraries such as
// PCRE.
// Can't use "\\0" since the next character might be a digit.
output.write(NULL_BYTES, 0, NULL_BYTES.length);
continue;
}
output.write('\\');
}
output.write(unquoted);
}
} } | public class class_name {
private static void writeLiteralRegex(ByteIterator input, ByteString.Output output) {
while (input.hasNext()) {
byte unquoted = input.nextByte();
if ((unquoted < 'a' || unquoted > 'z')
&& (unquoted < 'A' || unquoted > 'Z')
&& (unquoted < '0' || unquoted > '9')
&& unquoted != '_'
&&
// If this is the part of a UTF8 or Latin1 character, we need
// to copy this byte without escaping. Experimentally this is
// what works correctly with the regexp library.
(unquoted & 128) == 0) {
if (unquoted == '\0') { // Special handling for null chars.
// Note that this special handling is not strictly required for RE2,
// but this quoting is required for other regexp libraries such as
// PCRE.
// Can't use "\\0" since the next character might be a digit.
output.write(NULL_BYTES, 0, NULL_BYTES.length); // depends on control dependency: [if], data = [none]
continue;
}
output.write('\\'); // depends on control dependency: [if], data = [none]
}
output.write(unquoted); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
private static Writer unwrap(Writer out) throws IOException {
while(true) {
Class<? extends Writer> outClass = out.getClass();
// Note: bodyContentImplClass will be null when direct access disabled
if(outClass==bodyContentImplClass) {
try {
Writer writer = (Writer)writerField.get(out);
// When the writer field is non-null, BodyContent is pass-through and we may safely directly access the wrapped writer.
if(writer!=null) {
// Will keep looping to unwrap the wrapped out
out = writer;
} else {
// BodyContent is buffering, must use directly
return out;
}
} catch(IllegalAccessException e) {
throw new IOException(e);
}
} else {
// No unwrapping
return out;
}
}
} } | public class class_name {
private static Writer unwrap(Writer out) throws IOException {
while(true) {
Class<? extends Writer> outClass = out.getClass();
// Note: bodyContentImplClass will be null when direct access disabled
if(outClass==bodyContentImplClass) {
try {
Writer writer = (Writer)writerField.get(out);
// When the writer field is non-null, BodyContent is pass-through and we may safely directly access the wrapped writer.
if(writer!=null) {
// Will keep looping to unwrap the wrapped out
out = writer; // depends on control dependency: [if], data = [none]
} else {
// BodyContent is buffering, must use directly
return out; // depends on control dependency: [if], data = [none]
}
} catch(IllegalAccessException e) {
throw new IOException(e);
} // depends on control dependency: [catch], data = [none]
} else {
// No unwrapping
return out; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static boolean isJoinTable(final Table table) {
if (table.getPrimaryKey() == null) {
return false;
}
final boolean hasMultipartFK = (table.getPrimaryKey().getColumns().size() > 1);
for (final Column column : table.getColumns()) {
if (hasMultipartFK) {
// has to be both
if (!(column.isPartOfForeignKey() && column.isPartOfPrimaryKey())) {
return false;
}
} else {
// If there is a single column that is not part of a foreign key and not the primary key, it needs a separate class
if (!column.isPartOfForeignKey() && !column.isPartOfPrimaryKey()) {
return false;
}
}
}
return true;
} } | public class class_name {
public static boolean isJoinTable(final Table table) {
if (table.getPrimaryKey() == null) {
return false;
// depends on control dependency: [if], data = [none]
}
final boolean hasMultipartFK = (table.getPrimaryKey().getColumns().size() > 1);
for (final Column column : table.getColumns()) {
if (hasMultipartFK) {
// has to be both
if (!(column.isPartOfForeignKey() && column.isPartOfPrimaryKey())) {
return false;
// depends on control dependency: [if], data = [none]
}
} else {
// If there is a single column that is not part of a foreign key and not the primary key, it needs a separate class
if (!column.isPartOfForeignKey() && !column.isPartOfPrimaryKey()) {
return false;
// depends on control dependency: [if], data = [none]
}
}
}
return true;
} } |
public class class_name {
public Method getInvokableMethodForClass(final Class<?> valueClass) {
if (valueClass == null)
return null;
Method method = methods.get(valueClass);
if (method != null)
return method;
// get the list of all classes and interfaces.
// first classes.
Class<?> clazz = valueClass.getSuperclass();
while (clazz != null) {
method = methods.get(clazz);
if (method != null) {
methods.put(valueClass, method);
return method;
}
clazz = clazz.getSuperclass();
}
// now look through the interfaces.
for (final Class<?> iface : valueClass.getInterfaces()) {
method = methods.get(iface);
if (method != null) {
methods.put(valueClass, method);
return method;
}
}
return null;
} } | public class class_name {
public Method getInvokableMethodForClass(final Class<?> valueClass) {
if (valueClass == null)
return null;
Method method = methods.get(valueClass);
if (method != null)
return method;
// get the list of all classes and interfaces.
// first classes.
Class<?> clazz = valueClass.getSuperclass();
while (clazz != null) {
method = methods.get(clazz); // depends on control dependency: [while], data = [(clazz]
if (method != null) {
methods.put(valueClass, method); // depends on control dependency: [if], data = [none]
return method; // depends on control dependency: [if], data = [none]
}
clazz = clazz.getSuperclass(); // depends on control dependency: [while], data = [none]
}
// now look through the interfaces.
for (final Class<?> iface : valueClass.getInterfaces()) {
method = methods.get(iface); // depends on control dependency: [for], data = [iface]
if (method != null) {
methods.put(valueClass, method); // depends on control dependency: [if], data = [none]
return method; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public void addFaxMonitorEventListener(FaxMonitorEventListener listener)
{
boolean faxMonitorEventsSupported=this.isFaxMonitorEventsSupported();
if(faxMonitorEventsSupported)
{
synchronized(this.faxMonitorEventListeners)
{
this.faxMonitorEventListeners.add(listener);
}
}
else
{
this.throwUnsupportedException();
}
} } | public class class_name {
public void addFaxMonitorEventListener(FaxMonitorEventListener listener)
{
boolean faxMonitorEventsSupported=this.isFaxMonitorEventsSupported();
if(faxMonitorEventsSupported)
{
synchronized(this.faxMonitorEventListeners) // depends on control dependency: [if], data = [none]
{
this.faxMonitorEventListeners.add(listener);
}
}
else
{
this.throwUnsupportedException(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setTimeInMillis( long millis ) {
if (millis > MAX_MILLIS) {
if(isLenient()) {
millis = MAX_MILLIS;
} else {
throw new IllegalArgumentException("millis value greater than upper bounds for a Calendar : " + millis);
}
} else if (millis < MIN_MILLIS) {
if(isLenient()) {
millis = MIN_MILLIS;
} else {
throw new IllegalArgumentException("millis value less than lower bounds for a Calendar : " + millis);
}
}
time = millis;
areFieldsSet = areAllFieldsSet = false;
isTimeSet = areFieldsVirtuallySet = true;
for (int i=0; i<fields.length; ++i) {
fields[i] = stamp[i] = 0; // UNSET == 0
}
} } | public class class_name {
public void setTimeInMillis( long millis ) {
if (millis > MAX_MILLIS) {
if(isLenient()) {
millis = MAX_MILLIS; // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("millis value greater than upper bounds for a Calendar : " + millis);
}
} else if (millis < MIN_MILLIS) {
if(isLenient()) {
millis = MIN_MILLIS; // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("millis value less than lower bounds for a Calendar : " + millis);
}
}
time = millis;
areFieldsSet = areAllFieldsSet = false;
isTimeSet = areFieldsVirtuallySet = true;
for (int i=0; i<fields.length; ++i) {
fields[i] = stamp[i] = 0; // UNSET == 0 // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
public void fireLayerContentChangedEvent(MapLayerContentEvent event) {
if (isEventFirable()) {
final MapLayerListener[] theListeners = getListeners();
if (theListeners != null && theListeners.length > 0) {
for (final MapLayerListener listener : theListeners) {
listener.onMapLayerContentChanged(event);
}
}
// stop the event firing when it was consumed
if (event.isConsumed() && event.isDisappearingWhenConsumed()) {
return;
}
final GISLayerContainer<?> container = getContainer();
if (container != null) {
container.fireLayerContentChangedEvent(event);
}
}
} } | public class class_name {
public void fireLayerContentChangedEvent(MapLayerContentEvent event) {
if (isEventFirable()) {
final MapLayerListener[] theListeners = getListeners();
if (theListeners != null && theListeners.length > 0) {
for (final MapLayerListener listener : theListeners) {
listener.onMapLayerContentChanged(event); // depends on control dependency: [for], data = [listener]
}
}
// stop the event firing when it was consumed
if (event.isConsumed() && event.isDisappearingWhenConsumed()) {
return; // depends on control dependency: [if], data = [none]
}
final GISLayerContainer<?> container = getContainer();
if (container != null) {
container.fireLayerContentChangedEvent(event); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void parseFraction() {
// get past .
pos++;
outer:
while (pos < s.length()) {
switch (s.charAt(pos)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
pos++;
break;
case 'e':
case 'E':
parseExponent();
break;
default:
break outer;
}
}
} } | public class class_name {
public void parseFraction() {
// get past .
pos++;
outer:
while (pos < s.length()) {
switch (s.charAt(pos)) { // depends on control dependency: [while], data = [(pos]
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
pos++;
break;
case 'e':
case 'E':
parseExponent();
break;
default:
break outer;
}
}
} } |
public class class_name {
public void setBackgroundInterval(long interval, TimeUnit unit)
{
if (! isValid()) {
return;
}
long period = unit.toMillis(interval);
if (_state == StateProfile.IDLE) {
if (period > 0) {
_profileTask.setPeriod(period);
_profileTask.start();
_state = StateProfile.BACKGROUND;
}
}
else if (_state == StateProfile.BACKGROUND) {
if (period <= 0) {
_profileTask.stop();
_state = StateProfile.IDLE;
}
else if (period != _backgroundPeriod) {
_profileTask.stop();
_profileTask.setPeriod(period);
_profileTask.start();
}
}
_backgroundPeriod = period;
} } | public class class_name {
public void setBackgroundInterval(long interval, TimeUnit unit)
{
if (! isValid()) {
return; // depends on control dependency: [if], data = [none]
}
long period = unit.toMillis(interval);
if (_state == StateProfile.IDLE) {
if (period > 0) {
_profileTask.setPeriod(period); // depends on control dependency: [if], data = [(period]
_profileTask.start(); // depends on control dependency: [if], data = [none]
_state = StateProfile.BACKGROUND; // depends on control dependency: [if], data = [none]
}
}
else if (_state == StateProfile.BACKGROUND) {
if (period <= 0) {
_profileTask.stop(); // depends on control dependency: [if], data = [none]
_state = StateProfile.IDLE; // depends on control dependency: [if], data = [none]
}
else if (period != _backgroundPeriod) {
_profileTask.stop(); // depends on control dependency: [if], data = [none]
_profileTask.setPeriod(period); // depends on control dependency: [if], data = [(period]
_profileTask.start(); // depends on control dependency: [if], data = [none]
}
}
_backgroundPeriod = period;
} } |
public class class_name {
public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) {
HttpURLConnection conn = null;
try {
conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers);
conn.connect();
OutputStream out = conn.getOutputStream();
out.write(data != null ? data.getBytes(CHARSET) : null);
out.flush();
out.close();
return readResponseString(conn);
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
if (conn != null) {
conn.disconnect();
}
}
} } | public class class_name {
public static String post(String url, Map<String, String> queryParas, String data, Map<String, String> headers) {
HttpURLConnection conn = null;
try {
conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers); // depends on control dependency: [try], data = [none]
conn.connect(); // depends on control dependency: [try], data = [none]
OutputStream out = conn.getOutputStream();
out.write(data != null ? data.getBytes(CHARSET) : null); // depends on control dependency: [try], data = [none]
out.flush(); // depends on control dependency: [try], data = [none]
out.close(); // depends on control dependency: [try], data = [none]
return readResponseString(conn); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
finally {
if (conn != null) {
conn.disconnect(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Nonnull
public Query whereEqualTo(@Nonnull FieldPath fieldPath, @Nullable Object value) {
Preconditions.checkState(
options.startCursor == null && options.endCursor == null,
"Cannot call whereEqualTo() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
QueryOptions newOptions = new QueryOptions(options);
if (isUnaryComparison(value)) {
newOptions.fieldFilters.add(new UnaryFilter(fieldPath, value));
} else {
if (fieldPath.equals(FieldPath.DOCUMENT_ID)) {
value = this.convertReference(value);
}
newOptions.fieldFilters.add(new ComparisonFilter(fieldPath, EQUAL, value));
}
return new Query(firestore, path, newOptions);
} } | public class class_name {
@Nonnull
public Query whereEqualTo(@Nonnull FieldPath fieldPath, @Nullable Object value) {
Preconditions.checkState(
options.startCursor == null && options.endCursor == null,
"Cannot call whereEqualTo() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
QueryOptions newOptions = new QueryOptions(options);
if (isUnaryComparison(value)) {
newOptions.fieldFilters.add(new UnaryFilter(fieldPath, value)); // depends on control dependency: [if], data = [none]
} else {
if (fieldPath.equals(FieldPath.DOCUMENT_ID)) {
value = this.convertReference(value); // depends on control dependency: [if], data = [none]
}
newOptions.fieldFilters.add(new ComparisonFilter(fieldPath, EQUAL, value)); // depends on control dependency: [if], data = [none]
}
return new Query(firestore, path, newOptions);
} } |
public class class_name {
public void removeFile(final OFileMMap iFile) {
lockManager.acquireLock(Thread.currentThread(), iFile, OLockManager.LOCK.EXCLUSIVE);
try {
mapEntrySearchInfo.remove(iFile);
final OMMapBufferEntry[] entries = bufferPoolPerFile.remove(iFile);
removeFileEntries(entries);
} finally {
lockManager.releaseLock(Thread.currentThread(), iFile, OLockManager.LOCK.EXCLUSIVE);
}
} } | public class class_name {
public void removeFile(final OFileMMap iFile) {
lockManager.acquireLock(Thread.currentThread(), iFile, OLockManager.LOCK.EXCLUSIVE);
try {
mapEntrySearchInfo.remove(iFile);
// depends on control dependency: [try], data = [none]
final OMMapBufferEntry[] entries = bufferPoolPerFile.remove(iFile);
removeFileEntries(entries);
// depends on control dependency: [try], data = [none]
} finally {
lockManager.releaseLock(Thread.currentThread(), iFile, OLockManager.LOCK.EXCLUSIVE);
}
} } |
public class class_name {
protected JavaSource getJavaSourceForClass(String clazzname) {
String resource = clazzname.replaceAll("\\.", "/") + ".java";
FileObject fileObject = classPath.findResource(resource);
if (fileObject == null) {
return null;
}
Project project = FileOwnerQuery.getOwner(fileObject);
if (project == null) {
return null;
}
SourceGroup[] sourceGroups = ProjectUtils.getSources(project).getSourceGroups("java");
for (SourceGroup sourceGroup : sourceGroups) {
return JavaSource.create(ClasspathInfo.create(sourceGroup.getRootFolder()));
}
return null;
} } | public class class_name {
protected JavaSource getJavaSourceForClass(String clazzname) {
String resource = clazzname.replaceAll("\\.", "/") + ".java";
FileObject fileObject = classPath.findResource(resource);
if (fileObject == null) {
return null; // depends on control dependency: [if], data = [none]
}
Project project = FileOwnerQuery.getOwner(fileObject);
if (project == null) {
return null; // depends on control dependency: [if], data = [none]
}
SourceGroup[] sourceGroups = ProjectUtils.getSources(project).getSourceGroups("java");
for (SourceGroup sourceGroup : sourceGroups) {
return JavaSource.create(ClasspathInfo.create(sourceGroup.getRootFolder())); // depends on control dependency: [for], data = [sourceGroup]
}
return null;
} } |
public class class_name {
public DescribeImagesRequest withExecutableUsers(String... executableUsers) {
if (this.executableUsers == null) {
setExecutableUsers(new com.amazonaws.internal.SdkInternalList<String>(executableUsers.length));
}
for (String ele : executableUsers) {
this.executableUsers.add(ele);
}
return this;
} } | public class class_name {
public DescribeImagesRequest withExecutableUsers(String... executableUsers) {
if (this.executableUsers == null) {
setExecutableUsers(new com.amazonaws.internal.SdkInternalList<String>(executableUsers.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : executableUsers) {
this.executableUsers.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private Set<String> containerExposedPorts() {
final Set<String> ports = Sets.newHashSet();
for (final Map.Entry<String, PortMapping> entry : job.getPorts().entrySet()) {
final PortMapping mapping = entry.getValue();
ports.add(containerPort(mapping.getInternalPort(), mapping.getProtocol()));
}
return ports;
} } | public class class_name {
private Set<String> containerExposedPorts() {
final Set<String> ports = Sets.newHashSet();
for (final Map.Entry<String, PortMapping> entry : job.getPorts().entrySet()) {
final PortMapping mapping = entry.getValue();
ports.add(containerPort(mapping.getInternalPort(), mapping.getProtocol())); // depends on control dependency: [for], data = [none]
}
return ports;
} } |
public class class_name {
public ListAliasesResult withAliases(AliasConfiguration... aliases) {
if (this.aliases == null) {
setAliases(new com.amazonaws.internal.SdkInternalList<AliasConfiguration>(aliases.length));
}
for (AliasConfiguration ele : aliases) {
this.aliases.add(ele);
}
return this;
} } | public class class_name {
public ListAliasesResult withAliases(AliasConfiguration... aliases) {
if (this.aliases == null) {
setAliases(new com.amazonaws.internal.SdkInternalList<AliasConfiguration>(aliases.length)); // depends on control dependency: [if], data = [none]
}
for (AliasConfiguration ele : aliases) {
this.aliases.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public final void typeList() throws RecognitionException {
try {
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:130:5: ( type ( COMMA type )* )
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:130:7: type ( COMMA type )*
{
pushFollow(FOLLOW_type_in_typeList502);
type();
state._fsp--;
if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:130:12: ( COMMA type )*
loop5:
while (true) {
int alt5=2;
int LA5_0 = input.LA(1);
if ( (LA5_0==COMMA) ) {
alt5=1;
}
switch (alt5) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:130:13: COMMA type
{
match(input,COMMA,FOLLOW_COMMA_in_typeList505); if (state.failed) return;
pushFollow(FOLLOW_type_in_typeList507);
type();
state._fsp--;
if (state.failed) return;
}
break;
default :
break loop5;
}
}
}
}
catch (RecognitionException re) {
throw re;
}
finally {
// do for sure before leaving
}
} } | public class class_name {
public final void typeList() throws RecognitionException {
try {
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:130:5: ( type ( COMMA type )* )
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:130:7: type ( COMMA type )*
{
pushFollow(FOLLOW_type_in_typeList502);
type();
state._fsp--;
if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:130:12: ( COMMA type )*
loop5:
while (true) {
int alt5=2;
int LA5_0 = input.LA(1);
if ( (LA5_0==COMMA) ) {
alt5=1; // depends on control dependency: [if], data = [none]
}
switch (alt5) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:130:13: COMMA type
{
match(input,COMMA,FOLLOW_COMMA_in_typeList505); if (state.failed) return;
pushFollow(FOLLOW_type_in_typeList507);
type();
state._fsp--;
if (state.failed) return;
}
break;
default :
break loop5;
}
}
}
}
catch (RecognitionException re) {
throw re;
}
finally {
// do for sure before leaving
}
} } |
public class class_name {
public final <T> void registerType(Class<T> runtimeClass, TypeHandler<T> handler) {
if (started) {
// Can't add any more metrics anyway; harmless
return;
}
typeHandlers.put(runtimeClass, handler);
} } | public class class_name {
public final <T> void registerType(Class<T> runtimeClass, TypeHandler<T> handler) {
if (started) {
// Can't add any more metrics anyway; harmless
return; // depends on control dependency: [if], data = [none]
}
typeHandlers.put(runtimeClass, handler);
} } |
public class class_name {
public void setAvailableInstanceCapacity(java.util.Collection<InstanceCapacity> availableInstanceCapacity) {
if (availableInstanceCapacity == null) {
this.availableInstanceCapacity = null;
return;
}
this.availableInstanceCapacity = new com.amazonaws.internal.SdkInternalList<InstanceCapacity>(availableInstanceCapacity);
} } | public class class_name {
public void setAvailableInstanceCapacity(java.util.Collection<InstanceCapacity> availableInstanceCapacity) {
if (availableInstanceCapacity == null) {
this.availableInstanceCapacity = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.availableInstanceCapacity = new com.amazonaws.internal.SdkInternalList<InstanceCapacity>(availableInstanceCapacity);
} } |
public class class_name {
public static List<Specification> parseSpecification(File file) {
List<Specification> monitorables = new ArrayList<>();
try {
InputStream stream = new FileInputStream(file);
monitorables = parseInputSpecification(stream);
} catch (Exception e) {
logger.error(String.format("Ignoring file %s", file.getName()));
}
return monitorables;
} } | public class class_name {
public static List<Specification> parseSpecification(File file) {
List<Specification> monitorables = new ArrayList<>();
try {
InputStream stream = new FileInputStream(file);
monitorables = parseInputSpecification(stream); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error(String.format("Ignoring file %s", file.getName()));
} // depends on control dependency: [catch], data = [none]
return monitorables;
} } |
public class class_name {
private PropertyNode createFXProperty(PropertyNode orig) {
ClassNode origType = orig.getType();
ClassNode newType = PROPERTY_TYPE_MAP.get(origType);
// For the ObjectProperty, we need to add the generic type to it.
if (newType == null) {
if (isTypeCompatible(ClassHelper.LIST_TYPE, origType) || isTypeCompatible(OBSERVABLE_LIST_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_LIST_PROPERTY_CNODE);
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes);
} else if (isTypeCompatible(ClassHelper.MAP_TYPE, origType) || isTypeCompatible(OBSERVABLE_MAP_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_MAP_PROPERTY_CNODE);
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes);
} else if (isTypeCompatible(SET_TYPE, origType) || isTypeCompatible(OBSERVABLE_SET_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_SET_PROPERTY_CNODE);
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes);
} else { // Object Type
newType = makeClassSafe(OBJECT_PROPERTY_CNODE);
ClassNode genericType = origType;
if (genericType.isPrimaryClassNode()) {
genericType = ClassHelper.getWrapper(genericType);
}
newType.setGenericsTypes(new GenericsType[]{new GenericsType(genericType)});
}
}
FieldNode fieldNode = createFieldNodeCopy(orig.getName() + "Property", newType, orig.getField());
return new PropertyNode(fieldNode, orig.getModifiers(), orig.getGetterBlock(), orig.getSetterBlock());
} } | public class class_name {
private PropertyNode createFXProperty(PropertyNode orig) {
ClassNode origType = orig.getType();
ClassNode newType = PROPERTY_TYPE_MAP.get(origType);
// For the ObjectProperty, we need to add the generic type to it.
if (newType == null) {
if (isTypeCompatible(ClassHelper.LIST_TYPE, origType) || isTypeCompatible(OBSERVABLE_LIST_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_LIST_PROPERTY_CNODE); // depends on control dependency: [if], data = [none]
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes); // depends on control dependency: [if], data = [none]
} else if (isTypeCompatible(ClassHelper.MAP_TYPE, origType) || isTypeCompatible(OBSERVABLE_MAP_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_MAP_PROPERTY_CNODE); // depends on control dependency: [if], data = [none]
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes); // depends on control dependency: [if], data = [none]
} else if (isTypeCompatible(SET_TYPE, origType) || isTypeCompatible(OBSERVABLE_SET_CNODE, origType)) {
newType = makeClassSafe(SIMPLE_SET_PROPERTY_CNODE); // depends on control dependency: [if], data = [none]
GenericsType[] genericTypes = origType.getGenericsTypes();
newType.setGenericsTypes(genericTypes); // depends on control dependency: [if], data = [none]
} else { // Object Type
newType = makeClassSafe(OBJECT_PROPERTY_CNODE); // depends on control dependency: [if], data = [none]
ClassNode genericType = origType;
if (genericType.isPrimaryClassNode()) {
genericType = ClassHelper.getWrapper(genericType); // depends on control dependency: [if], data = [none]
}
newType.setGenericsTypes(new GenericsType[]{new GenericsType(genericType)}); // depends on control dependency: [if], data = [none]
}
}
FieldNode fieldNode = createFieldNodeCopy(orig.getName() + "Property", newType, orig.getField());
return new PropertyNode(fieldNode, orig.getModifiers(), orig.getGetterBlock(), orig.getSetterBlock());
} } |
public class class_name {
public String getBasePath() {
String docBase = null;
Container container = this;
while (container != null) {
if (container instanceof Host)
break;
container = container.getParent();
}
File file = new File(getDocBase());
if (!file.isAbsolute()) {
if (container == null) {
docBase = (new File(engineBase(), getDocBase())).getPath();
} else {
// Use the "appBase" property of this container
String appBase = ((Host) container).getAppBase();
file = new File(appBase);
if (!file.isAbsolute())
file = new File(engineBase(), appBase);
docBase = (new File(file, getDocBase())).getPath();
}
} else {
docBase = file.getPath();
}
return docBase;
} } | public class class_name {
public String getBasePath() {
String docBase = null;
Container container = this;
while (container != null) {
if (container instanceof Host)
break;
container = container.getParent(); // depends on control dependency: [while], data = [none]
}
File file = new File(getDocBase());
if (!file.isAbsolute()) {
if (container == null) {
docBase = (new File(engineBase(), getDocBase())).getPath(); // depends on control dependency: [if], data = [none]
} else {
// Use the "appBase" property of this container
String appBase = ((Host) container).getAppBase();
file = new File(appBase); // depends on control dependency: [if], data = [none]
if (!file.isAbsolute())
file = new File(engineBase(), appBase);
docBase = (new File(file, getDocBase())).getPath(); // depends on control dependency: [if], data = [none]
}
} else {
docBase = file.getPath(); // depends on control dependency: [if], data = [none]
}
return docBase;
} } |
public class class_name {
protected IWord getNextCJKWord(int c, int pos) throws IOException
{
char[] chars = nextCJKSentence(c);
int cjkidx = 0;
IWord w = null;
while ( cjkidx < chars.length ) {
/*
* find the next CJK word.
* the process will be different with the different algorithm
* @see getBestCJKChunk() from SimpleSeg or ComplexSeg.
*/
w = null;
/*
* check if there is Chinese numeric.
* make sure chars[cjkidx] is a Chinese numeric
* and it is not the last word.
*/
if ( cjkidx + 1 < chars.length
&& NumericUtil.isCNNumeric(chars[cjkidx]) > -1 ) {
//get the Chinese numeric chars
String num = nextCNNumeric( chars, cjkidx );
int NUMLEN = num.length();
/*
* check the Chinese fraction.
* old logic: {{{
* cjkidx + 3 < chars.length && chars[cjkidx+1] == '分'
* && chars[cjkidx+2] == '之'
* && CNNMFilter.isCNNumeric(chars[cjkidx+3]) > -1.
* }}}
*
* checkCF will be reset to be 'TRUE' it num is a Chinese fraction.
* @added 2013-12-14.
* */
if ( (ctrlMask & ISegment.CHECK_CF_MASK) != 0 ) {
w = new Word(num, IWord.T_CN_NUMERIC);
w.setPosition(pos+cjkidx);
w.setPartSpeech(IWord.NUMERIC_POSPEECH);
wordPool.add(w);
/*
* Here:
* Convert the Chinese fraction to Arabic fraction,
* if the Config.CNFRA_TO_ARABIC is true.
*/
if ( config.CNFRA_TO_ARABIC ) {
String[] split = num.split("分之");
IWord wd = new Word(
NumericUtil.cnNumericToArabic(split[1], true)+
"/"+NumericUtil.cnNumericToArabic(split[0], true),
IWord.T_CN_NUMERIC
);
wd.setPosition(w.getPosition());
wd.setPartSpeech(IWord.NUMERIC_POSPEECH);
wordPool.add(wd);
}
}
/*
* check the Chinese numeric and single units.
* type to find Chinese and unit composed word.
*/
else if ( NumericUtil.isCNNumeric(chars[cjkidx+1]) > -1
|| dic.match(ILexicon.CJK_UNIT, chars[cjkidx+1]+"") ) {
StringBuilder sb = new StringBuilder();
String temp = null;
String ONUM = num; //backup the old numeric
sb.append(num);
boolean matched = false;
int j;
/*
* find the word that made up with the numeric
* like: "五四运动"
*/
for ( j = num.length();
(cjkidx + j) < chars.length
&& j < config.MAX_LENGTH; j++ ) {
sb.append(chars[cjkidx + j]);
temp = sb.toString();
if ( dic.match(ILexicon.CJK_WORD, temp) ) {
w = dic.get(ILexicon.CJK_WORD, temp);
num = temp;
matched = true;
}
}
/*
* @Note: when matched is true, num maybe a word like '五月',
* yat, this will make it skip the Chinese numeric to Arabic logic
* so find the matched word that it maybe a single Chinese units word
*
* @added: 2014-06-06
*/
if ( matched == true && num.length() - NUMLEN == 1
&& dic.match(ILexicon.CJK_UNIT, num.substring(NUMLEN)) ) {
num = ONUM;
matched = false; //reset the matched
}
IWord wd = null;
if ( matched == false && config.CNNUM_TO_ARABIC ) {
String arabic = NumericUtil.cnNumericToArabic(num, true)+"";
if ( (cjkidx + num.length()) < chars.length
&& dic.match(ILexicon.CJK_UNIT, chars[cjkidx + num.length()]+"") ) {
char units = chars[ cjkidx + num.length() ];
num += units; arabic += units;
}
wd = new Word( arabic, IWord.T_CN_NUMERIC);
wd.setPartSpeech(IWord.NUMERIC_POSPEECH);
wd.setPosition(pos+cjkidx);
}
//clear the stop words as need
if ( config.CLEAR_STOPWORD
&& dic.match(ILexicon.STOP_WORD, num) ) {
cjkidx += num.length();
continue;
}
/*
* @Note: added at 2016/07/19
* we cannot share the position with the original word item in the
* global dictionary accessed with this.dic
*
* cuz at the concurrency that will lead to the position error
* so, we clone it if the word is directly get from the dictionary
*/
if ( w == null ) {
w = new Word(num, IWord.T_CN_NUMERIC);
w.setPartSpeech(IWord.NUMERIC_POSPEECH);
} else {
w = w.clone();
}
w.setPosition(pos + cjkidx);
wordPool.add(w);
if ( wd != null ) {
wordPool.add(wd);
}
}
if ( w != null ) {
cjkidx += w.getLength();
appendWordFeatures(w);
continue;
}
}
IChunk chunk = getBestCJKChunk(chars, cjkidx);
w = chunk.getWords()[0];
String wps = w.getPartSpeech()==null ? null : w.getPartSpeech()[0];
/*
* check and try to find a Chinese name.
*
* @Note at 2017/05/19
* add the origin part of speech check, if the
* w is a Chinese name already and just let it go
*/
int T = -1;
if ( config.I_CN_NAME && (!"nr".equals(wps))
&& w.getLength() <= 2 && chunk.getWords().length > 1 ) {
StringBuilder sb = new StringBuilder();
sb.append(w.getValue());
String str = null;
//the w is a Chinese last name.
if ( dic.match(ILexicon.CN_LNAME, w.getValue())
&& (str = findCHName(chars, 0, chunk)) != null) {
T = IWord.T_CN_NAME;
sb.append(str);
}
//the w is Chinese last name adorn
else if ( dic.match(ILexicon.CN_LNAME_ADORN, w.getValue())
&& chunk.getWords()[1].getLength() <= 2
&& dic.match(ILexicon.CN_LNAME,
chunk.getWords()[1].getValue())) {
T = IWord.T_CN_NICKNAME;
sb.append(chunk.getWords()[1].getValue());
}
/*
* the length of the w is 2:
* the last name and the first char make up a word
* for the double name.
*/
/*else if ( w.getLength() > 1
&& findCHName( w, chunk )) {
T = IWord.T_CN_NAME;
sb.append(chunk.getWords()[1].getValue().charAt(0));
}*/
if ( T != -1 ) {
w = new Word(sb.toString(), T);
w.setPartSpeech(IWord.NAME_POSPEECH);
}
}
//check and clear the stop words
if ( config.CLEAR_STOPWORD
&& dic.match(ILexicon.STOP_WORD, w.getValue()) ) {
cjkidx += w.getLength();
continue;
}
/*
* reach the end of the chars - the last word.
* check the existence of the Chinese and English mixed word
*/
IWord ce = null;
if ( (ctrlMask & ISegment.CHECK_CE_MASk) != 0
&& (chars.length - cjkidx) <= dic.mixPrefixLength ) {
ce = getNextMixedWord(chars, cjkidx);
if ( ce != null ) {
T = -1;
}
}
/*
* @Note: added at 2016/07/19
* if the ce word is null and if the T is -1
* the w should be a word that clone from itself
*/
if ( ce == null ) {
if ( T == -1 ) w = w.clone();
} else {
w = ce.clone();
}
w.setPosition(pos+cjkidx);
wordPool.add(w);
cjkidx += w.getLength();
/*
* check and append the Pinyin and the synonyms words.
*/
if ( T == -1 ) {
appendWordFeatures(w);
}
}
if ( wordPool.size() == 0 ) {
return null;
}
return wordPool.remove();
} } | public class class_name {
protected IWord getNextCJKWord(int c, int pos) throws IOException
{
char[] chars = nextCJKSentence(c);
int cjkidx = 0;
IWord w = null;
while ( cjkidx < chars.length ) {
/*
* find the next CJK word.
* the process will be different with the different algorithm
* @see getBestCJKChunk() from SimpleSeg or ComplexSeg.
*/
w = null;
/*
* check if there is Chinese numeric.
* make sure chars[cjkidx] is a Chinese numeric
* and it is not the last word.
*/
if ( cjkidx + 1 < chars.length
&& NumericUtil.isCNNumeric(chars[cjkidx]) > -1 ) {
//get the Chinese numeric chars
String num = nextCNNumeric( chars, cjkidx );
int NUMLEN = num.length();
/*
* check the Chinese fraction.
* old logic: {{{
* cjkidx + 3 < chars.length && chars[cjkidx+1] == '分'
* && chars[cjkidx+2] == '之'
* && CNNMFilter.isCNNumeric(chars[cjkidx+3]) > -1.
* }}}
*
* checkCF will be reset to be 'TRUE' it num is a Chinese fraction.
* @added 2013-12-14.
* */
if ( (ctrlMask & ISegment.CHECK_CF_MASK) != 0 ) {
w = new Word(num, IWord.T_CN_NUMERIC);
w.setPosition(pos+cjkidx);
w.setPartSpeech(IWord.NUMERIC_POSPEECH);
wordPool.add(w);
/*
* Here:
* Convert the Chinese fraction to Arabic fraction,
* if the Config.CNFRA_TO_ARABIC is true.
*/
if ( config.CNFRA_TO_ARABIC ) {
String[] split = num.split("分之");
IWord wd = new Word(
NumericUtil.cnNumericToArabic(split[1], true)+
"/"+NumericUtil.cnNumericToArabic(split[0], true),
IWord.T_CN_NUMERIC
);
wd.setPosition(w.getPosition()); // depends on control dependency: [if], data = [none]
wd.setPartSpeech(IWord.NUMERIC_POSPEECH); // depends on control dependency: [if], data = [none]
wordPool.add(wd); // depends on control dependency: [if], data = [none]
}
}
/*
* check the Chinese numeric and single units.
* type to find Chinese and unit composed word.
*/
else if ( NumericUtil.isCNNumeric(chars[cjkidx+1]) > -1
|| dic.match(ILexicon.CJK_UNIT, chars[cjkidx+1]+"") ) {
StringBuilder sb = new StringBuilder();
String temp = null;
String ONUM = num; //backup the old numeric
sb.append(num);
boolean matched = false;
int j;
/*
* find the word that made up with the numeric
* like: "五四运动"
*/
for ( j = num.length();
(cjkidx + j) < chars.length
&& j < config.MAX_LENGTH; j++ ) {
sb.append(chars[cjkidx + j]);
temp = sb.toString();
if ( dic.match(ILexicon.CJK_WORD, temp) ) {
w = dic.get(ILexicon.CJK_WORD, temp); // depends on control dependency: [if], data = [none]
num = temp; // depends on control dependency: [if], data = [none]
matched = true; // depends on control dependency: [if], data = [none]
}
}
/*
* @Note: when matched is true, num maybe a word like '五月',
* yat, this will make it skip the Chinese numeric to Arabic logic
* so find the matched word that it maybe a single Chinese units word
*
* @added: 2014-06-06
*/
if ( matched == true && num.length() - NUMLEN == 1
&& dic.match(ILexicon.CJK_UNIT, num.substring(NUMLEN)) ) {
num = ONUM;
matched = false; //reset the matched
}
IWord wd = null;
if ( matched == false && config.CNNUM_TO_ARABIC ) {
String arabic = NumericUtil.cnNumericToArabic(num, true)+"";
if ( (cjkidx + num.length()) < chars.length
&& dic.match(ILexicon.CJK_UNIT, chars[cjkidx + num.length()]+"") ) {
char units = chars[ cjkidx + num.length() ];
num += units; arabic += units;
}
wd = new Word( arabic, IWord.T_CN_NUMERIC);
wd.setPartSpeech(IWord.NUMERIC_POSPEECH);
wd.setPosition(pos+cjkidx);
}
//clear the stop words as need
if ( config.CLEAR_STOPWORD
&& dic.match(ILexicon.STOP_WORD, num) ) {
cjkidx += num.length();
continue;
}
/*
* @Note: added at 2016/07/19
* we cannot share the position with the original word item in the
* global dictionary accessed with this.dic
*
* cuz at the concurrency that will lead to the position error
* so, we clone it if the word is directly get from the dictionary
*/
if ( w == null ) {
w = new Word(num, IWord.T_CN_NUMERIC);
w.setPartSpeech(IWord.NUMERIC_POSPEECH);
} else {
w = w.clone();
}
w.setPosition(pos + cjkidx);
wordPool.add(w);
if ( wd != null ) {
wordPool.add(wd);
}
}
if ( w != null ) {
cjkidx += w.getLength();
appendWordFeatures(w);
continue;
}
}
IChunk chunk = getBestCJKChunk(chars, cjkidx);
w = chunk.getWords()[0];
String wps = w.getPartSpeech()==null ? null : w.getPartSpeech()[0];
/*
* check and try to find a Chinese name.
*
* @Note at 2017/05/19
* add the origin part of speech check, if the
* w is a Chinese name already and just let it go
*/
int T = -1;
if ( config.I_CN_NAME && (!"nr".equals(wps))
&& w.getLength() <= 2 && chunk.getWords().length > 1 ) {
StringBuilder sb = new StringBuilder();
sb.append(w.getValue());
String str = null;
//the w is a Chinese last name.
if ( dic.match(ILexicon.CN_LNAME, w.getValue())
&& (str = findCHName(chars, 0, chunk)) != null) {
T = IWord.T_CN_NAME;
sb.append(str);
}
//the w is Chinese last name adorn
else if ( dic.match(ILexicon.CN_LNAME_ADORN, w.getValue())
&& chunk.getWords()[1].getLength() <= 2
&& dic.match(ILexicon.CN_LNAME,
chunk.getWords()[1].getValue())) {
T = IWord.T_CN_NICKNAME;
sb.append(chunk.getWords()[1].getValue());
}
/*
* the length of the w is 2:
* the last name and the first char make up a word
* for the double name.
*/
/*else if ( w.getLength() > 1
&& findCHName( w, chunk )) {
T = IWord.T_CN_NAME;
sb.append(chunk.getWords()[1].getValue().charAt(0));
}*/
if ( T != -1 ) {
w = new Word(sb.toString(), T);
w.setPartSpeech(IWord.NAME_POSPEECH);
}
}
//check and clear the stop words
if ( config.CLEAR_STOPWORD
&& dic.match(ILexicon.STOP_WORD, w.getValue()) ) {
cjkidx += w.getLength();
continue;
}
/*
* reach the end of the chars - the last word.
* check the existence of the Chinese and English mixed word
*/
IWord ce = null;
if ( (ctrlMask & ISegment.CHECK_CE_MASk) != 0
&& (chars.length - cjkidx) <= dic.mixPrefixLength ) {
ce = getNextMixedWord(chars, cjkidx);
if ( ce != null ) {
T = -1;
}
}
/*
* @Note: added at 2016/07/19
* if the ce word is null and if the T is -1
* the w should be a word that clone from itself
*/
if ( ce == null ) {
if ( T == -1 ) w = w.clone();
} else {
w = ce.clone();
}
w.setPosition(pos+cjkidx);
wordPool.add(w);
cjkidx += w.getLength();
/*
* check and append the Pinyin and the synonyms words.
*/
if ( T == -1 ) {
appendWordFeatures(w);
}
}
if ( wordPool.size() == 0 ) {
return null;
}
return wordPool.remove();
} } |
public class class_name {
public String getExplorerBodyUri() {
String body = CmsWorkplace.VFS_PATH_VIEWS + "explorer/explorer_body_fs.jsp";
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_uri)) {
body += "?" + PARAMETER_URI + "=" + m_uri;
}
return getJsp().link(body);
} } | public class class_name {
public String getExplorerBodyUri() {
String body = CmsWorkplace.VFS_PATH_VIEWS + "explorer/explorer_body_fs.jsp";
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_uri)) {
body += "?" + PARAMETER_URI + "=" + m_uri; // depends on control dependency: [if], data = [none]
}
return getJsp().link(body);
} } |
public class class_name {
public void marshall(AssociateQualificationWithWorkerRequest associateQualificationWithWorkerRequest, ProtocolMarshaller protocolMarshaller) {
if (associateQualificationWithWorkerRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(associateQualificationWithWorkerRequest.getQualificationTypeId(), QUALIFICATIONTYPEID_BINDING);
protocolMarshaller.marshall(associateQualificationWithWorkerRequest.getWorkerId(), WORKERID_BINDING);
protocolMarshaller.marshall(associateQualificationWithWorkerRequest.getIntegerValue(), INTEGERVALUE_BINDING);
protocolMarshaller.marshall(associateQualificationWithWorkerRequest.getSendNotification(), SENDNOTIFICATION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(AssociateQualificationWithWorkerRequest associateQualificationWithWorkerRequest, ProtocolMarshaller protocolMarshaller) {
if (associateQualificationWithWorkerRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(associateQualificationWithWorkerRequest.getQualificationTypeId(), QUALIFICATIONTYPEID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(associateQualificationWithWorkerRequest.getWorkerId(), WORKERID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(associateQualificationWithWorkerRequest.getIntegerValue(), INTEGERVALUE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(associateQualificationWithWorkerRequest.getSendNotification(), SENDNOTIFICATION_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 {
protected Object formatObject(Object object)
{
Object formattedObject=object;
if(object==null)
{
formattedObject="";
}
else if(object instanceof String)
{
//get string
String string=(String)object;
//remove characters
string=string.replaceAll("\n","");
string=string.replaceAll("\r","");
string=string.replaceAll("\t","");
string=string.replaceAll("\f","");
string=string.replaceAll("\b","");
string=string.replaceAll("'","");
string=string.replaceAll("\"","");
//get reference
formattedObject=string;
}
else if(object instanceof File)
{
//get file
File file=(File)object;
String filePath=null;
try
{
filePath=file.getCanonicalPath();
}
catch(IOException exception)
{
throw new FaxException("Unable to get file path.",exception);
}
filePath=filePath.replaceAll("\\\\","\\\\\\\\");
//get reference
formattedObject=filePath;
}
return formattedObject;
} } | public class class_name {
protected Object formatObject(Object object)
{
Object formattedObject=object;
if(object==null)
{
formattedObject=""; // depends on control dependency: [if], data = [none]
}
else if(object instanceof String)
{
//get string
String string=(String)object;
//remove characters
string=string.replaceAll("\n",""); // depends on control dependency: [if], data = [none]
string=string.replaceAll("\r",""); // depends on control dependency: [if], data = [none]
string=string.replaceAll("\t",""); // depends on control dependency: [if], data = [none]
string=string.replaceAll("\f",""); // depends on control dependency: [if], data = [none]
string=string.replaceAll("\b",""); // depends on control dependency: [if], data = [none]
string=string.replaceAll("'",""); // depends on control dependency: [if], data = [none]
string=string.replaceAll("\"",""); // depends on control dependency: [if], data = [none]
//get reference
formattedObject=string; // depends on control dependency: [if], data = [none]
}
else if(object instanceof File)
{
//get file
File file=(File)object;
String filePath=null;
try
{
filePath=file.getCanonicalPath(); // depends on control dependency: [try], data = [none]
}
catch(IOException exception)
{
throw new FaxException("Unable to get file path.",exception);
} // depends on control dependency: [catch], data = [none]
filePath=filePath.replaceAll("\\\\","\\\\\\\\"); // depends on control dependency: [if], data = [none]
//get reference
formattedObject=filePath; // depends on control dependency: [if], data = [none]
}
return formattedObject;
} } |
public class class_name {
protected E generateMotionEvent(SensorEvent sensorEvent) {
try {
return motionDetector.getMotionEvent(sensorEvent);
}
catch (MotionDetectorException mde) {
Log.w(getClass().getSimpleName(), mde);
return null;
}
} } | public class class_name {
protected E generateMotionEvent(SensorEvent sensorEvent) {
try {
return motionDetector.getMotionEvent(sensorEvent); // depends on control dependency: [try], data = [none]
}
catch (MotionDetectorException mde) {
Log.w(getClass().getSimpleName(), mde);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void resolve(final ValueStack values) throws Exception
{
if (values.size() < 2)
throw new Exception("missing operands for " + toString());
try
{
final String tableName = values.popString();
final double baseAmount = values.popDouble();
final EquationSupport model = getEqu().getSupport();
final Hashtable<Double, Double> rateTable = model
.resolveRate(tableName, getEqu().getBaseDate(), baseAmount);
double blendedRate = 0;
/*
* only the last key in the table is used for banded rates
*/
for (final Enumeration<Double> limits = rateTable.keys(); limits.hasMoreElements();)
{
final Double limit = limits.nextElement();
blendedRate = (rateTable.get(limit)).doubleValue();
}
values.push(new Double(blendedRate));
} catch (final ParseException e)
{
e.fillInStackTrace();
throw new Exception(toString() + "; " + e.getMessage(), e);
}
} } | public class class_name {
@Override
public void resolve(final ValueStack values) throws Exception
{
if (values.size() < 2)
throw new Exception("missing operands for " + toString());
try
{
final String tableName = values.popString();
final double baseAmount = values.popDouble();
final EquationSupport model = getEqu().getSupport();
final Hashtable<Double, Double> rateTable = model
.resolveRate(tableName, getEqu().getBaseDate(), baseAmount);
double blendedRate = 0;
/*
* only the last key in the table is used for banded rates
*/
for (final Enumeration<Double> limits = rateTable.keys(); limits.hasMoreElements();)
{
final Double limit = limits.nextElement();
blendedRate = (rateTable.get(limit)).doubleValue(); // depends on control dependency: [for], data = [none]
}
values.push(new Double(blendedRate));
} catch (final ParseException e)
{
e.fillInStackTrace();
throw new Exception(toString() + "; " + e.getMessage(), e);
}
} } |
public class class_name {
private void addCdataSectionElement(String URI_and_localName, Vector v)
{
StringTokenizer tokenizer =
new StringTokenizer(URI_and_localName, "{}", false);
String s1 = tokenizer.nextToken();
String s2 = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
if (null == s2)
{
// add null URI and the local name
v.addElement(null);
v.addElement(s1);
}
else
{
// add URI, then local name
v.addElement(s1);
v.addElement(s2);
}
} } | public class class_name {
private void addCdataSectionElement(String URI_and_localName, Vector v)
{
StringTokenizer tokenizer =
new StringTokenizer(URI_and_localName, "{}", false);
String s1 = tokenizer.nextToken();
String s2 = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
if (null == s2)
{
// add null URI and the local name
v.addElement(null); // depends on control dependency: [if], data = [(null]
v.addElement(s1); // depends on control dependency: [if], data = [none]
}
else
{
// add URI, then local name
v.addElement(s1); // depends on control dependency: [if], data = [none]
v.addElement(s2); // depends on control dependency: [if], data = [s2)]
}
} } |
public class class_name {
@Override
public final CTNumDataSource getCTNumDataSourceFromCTSer(
final Object ctObjSer) {
if (ctObjSer instanceof CTPieSer) {
return ((CTPieSer) ctObjSer).getVal();
}
return null;
} } | public class class_name {
@Override
public final CTNumDataSource getCTNumDataSourceFromCTSer(
final Object ctObjSer) {
if (ctObjSer instanceof CTPieSer) {
return ((CTPieSer) ctObjSer).getVal();
// depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public void marshall(ModifyLunaClientRequest modifyLunaClientRequest, ProtocolMarshaller protocolMarshaller) {
if (modifyLunaClientRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(modifyLunaClientRequest.getClientArn(), CLIENTARN_BINDING);
protocolMarshaller.marshall(modifyLunaClientRequest.getCertificate(), CERTIFICATE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ModifyLunaClientRequest modifyLunaClientRequest, ProtocolMarshaller protocolMarshaller) {
if (modifyLunaClientRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(modifyLunaClientRequest.getClientArn(), CLIENTARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(modifyLunaClientRequest.getCertificate(), CERTIFICATE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setDirectoryServers(List<String> servers){
if(servers == null || servers.size() == 0){
return;
}
directoryServers = new DirectoryServers(servers);
connection.setDirectoryServers(directoryServers.getNextDirectoryServer());
} } | public class class_name {
public void setDirectoryServers(List<String> servers){
if(servers == null || servers.size() == 0){
return; // depends on control dependency: [if], data = [none]
}
directoryServers = new DirectoryServers(servers);
connection.setDirectoryServers(directoryServers.getNextDirectoryServer());
} } |
public class class_name {
public synchronized void save() {
if(BulkChange.contains(this)) return;
try {
getConfigFile().write(sites);
SaveableListener.fireOnChange(this, getConfigFile());
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e);
}
} } | public class class_name {
public synchronized void save() {
if(BulkChange.contains(this)) return;
try {
getConfigFile().write(sites); // depends on control dependency: [try], data = [none]
SaveableListener.fireOnChange(this, getConfigFile()); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static void buildAndDisplayAdUnitTree(AdUnit root, List<AdUnit> adUnits) {
Map<String, List<AdUnit>> treeMap = new HashMap<String, List<AdUnit>>();
for (AdUnit adUnit : adUnits) {
if (adUnit.getParentId() != null) {
if (treeMap.get(adUnit.getParentId()) == null) {
treeMap.put(adUnit.getParentId(), new ArrayList<AdUnit>());
}
treeMap.get(adUnit.getParentId()).add(adUnit);
}
}
if (root != null) {
displayInventoryTree(root, treeMap);
} else {
System.out.println("No root unit found.");
}
} } | public class class_name {
private static void buildAndDisplayAdUnitTree(AdUnit root, List<AdUnit> adUnits) {
Map<String, List<AdUnit>> treeMap = new HashMap<String, List<AdUnit>>();
for (AdUnit adUnit : adUnits) {
if (adUnit.getParentId() != null) {
if (treeMap.get(adUnit.getParentId()) == null) {
treeMap.put(adUnit.getParentId(), new ArrayList<AdUnit>()); // depends on control dependency: [if], data = [none]
}
treeMap.get(adUnit.getParentId()).add(adUnit); // depends on control dependency: [if], data = [(adUnit.getParentId()]
}
}
if (root != null) {
displayInventoryTree(root, treeMap); // depends on control dependency: [if], data = [(root]
} else {
System.out.println("No root unit found."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@FFDCIgnore(IllegalArgumentException.class)
private ProtectedString evaluateBindDnPassword(boolean immediateOnly) {
String result;
try {
result = elHelper.processString("bindDnPassword", this.idStoreDefinition.bindDnPassword(), immediateOnly, true);
} catch (IllegalArgumentException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isWarningEnabled()) {
Tr.warning(tc, "JAVAEESEC_WARNING_IDSTORE_CONFIG", new Object[] { "bindDnPassword", "" });
}
result = ""; /* Default value from spec. */
}
return (result == null) ? null : new ProtectedString(result.toCharArray());
} } | public class class_name {
@FFDCIgnore(IllegalArgumentException.class)
private ProtectedString evaluateBindDnPassword(boolean immediateOnly) {
String result;
try {
result = elHelper.processString("bindDnPassword", this.idStoreDefinition.bindDnPassword(), immediateOnly, true); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isWarningEnabled()) {
Tr.warning(tc, "JAVAEESEC_WARNING_IDSTORE_CONFIG", new Object[] { "bindDnPassword", "" }); // depends on control dependency: [if], data = [none]
}
result = ""; /* Default value from spec. */
} // depends on control dependency: [catch], data = [none]
return (result == null) ? null : new ProtectedString(result.toCharArray());
} } |
public class class_name {
protected void crawl(File file, MappedKeyEngineer<K,V> engineer)
{
if (!file.exists())
{
Debugger.println(file + " does not exist.");
return;
}
if (file.isDirectory())
{
File[] files = IO.listFiles(file, listPattern);
for (int i = 0; i < files.length; i++)
{
//recursive
if(!this.mustSkip(files[i]))
crawl(files[i],engineer);
}
}
else
{
try
{
engineer.construct(file.getPath(), this.constructMapToText(file.getPath()));
crawledPaths.add(file.getPath());
}
catch(NoDataFoundException e)
{
//print warning if found not
Debugger.printWarn(e);
}
}
} } | public class class_name {
protected void crawl(File file, MappedKeyEngineer<K,V> engineer)
{
if (!file.exists())
{
Debugger.println(file + " does not exist.");
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
if (file.isDirectory())
{
File[] files = IO.listFiles(file, listPattern);
for (int i = 0; i < files.length; i++)
{
//recursive
if(!this.mustSkip(files[i]))
crawl(files[i],engineer);
}
}
else
{
try
{
engineer.construct(file.getPath(), this.constructMapToText(file.getPath()));
// depends on control dependency: [try], data = [none]
crawledPaths.add(file.getPath());
// depends on control dependency: [try], data = [none]
}
catch(NoDataFoundException e)
{
//print warning if found not
Debugger.printWarn(e);
}
// depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public EClass getIfcGridPlacement() {
if (ifcGridPlacementEClass == null) {
ifcGridPlacementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(273);
}
return ifcGridPlacementEClass;
} } | public class class_name {
public EClass getIfcGridPlacement() {
if (ifcGridPlacementEClass == null) {
ifcGridPlacementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(273);
// depends on control dependency: [if], data = [none]
}
return ifcGridPlacementEClass;
} } |
public class class_name {
public void addEvent(FlowEvent event) throws IOException {
Put p = createPutForEvent(event);
Table eventTable = null;
try {
eventTable = hbaseConnection
.getTable(TableName.valueOf(Constants.FLOW_EVENT_TABLE));
eventTable.put(p);
} finally {
if (eventTable != null) {
eventTable.close();
}
}
} } | public class class_name {
public void addEvent(FlowEvent event) throws IOException {
Put p = createPutForEvent(event);
Table eventTable = null;
try {
eventTable = hbaseConnection
.getTable(TableName.valueOf(Constants.FLOW_EVENT_TABLE));
eventTable.put(p);
} finally {
if (eventTable != null) {
eventTable.close(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public Form getFormDefinitionById(Long formDefinitionIdParam)
{
Form form = new Form(formDefinitionIdParam);
if(this.serviceTicket != null)
{
form.setServiceTicket(this.serviceTicket);
}
return new Form(this.postJson(
form, WS.Path.FormDefinition.Version1.getById()));
} } | public class class_name {
public Form getFormDefinitionById(Long formDefinitionIdParam)
{
Form form = new Form(formDefinitionIdParam);
if(this.serviceTicket != null)
{
form.setServiceTicket(this.serviceTicket); // depends on control dependency: [if], data = [(this.serviceTicket]
}
return new Form(this.postJson(
form, WS.Path.FormDefinition.Version1.getById()));
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.