code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
void convertWith(Converter converter, String... attributes) {
for (String attribute : attributes) {
convertWith(converter, attribute);
}
} } | public class class_name {
void convertWith(Converter converter, String... attributes) {
for (String attribute : attributes) {
convertWith(converter, attribute); // depends on control dependency: [for], data = [attribute]
}
} } |
public class class_name {
private static String getColumnNameFromGetter(Method getter,Field f){
String columnName = "";
Column columnAnno = getter.getAnnotation(Column.class);
if(columnAnno != null){
//如果是列注解就读取name属性
columnName = columnAnno.name();
}
if(columnName == null || "".equals(columnName)){
//如果没有列注解就用命名方式去猜
columnName = IdUtils.toUnderscore(f.getName());
}
return columnName;
} } | public class class_name {
private static String getColumnNameFromGetter(Method getter,Field f){
String columnName = "";
Column columnAnno = getter.getAnnotation(Column.class);
if(columnAnno != null){
//如果是列注解就读取name属性
columnName = columnAnno.name(); // depends on control dependency: [if], data = [none]
}
if(columnName == null || "".equals(columnName)){
//如果没有列注解就用命名方式去猜
columnName = IdUtils.toUnderscore(f.getName()); // depends on control dependency: [if], data = [none]
}
return columnName;
} } |
public class class_name {
public T get(long duration, TimeUnit units, boolean throwException, boolean hasZF) throws InterruptedException, TimeoutException, ExecutionException {
final long startTime = System.currentTimeMillis();
boolean status = latch.await(duration, units);
if (!status) {
boolean gcPause = false;
final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
final long vmStartTime = runtimeBean.getStartTime();
final List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gcMXBean : gcMXBeans) {
if (gcMXBean instanceof com.sun.management.GarbageCollectorMXBean) {
final GcInfo lastGcInfo = ((com.sun.management.GarbageCollectorMXBean) gcMXBean).getLastGcInfo();
// If no GCs, there was no pause due to GC.
if (lastGcInfo == null) {
continue;
}
final long gcStartTime = lastGcInfo.getStartTime() + vmStartTime;
if (gcStartTime > startTime) {
gcPause = true;
final long gcDuration = lastGcInfo.getDuration();
final long pauseDuration = System.currentTimeMillis() - gcStartTime;
if (log.isDebugEnabled()) log.debug("Total GC duration = " + gcDuration + " msec.");
if (log.isDebugEnabled()) log.debug("Total pause duration due to gc event = " + pauseDuration + " msec.");
break;
}
}
}
if (!gcPause && log.isDebugEnabled()) {
log.debug("Total pause duration due to NON-GC event = " + (System.currentTimeMillis() - startTime) + " msec.");
}
// redo the same op once more since there was a chance of gc pause
status = latch.await(duration, units);
final long pauseDuration = System.currentTimeMillis() - startTime;
EVCacheMetricsFactory.getStatsTimer(appName, serverGroup, "Pause-get", gcPause ? "GC":"Scheduling", status ? "Succcess":"Fail").record(pauseDuration);
}
if (log.isDebugEnabled()) log.debug("Retry status : " + status);
if (!status) {
// whenever timeout occurs, continuous timeout counter will increase by 1.
MemcachedConnection.opTimedOut(op);
if (op != null) op.timeOut();
TagList tags = null;
if(op.getHandlingNode() instanceof EVCacheNodeImpl) {
tags = ((EVCacheNodeImpl)op.getHandlingNode()).getBaseTags();
} else {
tags = BasicTagList.of(DataSourceType.COUNTER);
}
if (!hasZF) EVCacheMetricsFactory.getCounter(appName, null, serverGroup.getName(), appName + "-get-CheckedOperationTimeout", tags).increment();
if (throwException) {
throw new CheckedOperationTimeoutException("Timed out waiting for operation", op);
}
} else {
// continuous timeout counter will be reset
MemcachedConnection.opSucceeded(op);
}
if (op != null && op.hasErrored()) {
if (throwException) {
throw new ExecutionException(op.getException());
}
}
if (isCancelled()) {
TagList tags = null;
if(op.getHandlingNode() instanceof EVCacheNodeImpl) {
tags = ((EVCacheNodeImpl)op.getHandlingNode()).getBaseTags();
} else {
tags = BasicTagList.of(DataSourceType.COUNTER);
}
if (!hasZF) EVCacheMetricsFactory.getCounter(appName, null, serverGroup.getName(), appName + "-get-Cancelled", tags).increment();
if (throwException) {
throw new ExecutionException(new CancellationException("Cancelled"));
}
}
if (op != null && op.isTimedOut()) {
// if (!hasZF) EVCacheMetricsFactory.getCounter(appName, null, serverGroup.getName(), appName + "-get-Error", DataSourceType.COUNTER).increment();
if (throwException) {
throw new ExecutionException(new CheckedOperationTimeoutException("Operation timed out.", op));
}
}
return objRef.get();
} } | public class class_name {
public T get(long duration, TimeUnit units, boolean throwException, boolean hasZF) throws InterruptedException, TimeoutException, ExecutionException {
final long startTime = System.currentTimeMillis();
boolean status = latch.await(duration, units);
if (!status) {
boolean gcPause = false;
final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
final long vmStartTime = runtimeBean.getStartTime();
final List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gcMXBean : gcMXBeans) {
if (gcMXBean instanceof com.sun.management.GarbageCollectorMXBean) {
final GcInfo lastGcInfo = ((com.sun.management.GarbageCollectorMXBean) gcMXBean).getLastGcInfo();
// If no GCs, there was no pause due to GC.
if (lastGcInfo == null) {
continue;
}
final long gcStartTime = lastGcInfo.getStartTime() + vmStartTime;
if (gcStartTime > startTime) {
gcPause = true; // depends on control dependency: [if], data = [none]
final long gcDuration = lastGcInfo.getDuration();
final long pauseDuration = System.currentTimeMillis() - gcStartTime;
if (log.isDebugEnabled()) log.debug("Total GC duration = " + gcDuration + " msec.");
if (log.isDebugEnabled()) log.debug("Total pause duration due to gc event = " + pauseDuration + " msec.");
break;
}
}
}
if (!gcPause && log.isDebugEnabled()) {
log.debug("Total pause duration due to NON-GC event = " + (System.currentTimeMillis() - startTime) + " msec."); // depends on control dependency: [if], data = [none]
}
// redo the same op once more since there was a chance of gc pause
status = latch.await(duration, units);
final long pauseDuration = System.currentTimeMillis() - startTime;
EVCacheMetricsFactory.getStatsTimer(appName, serverGroup, "Pause-get", gcPause ? "GC":"Scheduling", status ? "Succcess":"Fail").record(pauseDuration);
}
if (log.isDebugEnabled()) log.debug("Retry status : " + status);
if (!status) {
// whenever timeout occurs, continuous timeout counter will increase by 1.
MemcachedConnection.opTimedOut(op);
if (op != null) op.timeOut();
TagList tags = null;
if(op.getHandlingNode() instanceof EVCacheNodeImpl) {
tags = ((EVCacheNodeImpl)op.getHandlingNode()).getBaseTags(); // depends on control dependency: [if], data = [none]
} else {
tags = BasicTagList.of(DataSourceType.COUNTER); // depends on control dependency: [if], data = [none]
}
if (!hasZF) EVCacheMetricsFactory.getCounter(appName, null, serverGroup.getName(), appName + "-get-CheckedOperationTimeout", tags).increment();
if (throwException) {
throw new CheckedOperationTimeoutException("Timed out waiting for operation", op);
}
} else {
// continuous timeout counter will be reset
MemcachedConnection.opSucceeded(op);
}
if (op != null && op.hasErrored()) {
if (throwException) {
throw new ExecutionException(op.getException());
}
}
if (isCancelled()) {
TagList tags = null;
if(op.getHandlingNode() instanceof EVCacheNodeImpl) {
tags = ((EVCacheNodeImpl)op.getHandlingNode()).getBaseTags();
} else {
tags = BasicTagList.of(DataSourceType.COUNTER);
}
if (!hasZF) EVCacheMetricsFactory.getCounter(appName, null, serverGroup.getName(), appName + "-get-Cancelled", tags).increment();
if (throwException) {
throw new ExecutionException(new CancellationException("Cancelled"));
}
}
if (op != null && op.isTimedOut()) {
// if (!hasZF) EVCacheMetricsFactory.getCounter(appName, null, serverGroup.getName(), appName + "-get-Error", DataSourceType.COUNTER).increment();
if (throwException) {
throw new ExecutionException(new CheckedOperationTimeoutException("Operation timed out.", op));
}
}
return objRef.get();
} } |
public class class_name {
@Override
public double getReduceProcessingRate(long currentTime) {
Phase phase = getPhase();
if (phase != Phase.REDUCE) {
return 0;
}
@SuppressWarnings("deprecation")
long bytesProcessed = super.getCounters().findCounter
(Task.Counter.REDUCE_INPUT_BYTES).getCounter();
long timeSpentInReduce = 0;
long sortFinishTime = getSortFinishTime();
if (sortFinishTime >= currentTime) {
LOG.error("Sort finish time is " + sortFinishTime +
" which is >= current time " + currentTime +
" in " + this.getTaskID());
return 0;
}
timeSpentInReduce = currentTime - sortFinishTime;
reduceProcessingRate = bytesProcessed/timeSpentInReduce;
return reduceProcessingRate;
} } | public class class_name {
@Override
public double getReduceProcessingRate(long currentTime) {
Phase phase = getPhase();
if (phase != Phase.REDUCE) {
return 0; // depends on control dependency: [if], data = [none]
}
@SuppressWarnings("deprecation")
long bytesProcessed = super.getCounters().findCounter
(Task.Counter.REDUCE_INPUT_BYTES).getCounter();
long timeSpentInReduce = 0;
long sortFinishTime = getSortFinishTime();
if (sortFinishTime >= currentTime) {
LOG.error("Sort finish time is " + sortFinishTime +
" which is >= current time " + currentTime +
" in " + this.getTaskID()); // depends on control dependency: [if], data = [none]
return 0; // depends on control dependency: [if], data = [none]
}
timeSpentInReduce = currentTime - sortFinishTime;
reduceProcessingRate = bytesProcessed/timeSpentInReduce;
return reduceProcessingRate;
} } |
public class class_name {
public void setSitePath(String sitepath) {
if (!isLeafType() && !sitepath.endsWith("/")) {
sitepath = sitepath + "/";
}
m_sitePath = sitepath;
} } | public class class_name {
public void setSitePath(String sitepath) {
if (!isLeafType() && !sitepath.endsWith("/")) {
sitepath = sitepath + "/"; // depends on control dependency: [if], data = [none]
}
m_sitePath = sitepath;
} } |
public class class_name {
private OrdinalAttribute getMajorityClassification(String property, Iterable<State> examples)
throws LearningFailureException
{
/*log.fine("private OrdinalAttribute getMajorityClassification(String property, Collection<State> examples): called");*/
/*log.fine("property = " + property);*/
// Flag used to indicate that the map to hold the value counts in has been initialized.
Map<OrdinalAttribute, Integer> countMap = null;
// Used to hold the biggest count found so far.
int biggestCount = 0;
// Used to hold the value with the biggest count found so far.
OrdinalAttribute biggestAttribute = null;
// Loop over all the examples counting the number of occurences of each possible classification by the
// named property.
for (State example : examples)
{
OrdinalAttribute nextAttribute = (OrdinalAttribute) example.getProperty(property);
/*log.fine("nextAttribute = " + nextAttribute);*/
// If this is the first attribute then find out how many possible values it can take on.
if (countMap == null)
{
// A check has already been performed at the start of the learning method to ensure that the output
// property only takes on a finite number of values.
countMap = new HashMap<OrdinalAttribute, Integer>();
}
int count;
// Increment the count for the number of occurences of this classification.
if (!countMap.containsKey(nextAttribute))
{
count = 1;
countMap.put(nextAttribute, count);
}
else
{
count = countMap.get(nextAttribute);
countMap.put(nextAttribute, count++);
}
// Compare it to the biggest score found so far to see if it is bigger.
if (count > biggestCount)
{
// Update the biggest score.
biggestCount = count;
// Update the value of the majority classification.
biggestAttribute = nextAttribute;
}
}
// Return the majority classification found.
return biggestAttribute;
} } | public class class_name {
private OrdinalAttribute getMajorityClassification(String property, Iterable<State> examples)
throws LearningFailureException
{
/*log.fine("private OrdinalAttribute getMajorityClassification(String property, Collection<State> examples): called");*/
/*log.fine("property = " + property);*/
// Flag used to indicate that the map to hold the value counts in has been initialized.
Map<OrdinalAttribute, Integer> countMap = null;
// Used to hold the biggest count found so far.
int biggestCount = 0;
// Used to hold the value with the biggest count found so far.
OrdinalAttribute biggestAttribute = null;
// Loop over all the examples counting the number of occurences of each possible classification by the
// named property.
for (State example : examples)
{
OrdinalAttribute nextAttribute = (OrdinalAttribute) example.getProperty(property);
/*log.fine("nextAttribute = " + nextAttribute);*/
// If this is the first attribute then find out how many possible values it can take on.
if (countMap == null)
{
// A check has already been performed at the start of the learning method to ensure that the output
// property only takes on a finite number of values.
countMap = new HashMap<OrdinalAttribute, Integer>(); // depends on control dependency: [if], data = [none]
}
int count;
// Increment the count for the number of occurences of this classification.
if (!countMap.containsKey(nextAttribute))
{
count = 1; // depends on control dependency: [if], data = [none]
countMap.put(nextAttribute, count); // depends on control dependency: [if], data = [none]
}
else
{
count = countMap.get(nextAttribute); // depends on control dependency: [if], data = [none]
countMap.put(nextAttribute, count++); // depends on control dependency: [if], data = [none]
}
// Compare it to the biggest score found so far to see if it is bigger.
if (count > biggestCount)
{
// Update the biggest score.
biggestCount = count; // depends on control dependency: [if], data = [none]
// Update the value of the majority classification.
biggestAttribute = nextAttribute; // depends on control dependency: [if], data = [none]
}
}
// Return the majority classification found.
return biggestAttribute;
} } |
public class class_name {
@Override
public MatchResult matches(List<String> lines) {
// if the first line doesn't have '$RXN' then it can't match
if (lines.size() < 1 || !lines.get(0).contains("$RXN")) return NO_MATCH;
// check the header (fifth line)
String header = lines.size() > 4 ? lines.get(4) : "";
// atom count
if (header.length() < 3 || !Character.isDigit(header.charAt(2))) return NO_MATCH;
// bond count
if (header.length() < 6 || !Character.isDigit(header.charAt(5))) return NO_MATCH;
// check the rest of the header is only spaces and digits
if (header.length() > 6) {
String remainder = header.substring(6).trim();
for (int i = 0; i < remainder.length(); ++i) {
char c = remainder.charAt(i);
if (!(Character.isDigit(c) || Character.isWhitespace(c))) {
return NO_MATCH;
}
}
}
return new MatchResult(true, this, 0);
} } | public class class_name {
@Override
public MatchResult matches(List<String> lines) {
// if the first line doesn't have '$RXN' then it can't match
if (lines.size() < 1 || !lines.get(0).contains("$RXN")) return NO_MATCH;
// check the header (fifth line)
String header = lines.size() > 4 ? lines.get(4) : "";
// atom count
if (header.length() < 3 || !Character.isDigit(header.charAt(2))) return NO_MATCH;
// bond count
if (header.length() < 6 || !Character.isDigit(header.charAt(5))) return NO_MATCH;
// check the rest of the header is only spaces and digits
if (header.length() > 6) {
String remainder = header.substring(6).trim();
for (int i = 0; i < remainder.length(); ++i) {
char c = remainder.charAt(i);
if (!(Character.isDigit(c) || Character.isWhitespace(c))) {
return NO_MATCH; // depends on control dependency: [if], data = [none]
}
}
}
return new MatchResult(true, this, 0);
} } |
public class class_name {
static BlockCanaryInternals getInstance() {
if (sInstance == null) {
synchronized (BlockCanaryInternals.class) {
if (sInstance == null) {
sInstance = new BlockCanaryInternals();
}
}
}
return sInstance;
} } | public class class_name {
static BlockCanaryInternals getInstance() {
if (sInstance == null) {
synchronized (BlockCanaryInternals.class) { // depends on control dependency: [if], data = [none]
if (sInstance == null) {
sInstance = new BlockCanaryInternals(); // depends on control dependency: [if], data = [none]
}
}
}
return sInstance;
} } |
public class class_name {
public static Point3d centroid(Point3d[] x) {
Point3d center = new Point3d();
for (Point3d p : x) {
center.add(p);
}
center.scale(1.0 / x.length);
return center;
} } | public class class_name {
public static Point3d centroid(Point3d[] x) {
Point3d center = new Point3d();
for (Point3d p : x) {
center.add(p); // depends on control dependency: [for], data = [p]
}
center.scale(1.0 / x.length);
return center;
} } |
public class class_name {
SourcedToken getEquivalentToken(Token tok) {
if (unsourcedTokens.contains(tok.getValue())) {
for (int i=0; i<tokens.length; i++) {
if (tokens[i].getValue().equals(tok.getValue())) {
return tokens[i];
}
}
System.out.println("This is a problem");
return null;
} else {
return null;
}
} } | public class class_name {
SourcedToken getEquivalentToken(Token tok) {
if (unsourcedTokens.contains(tok.getValue())) {
for (int i=0; i<tokens.length; i++) {
if (tokens[i].getValue().equals(tok.getValue())) {
return tokens[i]; // depends on control dependency: [if], data = [none]
}
}
System.out.println("This is a problem"); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String getClusterName(Configuration conf) {
// ResourceManager address in Hadoop2
String clusterIdentifier = conf.get("yarn.resourcemanager.address");
clusterIdentifier = getClusterName(clusterIdentifier);
// If job is running outside of Hadoop (Standalone) use hostname
// If clusterIdentifier is localhost or 0.0.0.0 use hostname
if (clusterIdentifier == null || StringUtils.startsWithIgnoreCase(clusterIdentifier, "localhost")
|| StringUtils.startsWithIgnoreCase(clusterIdentifier, "0.0.0.0")) {
try {
clusterIdentifier = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
// Do nothing. Tag will not be generated
}
}
return clusterIdentifier;
} } | public class class_name {
public String getClusterName(Configuration conf) {
// ResourceManager address in Hadoop2
String clusterIdentifier = conf.get("yarn.resourcemanager.address");
clusterIdentifier = getClusterName(clusterIdentifier);
// If job is running outside of Hadoop (Standalone) use hostname
// If clusterIdentifier is localhost or 0.0.0.0 use hostname
if (clusterIdentifier == null || StringUtils.startsWithIgnoreCase(clusterIdentifier, "localhost")
|| StringUtils.startsWithIgnoreCase(clusterIdentifier, "0.0.0.0")) {
try {
clusterIdentifier = InetAddress.getLocalHost().getHostName(); // depends on control dependency: [try], data = [none]
} catch (UnknownHostException e) {
// Do nothing. Tag will not be generated
} // depends on control dependency: [catch], data = [none]
}
return clusterIdentifier;
} } |
public class class_name {
public void focusLost(FocusEvent e)
{
m_componentNextFocus = null;
Component component = (Component)e.getSource();
String string = component.getName();
FieldInfo field = null;
if (this.getFieldList() != null)
field = this.getFieldList().getField(string); // Get the fieldInfo for this component
if (field != null)
{
int iErrorCode = Constants.NORMAL_RETURN;
if (component instanceof FieldComponent)
iErrorCode = field.setData(((FieldComponent)component).getControlValue(), Constants.DISPLAY, Constants.SCREEN_MOVE);
else if (component instanceof JTextComponent)
iErrorCode = field.setString(((JTextComponent)component).getText(), Constants.DISPLAY, Constants.SCREEN_MOVE);
if (iErrorCode != Constants.NORMAL_RETURN)
{
field.displayField(); // Redisplay the old field value
m_componentNextFocus = component; // Next focus to this component
}
}
} } | public class class_name {
public void focusLost(FocusEvent e)
{
m_componentNextFocus = null;
Component component = (Component)e.getSource();
String string = component.getName();
FieldInfo field = null;
if (this.getFieldList() != null)
field = this.getFieldList().getField(string); // Get the fieldInfo for this component
if (field != null)
{
int iErrorCode = Constants.NORMAL_RETURN;
if (component instanceof FieldComponent)
iErrorCode = field.setData(((FieldComponent)component).getControlValue(), Constants.DISPLAY, Constants.SCREEN_MOVE);
else if (component instanceof JTextComponent)
iErrorCode = field.setString(((JTextComponent)component).getText(), Constants.DISPLAY, Constants.SCREEN_MOVE);
if (iErrorCode != Constants.NORMAL_RETURN)
{
field.displayField(); // Redisplay the old field value // depends on control dependency: [if], data = [none]
m_componentNextFocus = component; // Next focus to this component // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static Method getDeclaredMethod(Class<?> type, String methodName, Class<?>... parameterTypes) {
Method method = null;
try {
method = type.getDeclaredMethod(methodName, parameterTypes);
if(method.isBridge()){
method = MethodProvider.getInstance().unbride(method, type);
}
} catch (NoSuchMethodException e) {
Class<?> superclass = type.getSuperclass();
if (superclass != null) {
method = getDeclaredMethod(superclass, methodName, parameterTypes);
}
} catch (ClassNotFoundException e) {
Throwables.propagate(e);
} catch (IOException e) {
Throwables.propagate(e);
}
return method;
} } | public class class_name {
public static Method getDeclaredMethod(Class<?> type, String methodName, Class<?>... parameterTypes) {
Method method = null;
try {
method = type.getDeclaredMethod(methodName, parameterTypes); // depends on control dependency: [try], data = [none]
if(method.isBridge()){
method = MethodProvider.getInstance().unbride(method, type); // depends on control dependency: [if], data = [none]
}
} catch (NoSuchMethodException e) {
Class<?> superclass = type.getSuperclass();
if (superclass != null) {
method = getDeclaredMethod(superclass, methodName, parameterTypes); // depends on control dependency: [if], data = [(superclass]
}
} catch (ClassNotFoundException e) { // depends on control dependency: [catch], data = [none]
Throwables.propagate(e);
} catch (IOException e) { // depends on control dependency: [catch], data = [none]
Throwables.propagate(e);
} // depends on control dependency: [catch], data = [none]
return method;
} } |
public class class_name {
private Integer createObjectAndRegisterPrefix(String field, IndexOutput out,
BytesRef term, Long termRef, int startPosition, BytesRef payload,
Integer startOffset, Integer endOffset, IndexOutput outPrefix)
throws IOException {
try {
Integer mtasId = null;
String prefix = MtasToken.getPrefixFromValue(term.utf8ToString());
if (payload != null) {
MtasPayloadDecoder payloadDecoder = new MtasPayloadDecoder();
payloadDecoder.init(startPosition, Arrays.copyOfRange(payload.bytes,
payload.offset, (payload.offset + payload.length)));
mtasId = payloadDecoder.getMtasId();
Integer mtasParentId = payloadDecoder.getMtasParentId();
byte[] mtasPayload = payloadDecoder.getMtasPayload();
MtasPosition mtasPosition = payloadDecoder.getMtasPosition();
MtasOffset mtasOffset = payloadDecoder.getMtasOffset();
if (mtasOffset == null && startOffset != null) {
mtasOffset = new MtasOffset(startOffset, endOffset);
}
MtasOffset mtasRealOffset = payloadDecoder.getMtasRealOffset();
// only if really mtas object
if (mtasId != null) {
// compute flags
int objectFlags = 0;
if (mtasPosition != null) {
if (mtasPosition.checkType(MtasPosition.POSITION_RANGE)) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_RANGE;
registerPrefixStatsRangePositionValue(field, prefix, outPrefix);
} else if (mtasPosition.checkType(MtasPosition.POSITION_SET)) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_SET;
registerPrefixStatsSetPositionValue(field, prefix, outPrefix);
} else {
registerPrefixStatsSinglePositionValue(field, prefix, outPrefix);
}
} else {
throw new IOException("no position");
}
if (mtasParentId != null) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PARENT;
}
if (mtasOffset != null) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_OFFSET;
}
if (mtasRealOffset != null) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_REALOFFSET;
}
if (mtasPayload != null) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PAYLOAD;
}
// create object
out.writeVInt(mtasId);
out.writeVInt(objectFlags);
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PARENT) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PARENT) {
out.writeVInt(mtasParentId);
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_RANGE) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_RANGE) {
int tmpStart = mtasPosition.getStart();
out.writeVInt(tmpStart);
out.writeVInt((mtasPosition.getEnd() - tmpStart));
} else if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_SET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_SET) {
int[] positions = mtasPosition.getPositions();
out.writeVInt(positions.length);
int tmpPrevious = 0;
for (int position : positions) {
out.writeVInt((position - tmpPrevious));
tmpPrevious = position;
}
} else {
out.writeVInt(mtasPosition.getStart());
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_OFFSET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_OFFSET) {
int tmpStart = mtasOffset.getStart();
out.writeVInt(mtasOffset.getStart());
out.writeVInt((mtasOffset.getEnd() - tmpStart));
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_REALOFFSET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_REALOFFSET) {
int tmpStart = mtasRealOffset.getStart();
out.writeVInt(mtasRealOffset.getStart());
out.writeVInt((mtasRealOffset.getEnd() - tmpStart));
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PAYLOAD) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PAYLOAD) {
if (mtasPayload != null) {
out.writeVInt(mtasPayload.length);
out.writeBytes(mtasPayload, mtasPayload.length);
} else {
out.writeVInt(0);
}
}
out.writeVLong(termRef);
} // storage token
}
return mtasId;
} catch (Exception e) {
log.error(e);
throw new IOException(e);
}
} } | public class class_name {
private Integer createObjectAndRegisterPrefix(String field, IndexOutput out,
BytesRef term, Long termRef, int startPosition, BytesRef payload,
Integer startOffset, Integer endOffset, IndexOutput outPrefix)
throws IOException {
try {
Integer mtasId = null;
String prefix = MtasToken.getPrefixFromValue(term.utf8ToString());
if (payload != null) {
MtasPayloadDecoder payloadDecoder = new MtasPayloadDecoder();
payloadDecoder.init(startPosition, Arrays.copyOfRange(payload.bytes,
payload.offset, (payload.offset + payload.length)));
mtasId = payloadDecoder.getMtasId();
Integer mtasParentId = payloadDecoder.getMtasParentId();
byte[] mtasPayload = payloadDecoder.getMtasPayload();
MtasPosition mtasPosition = payloadDecoder.getMtasPosition();
MtasOffset mtasOffset = payloadDecoder.getMtasOffset();
if (mtasOffset == null && startOffset != null) {
mtasOffset = new MtasOffset(startOffset, endOffset);
}
MtasOffset mtasRealOffset = payloadDecoder.getMtasRealOffset();
// only if really mtas object
if (mtasId != null) {
// compute flags
int objectFlags = 0;
if (mtasPosition != null) {
if (mtasPosition.checkType(MtasPosition.POSITION_RANGE)) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_RANGE; // depends on control dependency: [if], data = [none]
registerPrefixStatsRangePositionValue(field, prefix, outPrefix); // depends on control dependency: [if], data = [none]
} else if (mtasPosition.checkType(MtasPosition.POSITION_SET)) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_SET; // depends on control dependency: [if], data = [none]
registerPrefixStatsSetPositionValue(field, prefix, outPrefix); // depends on control dependency: [if], data = [none]
} else {
registerPrefixStatsSinglePositionValue(field, prefix, outPrefix); // depends on control dependency: [if], data = [none]
}
} else {
throw new IOException("no position");
}
if (mtasParentId != null) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PARENT;
}
if (mtasOffset != null) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_OFFSET;
}
if (mtasRealOffset != null) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_REALOFFSET;
}
if (mtasPayload != null) {
objectFlags = objectFlags
| MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PAYLOAD;
}
// create object
out.writeVInt(mtasId);
out.writeVInt(objectFlags);
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PARENT) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PARENT) {
out.writeVInt(mtasParentId);
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_RANGE) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_RANGE) {
int tmpStart = mtasPosition.getStart();
out.writeVInt(tmpStart);
out.writeVInt((mtasPosition.getEnd() - tmpStart));
} else if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_SET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_POSITION_SET) {
int[] positions = mtasPosition.getPositions();
out.writeVInt(positions.length);
int tmpPrevious = 0;
for (int position : positions) {
out.writeVInt((position - tmpPrevious)); // depends on control dependency: [for], data = [position]
tmpPrevious = position; // depends on control dependency: [for], data = [position]
}
} else {
out.writeVInt(mtasPosition.getStart());
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_OFFSET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_OFFSET) {
int tmpStart = mtasOffset.getStart();
out.writeVInt(mtasOffset.getStart());
out.writeVInt((mtasOffset.getEnd() - tmpStart));
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_REALOFFSET) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_REALOFFSET) {
int tmpStart = mtasRealOffset.getStart();
out.writeVInt(mtasRealOffset.getStart());
out.writeVInt((mtasRealOffset.getEnd() - tmpStart));
}
if ((objectFlags
& MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PAYLOAD) == MtasCodecPostingsFormat.MTAS_OBJECT_HAS_PAYLOAD) {
if (mtasPayload != null) {
out.writeVInt(mtasPayload.length); // depends on control dependency: [if], data = [(mtasPayload]
out.writeBytes(mtasPayload, mtasPayload.length); // depends on control dependency: [if], data = [(mtasPayload]
} else {
out.writeVInt(0); // depends on control dependency: [if], data = [none]
}
}
out.writeVLong(termRef);
} // storage token
}
return mtasId;
} catch (Exception e) {
log.error(e);
throw new IOException(e);
}
} } |
public class class_name {
public void updateAddresses(List<EquivalentAddressGroup> newAddressGroups) {
Preconditions.checkNotNull(newAddressGroups, "newAddressGroups");
checkListHasNoNulls(newAddressGroups, "newAddressGroups contains null entry");
Preconditions.checkArgument(!newAddressGroups.isEmpty(), "newAddressGroups is empty");
newAddressGroups =
Collections.unmodifiableList(new ArrayList<>(newAddressGroups));
ManagedClientTransport savedTransport = null;
try {
synchronized (lock) {
SocketAddress previousAddress = addressIndex.getCurrentAddress();
addressIndex.updateGroups(newAddressGroups);
if (state.getState() == READY || state.getState() == CONNECTING) {
if (!addressIndex.seekTo(previousAddress)) {
// Forced to drop the connection
if (state.getState() == READY) {
savedTransport = activeTransport;
activeTransport = null;
addressIndex.reset();
gotoNonErrorState(IDLE);
} else {
savedTransport = pendingTransport;
pendingTransport = null;
addressIndex.reset();
startNewTransport();
}
}
}
}
} finally {
syncContext.drain();
}
if (savedTransport != null) {
savedTransport.shutdown(
Status.UNAVAILABLE.withDescription(
"InternalSubchannel closed transport due to address change"));
}
} } | public class class_name {
public void updateAddresses(List<EquivalentAddressGroup> newAddressGroups) {
Preconditions.checkNotNull(newAddressGroups, "newAddressGroups");
checkListHasNoNulls(newAddressGroups, "newAddressGroups contains null entry");
Preconditions.checkArgument(!newAddressGroups.isEmpty(), "newAddressGroups is empty");
newAddressGroups =
Collections.unmodifiableList(new ArrayList<>(newAddressGroups));
ManagedClientTransport savedTransport = null;
try {
synchronized (lock) { // depends on control dependency: [try], data = [none]
SocketAddress previousAddress = addressIndex.getCurrentAddress();
addressIndex.updateGroups(newAddressGroups);
if (state.getState() == READY || state.getState() == CONNECTING) {
if (!addressIndex.seekTo(previousAddress)) {
// Forced to drop the connection
if (state.getState() == READY) {
savedTransport = activeTransport; // depends on control dependency: [if], data = [none]
activeTransport = null; // depends on control dependency: [if], data = [none]
addressIndex.reset(); // depends on control dependency: [if], data = [none]
gotoNonErrorState(IDLE); // depends on control dependency: [if], data = [none]
} else {
savedTransport = pendingTransport; // depends on control dependency: [if], data = [none]
pendingTransport = null; // depends on control dependency: [if], data = [none]
addressIndex.reset(); // depends on control dependency: [if], data = [none]
startNewTransport(); // depends on control dependency: [if], data = [none]
}
}
}
}
} finally {
syncContext.drain();
}
if (savedTransport != null) {
savedTransport.shutdown(
Status.UNAVAILABLE.withDescription(
"InternalSubchannel closed transport due to address change")); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void initializeUnknownCategoricalsPerColumn(GenModel model) {
unknownCategoricalsPerColumn = new ConcurrentHashMap<>();
for (int i = 0; i < model.getNumCols(); i++) {
String[] domainValues = model.getDomainValues(i);
if (domainValues != null) {
unknownCategoricalsPerColumn.put(model.getNames()[i], new AtomicLong());
}
}
unknownCategoricalsPerColumn = Collections.unmodifiableMap(unknownCategoricalsPerColumn);
} } | public class class_name {
private void initializeUnknownCategoricalsPerColumn(GenModel model) {
unknownCategoricalsPerColumn = new ConcurrentHashMap<>();
for (int i = 0; i < model.getNumCols(); i++) {
String[] domainValues = model.getDomainValues(i);
if (domainValues != null) {
unknownCategoricalsPerColumn.put(model.getNames()[i], new AtomicLong()); // depends on control dependency: [if], data = [none]
}
}
unknownCategoricalsPerColumn = Collections.unmodifiableMap(unknownCategoricalsPerColumn);
} } |
public class class_name {
private static double getSegDistSq(double px, double py, Coordinate a, Coordinate b) {
double x = a.x;
double y = a.y;
double dx = b.x - x;
double dy = b.y - y;
if (dx != 0f || dy != 0f) {
double t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = b.x;
y = b.y;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = px - x;
dy = py - y;
return dx * dx + dy * dy;
} } | public class class_name {
private static double getSegDistSq(double px, double py, Coordinate a, Coordinate b) {
double x = a.x;
double y = a.y;
double dx = b.x - x;
double dy = b.y - y;
if (dx != 0f || dy != 0f) {
double t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = b.x; // depends on control dependency: [if], data = [none]
y = b.y; // depends on control dependency: [if], data = [none]
} else if (t > 0) {
x += dx * t; // depends on control dependency: [if], data = [none]
y += dy * t; // depends on control dependency: [if], data = [none]
}
}
dx = px - x;
dy = py - y;
return dx * dx + dy * dy;
} } |
public class class_name {
protected String genCountStatement() {
StringBuilder countString = new StringBuilder("select count(*) ");
// 原始查询语句
final String genQueryStr = genQueryStatement(false);
if (isEmpty(genQueryStr)) { return ""; }
final String lowerCaseQueryStr = genQueryStr.toLowerCase();
if (contains(lowerCaseQueryStr, " group ")) { return ""; }
if (contains(lowerCaseQueryStr, " union ")) { return ""; }
final int indexOfFrom = findIndexOfFrom(lowerCaseQueryStr);
final String selectWhat = lowerCaseQueryStr.substring(0, indexOfFrom);
final int indexOfDistinct = selectWhat.indexOf("distinct");
// select distinct a from table;
if (-1 != indexOfDistinct) {
if (contains(selectWhat, ",")) {
return "";
} else {
countString = new StringBuilder("select count(");
countString.append(genQueryStr.substring(indexOfDistinct, indexOfFrom)).append(") ");
}
}
int orderIdx = genQueryStr.lastIndexOf(" order ");
if (-1 == orderIdx) orderIdx = genQueryStr.length();
countString.append(genQueryStr.substring(indexOfFrom, orderIdx));
return countString.toString();
} } | public class class_name {
protected String genCountStatement() {
StringBuilder countString = new StringBuilder("select count(*) ");
// 原始查询语句
final String genQueryStr = genQueryStatement(false);
if (isEmpty(genQueryStr)) { return ""; } // depends on control dependency: [if], data = [none]
final String lowerCaseQueryStr = genQueryStr.toLowerCase();
if (contains(lowerCaseQueryStr, " group ")) { return ""; } // depends on control dependency: [if], data = [none]
if (contains(lowerCaseQueryStr, " union ")) { return ""; } // depends on control dependency: [if], data = [none]
final int indexOfFrom = findIndexOfFrom(lowerCaseQueryStr);
final String selectWhat = lowerCaseQueryStr.substring(0, indexOfFrom);
final int indexOfDistinct = selectWhat.indexOf("distinct");
// select distinct a from table;
if (-1 != indexOfDistinct) {
if (contains(selectWhat, ",")) {
return ""; // depends on control dependency: [if], data = [none]
} else {
countString = new StringBuilder("select count("); // depends on control dependency: [if], data = [none]
countString.append(genQueryStr.substring(indexOfDistinct, indexOfFrom)).append(") "); // depends on control dependency: [if], data = [none]
}
}
int orderIdx = genQueryStr.lastIndexOf(" order ");
if (-1 == orderIdx) orderIdx = genQueryStr.length();
countString.append(genQueryStr.substring(indexOfFrom, orderIdx));
return countString.toString();
} } |
public class class_name {
private MediaType getStorageMediaType(Configuration configuration, boolean embeddedMode) {
EncodingConfiguration encodingConfiguration = configuration.encoding();
ContentTypeConfiguration contentTypeConfiguration = isKey ? encodingConfiguration.keyDataType() : encodingConfiguration.valueDataType();
// If explicitly configured, use the value provided
if (contentTypeConfiguration.isMediaTypeChanged()) {
return contentTypeConfiguration.mediaType();
}
// Indexed caches started by the server will assume application/protostream as storage media type
if (!embeddedMode && configuration.indexing().index().isEnabled() && contentTypeConfiguration.mediaType() == null) {
return MediaType.APPLICATION_PROTOSTREAM;
}
return MediaType.APPLICATION_UNKNOWN;
} } | public class class_name {
private MediaType getStorageMediaType(Configuration configuration, boolean embeddedMode) {
EncodingConfiguration encodingConfiguration = configuration.encoding();
ContentTypeConfiguration contentTypeConfiguration = isKey ? encodingConfiguration.keyDataType() : encodingConfiguration.valueDataType();
// If explicitly configured, use the value provided
if (contentTypeConfiguration.isMediaTypeChanged()) {
return contentTypeConfiguration.mediaType(); // depends on control dependency: [if], data = [none]
}
// Indexed caches started by the server will assume application/protostream as storage media type
if (!embeddedMode && configuration.indexing().index().isEnabled() && contentTypeConfiguration.mediaType() == null) {
return MediaType.APPLICATION_PROTOSTREAM; // depends on control dependency: [if], data = [none]
}
return MediaType.APPLICATION_UNKNOWN;
} } |
public class class_name {
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
{
String lang = m_arg0.execute(xctxt).str();
int parent = xctxt.getCurrentNode();
boolean isLang = false;
DTM dtm = xctxt.getDTM(parent);
while (DTM.NULL != parent)
{
if (DTM.ELEMENT_NODE == dtm.getNodeType(parent))
{
int langAttr = dtm.getAttributeNode(parent, "http://www.w3.org/XML/1998/namespace", "lang");
if (DTM.NULL != langAttr)
{
String langVal = dtm.getNodeValue(langAttr);
// %OPT%
if (langVal.toLowerCase().startsWith(lang.toLowerCase()))
{
int valLen = lang.length();
if ((langVal.length() == valLen)
|| (langVal.charAt(valLen) == '-'))
{
isLang = true;
}
}
break;
}
}
parent = dtm.getParent(parent);
}
return isLang ? XBoolean.S_TRUE : XBoolean.S_FALSE;
} } | public class class_name {
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
{
String lang = m_arg0.execute(xctxt).str();
int parent = xctxt.getCurrentNode();
boolean isLang = false;
DTM dtm = xctxt.getDTM(parent);
while (DTM.NULL != parent)
{
if (DTM.ELEMENT_NODE == dtm.getNodeType(parent))
{
int langAttr = dtm.getAttributeNode(parent, "http://www.w3.org/XML/1998/namespace", "lang");
if (DTM.NULL != langAttr)
{
String langVal = dtm.getNodeValue(langAttr);
// %OPT%
if (langVal.toLowerCase().startsWith(lang.toLowerCase()))
{
int valLen = lang.length();
if ((langVal.length() == valLen)
|| (langVal.charAt(valLen) == '-'))
{
isLang = true; // depends on control dependency: [if], data = [none]
}
}
break;
}
}
parent = dtm.getParent(parent);
}
return isLang ? XBoolean.S_TRUE : XBoolean.S_FALSE;
} } |
public class class_name {
@Override
public int[] doBatch(final SqlContext sqlContext, final PreparedStatement preparedStatement, final int[] result) {
if (LOG.isDebugEnabled()) {
int[] counts = result;
try {
counts = new int[] { preparedStatement.getUpdateCount() };
} catch (SQLException ex) {
ex.printStackTrace();
}
StringBuilder builder = new StringBuilder();
for (int val : counts) {
builder.append(val).append(", ");
}
LOG.debug("SQL:{} executed. Result:{}", sqlContext.getSqlName(), builder.toString());
}
return result;
} } | public class class_name {
@Override
public int[] doBatch(final SqlContext sqlContext, final PreparedStatement preparedStatement, final int[] result) {
if (LOG.isDebugEnabled()) {
int[] counts = result;
try {
counts = new int[] { preparedStatement.getUpdateCount() }; // depends on control dependency: [try], data = [none]
} catch (SQLException ex) {
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
StringBuilder builder = new StringBuilder();
for (int val : counts) {
builder.append(val).append(", "); // depends on control dependency: [for], data = [val]
}
LOG.debug("SQL:{} executed. Result:{}", sqlContext.getSqlName(), builder.toString()); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
private void textFieldSearchTextKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldSearchTextKeyPressed
switch (evt.getKeyCode()) {
case KeyEvent.VK_ESCAPE: {
this.setVisible(false);
this.baseEditor.requestActive();
evt.consume();
}
break;
case KeyEvent.VK_ENTER: {
if (evt.isShiftDown()) {
findPrev();
} else {
findNext();
}
evt.consume();
}
break;
}
} } | public class class_name {
private void textFieldSearchTextKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldSearchTextKeyPressed
switch (evt.getKeyCode()) {
case KeyEvent.VK_ESCAPE: {
this.setVisible(false);
this.baseEditor.requestActive();
evt.consume();
}
break;
case KeyEvent.VK_ENTER: {
if (evt.isShiftDown()) {
findPrev(); // depends on control dependency: [if], data = [none]
} else {
findNext(); // depends on control dependency: [if], data = [none]
}
evt.consume();
}
break;
}
} } |
public class class_name {
public void marshall(DescribeEffectiveInstanceAssociationsRequest describeEffectiveInstanceAssociationsRequest, ProtocolMarshaller protocolMarshaller) {
if (describeEffectiveInstanceAssociationsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeEffectiveInstanceAssociationsRequest.getInstanceId(), INSTANCEID_BINDING);
protocolMarshaller.marshall(describeEffectiveInstanceAssociationsRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(describeEffectiveInstanceAssociationsRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DescribeEffectiveInstanceAssociationsRequest describeEffectiveInstanceAssociationsRequest, ProtocolMarshaller protocolMarshaller) {
if (describeEffectiveInstanceAssociationsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeEffectiveInstanceAssociationsRequest.getInstanceId(), INSTANCEID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(describeEffectiveInstanceAssociationsRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(describeEffectiveInstanceAssociationsRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private Registration getRegistration(EventEnvelope eventEnvelope, String serviceName) {
EventServiceSegment segment = eventService.getSegment(serviceName, false);
if (segment == null) {
if (eventService.nodeEngine.isRunning()) {
eventService.logger.warning("No service registration found for " + serviceName);
}
return null;
}
String id = eventEnvelope.getEventId();
Registration registration = (Registration) segment.getRegistrationIdMap().get(id);
if (registration == null) {
if (eventService.nodeEngine.isRunning()) {
if (eventService.logger.isFinestEnabled()) {
eventService.logger.finest("No registration found for " + serviceName + " / " + id);
}
}
return null;
}
if (!eventService.isLocal(registration)) {
eventService.logger.severe("Invalid target for " + registration);
return null;
}
if (registration.getListener() == null) {
eventService.logger.warning("Something seems wrong! Subscriber is local but listener instance is null! -> "
+ registration);
return null;
}
return registration;
} } | public class class_name {
private Registration getRegistration(EventEnvelope eventEnvelope, String serviceName) {
EventServiceSegment segment = eventService.getSegment(serviceName, false);
if (segment == null) {
if (eventService.nodeEngine.isRunning()) {
eventService.logger.warning("No service registration found for " + serviceName); // depends on control dependency: [if], data = [none]
}
return null; // depends on control dependency: [if], data = [none]
}
String id = eventEnvelope.getEventId();
Registration registration = (Registration) segment.getRegistrationIdMap().get(id);
if (registration == null) {
if (eventService.nodeEngine.isRunning()) {
if (eventService.logger.isFinestEnabled()) {
eventService.logger.finest("No registration found for " + serviceName + " / " + id); // depends on control dependency: [if], data = [none]
}
}
return null; // depends on control dependency: [if], data = [none]
}
if (!eventService.isLocal(registration)) {
eventService.logger.severe("Invalid target for " + registration);
return null;
}
if (registration.getListener() == null) {
eventService.logger.warning("Something seems wrong! Subscriber is local but listener instance is null! -> "
+ registration);
return null;
}
return registration;
} } |
public class class_name {
public void collectVariables(EnvVars env, Run build, TaskListener listener) {
EnvVars buildParameters = Utils.extractBuildParameters(build, listener);
if (buildParameters != null) {
env.putAll(buildParameters);
}
addAllWithFilter(envVars, env, filter.getPatternFilter());
Map<String, String> sysEnv = new HashMap<>();
Properties systemProperties = System.getProperties();
Enumeration<?> enumeration = systemProperties.propertyNames();
while (enumeration.hasMoreElements()) {
String propertyKey = (String) enumeration.nextElement();
sysEnv.put(propertyKey, systemProperties.getProperty(propertyKey));
}
addAllWithFilter(sysVars, sysEnv, filter.getPatternFilter());
} } | public class class_name {
public void collectVariables(EnvVars env, Run build, TaskListener listener) {
EnvVars buildParameters = Utils.extractBuildParameters(build, listener);
if (buildParameters != null) {
env.putAll(buildParameters); // depends on control dependency: [if], data = [(buildParameters]
}
addAllWithFilter(envVars, env, filter.getPatternFilter());
Map<String, String> sysEnv = new HashMap<>();
Properties systemProperties = System.getProperties();
Enumeration<?> enumeration = systemProperties.propertyNames();
while (enumeration.hasMoreElements()) {
String propertyKey = (String) enumeration.nextElement();
sysEnv.put(propertyKey, systemProperties.getProperty(propertyKey)); // depends on control dependency: [while], data = [none]
}
addAllWithFilter(sysVars, sysEnv, filter.getPatternFilter());
} } |
public class class_name {
public boolean set(Object value, long seconds) {
if (value == null)
return false;
try {
boolean result = false;
if(isCluster(groupName)){
result = getBinaryJedisClusterCommands(groupName).set(keyBytes, valueSerialize(value)).equals(RESP_OK);
}else{
result = getBinaryJedisCommands(groupName).set(keyBytes, valueSerialize(value)).equals(RESP_OK);
}
if(result){
result = setExpire(seconds);
//set可能是更新缓存,所以统一通知各节点清除本地缓存
Level1CacheSupport.getInstance().publishSyncEvent(key);
}
return result;
} finally {
getJedisProvider(groupName).release();
}
} } | public class class_name {
public boolean set(Object value, long seconds) {
if (value == null)
return false;
try {
boolean result = false;
if(isCluster(groupName)){
result = getBinaryJedisClusterCommands(groupName).set(keyBytes, valueSerialize(value)).equals(RESP_OK); // depends on control dependency: [if], data = [none]
}else{
result = getBinaryJedisCommands(groupName).set(keyBytes, valueSerialize(value)).equals(RESP_OK); // depends on control dependency: [if], data = [none]
}
if(result){
result = setExpire(seconds); // depends on control dependency: [if], data = [none]
//set可能是更新缓存,所以统一通知各节点清除本地缓存
Level1CacheSupport.getInstance().publishSyncEvent(key); // depends on control dependency: [if], data = [none]
}
return result; // depends on control dependency: [try], data = [none]
} finally {
getJedisProvider(groupName).release();
}
} } |
public class class_name {
public static ByteMap<byte[]> getTagUids(final byte[] row) {
final ByteMap<byte[]> uids = new ByteMap<byte[]>();
final short name_width = TSDB.tagk_width();
final short value_width = TSDB.tagv_width();
final short tag_bytes = (short) (name_width + value_width);
final short metric_ts_bytes = (short) (TSDB.metrics_width()
+ Const.TIMESTAMP_BYTES
+ Const.SALT_WIDTH());
for (short pos = metric_ts_bytes; pos < row.length; pos += tag_bytes) {
final byte[] tmp_name = new byte[name_width];
final byte[] tmp_value = new byte[value_width];
System.arraycopy(row, pos, tmp_name, 0, name_width);
System.arraycopy(row, pos + name_width, tmp_value, 0, value_width);
uids.put(tmp_name, tmp_value);
}
return uids;
} } | public class class_name {
public static ByteMap<byte[]> getTagUids(final byte[] row) {
final ByteMap<byte[]> uids = new ByteMap<byte[]>();
final short name_width = TSDB.tagk_width();
final short value_width = TSDB.tagv_width();
final short tag_bytes = (short) (name_width + value_width);
final short metric_ts_bytes = (short) (TSDB.metrics_width()
+ Const.TIMESTAMP_BYTES
+ Const.SALT_WIDTH());
for (short pos = metric_ts_bytes; pos < row.length; pos += tag_bytes) {
final byte[] tmp_name = new byte[name_width];
final byte[] tmp_value = new byte[value_width];
System.arraycopy(row, pos, tmp_name, 0, name_width); // depends on control dependency: [for], data = [pos]
System.arraycopy(row, pos + name_width, tmp_value, 0, value_width); // depends on control dependency: [for], data = [pos]
uids.put(tmp_name, tmp_value); // depends on control dependency: [for], data = [none]
}
return uids;
} } |
public class class_name {
private double[][] computeLookupADC(double[] qVector) {
double[][] distances = new double[numSubVectors][numProductCentroids];
for (int i = 0; i < numSubVectors; i++) {
int subVectorStart = i * subVectorLength;
for (int j = 0; j < numProductCentroids; j++) {
for (int k = 0; k < subVectorLength; k++) {
distances[i][j] += (qVector[subVectorStart + k] - productQuantizer[i][j][k])
* (qVector[subVectorStart + k] - productQuantizer[i][j][k]);
}
}
}
return distances;
} } | public class class_name {
private double[][] computeLookupADC(double[] qVector) {
double[][] distances = new double[numSubVectors][numProductCentroids];
for (int i = 0; i < numSubVectors; i++) {
int subVectorStart = i * subVectorLength;
for (int j = 0; j < numProductCentroids; j++) {
for (int k = 0; k < subVectorLength; k++) {
distances[i][j] += (qVector[subVectorStart + k] - productQuantizer[i][j][k])
* (qVector[subVectorStart + k] - productQuantizer[i][j][k]);
// depends on control dependency: [for], data = [k]
}
}
}
return distances;
} } |
public class class_name {
@Override
protected void initParser() throws MtasConfigException {
super.initParser();
if (config != null) {
// always word, no mappings
wordType = new MtasParserType<>(MAPPING_TYPE_WORD, null, false);
for (int i = 0; i < config.children.size(); i++) {
MtasConfiguration current = config.children.get(i);
if (current.name.equals("mappings")) {
for (int j = 0; j < current.children.size(); j++) {
if (current.children.get(j).name.equals("mapping")) {
MtasConfiguration mapping = current.children.get(j);
String typeMapping = mapping.attributes.get("type");
String nameMapping = mapping.attributes.get("name");
if ((typeMapping != null)) {
if (typeMapping.equals(MAPPING_TYPE_WORD)) {
MtasSketchParserMappingWord m = new MtasSketchParserMappingWord();
m.processConfig(mapping);
wordType.addItem(m);
} else if (typeMapping.equals(MAPPING_TYPE_WORD_ANNOTATION)
&& (nameMapping != null)) {
MtasSketchParserMappingWordAnnotation m = new MtasSketchParserMappingWordAnnotation();
m.processConfig(mapping);
if (wordAnnotationTypes
.containsKey(Integer.parseInt(nameMapping))) {
wordAnnotationTypes.get(Integer.parseInt(nameMapping))
.addItem(m);
} else {
MtasParserType<MtasParserMapping<?>> t = new MtasParserType<>(
typeMapping, nameMapping, false);
t.addItem(m);
wordAnnotationTypes.put(Integer.parseInt(nameMapping), t);
}
} else if (typeMapping.equals(MAPPING_TYPE_GROUP)
&& (nameMapping != null)) {
MtasSketchParserMappingGroup m = new MtasSketchParserMappingGroup();
m.processConfig(mapping);
if (groupTypes.containsKey(nameMapping)) {
groupTypes.get(nameMapping).addItem(m);
} else {
MtasParserType<MtasParserMapping<?>> t = new MtasParserType<>(
typeMapping, nameMapping, false);
t.addItem(m);
groupTypes.put(nameMapping, t);
}
} else {
throw new MtasConfigException("unknown mapping type "
+ typeMapping + " or missing name");
}
}
}
}
}
}
}
} } | public class class_name {
@Override
protected void initParser() throws MtasConfigException {
super.initParser();
if (config != null) {
// always word, no mappings
wordType = new MtasParserType<>(MAPPING_TYPE_WORD, null, false);
for (int i = 0; i < config.children.size(); i++) {
MtasConfiguration current = config.children.get(i);
if (current.name.equals("mappings")) {
for (int j = 0; j < current.children.size(); j++) {
if (current.children.get(j).name.equals("mapping")) {
MtasConfiguration mapping = current.children.get(j);
String typeMapping = mapping.attributes.get("type");
String nameMapping = mapping.attributes.get("name");
if ((typeMapping != null)) {
if (typeMapping.equals(MAPPING_TYPE_WORD)) {
MtasSketchParserMappingWord m = new MtasSketchParserMappingWord();
m.processConfig(mapping); // depends on control dependency: [if], data = [none]
wordType.addItem(m); // depends on control dependency: [if], data = [none]
} else if (typeMapping.equals(MAPPING_TYPE_WORD_ANNOTATION)
&& (nameMapping != null)) {
MtasSketchParserMappingWordAnnotation m = new MtasSketchParserMappingWordAnnotation();
m.processConfig(mapping); // depends on control dependency: [if], data = [none]
if (wordAnnotationTypes
.containsKey(Integer.parseInt(nameMapping))) {
wordAnnotationTypes.get(Integer.parseInt(nameMapping))
.addItem(m); // depends on control dependency: [if], data = [none]
} else {
MtasParserType<MtasParserMapping<?>> t = new MtasParserType<>(
typeMapping, nameMapping, false); // depends on control dependency: [if], data = [none]
t.addItem(m); // depends on control dependency: [if], data = [none]
wordAnnotationTypes.put(Integer.parseInt(nameMapping), t); // depends on control dependency: [if], data = [none]
}
} else if (typeMapping.equals(MAPPING_TYPE_GROUP)
&& (nameMapping != null)) {
MtasSketchParserMappingGroup m = new MtasSketchParserMappingGroup();
m.processConfig(mapping); // depends on control dependency: [if], data = [none]
if (groupTypes.containsKey(nameMapping)) {
groupTypes.get(nameMapping).addItem(m); // depends on control dependency: [if], data = [none]
} else {
MtasParserType<MtasParserMapping<?>> t = new MtasParserType<>(
typeMapping, nameMapping, false); // depends on control dependency: [if], data = [none]
t.addItem(m); // depends on control dependency: [if], data = [none]
groupTypes.put(nameMapping, t); // depends on control dependency: [if], data = [none]
}
} else {
throw new MtasConfigException("unknown mapping type "
+ typeMapping + " or missing name");
}
}
}
}
}
}
}
} } |
public class class_name {
private long addLogRecord(LogRecord logRecord,
long reservedDelta,
boolean setMark,
boolean checkSpace,
boolean flush)
throws ObjectManagerException
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
"addLogRecord",
new Object[] { logRecord,
new Long(reservedDelta),
new Boolean(setMark),
new Boolean(checkSpace),
new Boolean(flush) });
// Find the number of bytes we want to write.
int totalBytes = logRecord.getBytesLeft();
// Make sure the whole logRecord will fit in the log file, along with any extra space it
// has reserved. This does not account for any space that will be wasted by writing
// PaddingLogRecords. This check ensures that this buffer will not take us past the
// start point of the log written in the logHeader overwriting log records that we
// need for restart. The transactions reserve space assuming a worst case of a
// PaddingLogRecord for each commit. If we discover part way through a transaction
// the the log is full we can always successfully release our reserved space and commit the
// transaction.
// Note that we don't have to account for sector bytes because they are already incoporated
// into the reserved space.
long newSpaceAllocatedInLogFile = 0;
// Include any reserved space, the logData and completely filled parts.
newSpaceAllocatedInLogFile = reservedDelta + totalBytes + partHeaderLength * (totalBytes / maximumLogRecordPart);
// Add an extra part if one is partially filled.
if (totalBytes % maximumLogRecordPart > 0)
newSpaceAllocatedInLogFile = newSpaceAllocatedInLogFile + partHeaderLength;
// Make sure the logRecord will fit in the log file if we are requesting new space.
// If we are returning space then this is done after writing the log record so that
// the record will be written and if required, flushed within its already reserved space.
if (checkSpace && newSpaceAllocatedInLogFile > 0) {
long unavailable = reserveLogFileSpace(newSpaceAllocatedInLogFile);
if (unavailable != 0) {
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
"addLogRecord",
new Object[] { "via LogFileFullException",
new Long(unavailable),
new Long(newSpaceAllocatedInLogFile),
new Long(reservedDelta) });
throw new LogFileFullException(this,
newSpaceAllocatedInLogFile,
reservedDelta,
newSpaceAllocatedInLogFile - unavailable);
} // if (!reserve(newSpaceAllocatedInLogFile).
} // if (checkSpace...
// Decide if we need to split the log record into multiple parts. we do not allow long logRecords
// to be written into the LogBuffer as a single piece because that would stop other log records
// from being written if they used up the whole of the log buffer. Additionally this would also mean that
// log records must be smaller than the log buffer in order to fit into it.
if (totalBytes > maximumLogRecordPart) {
idNotFound: while (logRecord.multiPartID == 0) {
synchronized (multiPartIDLock) {
for (int i = 1; i < multiPartIdentifersUsed.length; i++) {
if (!multiPartIdentifersUsed[i]) {
logRecord.multiPartID = (byte) i;
multiPartIdentifersUsed[i] = true;
break idNotFound;
} // if(!multiPartIdentifersUsed[i]).
} // for multiPartIdentifersUsed...
} // synchronized (multiPartIDLock).
// Wait and see if an identifier becomes available as other long
// logRecords complete.
Object lock = new Object();
synchronized (lock) {
stalledForMultiPartID++;
try {
if (Tracing.isAnyTracingEnabled() && trace.isDebugEnabled())
trace.debug(this,
cclass,
"addLogRecord",
"About to wait for 10 milliseconds.");
lock.wait(10);
} catch (InterruptedException exception) {
// No FFDC Code Needed.
ObjectManager.ffdc.processException(this,
cclass,
"addLogRecord",
exception,
"1:1324:1.52");
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
"addLogRecord",
exception);
throw new UnexpectedExceptionException(this,
exception);
} // catch (InterruptedException exception).
} // synchronized (lock).
} // while (logRecord.multiPartID == 0).
} // if ( totalBytes > maximumLogRecordPart ).
// Repeat attempts to add to the logBuffer until we find one that has space
// for the LogRecord or we have added all of the parts.
long logSequenceNumber = 0;
for (;;) {
logSequenceNumber = addBuffers(logRecord,
setMark,
checkSpace,
flush);
if (logSequenceNumber == -1)
flush();
else if (logSequenceNumber > 0)
break;
} // for (;;).
// Return any reserved space.
if (checkSpace && newSpaceAllocatedInLogFile < 0) {
paddingReserveLogSpace(newSpaceAllocatedInLogFile);
} // if (checkSpace...
// Did the logRecord get split?
if (logRecord.multiPartID != 0) {
multiPartIdentifersUsed[logRecord.multiPartID] = false;
} // if (logRecord.multiPartID != 0).
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
"addLogRecord",
new Object[] { new Long(logSequenceNumber) });
return logSequenceNumber;
} } | public class class_name {
private long addLogRecord(LogRecord logRecord,
long reservedDelta,
boolean setMark,
boolean checkSpace,
boolean flush)
throws ObjectManagerException
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
"addLogRecord",
new Object[] { logRecord,
new Long(reservedDelta),
new Boolean(setMark),
new Boolean(checkSpace),
new Boolean(flush) });
// Find the number of bytes we want to write.
int totalBytes = logRecord.getBytesLeft();
// Make sure the whole logRecord will fit in the log file, along with any extra space it
// has reserved. This does not account for any space that will be wasted by writing
// PaddingLogRecords. This check ensures that this buffer will not take us past the
// start point of the log written in the logHeader overwriting log records that we
// need for restart. The transactions reserve space assuming a worst case of a
// PaddingLogRecord for each commit. If we discover part way through a transaction
// the the log is full we can always successfully release our reserved space and commit the
// transaction.
// Note that we don't have to account for sector bytes because they are already incoporated
// into the reserved space.
long newSpaceAllocatedInLogFile = 0;
// Include any reserved space, the logData and completely filled parts.
newSpaceAllocatedInLogFile = reservedDelta + totalBytes + partHeaderLength * (totalBytes / maximumLogRecordPart);
// Add an extra part if one is partially filled.
if (totalBytes % maximumLogRecordPart > 0)
newSpaceAllocatedInLogFile = newSpaceAllocatedInLogFile + partHeaderLength;
// Make sure the logRecord will fit in the log file if we are requesting new space.
// If we are returning space then this is done after writing the log record so that
// the record will be written and if required, flushed within its already reserved space.
if (checkSpace && newSpaceAllocatedInLogFile > 0) {
long unavailable = reserveLogFileSpace(newSpaceAllocatedInLogFile);
if (unavailable != 0) {
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
"addLogRecord",
new Object[] { "via LogFileFullException",
new Long(unavailable),
new Long(newSpaceAllocatedInLogFile),
new Long(reservedDelta) });
throw new LogFileFullException(this,
newSpaceAllocatedInLogFile,
reservedDelta,
newSpaceAllocatedInLogFile - unavailable);
} // if (!reserve(newSpaceAllocatedInLogFile).
} // if (checkSpace...
// Decide if we need to split the log record into multiple parts. we do not allow long logRecords
// to be written into the LogBuffer as a single piece because that would stop other log records
// from being written if they used up the whole of the log buffer. Additionally this would also mean that
// log records must be smaller than the log buffer in order to fit into it.
if (totalBytes > maximumLogRecordPart) {
idNotFound: while (logRecord.multiPartID == 0) {
synchronized (multiPartIDLock) { // depends on control dependency: [while], data = [none]
for (int i = 1; i < multiPartIdentifersUsed.length; i++) {
if (!multiPartIdentifersUsed[i]) {
logRecord.multiPartID = (byte) i; // depends on control dependency: [if], data = [none]
multiPartIdentifersUsed[i] = true; // depends on control dependency: [if], data = [none]
break idNotFound;
} // if(!multiPartIdentifersUsed[i]).
} // for multiPartIdentifersUsed...
} // synchronized (multiPartIDLock).
// Wait and see if an identifier becomes available as other long
// logRecords complete.
Object lock = new Object();
synchronized (lock) { // depends on control dependency: [while], data = [none]
stalledForMultiPartID++;
try {
if (Tracing.isAnyTracingEnabled() && trace.isDebugEnabled())
trace.debug(this,
cclass,
"addLogRecord",
"About to wait for 10 milliseconds.");
lock.wait(10); // depends on control dependency: [try], data = [none]
} catch (InterruptedException exception) {
// No FFDC Code Needed.
ObjectManager.ffdc.processException(this,
cclass,
"addLogRecord",
exception,
"1:1324:1.52");
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
"addLogRecord",
exception);
throw new UnexpectedExceptionException(this,
exception);
} // catch (InterruptedException exception). // depends on control dependency: [catch], data = [none]
} // synchronized (lock).
} // while (logRecord.multiPartID == 0).
} // if ( totalBytes > maximumLogRecordPart ).
// Repeat attempts to add to the logBuffer until we find one that has space
// for the LogRecord or we have added all of the parts.
long logSequenceNumber = 0;
for (;;) {
logSequenceNumber = addBuffers(logRecord,
setMark,
checkSpace,
flush);
if (logSequenceNumber == -1)
flush();
else if (logSequenceNumber > 0)
break;
} // for (;;).
// Return any reserved space.
if (checkSpace && newSpaceAllocatedInLogFile < 0) {
paddingReserveLogSpace(newSpaceAllocatedInLogFile);
} // if (checkSpace...
// Did the logRecord get split?
if (logRecord.multiPartID != 0) {
multiPartIdentifersUsed[logRecord.multiPartID] = false;
} // if (logRecord.multiPartID != 0).
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
"addLogRecord",
new Object[] { new Long(logSequenceNumber) });
return logSequenceNumber;
} } |
public class class_name {
public static String convertTabsToSpaces(final String line, final int tabWidth) {
int tab_index, tab_size;
int last_tab_index = 0;
int added_chars = 0;
if (tabWidth == 0) {
return StringUtil.remove(line, '\t');
}
StringBuilder result = new StringBuilder();
while ((tab_index = line.indexOf('\t', last_tab_index)) != -1) {
tab_size = tabWidth - ((tab_index + added_chars) % tabWidth);
if (tab_size == 0) {
tab_size = tabWidth;
}
added_chars += tab_size - 1;
result.append(line, last_tab_index, tab_index);
result.append(StringUtil.repeat(' ', tab_size));
last_tab_index = tab_index+1;
}
if (last_tab_index == 0) {
return line;
}
result.append(line.substring(last_tab_index));
return result.toString();
} } | public class class_name {
public static String convertTabsToSpaces(final String line, final int tabWidth) {
int tab_index, tab_size;
int last_tab_index = 0;
int added_chars = 0;
if (tabWidth == 0) {
return StringUtil.remove(line, '\t'); // depends on control dependency: [if], data = [none]
}
StringBuilder result = new StringBuilder();
while ((tab_index = line.indexOf('\t', last_tab_index)) != -1) {
tab_size = tabWidth - ((tab_index + added_chars) % tabWidth); // depends on control dependency: [while], data = [none]
if (tab_size == 0) {
tab_size = tabWidth; // depends on control dependency: [if], data = [none]
}
added_chars += tab_size - 1; // depends on control dependency: [while], data = [none]
result.append(line, last_tab_index, tab_index); // depends on control dependency: [while], data = [none]
result.append(StringUtil.repeat(' ', tab_size)); // depends on control dependency: [while], data = [none]
last_tab_index = tab_index+1; // depends on control dependency: [while], data = [none]
}
if (last_tab_index == 0) {
return line; // depends on control dependency: [if], data = [none]
}
result.append(line.substring(last_tab_index));
return result.toString();
} } |
public class class_name {
private static List<String> normalizePackagePrefixes(List<String> packages)
{
if (packages == null)
return null;
List<String> result = new ArrayList<>(packages.size());
for (String pkg : packages)
{
if(pkg.endsWith(".*")){
System.out.println("Warning: removing the .* suffix from the package prefix: " + pkg);
}
result.add(StringUtils.removeEndIgnoreCase(pkg, ".*"));
}
return packages;
} } | public class class_name {
private static List<String> normalizePackagePrefixes(List<String> packages)
{
if (packages == null)
return null;
List<String> result = new ArrayList<>(packages.size());
for (String pkg : packages)
{
if(pkg.endsWith(".*")){
System.out.println("Warning: removing the .* suffix from the package prefix: " + pkg); // depends on control dependency: [if], data = [none]
}
result.add(StringUtils.removeEndIgnoreCase(pkg, ".*")); // depends on control dependency: [for], data = [pkg]
}
return packages;
} } |
public class class_name {
private int findSlotBefore(SearchKey searchKey) {
/*
* int slot = 0; while (slot < contents.getNumRecords() &&
* getKey(contents, slot).compareTo(searchKey) < 0) slot++; return slot
* - 1;
*/
// Optimization: Use binary search rather than sequential search
int startSlot = 0, endSlot = currentPage.getNumRecords() - 1;
int middleSlot = (startSlot + endSlot) / 2;
if (endSlot >= 0) {
while (middleSlot != startSlot) {
if (getKey(currentPage, middleSlot, keyType.length())
.compareTo(searchKey) < 0)
startSlot = middleSlot;
else
endSlot = middleSlot;
middleSlot = (startSlot + endSlot) / 2;
}
if (getKey(currentPage, endSlot, keyType.length()).compareTo(searchKey) < 0)
return endSlot;
else if (getKey(currentPage, startSlot, keyType.length())
.compareTo(searchKey) < 0)
return startSlot;
else
return startSlot - 1;
} else
return -1;
} } | public class class_name {
private int findSlotBefore(SearchKey searchKey) {
/*
* int slot = 0; while (slot < contents.getNumRecords() &&
* getKey(contents, slot).compareTo(searchKey) < 0) slot++; return slot
* - 1;
*/
// Optimization: Use binary search rather than sequential search
int startSlot = 0, endSlot = currentPage.getNumRecords() - 1;
int middleSlot = (startSlot + endSlot) / 2;
if (endSlot >= 0) {
while (middleSlot != startSlot) {
if (getKey(currentPage, middleSlot, keyType.length())
.compareTo(searchKey) < 0)
startSlot = middleSlot;
else
endSlot = middleSlot;
middleSlot = (startSlot + endSlot) / 2;
// depends on control dependency: [while], data = [none]
}
if (getKey(currentPage, endSlot, keyType.length()).compareTo(searchKey) < 0)
return endSlot;
else if (getKey(currentPage, startSlot, keyType.length())
.compareTo(searchKey) < 0)
return startSlot;
else
return startSlot - 1;
} else
return -1;
} } |
public class class_name {
public CodedValueType getAuditSourceTypeCode() {
if (EventUtils.isEmptyOrNull(auditSourceTypeCode)) {
return null;
}
AuditSourceType auditSourceType = auditSourceTypeCode.get(0);
CodedValueType codedValueType = new CodedValueType();
codedValueType.setCode(auditSourceType.getCode());
codedValueType.setCodeSystem(auditSourceType.getCodeSystem());
codedValueType.setCodeSystemName(auditSourceType.getCodeSystemName());
codedValueType.setOriginalText(auditSourceType.getOriginalText());
return codedValueType;
} } | public class class_name {
public CodedValueType getAuditSourceTypeCode() {
if (EventUtils.isEmptyOrNull(auditSourceTypeCode)) {
return null; // depends on control dependency: [if], data = [none]
}
AuditSourceType auditSourceType = auditSourceTypeCode.get(0);
CodedValueType codedValueType = new CodedValueType();
codedValueType.setCode(auditSourceType.getCode());
codedValueType.setCodeSystem(auditSourceType.getCodeSystem());
codedValueType.setCodeSystemName(auditSourceType.getCodeSystemName());
codedValueType.setOriginalText(auditSourceType.getOriginalText());
return codedValueType;
} } |
public class class_name {
public Object methodMissing(String name, Object arg) {
Object[] args = (Object[])arg;
if(args.length == 0)
throw new MissingMethodException(name,getClass(),args);
if(args[0] instanceof Closure) {
// abstract bean definition
return invokeBeanDefiningMethod(name, args);
}
else if(args[0] instanceof Class || args[0] instanceof RuntimeBeanReference || args[0] instanceof Map) {
return invokeBeanDefiningMethod(name, args);
}
else if (args.length > 1 && args[args.length -1] instanceof Closure) {
return invokeBeanDefiningMethod(name, args);
}
WebApplicationContext ctx = springConfig.getUnrefreshedApplicationContext();
MetaClass mc = DefaultGroovyMethods.getMetaClass(ctx);
if(!mc.respondsTo(ctx, name, args).isEmpty()){
return mc.invokeMethod(ctx,name, args);
}
return this;
} } | public class class_name {
public Object methodMissing(String name, Object arg) {
Object[] args = (Object[])arg;
if(args.length == 0)
throw new MissingMethodException(name,getClass(),args);
if(args[0] instanceof Closure) {
// abstract bean definition
return invokeBeanDefiningMethod(name, args); // depends on control dependency: [if], data = [none]
}
else if(args[0] instanceof Class || args[0] instanceof RuntimeBeanReference || args[0] instanceof Map) {
return invokeBeanDefiningMethod(name, args); // depends on control dependency: [if], data = [none]
}
else if (args.length > 1 && args[args.length -1] instanceof Closure) {
return invokeBeanDefiningMethod(name, args); // depends on control dependency: [if], data = [none]
}
WebApplicationContext ctx = springConfig.getUnrefreshedApplicationContext();
MetaClass mc = DefaultGroovyMethods.getMetaClass(ctx);
if(!mc.respondsTo(ctx, name, args).isEmpty()){
return mc.invokeMethod(ctx,name, args); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
protected boolean keyReleased (KeyEvent e)
{
logKey("keyReleased", e);
// get the info object for this key
KeyInfo info = _keys.get(e.getKeyCode());
if (info != null) {
// remember the last time we received a key release
info.setReleaseTime(RunAnywhere.getWhen(e));
}
// notify any key observers of the key release
notifyObservers(KeyEvent.KEY_RELEASED, e.getKeyCode(), RunAnywhere.getWhen(e));
return (info != null);
} } | public class class_name {
protected boolean keyReleased (KeyEvent e)
{
logKey("keyReleased", e);
// get the info object for this key
KeyInfo info = _keys.get(e.getKeyCode());
if (info != null) {
// remember the last time we received a key release
info.setReleaseTime(RunAnywhere.getWhen(e)); // depends on control dependency: [if], data = [none]
}
// notify any key observers of the key release
notifyObservers(KeyEvent.KEY_RELEASED, e.getKeyCode(), RunAnywhere.getWhen(e));
return (info != null);
} } |
public class class_name {
public List<CheckResult> check(MetricName actualTarget, Map<String, Number> currentValuesByMetric) {
SortedMap<CheckResult.Status, List<Threshold>> sortedThresholds = new TreeMap<CheckResult.Status, List<Threshold>>(thresholds);
for (Map.Entry<CheckResult.Status, List<Threshold>> entry : sortedThresholds.entrySet()) {
List<CheckResult> results = checkThresholds(entry.getValue(), entry.getKey(), actualTarget, currentValuesByMetric);
if (!results.isEmpty()) {
return results;
}
}
return Collections.emptyList();
} } | public class class_name {
public List<CheckResult> check(MetricName actualTarget, Map<String, Number> currentValuesByMetric) {
SortedMap<CheckResult.Status, List<Threshold>> sortedThresholds = new TreeMap<CheckResult.Status, List<Threshold>>(thresholds);
for (Map.Entry<CheckResult.Status, List<Threshold>> entry : sortedThresholds.entrySet()) {
List<CheckResult> results = checkThresholds(entry.getValue(), entry.getKey(), actualTarget, currentValuesByMetric);
if (!results.isEmpty()) {
return results; // depends on control dependency: [if], data = [none]
}
}
return Collections.emptyList();
} } |
public class class_name {
@Override
public synchronized boolean updateNode(IUserLayoutNodeDescription node) throws PortalException {
if (canUpdateNode(node)) {
String nodeId = node.getId();
IUserLayoutNodeDescription oldNode = getNode(nodeId);
if (oldNode instanceof IUserLayoutChannelDescription) {
IUserLayoutChannelDescription oldChanDesc = (IUserLayoutChannelDescription) oldNode;
if (!(node instanceof IUserLayoutChannelDescription)) {
throw new PortalException(
"Change channel to folder is "
+ "not allowed by updateNode() method! Occurred "
+ "in layout for "
+ owner.getUserName()
+ ".");
}
IUserLayoutChannelDescription newChanDesc = (IUserLayoutChannelDescription) node;
updateChannelNode(nodeId, newChanDesc, oldChanDesc);
} else {
// must be a folder
IUserLayoutFolderDescription oldFolderDesc = (IUserLayoutFolderDescription) oldNode;
if (oldFolderDesc.getId().equals(getRootFolderId()))
throw new PortalException("Update of root node is not currently allowed!");
if (node instanceof IUserLayoutFolderDescription) {
IUserLayoutFolderDescription newFolderDesc =
(IUserLayoutFolderDescription) node;
updateFolderNode(nodeId, newFolderDesc, oldFolderDesc);
}
}
this.updateCacheKey();
return true;
}
return false;
} } | public class class_name {
@Override
public synchronized boolean updateNode(IUserLayoutNodeDescription node) throws PortalException {
if (canUpdateNode(node)) {
String nodeId = node.getId();
IUserLayoutNodeDescription oldNode = getNode(nodeId);
if (oldNode instanceof IUserLayoutChannelDescription) {
IUserLayoutChannelDescription oldChanDesc = (IUserLayoutChannelDescription) oldNode;
if (!(node instanceof IUserLayoutChannelDescription)) {
throw new PortalException(
"Change channel to folder is "
+ "not allowed by updateNode() method! Occurred "
+ "in layout for "
+ owner.getUserName()
+ ".");
}
IUserLayoutChannelDescription newChanDesc = (IUserLayoutChannelDescription) node;
updateChannelNode(nodeId, newChanDesc, oldChanDesc); // depends on control dependency: [if], data = [none]
} else {
// must be a folder
IUserLayoutFolderDescription oldFolderDesc = (IUserLayoutFolderDescription) oldNode;
if (oldFolderDesc.getId().equals(getRootFolderId()))
throw new PortalException("Update of root node is not currently allowed!");
if (node instanceof IUserLayoutFolderDescription) {
IUserLayoutFolderDescription newFolderDesc =
(IUserLayoutFolderDescription) node;
updateFolderNode(nodeId, newFolderDesc, oldFolderDesc); // depends on control dependency: [if], data = [none]
}
}
this.updateCacheKey();
return true;
}
return false;
} } |
public class class_name {
private void processElementRotate(GeneratorSingleCluster cluster, Node cur) {
int axis1 = 0;
int axis2 = 0;
double angle = 0.0;
String a1str = ((Element) cur).getAttribute(ATTR_AXIS1);
if(a1str != null && a1str.length() > 0) {
axis1 = ParseUtil.parseIntBase10(a1str);
}
String a2str = ((Element) cur).getAttribute(ATTR_AXIS2);
if(a2str != null && a2str.length() > 0) {
axis2 = ParseUtil.parseIntBase10(a2str);
}
String anstr = ((Element) cur).getAttribute(ATTR_ANGLE);
if(anstr != null && anstr.length() > 0) {
angle = ParseUtil.parseDouble(anstr);
}
if(axis1 <= 0 || axis1 > cluster.getDim()) {
throw new AbortException("Invalid axis1 number given in specification file.");
}
if(axis2 <= 0 || axis2 > cluster.getDim()) {
throw new AbortException("Invalid axis2 number given in specification file.");
}
if(axis1 == axis2) {
throw new AbortException("Invalid axis numbers given in specification file.");
}
// Add rotation to cluster.
cluster.addRotation(axis1 - 1, axis2 - 1, Math.toRadians(angle));
// TODO: check for unknown attributes.
XMLNodeIterator iter = new XMLNodeIterator(cur.getFirstChild());
while(iter.hasNext()) {
Node child = iter.next();
if(child.getNodeType() == Node.ELEMENT_NODE) {
LOG.warning("Unknown element in XML specification file: " + child.getNodeName());
}
}
} } | public class class_name {
private void processElementRotate(GeneratorSingleCluster cluster, Node cur) {
int axis1 = 0;
int axis2 = 0;
double angle = 0.0;
String a1str = ((Element) cur).getAttribute(ATTR_AXIS1);
if(a1str != null && a1str.length() > 0) {
axis1 = ParseUtil.parseIntBase10(a1str); // depends on control dependency: [if], data = [(a1str]
}
String a2str = ((Element) cur).getAttribute(ATTR_AXIS2);
if(a2str != null && a2str.length() > 0) {
axis2 = ParseUtil.parseIntBase10(a2str); // depends on control dependency: [if], data = [(a2str]
}
String anstr = ((Element) cur).getAttribute(ATTR_ANGLE);
if(anstr != null && anstr.length() > 0) {
angle = ParseUtil.parseDouble(anstr); // depends on control dependency: [if], data = [(anstr]
}
if(axis1 <= 0 || axis1 > cluster.getDim()) {
throw new AbortException("Invalid axis1 number given in specification file.");
}
if(axis2 <= 0 || axis2 > cluster.getDim()) {
throw new AbortException("Invalid axis2 number given in specification file.");
}
if(axis1 == axis2) {
throw new AbortException("Invalid axis numbers given in specification file.");
}
// Add rotation to cluster.
cluster.addRotation(axis1 - 1, axis2 - 1, Math.toRadians(angle));
// TODO: check for unknown attributes.
XMLNodeIterator iter = new XMLNodeIterator(cur.getFirstChild());
while(iter.hasNext()) {
Node child = iter.next();
if(child.getNodeType() == Node.ELEMENT_NODE) {
LOG.warning("Unknown element in XML specification file: " + child.getNodeName()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public boolean createChildScope(String name) {
if (!scope.hasChildScope(name)) {
return scope.createChildScope(name);
}
return false;
} } | public class class_name {
public boolean createChildScope(String name) {
if (!scope.hasChildScope(name)) {
return scope.createChildScope(name); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public void saveCurrentPlot() {
// TODO: exclude "do not export" layers!
final SVGPlot currentPlot = svgCanvas.getPlot();
if(currentPlot != null) {
SVGSaveDialog.showSaveDialog(currentPlot, 512, 512);
}
else {
LoggingUtil.warning("saveCurrentPlot() called without a visible plot!");
}
} } | public class class_name {
public void saveCurrentPlot() {
// TODO: exclude "do not export" layers!
final SVGPlot currentPlot = svgCanvas.getPlot();
if(currentPlot != null) {
SVGSaveDialog.showSaveDialog(currentPlot, 512, 512); // depends on control dependency: [if], data = [(currentPlot]
}
else {
LoggingUtil.warning("saveCurrentPlot() called without a visible plot!"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void processElement(Wrapper<Element> element) {
activeElement = element.getContent();
if (parentElement != null) {
parentElement.addContent(activeElement);
}
} } | public class class_name {
@Override
public void processElement(Wrapper<Element> element) {
activeElement = element.getContent();
if (parentElement != null) {
parentElement.addContent(activeElement); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static IDifference difference(IChemObject first, IChemObject second) {
if (!(first instanceof IElectronContainer && second instanceof IElectronContainer)) {
return null;
}
IElectronContainer firstEC = (IElectronContainer) first;
IElectronContainer secondEC = (IElectronContainer) second;
IDifferenceList totalDiff = new ChemObjectDifference("ElectronContainerDiff");
totalDiff.addChild(IntegerDifference.construct("eCount", firstEC.getElectronCount(),
secondEC.getElectronCount()));
totalDiff.addChild(ChemObjectDiff.difference(first, second));
if (totalDiff.childCount() > 0) {
return totalDiff;
} else {
return null;
}
} } | public class class_name {
public static IDifference difference(IChemObject first, IChemObject second) {
if (!(first instanceof IElectronContainer && second instanceof IElectronContainer)) {
return null; // depends on control dependency: [if], data = [none]
}
IElectronContainer firstEC = (IElectronContainer) first;
IElectronContainer secondEC = (IElectronContainer) second;
IDifferenceList totalDiff = new ChemObjectDifference("ElectronContainerDiff");
totalDiff.addChild(IntegerDifference.construct("eCount", firstEC.getElectronCount(),
secondEC.getElectronCount()));
totalDiff.addChild(ChemObjectDiff.difference(first, second));
if (totalDiff.childCount() > 0) {
return totalDiff; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("fallthrough")
@SuppressFBWarnings(justification = "As this is an encoding method the fallthrough is intentional", value = {"SF_SWITCH_NO_DEFAULT"})
public static void appendEscapedLuceneQuery(StringBuilder buf,
final CharSequence text) {
if (text == null || buf == null) {
return;
}
for (int i = 0; i < text.length(); i++) {
final char c = text.charAt(i);
switch (c) {
case '+':
case '-':
case '&':
case '|':
case '!':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case '^':
case '"':
case '~':
case '*':
case '?':
case ':':
case '/':
case '\\': //it is supposed to fall through here
buf.append('\\');
default:
buf.append(c);
break;
}
}
} } | public class class_name {
@SuppressWarnings("fallthrough")
@SuppressFBWarnings(justification = "As this is an encoding method the fallthrough is intentional", value = {"SF_SWITCH_NO_DEFAULT"})
public static void appendEscapedLuceneQuery(StringBuilder buf,
final CharSequence text) {
if (text == null || buf == null) {
return; // depends on control dependency: [if], data = [none]
}
for (int i = 0; i < text.length(); i++) {
final char c = text.charAt(i);
switch (c) {
case '+':
case '-':
case '&':
case '|':
case '!':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case '^':
case '"':
case '~':
case '*':
case '?':
case ':':
case '/':
case '\\': //it is supposed to fall through here
buf.append('\\');
default:
buf.append(c);
break;
}
}
} } |
public class class_name {
@SuppressWarnings("deprecation")
public BigDecimal getDecimalMillis()
{
switch (this._precision) {
case YEAR:
case MONTH:
case DAY:
case MINUTE:
case SECOND:
case FRACTION:
long millis = Date.UTC(this._year - 1900, this._month - 1, this._day, this._hour, this._minute, this._second);
BigDecimal dec = BigDecimal.valueOf(millis);
if (_fraction != null) {
dec = dec.add(this._fraction.movePointRight(3));
}
return dec;
}
throw new IllegalArgumentException();
} } | public class class_name {
@SuppressWarnings("deprecation")
public BigDecimal getDecimalMillis()
{
switch (this._precision) {
case YEAR:
case MONTH:
case DAY:
case MINUTE:
case SECOND:
case FRACTION:
long millis = Date.UTC(this._year - 1900, this._month - 1, this._day, this._hour, this._minute, this._second);
BigDecimal dec = BigDecimal.valueOf(millis);
if (_fraction != null) {
dec = dec.add(this._fraction.movePointRight(3)); // depends on control dependency: [if], data = [none]
}
return dec;
}
throw new IllegalArgumentException();
} } |
public class class_name {
public URLTemplate getURLTemplate( String name )
{
assert _urlTemplates != null : "The template config file has not been loaded.";
if ( _urlTemplates == null )
{
return null;
}
return _urlTemplates.getTemplate( name );
} } | public class class_name {
public URLTemplate getURLTemplate( String name )
{
assert _urlTemplates != null : "The template config file has not been loaded.";
if ( _urlTemplates == null )
{
return null; // depends on control dependency: [if], data = [none]
}
return _urlTemplates.getTemplate( name );
} } |
public class class_name {
protected Map<String, String> getStringDataMap(final JobDataMap jobDataMap){
Map<String, String> stringMap = new HashMap<>();
for (Map.Entry<String, Object> entry : jobDataMap.entrySet()) {
if(entry.getValue() != null){
stringMap.put(entry.getKey(), entry.getValue().toString());
}
}
return stringMap;
} } | public class class_name {
protected Map<String, String> getStringDataMap(final JobDataMap jobDataMap){
Map<String, String> stringMap = new HashMap<>();
for (Map.Entry<String, Object> entry : jobDataMap.entrySet()) {
if(entry.getValue() != null){
stringMap.put(entry.getKey(), entry.getValue().toString()); // depends on control dependency: [if], data = [none]
}
}
return stringMap;
} } |
public class class_name {
private Mapper createCustomMapper(Field field, PropertyMapper propertyMapperAnnotation) {
Class<? extends Mapper> mapperClass = propertyMapperAnnotation.value();
Constructor<? extends Mapper> constructor = IntrospectionUtils.getConstructor(mapperClass,
Field.class);
if (constructor != null) {
try {
return constructor.newInstance(field);
} catch (Exception exp) {
throw new EntityManagerException(exp);
}
}
throw new EntityManagerException(
String.format("Mapper class %s must have a public constructor with a parameter type of %s",
mapperClass.getName(), Field.class.getName()));
} } | public class class_name {
private Mapper createCustomMapper(Field field, PropertyMapper propertyMapperAnnotation) {
Class<? extends Mapper> mapperClass = propertyMapperAnnotation.value();
Constructor<? extends Mapper> constructor = IntrospectionUtils.getConstructor(mapperClass,
Field.class);
if (constructor != null) {
try {
return constructor.newInstance(field); // depends on control dependency: [try], data = [none]
} catch (Exception exp) {
throw new EntityManagerException(exp);
} // depends on control dependency: [catch], data = [none]
}
throw new EntityManagerException(
String.format("Mapper class %s must have a public constructor with a parameter type of %s",
mapperClass.getName(), Field.class.getName()));
} } |
public class class_name {
private static TemplateEngine doCreate(TemplateConfig config) {
try {
return new BeetlEngine(config);
} catch (NoClassDefFoundError e) {
// ignore
}
try {
return new FreemarkerEngine(config);
} catch (NoClassDefFoundError e) {
// ignore
}
try {
return new VelocityEngine(config);
} catch (NoClassDefFoundError e) {
// ignore
}
try {
return new RythmEngine(config);
} catch (NoClassDefFoundError e) {
// ignore
}
try {
return new EnjoyEngine(config);
} catch (NoClassDefFoundError e) {
// ignore
}
try {
return new ThymeleafEngine(config);
} catch (NoClassDefFoundError e) {
// ignore
}
throw new TemplateException("No template found ! Please add one of template jar to your project !");
} } | public class class_name {
private static TemplateEngine doCreate(TemplateConfig config) {
try {
return new BeetlEngine(config);
// depends on control dependency: [try], data = [none]
} catch (NoClassDefFoundError e) {
// ignore
}
// depends on control dependency: [catch], data = [none]
try {
return new FreemarkerEngine(config);
// depends on control dependency: [try], data = [none]
} catch (NoClassDefFoundError e) {
// ignore
}
// depends on control dependency: [catch], data = [none]
try {
return new VelocityEngine(config);
// depends on control dependency: [try], data = [none]
} catch (NoClassDefFoundError e) {
// ignore
}
// depends on control dependency: [catch], data = [none]
try {
return new RythmEngine(config);
// depends on control dependency: [try], data = [none]
} catch (NoClassDefFoundError e) {
// ignore
}
// depends on control dependency: [catch], data = [none]
try {
return new EnjoyEngine(config);
// depends on control dependency: [try], data = [none]
} catch (NoClassDefFoundError e) {
// ignore
}
// depends on control dependency: [catch], data = [none]
try {
return new ThymeleafEngine(config);
// depends on control dependency: [try], data = [none]
} catch (NoClassDefFoundError e) {
// ignore
}
// depends on control dependency: [catch], data = [none]
throw new TemplateException("No template found ! Please add one of template jar to your project !");
} } |
public class class_name {
public java.util.List<ChangeSetSummary> getSummaries() {
if (summaries == null) {
summaries = new com.amazonaws.internal.SdkInternalList<ChangeSetSummary>();
}
return summaries;
} } | public class class_name {
public java.util.List<ChangeSetSummary> getSummaries() {
if (summaries == null) {
summaries = new com.amazonaws.internal.SdkInternalList<ChangeSetSummary>(); // depends on control dependency: [if], data = [none]
}
return summaries;
} } |
public class class_name {
public void marshall(ExecutionAbortedEventDetails executionAbortedEventDetails, ProtocolMarshaller protocolMarshaller) {
if (executionAbortedEventDetails == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(executionAbortedEventDetails.getError(), ERROR_BINDING);
protocolMarshaller.marshall(executionAbortedEventDetails.getCause(), CAUSE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ExecutionAbortedEventDetails executionAbortedEventDetails, ProtocolMarshaller protocolMarshaller) {
if (executionAbortedEventDetails == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(executionAbortedEventDetails.getError(), ERROR_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(executionAbortedEventDetails.getCause(), CAUSE_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 Number getNumber(int index) throws JSONException {
Object object = this.get(index);
try {
if (object instanceof Number) {
return (Number)object;
}
return JSONObject.stringToNumber(object.toString());
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.", e);
}
} } | public class class_name {
public Number getNumber(int index) throws JSONException {
Object object = this.get(index);
try {
if (object instanceof Number) {
return (Number)object; // depends on control dependency: [if], data = [none]
}
return JSONObject.stringToNumber(object.toString());
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.", e);
}
} } |
public class class_name {
public void restore() {
if (window instanceof RootPaneContainer) {
final Component glassPane = ((RootPaneContainer) window).getGlassPane();
glassPane.setVisible(windowGlassPaneVisible);
glassPane.setCursor(oldWindowCursor);
}
if (window != null) {
window.setCursor(oldWindowCursor);
}
} } | public class class_name {
public void restore() {
if (window instanceof RootPaneContainer) {
final Component glassPane = ((RootPaneContainer) window).getGlassPane();
glassPane.setVisible(windowGlassPaneVisible);
// depends on control dependency: [if], data = [none]
glassPane.setCursor(oldWindowCursor);
// depends on control dependency: [if], data = [none]
}
if (window != null) {
window.setCursor(oldWindowCursor);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Endpoint withDefaultPort(int defaultPort) {
ensureSingle();
validatePort("defaultPort", defaultPort);
if (port != 0) {
return this;
}
return new Endpoint(host(), ipAddr(), defaultPort, weight(), hostType);
} } | public class class_name {
public Endpoint withDefaultPort(int defaultPort) {
ensureSingle();
validatePort("defaultPort", defaultPort);
if (port != 0) {
return this; // depends on control dependency: [if], data = [none]
}
return new Endpoint(host(), ipAddr(), defaultPort, weight(), hostType);
} } |
public class class_name {
private void btCancelActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btCancelActionPerformed
{//GEN-HEADEREND:event_btCancelActionPerformed
if (isImporting)
{
worker.cancel(true);
statementController.cancelStatements();
}
setVisible(false);
} } | public class class_name {
private void btCancelActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btCancelActionPerformed
{//GEN-HEADEREND:event_btCancelActionPerformed
if (isImporting)
{
worker.cancel(true); // depends on control dependency: [if], data = [none]
statementController.cancelStatements(); // depends on control dependency: [if], data = [none]
}
setVisible(false);
} } |
public class class_name {
@Override
public void unset(String propName) {
/*
* Require a property name.
*/
if (propName == null || propName.trim().isEmpty()) {
return;
}
if (propName.equals(PROP_MEMBERS)) {
unsetMembers();
}
if (propName.equals(PROP_DISPLAY_NAME)) {
unsetDisplayName();
}
if (propName.equals(PROP_DESCRIPTION)) {
unsetDescription();
}
if (propName.equals(PROP_BUSINESS_CATEGORY)) {
unsetBusinessCategory();
}
if (propName.equals(PROP_SEE_ALSO)) {
unsetSeeAlso();
}
if (extendedPropertiesDataType.containsKey(propName))
unSetExtendedProperty(propName);
super.unset(propName);
} } | public class class_name {
@Override
public void unset(String propName) {
/*
* Require a property name.
*/
if (propName == null || propName.trim().isEmpty()) {
return; // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_MEMBERS)) {
unsetMembers(); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_DISPLAY_NAME)) {
unsetDisplayName(); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_DESCRIPTION)) {
unsetDescription(); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_BUSINESS_CATEGORY)) {
unsetBusinessCategory(); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_SEE_ALSO)) {
unsetSeeAlso(); // depends on control dependency: [if], data = [none]
}
if (extendedPropertiesDataType.containsKey(propName))
unSetExtendedProperty(propName);
super.unset(propName);
} } |
public class class_name {
public void makeSelect(final AbstractPrintQuery _print)
throws EFapsException
{
for (final String expression : getExpressions()) {
// TODO remove, only selects allowed
if (_print.getMainType().getAttributes().containsKey(expression)) {
_print.addAttribute(expression);
ValueList.LOG.warn(
"The arguments for ValueList must only contain selects. Invalid: '{}' for ValueList: {}",
expression, getValueList());
} else if (expression.contains("[") || expression.equals(expression.toLowerCase())) {
_print.addSelect(expression);
} else {
ValueList.LOG.warn(
"The arguments for ValueList must only contain selects. Invalid: '{}' for ValueList: {}",
expression, getValueList());
}
}
} } | public class class_name {
public void makeSelect(final AbstractPrintQuery _print)
throws EFapsException
{
for (final String expression : getExpressions()) {
// TODO remove, only selects allowed
if (_print.getMainType().getAttributes().containsKey(expression)) {
_print.addAttribute(expression); // depends on control dependency: [if], data = [none]
ValueList.LOG.warn(
"The arguments for ValueList must only contain selects. Invalid: '{}' for ValueList: {}",
expression, getValueList()); // depends on control dependency: [if], data = [none]
} else if (expression.contains("[") || expression.equals(expression.toLowerCase())) {
_print.addSelect(expression); // depends on control dependency: [if], data = [none]
} else {
ValueList.LOG.warn(
"The arguments for ValueList must only contain selects. Invalid: '{}' for ValueList: {}",
expression, getValueList()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
protected void computeINFLO(Relation<O> relation, ModifiableDBIDs pruned, KNNQuery<O> knnq, WritableDataStore<ModifiableDBIDs> rNNminuskNNs, WritableDoubleDataStore inflos, DoubleMinMax inflominmax) {
FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Computing INFLOs", relation.size(), LOG) : null;
HashSetModifiableDBIDs set = DBIDUtil.newHashSet();
for(DBIDIter iter = relation.iterDBIDs(); iter.valid(); iter.advance()) {
if(pruned.contains(iter)) {
inflos.putDouble(iter, 1.);
inflominmax.put(1.);
LOG.incrementProcessed(prog);
continue;
}
final KNNList knn = knnq.getKNNForDBID(iter, kplus1);
if(knn.getKNNDistance() == 0.) {
inflos.putDouble(iter, 1.);
inflominmax.put(1.);
LOG.incrementProcessed(prog);
continue;
}
set.clear();
set.addDBIDs(knn);
set.addDBIDs(rNNminuskNNs.get(iter));
// Compute mean density of NN \cup RNN
double sum = 0.;
int c = 0;
for(DBIDIter niter = set.iter(); niter.valid(); niter.advance()) {
if(DBIDUtil.equal(iter, niter)) {
continue;
}
final double kdist = knnq.getKNNForDBID(niter, kplus1).getKNNDistance();
if(kdist <= 0) {
sum = Double.POSITIVE_INFINITY;
c++;
break;
}
sum += 1. / kdist;
c++;
}
sum *= knn.getKNNDistance();
final double inflo = sum == 0 ? 1. : sum / c;
inflos.putDouble(iter, inflo);
inflominmax.put(inflo);
LOG.incrementProcessed(prog);
}
LOG.ensureCompleted(prog);
} } | public class class_name {
protected void computeINFLO(Relation<O> relation, ModifiableDBIDs pruned, KNNQuery<O> knnq, WritableDataStore<ModifiableDBIDs> rNNminuskNNs, WritableDoubleDataStore inflos, DoubleMinMax inflominmax) {
FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Computing INFLOs", relation.size(), LOG) : null;
HashSetModifiableDBIDs set = DBIDUtil.newHashSet();
for(DBIDIter iter = relation.iterDBIDs(); iter.valid(); iter.advance()) {
if(pruned.contains(iter)) {
inflos.putDouble(iter, 1.); // depends on control dependency: [if], data = [none]
inflominmax.put(1.); // depends on control dependency: [if], data = [none]
LOG.incrementProcessed(prog); // depends on control dependency: [if], data = [none]
continue;
}
final KNNList knn = knnq.getKNNForDBID(iter, kplus1);
if(knn.getKNNDistance() == 0.) {
inflos.putDouble(iter, 1.); // depends on control dependency: [if], data = [none]
inflominmax.put(1.); // depends on control dependency: [if], data = [none]
LOG.incrementProcessed(prog); // depends on control dependency: [if], data = [none]
continue;
}
set.clear(); // depends on control dependency: [for], data = [none]
set.addDBIDs(knn); // depends on control dependency: [for], data = [none]
set.addDBIDs(rNNminuskNNs.get(iter)); // depends on control dependency: [for], data = [iter]
// Compute mean density of NN \cup RNN
double sum = 0.;
int c = 0;
for(DBIDIter niter = set.iter(); niter.valid(); niter.advance()) {
if(DBIDUtil.equal(iter, niter)) {
continue;
}
final double kdist = knnq.getKNNForDBID(niter, kplus1).getKNNDistance();
if(kdist <= 0) {
sum = Double.POSITIVE_INFINITY; // depends on control dependency: [if], data = [none]
c++; // depends on control dependency: [if], data = [none]
break;
}
sum += 1. / kdist; // depends on control dependency: [for], data = [none]
c++; // depends on control dependency: [for], data = [none]
}
sum *= knn.getKNNDistance(); // depends on control dependency: [for], data = [none]
final double inflo = sum == 0 ? 1. : sum / c;
inflos.putDouble(iter, inflo); // depends on control dependency: [for], data = [iter]
inflominmax.put(inflo); // depends on control dependency: [for], data = [none]
LOG.incrementProcessed(prog); // depends on control dependency: [for], data = [none]
}
LOG.ensureCompleted(prog);
} } |
public class class_name {
public void resolveBundles(BundleContext bContext, List<Bundle> bundlesToResolve) {
if (bundlesToResolve == null || bundlesToResolve.size() == 0) {
return;
}
FrameworkWiring wiring = adaptSystemBundle(bContext, FrameworkWiring.class);
if (wiring != null) {
ResolutionReportHelper rrh = null;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
rrh = new ResolutionReportHelper();
rrh.startHelper(bContext);
}
try {
wiring.resolveBundles(bundlesToResolve);
} finally {
if (rrh != null) {
rrh.stopHelper();
Tr.debug(this, tc, rrh.getResolutionReportString());
}
}
}
} } | public class class_name {
public void resolveBundles(BundleContext bContext, List<Bundle> bundlesToResolve) {
if (bundlesToResolve == null || bundlesToResolve.size() == 0) {
return; // depends on control dependency: [if], data = [none]
}
FrameworkWiring wiring = adaptSystemBundle(bContext, FrameworkWiring.class);
if (wiring != null) {
ResolutionReportHelper rrh = null;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
rrh = new ResolutionReportHelper(); // depends on control dependency: [if], data = [none]
rrh.startHelper(bContext); // depends on control dependency: [if], data = [none]
}
try {
wiring.resolveBundles(bundlesToResolve); // depends on control dependency: [try], data = [none]
} finally {
if (rrh != null) {
rrh.stopHelper(); // depends on control dependency: [if], data = [none]
Tr.debug(this, tc, rrh.getResolutionReportString()); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
@Override
public EEnum getIfcBSplineSurfaceForm() {
if (ifcBSplineSurfaceFormEEnum == null) {
ifcBSplineSurfaceFormEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(919);
}
return ifcBSplineSurfaceFormEEnum;
} } | public class class_name {
@Override
public EEnum getIfcBSplineSurfaceForm() {
if (ifcBSplineSurfaceFormEEnum == null) {
ifcBSplineSurfaceFormEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(919);
// depends on control dependency: [if], data = [none]
}
return ifcBSplineSurfaceFormEEnum;
} } |
public class class_name {
private Map<String, ParseTreeNode> getTokens() throws GrammarException,
TreeException {
Map<String, ParseTreeNode> tokens = new HashMap<String, ParseTreeNode>();
ParseTreeNode tokensTree = parserTree.getChild("Tokens");
ParseTreeNode tokenDefinitions = tokensTree.getChild("TokenDefinitions");
for (ParseTreeNode tokenDefinition : tokenDefinitions
.getChildren("TokenDefinition")) {
// identifier...
String identifier = tokenDefinition.getChild("IDENTIFIER")
.getText();
// token parts...
tokens.put(identifier, tokenDefinition);
// visibility...
ParseTreeNode visibilityAST = tokenDefinition.getChild("Visibility");
if (visibilityAST.hasChild("HIDE")) {
tokenVisibility.put(identifier, Visibility.HIDDEN);
} else if (visibilityAST.hasChild("IGNORE")) {
tokenVisibility.put(identifier, Visibility.IGNORED);
} else {
tokenVisibility.put(identifier, Visibility.VISIBLE);
}
}
return tokens;
} } | public class class_name {
private Map<String, ParseTreeNode> getTokens() throws GrammarException,
TreeException {
Map<String, ParseTreeNode> tokens = new HashMap<String, ParseTreeNode>();
ParseTreeNode tokensTree = parserTree.getChild("Tokens");
ParseTreeNode tokenDefinitions = tokensTree.getChild("TokenDefinitions");
for (ParseTreeNode tokenDefinition : tokenDefinitions
.getChildren("TokenDefinition")) {
// identifier...
String identifier = tokenDefinition.getChild("IDENTIFIER")
.getText();
// token parts...
tokens.put(identifier, tokenDefinition);
// visibility...
ParseTreeNode visibilityAST = tokenDefinition.getChild("Visibility");
if (visibilityAST.hasChild("HIDE")) {
tokenVisibility.put(identifier, Visibility.HIDDEN); // depends on control dependency: [if], data = [none]
} else if (visibilityAST.hasChild("IGNORE")) {
tokenVisibility.put(identifier, Visibility.IGNORED); // depends on control dependency: [if], data = [none]
} else {
tokenVisibility.put(identifier, Visibility.VISIBLE); // depends on control dependency: [if], data = [none]
}
}
return tokens;
} } |
public class class_name {
public ServiceCall<Synonym> updateSynonym(UpdateSynonymOptions updateSynonymOptions) {
Validator.notNull(updateSynonymOptions, "updateSynonymOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values", "synonyms" };
String[] pathParameters = { updateSynonymOptions.workspaceId(), updateSynonymOptions.entity(), updateSynonymOptions
.value(), updateSynonymOptions.synonym() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "updateSynonym");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
final JsonObject contentJson = new JsonObject();
if (updateSynonymOptions.newSynonym() != null) {
contentJson.addProperty("synonym", updateSynonymOptions.newSynonym());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Synonym.class));
} } | public class class_name {
public ServiceCall<Synonym> updateSynonym(UpdateSynonymOptions updateSynonymOptions) {
Validator.notNull(updateSynonymOptions, "updateSynonymOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities", "values", "synonyms" };
String[] pathParameters = { updateSynonymOptions.workspaceId(), updateSynonymOptions.entity(), updateSynonymOptions
.value(), updateSynonymOptions.synonym() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "updateSynonym");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue()); // depends on control dependency: [for], data = [header]
}
builder.header("Accept", "application/json");
final JsonObject contentJson = new JsonObject();
if (updateSynonymOptions.newSynonym() != null) {
contentJson.addProperty("synonym", updateSynonymOptions.newSynonym()); // depends on control dependency: [if], data = [none]
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Synonym.class));
} } |
public class class_name {
static void putStringHashIfNotNull(
@NonNull JSONObject jsonObject,
@NonNull @Size(min = 1) String fieldName,
@Nullable Map<String, String> value) {
if (value == null) {
return;
}
JSONObject jsonHash = stringHashToJsonObject(value);
if (jsonHash == null) {
return;
}
try {
jsonObject.put(fieldName, jsonHash);
} catch (JSONException ignored) { }
} } | public class class_name {
static void putStringHashIfNotNull(
@NonNull JSONObject jsonObject,
@NonNull @Size(min = 1) String fieldName,
@Nullable Map<String, String> value) {
if (value == null) {
return; // depends on control dependency: [if], data = [none]
}
JSONObject jsonHash = stringHashToJsonObject(value);
if (jsonHash == null) {
return; // depends on control dependency: [if], data = [none]
}
try {
jsonObject.put(fieldName, jsonHash); // depends on control dependency: [try], data = [none]
} catch (JSONException ignored) { } // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public String getBroadcastMessageString() {
CmsSessionInfo sessionInfo = OpenCms.getSessionManager().getSessionInfo(getSession());
if (sessionInfo == null) {
return null;
}
String sessionId = sessionInfo.getSessionId().toString();
Buffer messageQueue = OpenCms.getSessionManager().getBroadcastQueue(sessionId);
if (!messageQueue.isEmpty()) {
// create message String
StringBuffer result = new StringBuffer(512);
// the user has pending messages, display them all
while (!messageQueue.isEmpty()) {
CmsBroadcast message = (CmsBroadcast)messageQueue.remove();
result.append('[');
result.append(getMessages().getDateTime(message.getSendTime()));
result.append("] ");
result.append(key(Messages.GUI_LABEL_BROADCASTMESSAGEFROM_0));
result.append(' ');
if (message.getUser() != null) {
result.append(message.getUser().getName());
} else {
// system message
result.append(key(Messages.GUI_LABEL_BROADCAST_FROM_SYSTEM_0));
}
result.append(":\n");
result.append(message.getMessage());
result.append("\n\n");
}
return result.toString();
}
// no message pending, return null
return null;
} } | public class class_name {
public String getBroadcastMessageString() {
CmsSessionInfo sessionInfo = OpenCms.getSessionManager().getSessionInfo(getSession());
if (sessionInfo == null) {
return null; // depends on control dependency: [if], data = [none]
}
String sessionId = sessionInfo.getSessionId().toString();
Buffer messageQueue = OpenCms.getSessionManager().getBroadcastQueue(sessionId);
if (!messageQueue.isEmpty()) {
// create message String
StringBuffer result = new StringBuffer(512);
// the user has pending messages, display them all
while (!messageQueue.isEmpty()) {
CmsBroadcast message = (CmsBroadcast)messageQueue.remove();
result.append('['); // depends on control dependency: [while], data = [none]
result.append(getMessages().getDateTime(message.getSendTime())); // depends on control dependency: [while], data = [none]
result.append("] "); // depends on control dependency: [while], data = [none]
result.append(key(Messages.GUI_LABEL_BROADCASTMESSAGEFROM_0)); // depends on control dependency: [while], data = [none]
result.append(' '); // depends on control dependency: [while], data = [none]
if (message.getUser() != null) {
result.append(message.getUser().getName()); // depends on control dependency: [if], data = [(message.getUser()]
} else {
// system message
result.append(key(Messages.GUI_LABEL_BROADCAST_FROM_SYSTEM_0)); // depends on control dependency: [if], data = [none]
}
result.append(":\n"); // depends on control dependency: [while], data = [none]
result.append(message.getMessage()); // depends on control dependency: [while], data = [none]
result.append("\n\n"); // depends on control dependency: [while], data = [none]
}
return result.toString(); // depends on control dependency: [if], data = [none]
}
// no message pending, return null
return null;
} } |
public class class_name {
public OutlierResult run(Database database, Relation<N> nrel, Relation<? extends NumberVector> relation) {
final NeighborSetPredicate npred = getNeighborSetPredicateFactory().instantiate(database, nrel);
WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_STATIC);
MeanVariance mv = new MeanVariance();
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
DBIDs neighbors = npred.getNeighborDBIDs(iditer);
final double median;
{
double[] fi = new double[neighbors.size()];
// calculate and store Median of neighborhood
int c = 0;
for(DBIDIter iter = neighbors.iter(); iter.valid(); iter.advance()) {
if(DBIDUtil.equal(iditer, iter)) {
continue;
}
fi[c] = relation.get(iter).doubleValue(0);
c++;
}
if(c > 0) {
median = QuickSelect.median(fi, 0, c);
}
else {
median = relation.get(iditer).doubleValue(0);
}
}
double h = relation.get(iditer).doubleValue(0) - median;
scores.putDouble(iditer, h);
mv.put(h);
}
// Normalize scores
final double mean = mv.getMean();
final double stddev = mv.getNaiveStddev();
DoubleMinMax minmax = new DoubleMinMax();
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
double score = Math.abs((scores.doubleValue(iditer) - mean) / stddev);
minmax.put(score);
scores.putDouble(iditer, score);
}
DoubleRelation scoreResult = new MaterializedDoubleRelation("MO", "Median-outlier", scores, relation.getDBIDs());
OutlierScoreMeta scoreMeta = new BasicOutlierScoreMeta(minmax.getMin(), minmax.getMax(), 0.0, Double.POSITIVE_INFINITY, 0);
OutlierResult or = new OutlierResult(scoreMeta, scoreResult);
or.addChildResult(npred);
return or;
} } | public class class_name {
public OutlierResult run(Database database, Relation<N> nrel, Relation<? extends NumberVector> relation) {
final NeighborSetPredicate npred = getNeighborSetPredicateFactory().instantiate(database, nrel);
WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_STATIC);
MeanVariance mv = new MeanVariance();
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
DBIDs neighbors = npred.getNeighborDBIDs(iditer);
final double median;
{
double[] fi = new double[neighbors.size()];
// calculate and store Median of neighborhood
int c = 0;
for(DBIDIter iter = neighbors.iter(); iter.valid(); iter.advance()) {
if(DBIDUtil.equal(iditer, iter)) {
continue;
}
fi[c] = relation.get(iter).doubleValue(0); // depends on control dependency: [for], data = [iter]
c++; // depends on control dependency: [for], data = [none]
}
if(c > 0) {
median = QuickSelect.median(fi, 0, c); // depends on control dependency: [if], data = [none]
}
else {
median = relation.get(iditer).doubleValue(0); // depends on control dependency: [if], data = [0)]
}
}
double h = relation.get(iditer).doubleValue(0) - median;
scores.putDouble(iditer, h); // depends on control dependency: [for], data = [iditer]
mv.put(h); // depends on control dependency: [for], data = [none]
}
// Normalize scores
final double mean = mv.getMean();
final double stddev = mv.getNaiveStddev();
DoubleMinMax minmax = new DoubleMinMax();
for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
double score = Math.abs((scores.doubleValue(iditer) - mean) / stddev);
minmax.put(score); // depends on control dependency: [for], data = [none]
scores.putDouble(iditer, score); // depends on control dependency: [for], data = [iditer]
}
DoubleRelation scoreResult = new MaterializedDoubleRelation("MO", "Median-outlier", scores, relation.getDBIDs());
OutlierScoreMeta scoreMeta = new BasicOutlierScoreMeta(minmax.getMin(), minmax.getMax(), 0.0, Double.POSITIVE_INFINITY, 0);
OutlierResult or = new OutlierResult(scoreMeta, scoreResult);
or.addChildResult(npred);
return or;
} } |
public class class_name {
public java.util.List<String> getOperations() {
if (operations == null) {
operations = new com.amazonaws.internal.SdkInternalList<String>();
}
return operations;
} } | public class class_name {
public java.util.List<String> getOperations() {
if (operations == null) {
operations = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return operations;
} } |
public class class_name {
public void marshall(CreateAliasRequest createAliasRequest, ProtocolMarshaller protocolMarshaller) {
if (createAliasRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createAliasRequest.getOrganizationId(), ORGANIZATIONID_BINDING);
protocolMarshaller.marshall(createAliasRequest.getEntityId(), ENTITYID_BINDING);
protocolMarshaller.marshall(createAliasRequest.getAlias(), ALIAS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateAliasRequest createAliasRequest, ProtocolMarshaller protocolMarshaller) {
if (createAliasRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createAliasRequest.getOrganizationId(), ORGANIZATIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createAliasRequest.getEntityId(), ENTITYID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createAliasRequest.getAlias(), ALIAS_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 boolean loadedByThisOrChild(Class clazz)
{
boolean result = false;
for (ClassLoader classLoader = clazz.getClassLoader();
null != classLoader; classLoader = classLoader.getParent()) {
if (classLoader.equals(this)) {
result = true;
break;
}
}
return result;
} } | public class class_name {
protected boolean loadedByThisOrChild(Class clazz)
{
boolean result = false;
for (ClassLoader classLoader = clazz.getClassLoader();
null != classLoader; classLoader = classLoader.getParent()) {
if (classLoader.equals(this)) {
result = true; // depends on control dependency: [if], data = [none]
break;
}
}
return result;
} } |
public class class_name {
@Override
protected Image parseImage(final Element rssRoot) {
final Image image = super.parseImage(rssRoot);
if (image != null) {
final Element eImage = getImage(rssRoot);
final Element width = eImage.getChild("width", getRSSNamespace());
if (width != null) {
final Integer val = NumberParser.parseInt(width.getText());
if (val != null) {
image.setWidth(val);
}
}
final Element height = eImage.getChild("height", getRSSNamespace());
if (height != null) {
final Integer val = NumberParser.parseInt(height.getText());
if (val != null) {
image.setHeight(val);
}
}
final Element description = eImage.getChild("description", getRSSNamespace());
if (description != null) {
image.setDescription(description.getText());
}
}
return image;
} } | public class class_name {
@Override
protected Image parseImage(final Element rssRoot) {
final Image image = super.parseImage(rssRoot);
if (image != null) {
final Element eImage = getImage(rssRoot);
final Element width = eImage.getChild("width", getRSSNamespace());
if (width != null) {
final Integer val = NumberParser.parseInt(width.getText());
if (val != null) {
image.setWidth(val); // depends on control dependency: [if], data = [(val]
}
}
final Element height = eImage.getChild("height", getRSSNamespace());
if (height != null) {
final Integer val = NumberParser.parseInt(height.getText());
if (val != null) {
image.setHeight(val); // depends on control dependency: [if], data = [(val]
}
}
final Element description = eImage.getChild("description", getRSSNamespace());
if (description != null) {
image.setDescription(description.getText()); // depends on control dependency: [if], data = [(description]
}
}
return image;
} } |
public class class_name {
public static <T> ImmutableMultimap<T, Integer> itemToIndexMultimap(
Iterable<T> iterable) {
final ImmutableMultimap.Builder<T, Integer> ret = ImmutableMultimap.builder();
int idx = 0;
for (final T x : iterable) {
ret.put(x, idx++);
}
return ret.build();
} } | public class class_name {
public static <T> ImmutableMultimap<T, Integer> itemToIndexMultimap(
Iterable<T> iterable) {
final ImmutableMultimap.Builder<T, Integer> ret = ImmutableMultimap.builder();
int idx = 0;
for (final T x : iterable) {
ret.put(x, idx++); // depends on control dependency: [for], data = [x]
}
return ret.build();
} } |
public class class_name {
public final void setElementAt(int value, int index)
{
if (index >= m_mapSize)
{
int oldSize = m_mapSize;
m_mapSize += m_blocksize;
int newMap[] = new int[m_mapSize];
System.arraycopy(m_map, 0, newMap, 0, oldSize);
m_map = newMap;
}
m_map[index] = value;
} } | public class class_name {
public final void setElementAt(int value, int index)
{
if (index >= m_mapSize)
{
int oldSize = m_mapSize;
m_mapSize += m_blocksize; // depends on control dependency: [if], data = [none]
int newMap[] = new int[m_mapSize];
System.arraycopy(m_map, 0, newMap, 0, oldSize); // depends on control dependency: [if], data = [none]
m_map = newMap; // depends on control dependency: [if], data = [none]
}
m_map[index] = value;
} } |
public class class_name {
public static double[] getMaximumValues(Front front) {
if (front == null) {
throw new NullFrontException() ;
} else if (front.getNumberOfPoints() == 0) {
throw new EmptyFrontException() ;
}
int numberOfObjectives = front.getPoint(0).getDimension() ;
double[] maximumValue = new double[numberOfObjectives];
for (int i = 0; i < numberOfObjectives; i++) {
maximumValue[i] = Double.NEGATIVE_INFINITY;
}
for (int i = 0 ; i < front.getNumberOfPoints(); i++) {
for (int j = 0; j < numberOfObjectives; j++) {
if (front.getPoint(i).getValue(j) > maximumValue[j]) {
maximumValue[j] = front.getPoint(i).getValue(j);
}
}
}
return maximumValue;
} } | public class class_name {
public static double[] getMaximumValues(Front front) {
if (front == null) {
throw new NullFrontException() ;
} else if (front.getNumberOfPoints() == 0) {
throw new EmptyFrontException() ;
}
int numberOfObjectives = front.getPoint(0).getDimension() ;
double[] maximumValue = new double[numberOfObjectives];
for (int i = 0; i < numberOfObjectives; i++) {
maximumValue[i] = Double.NEGATIVE_INFINITY; // depends on control dependency: [for], data = [i]
}
for (int i = 0 ; i < front.getNumberOfPoints(); i++) {
for (int j = 0; j < numberOfObjectives; j++) {
if (front.getPoint(i).getValue(j) > maximumValue[j]) {
maximumValue[j] = front.getPoint(i).getValue(j); // depends on control dependency: [if], data = [none]
}
}
}
return maximumValue;
} } |
public class class_name {
public void removeLRU() {
int removeCount = (int) Math.max((size() * trimFactor), 1);
while ((removeCount--) > 0) {
removeEntry(head.next);
}
} } | public class class_name {
public void removeLRU() {
int removeCount = (int) Math.max((size() * trimFactor), 1);
while ((removeCount--) > 0) {
removeEntry(head.next);
// depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
private Expression parseVersionExpression() {
int major = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
if (tokens.positiveLookahead(STAR)) {
tokens.consume();
return new And(new GreaterOrEqual(versionOf(major, 0, 0)),
new Less(versionOf(major + 1, 0, 0)));
}
int minor = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
consumeNextToken(STAR);
return new And(new GreaterOrEqual(versionOf(major, minor, 0)),
new Less(versionOf(major, minor + 1, 0)));
} } | public class class_name {
private Expression parseVersionExpression() {
int major = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
if (tokens.positiveLookahead(STAR)) {
tokens.consume(); // depends on control dependency: [if], data = [none]
return new And(new GreaterOrEqual(versionOf(major, 0, 0)),
new Less(versionOf(major + 1, 0, 0))); // depends on control dependency: [if], data = [none]
}
int minor = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
consumeNextToken(STAR);
return new And(new GreaterOrEqual(versionOf(major, minor, 0)),
new Less(versionOf(major, minor + 1, 0)));
} } |
public class class_name {
public static double J0(double x) {
double ax;
if ((ax = Math.abs(x)) < 8.0) {
double y = x * x;
double ans1 = 57568490574.0 + y * (-13362590354.0 + y * (651619640.7
+ y * (-11214424.18 + y * (77392.33017 + y * (-184.9052456)))));
double ans2 = 57568490411.0 + y * (1029532985.0 + y * (9494680.718
+ y * (59272.64853 + y * (267.8532712 + y * 1.0))));
return ans1 / ans2;
} else {
double z = 8.0 / ax;
double y = z * z;
double xx = ax - 0.785398164;
double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4
+ y * (-0.2073370639e-5 + y * 0.2093887211e-6)));
double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3
+ y * (-0.6911147651e-5 + y * (0.7621095161e-6
- y * 0.934935152e-7)));
return Math.sqrt(0.636619772 / ax) *
(Math.cos(xx) * ans1 - z * Math.sin(xx) * ans2);
}
} } | public class class_name {
public static double J0(double x) {
double ax;
if ((ax = Math.abs(x)) < 8.0) {
double y = x * x;
double ans1 = 57568490574.0 + y * (-13362590354.0 + y * (651619640.7
+ y * (-11214424.18 + y * (77392.33017 + y * (-184.9052456)))));
double ans2 = 57568490411.0 + y * (1029532985.0 + y * (9494680.718
+ y * (59272.64853 + y * (267.8532712 + y * 1.0))));
return ans1 / ans2;
// depends on control dependency: [if], data = [none]
} else {
double z = 8.0 / ax;
double y = z * z;
double xx = ax - 0.785398164;
double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4
+ y * (-0.2073370639e-5 + y * 0.2093887211e-6)));
double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3
+ y * (-0.6911147651e-5 + y * (0.7621095161e-6
- y * 0.934935152e-7)));
return Math.sqrt(0.636619772 / ax) *
(Math.cos(xx) * ans1 - z * Math.sin(xx) * ans2);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static <R> ImmutableCell<R> copyOf(Cell<? extends R> cell) {
if (cell == null) {
throw new IllegalArgumentException("Cell must not be null");
}
if (cell instanceof ImmutableCell) {
@SuppressWarnings("unchecked")
ImmutableCell<R> result = (ImmutableCell<R>) cell;
return result;
}
return ImmutableCell.<R>of(cell.getRow(), cell.getColumn(), cell.getValue());
} } | public class class_name {
public static <R> ImmutableCell<R> copyOf(Cell<? extends R> cell) {
if (cell == null) {
throw new IllegalArgumentException("Cell must not be null");
}
if (cell instanceof ImmutableCell) {
@SuppressWarnings("unchecked")
ImmutableCell<R> result = (ImmutableCell<R>) cell;
return result; // depends on control dependency: [if], data = [none]
}
return ImmutableCell.<R>of(cell.getRow(), cell.getColumn(), cell.getValue());
} } |
public class class_name {
public static <T extends Annotation> Optional<T> getAnnotation( String annotation, List<? extends HasAnnotations>
hasAnnotationsList ) {
try {
Class clazz = Class.forName( annotation );
return getAnnotation( clazz, hasAnnotationsList );
} catch ( ClassNotFoundException e ) {
return Optional.absent();
}
} } | public class class_name {
public static <T extends Annotation> Optional<T> getAnnotation( String annotation, List<? extends HasAnnotations>
hasAnnotationsList ) {
try {
Class clazz = Class.forName( annotation );
return getAnnotation( clazz, hasAnnotationsList ); // depends on control dependency: [try], data = [none]
} catch ( ClassNotFoundException e ) {
return Optional.absent();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(StructValue structValue, ProtocolMarshaller protocolMarshaller) {
if (structValue == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(structValue.getAttributes(), ATTRIBUTES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(StructValue structValue, ProtocolMarshaller protocolMarshaller) {
if (structValue == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(structValue.getAttributes(), ATTRIBUTES_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static ArrayList<DateMatch> matchDatesWithSeparator(Configuration configuration, String password)
{
// Initialize the list of matching dates
ArrayList<DateMatch> dateMatches = new ArrayList<>();
// Create all possible subsequences of the password
for (int start = 0; start < password.length(); start++)
{
for (int end = start + 6; end <= password.length(); end++)
{
// Get the subsequence
String passwordChunk = password.substring(start, end);
// Extract the date (if there is one) with the year as prefix
Matcher m1 = DATE_WITH_SEPARATOR_YEAR_SUFFIX.matcher(passwordChunk);
if (m1.matches())
{
ValidDateSplit split = isDateValid(m1.group(1), m1.group(3), m1.group(4));
if (split != null)
{
dateMatches.add(new DateMatch(passwordChunk, configuration, split.date, split.month, split.year, m1.group(2), start, end - 1));
}
}
// Extract the date (if there is one) with the year as suffix
Matcher m2 = DATE_WITH_SEPARATOR_YEAR_PREFIX.matcher(passwordChunk);
if (m2.matches())
{
ValidDateSplit split = isDateValid(m2.group(4), m2.group(3), m2.group(1));
if (split != null)
{
dateMatches.add(new DateMatch(passwordChunk, configuration, split.date, split.month, split.year, m2.group(2), start, end - 1));
}
}
}
}
return dateMatches;
} } | public class class_name {
private static ArrayList<DateMatch> matchDatesWithSeparator(Configuration configuration, String password)
{
// Initialize the list of matching dates
ArrayList<DateMatch> dateMatches = new ArrayList<>();
// Create all possible subsequences of the password
for (int start = 0; start < password.length(); start++)
{
for (int end = start + 6; end <= password.length(); end++)
{
// Get the subsequence
String passwordChunk = password.substring(start, end);
// Extract the date (if there is one) with the year as prefix
Matcher m1 = DATE_WITH_SEPARATOR_YEAR_SUFFIX.matcher(passwordChunk);
if (m1.matches())
{
ValidDateSplit split = isDateValid(m1.group(1), m1.group(3), m1.group(4));
if (split != null)
{
dateMatches.add(new DateMatch(passwordChunk, configuration, split.date, split.month, split.year, m1.group(2), start, end - 1)); // depends on control dependency: [if], data = [none]
}
}
// Extract the date (if there is one) with the year as suffix
Matcher m2 = DATE_WITH_SEPARATOR_YEAR_PREFIX.matcher(passwordChunk);
if (m2.matches())
{
ValidDateSplit split = isDateValid(m2.group(4), m2.group(3), m2.group(1));
if (split != null)
{
dateMatches.add(new DateMatch(passwordChunk, configuration, split.date, split.month, split.year, m2.group(2), start, end - 1)); // depends on control dependency: [if], data = [none]
}
}
}
}
return dateMatches;
} } |
public class class_name {
private void performScriptedStep() {
double scale = computeBulgeScale();
if( steps > giveUpOnKnown ) {
// give up on the script
followScript = false;
} else {
// use previous singular value to step
double s = values[x2]/scale;
performImplicitSingleStep(scale,s*s,false);
}
} } | public class class_name {
private void performScriptedStep() {
double scale = computeBulgeScale();
if( steps > giveUpOnKnown ) {
// give up on the script
followScript = false; // depends on control dependency: [if], data = [none]
} else {
// use previous singular value to step
double s = values[x2]/scale;
performImplicitSingleStep(scale,s*s,false); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
protected List<String> mate(String parent1,
String parent2,
int numberOfCrossoverPoints,
Random rng)
{
if (parent1.length() != parent2.length())
{
throw new IllegalArgumentException("Cannot perform cross-over with different length parents.");
}
StringBuilder offspring1 = new StringBuilder(parent1);
StringBuilder offspring2 = new StringBuilder(parent2);
// Apply as many cross-overs as required.
for (int i = 0; i < numberOfCrossoverPoints; i++)
{
// Cross-over index is always greater than zero and less than
// the length of the parent so that we always pick a point that
// will result in a meaningful cross-over.
int crossoverIndex = (1 + rng.nextInt(parent1.length() - 1));
for (int j = 0; j < crossoverIndex; j++)
{
char temp = offspring1.charAt(j);
offspring1.setCharAt(j, offspring2.charAt(j));
offspring2.setCharAt(j, temp);
}
}
List<String> result = new ArrayList<String>(2);
result.add(offspring1.toString());
result.add(offspring2.toString());
return result;
} } | public class class_name {
@Override
protected List<String> mate(String parent1,
String parent2,
int numberOfCrossoverPoints,
Random rng)
{
if (parent1.length() != parent2.length())
{
throw new IllegalArgumentException("Cannot perform cross-over with different length parents.");
}
StringBuilder offspring1 = new StringBuilder(parent1);
StringBuilder offspring2 = new StringBuilder(parent2);
// Apply as many cross-overs as required.
for (int i = 0; i < numberOfCrossoverPoints; i++)
{
// Cross-over index is always greater than zero and less than
// the length of the parent so that we always pick a point that
// will result in a meaningful cross-over.
int crossoverIndex = (1 + rng.nextInt(parent1.length() - 1));
for (int j = 0; j < crossoverIndex; j++)
{
char temp = offspring1.charAt(j);
offspring1.setCharAt(j, offspring2.charAt(j)); // depends on control dependency: [for], data = [j]
offspring2.setCharAt(j, temp); // depends on control dependency: [for], data = [j]
}
}
List<String> result = new ArrayList<String>(2);
result.add(offspring1.toString());
result.add(offspring2.toString());
return result;
} } |
public class class_name {
public static void close (Reader in)
{
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
log.warning("Error closing reader", "reader", in, "cause", ioe);
}
}
} } | public class class_name {
public static void close (Reader in)
{
if (in != null) {
try {
in.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
log.warning("Error closing reader", "reader", in, "cause", ioe);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public static void substituteExternalGraphics( Rule rule, URL externalGraphicsUrl ) {
String urlString = externalGraphicsUrl.toString();
String format = "";
if (urlString.toLowerCase().endsWith(".png")) {
format = "image/png";
} else if (urlString.toLowerCase().endsWith(".jpg")) {
format = "image/jpg";
} else if (urlString.toLowerCase().endsWith(".svg")) {
format = "image/svg+xml";
} else {
urlString = "";
try {
externalGraphicsUrl = new URL("file:");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule);
Graphic graphic = SLD.graphic(pointSymbolizer);
graphic.graphicalSymbols().clear();
ExternalGraphic exGraphic = sf.createExternalGraphic(externalGraphicsUrl, format);
graphic.graphicalSymbols().add(exGraphic);
} } | public class class_name {
public static void substituteExternalGraphics( Rule rule, URL externalGraphicsUrl ) {
String urlString = externalGraphicsUrl.toString();
String format = "";
if (urlString.toLowerCase().endsWith(".png")) {
format = "image/png"; // depends on control dependency: [if], data = [none]
} else if (urlString.toLowerCase().endsWith(".jpg")) {
format = "image/jpg"; // depends on control dependency: [if], data = [none]
} else if (urlString.toLowerCase().endsWith(".svg")) {
format = "image/svg+xml"; // depends on control dependency: [if], data = [none]
} else {
urlString = ""; // depends on control dependency: [if], data = [none]
try {
externalGraphicsUrl = new URL("file:"); // depends on control dependency: [try], data = [none]
} catch (MalformedURLException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule);
Graphic graphic = SLD.graphic(pointSymbolizer);
graphic.graphicalSymbols().clear();
ExternalGraphic exGraphic = sf.createExternalGraphic(externalGraphicsUrl, format);
graphic.graphicalSymbols().add(exGraphic);
} } |
public class class_name {
public synchronized void destroy()
{
if (state == Destroyed)
return;
if (state != Disconnected)
try {
tl.disconnect(this);
}
catch (final KNXLinkClosedException e) {
// we already should've been destroyed on catching this exception
}
setState(Destroyed, null);
tl.destroyDestination(this);
} } | public class class_name {
public synchronized void destroy()
{
if (state == Destroyed)
return;
if (state != Disconnected)
try {
tl.disconnect(this); // depends on control dependency: [try], data = [none]
}
catch (final KNXLinkClosedException e) {
// we already should've been destroyed on catching this exception
} // depends on control dependency: [catch], data = [none]
setState(Destroyed, null);
tl.destroyDestination(this);
} } |
public class class_name {
public Observable<ServiceResponseWithHeaders<Void, ComputeNodeDisableSchedulingHeaders>> disableSchedulingWithServiceResponseAsync(String poolId, String nodeId) {
if (this.client.batchUrl() == null) {
throw new IllegalArgumentException("Parameter this.client.batchUrl() is required and cannot be null.");
}
if (poolId == null) {
throw new IllegalArgumentException("Parameter poolId is required and cannot be null.");
}
if (nodeId == null) {
throw new IllegalArgumentException("Parameter nodeId is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
final DisableComputeNodeSchedulingOption nodeDisableSchedulingOption = null;
final ComputeNodeDisableSchedulingOptions computeNodeDisableSchedulingOptions = null;
Integer timeout = null;
UUID clientRequestId = null;
Boolean returnClientRequestId = null;
DateTime ocpDate = null;
NodeDisableSchedulingParameter nodeDisableSchedulingParameter = new NodeDisableSchedulingParameter();
nodeDisableSchedulingParameter.withNodeDisableSchedulingOption(null);
String parameterizedHost = Joiner.on(", ").join("{batchUrl}", this.client.batchUrl());
DateTimeRfc1123 ocpDateConverted = null;
if (ocpDate != null) {
ocpDateConverted = new DateTimeRfc1123(ocpDate);
}
return service.disableScheduling(poolId, nodeId, this.client.apiVersion(), this.client.acceptLanguage(), timeout, clientRequestId, returnClientRequestId, ocpDateConverted, nodeDisableSchedulingParameter, parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponseWithHeaders<Void, ComputeNodeDisableSchedulingHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Void, ComputeNodeDisableSchedulingHeaders>> call(Response<ResponseBody> response) {
try {
ServiceResponseWithHeaders<Void, ComputeNodeDisableSchedulingHeaders> clientResponse = disableSchedulingDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponseWithHeaders<Void, ComputeNodeDisableSchedulingHeaders>> disableSchedulingWithServiceResponseAsync(String poolId, String nodeId) {
if (this.client.batchUrl() == null) {
throw new IllegalArgumentException("Parameter this.client.batchUrl() is required and cannot be null.");
}
if (poolId == null) {
throw new IllegalArgumentException("Parameter poolId is required and cannot be null.");
}
if (nodeId == null) {
throw new IllegalArgumentException("Parameter nodeId is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
final DisableComputeNodeSchedulingOption nodeDisableSchedulingOption = null;
final ComputeNodeDisableSchedulingOptions computeNodeDisableSchedulingOptions = null;
Integer timeout = null;
UUID clientRequestId = null;
Boolean returnClientRequestId = null;
DateTime ocpDate = null;
NodeDisableSchedulingParameter nodeDisableSchedulingParameter = new NodeDisableSchedulingParameter();
nodeDisableSchedulingParameter.withNodeDisableSchedulingOption(null);
String parameterizedHost = Joiner.on(", ").join("{batchUrl}", this.client.batchUrl());
DateTimeRfc1123 ocpDateConverted = null;
if (ocpDate != null) {
ocpDateConverted = new DateTimeRfc1123(ocpDate); // depends on control dependency: [if], data = [(ocpDate]
}
return service.disableScheduling(poolId, nodeId, this.client.apiVersion(), this.client.acceptLanguage(), timeout, clientRequestId, returnClientRequestId, ocpDateConverted, nodeDisableSchedulingParameter, parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponseWithHeaders<Void, ComputeNodeDisableSchedulingHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Void, ComputeNodeDisableSchedulingHeaders>> call(Response<ResponseBody> response) {
try {
ServiceResponseWithHeaders<Void, ComputeNodeDisableSchedulingHeaders> clientResponse = disableSchedulingDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public Observable<ServiceResponseWithHeaders<Page<PoolUsageMetrics>, PoolListUsageMetricsHeaders>> listUsageMetricsWithServiceResponseAsync(final PoolListUsageMetricsOptions poolListUsageMetricsOptions) {
return listUsageMetricsSinglePageAsync(poolListUsageMetricsOptions)
.concatMap(new Func1<ServiceResponseWithHeaders<Page<PoolUsageMetrics>, PoolListUsageMetricsHeaders>, Observable<ServiceResponseWithHeaders<Page<PoolUsageMetrics>, PoolListUsageMetricsHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<PoolUsageMetrics>, PoolListUsageMetricsHeaders>> call(ServiceResponseWithHeaders<Page<PoolUsageMetrics>, PoolListUsageMetricsHeaders> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
PoolListUsageMetricsNextOptions poolListUsageMetricsNextOptions = null;
if (poolListUsageMetricsOptions != null) {
poolListUsageMetricsNextOptions = new PoolListUsageMetricsNextOptions();
poolListUsageMetricsNextOptions.withClientRequestId(poolListUsageMetricsOptions.clientRequestId());
poolListUsageMetricsNextOptions.withReturnClientRequestId(poolListUsageMetricsOptions.returnClientRequestId());
poolListUsageMetricsNextOptions.withOcpDate(poolListUsageMetricsOptions.ocpDate());
}
return Observable.just(page).concatWith(listUsageMetricsNextWithServiceResponseAsync(nextPageLink, poolListUsageMetricsNextOptions));
}
});
} } | public class class_name {
public Observable<ServiceResponseWithHeaders<Page<PoolUsageMetrics>, PoolListUsageMetricsHeaders>> listUsageMetricsWithServiceResponseAsync(final PoolListUsageMetricsOptions poolListUsageMetricsOptions) {
return listUsageMetricsSinglePageAsync(poolListUsageMetricsOptions)
.concatMap(new Func1<ServiceResponseWithHeaders<Page<PoolUsageMetrics>, PoolListUsageMetricsHeaders>, Observable<ServiceResponseWithHeaders<Page<PoolUsageMetrics>, PoolListUsageMetricsHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<PoolUsageMetrics>, PoolListUsageMetricsHeaders>> call(ServiceResponseWithHeaders<Page<PoolUsageMetrics>, PoolListUsageMetricsHeaders> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page); // depends on control dependency: [if], data = [none]
}
PoolListUsageMetricsNextOptions poolListUsageMetricsNextOptions = null;
if (poolListUsageMetricsOptions != null) {
poolListUsageMetricsNextOptions = new PoolListUsageMetricsNextOptions(); // depends on control dependency: [if], data = [none]
poolListUsageMetricsNextOptions.withClientRequestId(poolListUsageMetricsOptions.clientRequestId()); // depends on control dependency: [if], data = [(poolListUsageMetricsOptions]
poolListUsageMetricsNextOptions.withReturnClientRequestId(poolListUsageMetricsOptions.returnClientRequestId()); // depends on control dependency: [if], data = [(poolListUsageMetricsOptions]
poolListUsageMetricsNextOptions.withOcpDate(poolListUsageMetricsOptions.ocpDate()); // depends on control dependency: [if], data = [(poolListUsageMetricsOptions]
}
return Observable.just(page).concatWith(listUsageMetricsNextWithServiceResponseAsync(nextPageLink, poolListUsageMetricsNextOptions));
}
});
} } |
public class class_name {
private final int ensureRunBreak(int offset, boolean copyAttrs) {
if (offset == length()) {
return runCount;
}
// search for the run index where this offset should be
int runIndex = 0;
while (runIndex < runCount && runStarts[runIndex] < offset) {
runIndex++;
}
// if the offset is at a run start already, we're done
if (runIndex < runCount && runStarts[runIndex] == offset) {
return runIndex;
}
// we'll have to break up a run
// first, make sure we have enough space in our arrays
if (runCount == runArraySize) {
int newArraySize = runArraySize + ARRAY_SIZE_INCREMENT;
int newRunStarts[] = new int[newArraySize];
Vector newRunAttributes[] = new Vector[newArraySize];
Vector newRunAttributeValues[] = new Vector[newArraySize];
for (int i = 0; i < runArraySize; i++) {
newRunStarts[i] = runStarts[i];
newRunAttributes[i] = runAttributes[i];
newRunAttributeValues[i] = runAttributeValues[i];
}
runStarts = newRunStarts;
runAttributes = newRunAttributes;
runAttributeValues = newRunAttributeValues;
runArraySize = newArraySize;
}
// make copies of the attribute information of the old run that the new one used to be part of
// use temporary variables so things remain consistent in case of an exception
Vector newRunAttributes = null;
Vector newRunAttributeValues = null;
if (copyAttrs) {
Vector oldRunAttributes = runAttributes[runIndex - 1];
Vector oldRunAttributeValues = runAttributeValues[runIndex - 1];
if (oldRunAttributes != null) {
newRunAttributes = (Vector) oldRunAttributes.clone();
}
if (oldRunAttributeValues != null) {
newRunAttributeValues = (Vector) oldRunAttributeValues.clone();
}
}
// now actually break up the run
runCount++;
for (int i = runCount - 1; i > runIndex; i--) {
runStarts[i] = runStarts[i - 1];
runAttributes[i] = runAttributes[i - 1];
runAttributeValues[i] = runAttributeValues[i - 1];
}
runStarts[runIndex] = offset;
runAttributes[runIndex] = newRunAttributes;
runAttributeValues[runIndex] = newRunAttributeValues;
return runIndex;
} } | public class class_name {
private final int ensureRunBreak(int offset, boolean copyAttrs) {
if (offset == length()) {
return runCount; // depends on control dependency: [if], data = [none]
}
// search for the run index where this offset should be
int runIndex = 0;
while (runIndex < runCount && runStarts[runIndex] < offset) {
runIndex++; // depends on control dependency: [while], data = [none]
}
// if the offset is at a run start already, we're done
if (runIndex < runCount && runStarts[runIndex] == offset) {
return runIndex; // depends on control dependency: [if], data = [none]
}
// we'll have to break up a run
// first, make sure we have enough space in our arrays
if (runCount == runArraySize) {
int newArraySize = runArraySize + ARRAY_SIZE_INCREMENT;
int newRunStarts[] = new int[newArraySize];
Vector newRunAttributes[] = new Vector[newArraySize];
Vector newRunAttributeValues[] = new Vector[newArraySize];
for (int i = 0; i < runArraySize; i++) {
newRunStarts[i] = runStarts[i]; // depends on control dependency: [for], data = [i]
newRunAttributes[i] = runAttributes[i]; // depends on control dependency: [for], data = [i]
newRunAttributeValues[i] = runAttributeValues[i]; // depends on control dependency: [for], data = [i]
}
runStarts = newRunStarts; // depends on control dependency: [if], data = [none]
runAttributes = newRunAttributes; // depends on control dependency: [if], data = [none]
runAttributeValues = newRunAttributeValues; // depends on control dependency: [if], data = [none]
runArraySize = newArraySize; // depends on control dependency: [if], data = [none]
}
// make copies of the attribute information of the old run that the new one used to be part of
// use temporary variables so things remain consistent in case of an exception
Vector newRunAttributes = null;
Vector newRunAttributeValues = null;
if (copyAttrs) {
Vector oldRunAttributes = runAttributes[runIndex - 1];
Vector oldRunAttributeValues = runAttributeValues[runIndex - 1];
if (oldRunAttributes != null) {
newRunAttributes = (Vector) oldRunAttributes.clone(); // depends on control dependency: [if], data = [none]
}
if (oldRunAttributeValues != null) {
newRunAttributeValues = (Vector) oldRunAttributeValues.clone(); // depends on control dependency: [if], data = [none]
}
}
// now actually break up the run
runCount++;
for (int i = runCount - 1; i > runIndex; i--) {
runStarts[i] = runStarts[i - 1]; // depends on control dependency: [for], data = [i]
runAttributes[i] = runAttributes[i - 1]; // depends on control dependency: [for], data = [i]
runAttributeValues[i] = runAttributeValues[i - 1]; // depends on control dependency: [for], data = [i]
}
runStarts[runIndex] = offset;
runAttributes[runIndex] = newRunAttributes;
runAttributeValues[runIndex] = newRunAttributeValues;
return runIndex;
} } |
public class class_name {
public HTMLGen directive(String tag, String ... attrs) {
forward.append('<');
forward.append(tag);
addAttrs(attrs);
forward.append('>');
if(pretty) {
forward.println();
}
return this;
} } | public class class_name {
public HTMLGen directive(String tag, String ... attrs) {
forward.append('<');
forward.append(tag);
addAttrs(attrs);
forward.append('>');
if(pretty) {
forward.println(); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
protected void setCalendarHour(Calendar cal, int hour) {
cal.set(Calendar.HOUR_OF_DAY, hour);
if (cal.get(Calendar.HOUR_OF_DAY) != hour && hour != 24) {
cal.set(Calendar.HOUR_OF_DAY, hour + 1);
}
} } | public class class_name {
protected void setCalendarHour(Calendar cal, int hour) {
cal.set(Calendar.HOUR_OF_DAY, hour);
if (cal.get(Calendar.HOUR_OF_DAY) != hour && hour != 24) {
cal.set(Calendar.HOUR_OF_DAY, hour + 1); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected void startReplications() {
if (mReplicationPolicyManager != null) {
// Make sure we've got a WiFi lock so that the wifi isn't switched off while we're
// trying to replicate.
if (mWifiLock != null) {
synchronized (mWifiLock) {
if (!mWifiLock.isHeld()) {
mWifiLock.acquire();
}
}
}
mReplicationPolicyManager.startReplications();
}
} } | public class class_name {
protected void startReplications() {
if (mReplicationPolicyManager != null) {
// Make sure we've got a WiFi lock so that the wifi isn't switched off while we're
// trying to replicate.
if (mWifiLock != null) {
synchronized (mWifiLock) { // depends on control dependency: [if], data = [(mWifiLock]
if (!mWifiLock.isHeld()) {
mWifiLock.acquire(); // depends on control dependency: [if], data = [none]
}
}
}
mReplicationPolicyManager.startReplications(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
DataOutputStream openDataOutputStream()
{
final OutputStream os = getOutputStream();
if (os instanceof DataOutputStream) {
return (DataOutputStream) os;
}
return new DataOutputStream(os);
} } | public class class_name {
DataOutputStream openDataOutputStream()
{
final OutputStream os = getOutputStream();
if (os instanceof DataOutputStream) {
return (DataOutputStream) os;
// depends on control dependency: [if], data = [none]
}
return new DataOutputStream(os);
} } |
public class class_name {
public void startMetricReporting(Properties properties) {
if (this.metricsReportingStarted) {
LOGGER.warn("Metric reporting has already started");
return;
}
TimeUnit reportTimeUnit = TimeUnit.MILLISECONDS;
long reportInterval = Long.parseLong(properties
.getProperty(ConfigurationKeys.METRICS_REPORT_INTERVAL_KEY, ConfigurationKeys.DEFAULT_METRICS_REPORT_INTERVAL));
ScheduledReporter.setReportingInterval(properties, reportInterval, reportTimeUnit);
long startTime = System.currentTimeMillis();
try {
// Build and start the JMX reporter
buildJmxMetricReporter(properties);
if (this.jmxReporter.isPresent()) {
LOGGER.info("Will start reporting metrics to JMX");
this.jmxReporter.get().start();
}
// Build all other reporters
buildFileMetricReporter(properties);
buildKafkaMetricReporter(properties);
buildGraphiteMetricReporter(properties);
buildInfluxDBMetricReporter(properties);
buildCustomMetricReporters(properties);
buildFileFailureEventReporter(properties);
// Start reporters that implement org.apache.gobblin.metrics.report.ScheduledReporter
RootMetricContext.get().startReporting();
// Start reporters that implement com.codahale.metrics.ScheduledReporter
for (com.codahale.metrics.ScheduledReporter scheduledReporter : this.codahaleScheduledReporters) {
scheduledReporter.start(reportInterval, reportTimeUnit);
}
} catch (Exception e) {
LOGGER.error("Metrics reporting cannot be started due to {}", ExceptionUtils.getFullStackTrace(e));
throw e;
}
this.metricsReportingStarted = true;
LOGGER.info("Metrics reporting has been started in {} ms: GobblinMetrics {}",
System.currentTimeMillis() - startTime, this.toString());
} } | public class class_name {
public void startMetricReporting(Properties properties) {
if (this.metricsReportingStarted) {
LOGGER.warn("Metric reporting has already started"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
TimeUnit reportTimeUnit = TimeUnit.MILLISECONDS;
long reportInterval = Long.parseLong(properties
.getProperty(ConfigurationKeys.METRICS_REPORT_INTERVAL_KEY, ConfigurationKeys.DEFAULT_METRICS_REPORT_INTERVAL));
ScheduledReporter.setReportingInterval(properties, reportInterval, reportTimeUnit);
long startTime = System.currentTimeMillis();
try {
// Build and start the JMX reporter
buildJmxMetricReporter(properties); // depends on control dependency: [try], data = [none]
if (this.jmxReporter.isPresent()) {
LOGGER.info("Will start reporting metrics to JMX"); // depends on control dependency: [if], data = [none]
this.jmxReporter.get().start(); // depends on control dependency: [if], data = [none]
}
// Build all other reporters
buildFileMetricReporter(properties); // depends on control dependency: [try], data = [none]
buildKafkaMetricReporter(properties); // depends on control dependency: [try], data = [none]
buildGraphiteMetricReporter(properties); // depends on control dependency: [try], data = [none]
buildInfluxDBMetricReporter(properties); // depends on control dependency: [try], data = [none]
buildCustomMetricReporters(properties); // depends on control dependency: [try], data = [none]
buildFileFailureEventReporter(properties); // depends on control dependency: [try], data = [none]
// Start reporters that implement org.apache.gobblin.metrics.report.ScheduledReporter
RootMetricContext.get().startReporting(); // depends on control dependency: [try], data = [none]
// Start reporters that implement com.codahale.metrics.ScheduledReporter
for (com.codahale.metrics.ScheduledReporter scheduledReporter : this.codahaleScheduledReporters) {
scheduledReporter.start(reportInterval, reportTimeUnit); // depends on control dependency: [for], data = [scheduledReporter]
}
} catch (Exception e) {
LOGGER.error("Metrics reporting cannot be started due to {}", ExceptionUtils.getFullStackTrace(e));
throw e;
} // depends on control dependency: [catch], data = [none]
this.metricsReportingStarted = true;
LOGGER.info("Metrics reporting has been started in {} ms: GobblinMetrics {}",
System.currentTimeMillis() - startTime, this.toString());
} } |
public class class_name {
public static DynaBean newDynaBean( JSONObject jsonObject, JsonConfig jsonConfig ) {
Map props = getProperties( jsonObject );
for( Iterator entries = props.entrySet()
.iterator(); entries.hasNext(); ){
Map.Entry entry = (Map.Entry) entries.next();
String key = (String) entry.getKey();
if( !JSONUtils.isJavaIdentifier( key ) ){
String parsedKey = JSONUtils.convertToJavaIdentifier( key, jsonConfig );
if( parsedKey.compareTo( key ) != 0 ){
props.put( parsedKey, props.remove( key ) );
}
}
}
MorphDynaClass dynaClass = new MorphDynaClass( props );
MorphDynaBean dynaBean = null;
try{
dynaBean = (MorphDynaBean) dynaClass.newInstance();
dynaBean.setDynaBeanClass( dynaClass );
}catch( Exception e ){
throw new JSONException( e );
}
return dynaBean;
} } | public class class_name {
public static DynaBean newDynaBean( JSONObject jsonObject, JsonConfig jsonConfig ) {
Map props = getProperties( jsonObject );
for( Iterator entries = props.entrySet()
.iterator(); entries.hasNext(); ){
Map.Entry entry = (Map.Entry) entries.next();
String key = (String) entry.getKey();
if( !JSONUtils.isJavaIdentifier( key ) ){
String parsedKey = JSONUtils.convertToJavaIdentifier( key, jsonConfig );
if( parsedKey.compareTo( key ) != 0 ){
props.put( parsedKey, props.remove( key ) ); // depends on control dependency: [if], data = [none]
}
}
}
MorphDynaClass dynaClass = new MorphDynaClass( props );
MorphDynaBean dynaBean = null;
try{
dynaBean = (MorphDynaBean) dynaClass.newInstance(); // depends on control dependency: [try], data = [none]
dynaBean.setDynaBeanClass( dynaClass ); // depends on control dependency: [try], data = [none]
}catch( Exception e ){
throw new JSONException( e );
} // depends on control dependency: [catch], data = [none]
return dynaBean;
} } |
public class class_name {
static void putLongIfNotNull(
@NonNull JSONObject jsonObject,
@NonNull @Size(min = 1) String fieldName,
@Nullable Long value) {
if (value == null) {
return;
}
try {
jsonObject.put(fieldName, value.longValue());
} catch (JSONException ignored) { }
} } | public class class_name {
static void putLongIfNotNull(
@NonNull JSONObject jsonObject,
@NonNull @Size(min = 1) String fieldName,
@Nullable Long value) {
if (value == null) {
return; // depends on control dependency: [if], data = [none]
}
try {
jsonObject.put(fieldName, value.longValue()); // depends on control dependency: [try], data = [none]
} catch (JSONException ignored) { } // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public PersonDocument findByFileAndString(final String filename,
final String string) {
final Query searchQuery = new Query(Criteria.where("string").is(string)
.and("filename").is(filename));
final PersonDocument personDocument = mongoTemplate.findOne(
searchQuery, PersonDocumentMongo.class);
if (personDocument == null) {
return null;
}
final Person person =
(Person) toObjConverter.createGedObject(null, personDocument);
personDocument.setGedObject(person);
return personDocument;
} } | public class class_name {
@Override
public PersonDocument findByFileAndString(final String filename,
final String string) {
final Query searchQuery = new Query(Criteria.where("string").is(string)
.and("filename").is(filename));
final PersonDocument personDocument = mongoTemplate.findOne(
searchQuery, PersonDocumentMongo.class);
if (personDocument == null) {
return null; // depends on control dependency: [if], data = [none]
}
final Person person =
(Person) toObjConverter.createGedObject(null, personDocument);
personDocument.setGedObject(person);
return personDocument;
} } |
public class class_name {
@Pure
public static String getSystemSharedLibraryDirectoryNameFor(String software) {
final File f = getSystemSharedLibraryDirectoryFor(software);
if (f == null) {
return null;
}
return f.getAbsolutePath();
} } | public class class_name {
@Pure
public static String getSystemSharedLibraryDirectoryNameFor(String software) {
final File f = getSystemSharedLibraryDirectoryFor(software);
if (f == null) {
return null; // depends on control dependency: [if], data = [none]
}
return f.getAbsolutePath();
} } |
public class class_name {
private FileHandlerResult processDir(final File dir) {
// CHECKSTYLE:ON
final FileHandlerResult dirResult = handler.handleFile(dir);
if (dirResult == FileHandlerResult.STOP) {
return FileHandlerResult.STOP;
}
if (dirResult == FileHandlerResult.SKIP_ALL) {
return FileHandlerResult.CONTINUE;
}
final File[] files = dir.listFiles();
if (files != null) {
final List<File> sortedFiles = asList(files);
for (int i = 0; i < sortedFiles.size(); i++) {
final File file = sortedFiles.get(i);
FileHandlerResult result = FileHandlerResult.CONTINUE;
if (file.isDirectory() && (dirResult != FileHandlerResult.SKIP_SUBDIRS)) {
result = processDir(file);
} else if (file.isFile() && (dirResult != FileHandlerResult.SKIP_FILES)) {
result = handler.handleFile(file);
}
if (result == FileHandlerResult.STOP) {
return FileHandlerResult.STOP;
}
if (result == FileHandlerResult.SKIP_ALL) {
return FileHandlerResult.CONTINUE;
}
}
}
return FileHandlerResult.CONTINUE;
} } | public class class_name {
private FileHandlerResult processDir(final File dir) {
// CHECKSTYLE:ON
final FileHandlerResult dirResult = handler.handleFile(dir);
if (dirResult == FileHandlerResult.STOP) {
return FileHandlerResult.STOP;
// depends on control dependency: [if], data = [none]
}
if (dirResult == FileHandlerResult.SKIP_ALL) {
return FileHandlerResult.CONTINUE;
// depends on control dependency: [if], data = [none]
}
final File[] files = dir.listFiles();
if (files != null) {
final List<File> sortedFiles = asList(files);
for (int i = 0; i < sortedFiles.size(); i++) {
final File file = sortedFiles.get(i);
FileHandlerResult result = FileHandlerResult.CONTINUE;
if (file.isDirectory() && (dirResult != FileHandlerResult.SKIP_SUBDIRS)) {
result = processDir(file);
// depends on control dependency: [if], data = [none]
} else if (file.isFile() && (dirResult != FileHandlerResult.SKIP_FILES)) {
result = handler.handleFile(file);
// depends on control dependency: [if], data = [none]
}
if (result == FileHandlerResult.STOP) {
return FileHandlerResult.STOP;
// depends on control dependency: [if], data = [none]
}
if (result == FileHandlerResult.SKIP_ALL) {
return FileHandlerResult.CONTINUE;
// depends on control dependency: [if], data = [none]
}
}
}
return FileHandlerResult.CONTINUE;
} } |
public class class_name {
private String buildString() {
if (type.isSimpleType()) {
return '"' + type.name().toLowerCase() + '"';
}
StringBuilder builder = new StringBuilder();
JsonWriter writer = new JsonWriter(CharStreams.asWriter(builder));
try {
new SchemaTypeAdapter().write(writer, this);
writer.close();
return builder.toString();
} catch (IOException e) {
// It should never throw IOException on the StringBuilder Writer, if it does, something very wrong.
throw Throwables.propagate(e);
}
} } | public class class_name {
private String buildString() {
if (type.isSimpleType()) {
return '"' + type.name().toLowerCase() + '"'; // depends on control dependency: [if], data = [none]
}
StringBuilder builder = new StringBuilder();
JsonWriter writer = new JsonWriter(CharStreams.asWriter(builder));
try {
new SchemaTypeAdapter().write(writer, this); // depends on control dependency: [try], data = [none]
writer.close(); // depends on control dependency: [try], data = [none]
return builder.toString(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
// It should never throw IOException on the StringBuilder Writer, if it does, something very wrong.
throw Throwables.propagate(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public List<Transition> getTransitions(Long fromWorkId, Integer eventType, String completionCode) {
List<Transition> allTransitions = getAllTransitions(fromWorkId);
List<Transition> returnSet = findTransitions(allTransitions, eventType, completionCode);
if (returnSet.size() > 0)
return returnSet;
// look for default transition
boolean noLabelIsDefault = getTransitionWithNoLabel().equals(TRANSITION_ON_DEFAULT);
if (noLabelIsDefault) returnSet = findTransitions(allTransitions, eventType, null);
else returnSet = findTransitions(allTransitions, eventType, ActivityResultCodeConstant.RESULT_DEFAULT);
if (returnSet.size() > 0)
return returnSet;
// look for resume transition
if (eventType.equals(EventType.FINISH)) {
returnSet = new ArrayList<Transition>();
for (Transition trans : allTransitions) {
if (trans.getEventType().equals(EventType.RESUME))
returnSet.add(trans);
}
}
return returnSet;
} } | public class class_name {
public List<Transition> getTransitions(Long fromWorkId, Integer eventType, String completionCode) {
List<Transition> allTransitions = getAllTransitions(fromWorkId);
List<Transition> returnSet = findTransitions(allTransitions, eventType, completionCode);
if (returnSet.size() > 0)
return returnSet;
// look for default transition
boolean noLabelIsDefault = getTransitionWithNoLabel().equals(TRANSITION_ON_DEFAULT);
if (noLabelIsDefault) returnSet = findTransitions(allTransitions, eventType, null);
else returnSet = findTransitions(allTransitions, eventType, ActivityResultCodeConstant.RESULT_DEFAULT);
if (returnSet.size() > 0)
return returnSet;
// look for resume transition
if (eventType.equals(EventType.FINISH)) {
returnSet = new ArrayList<Transition>(); // depends on control dependency: [if], data = [none]
for (Transition trans : allTransitions) {
if (trans.getEventType().equals(EventType.RESUME))
returnSet.add(trans);
}
}
return returnSet;
} } |
public class class_name {
public MockResponse setBody(String body) {
try {
return setBody(body.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new AssertionError();
}
} } | public class class_name {
public MockResponse setBody(String body) {
try {
return setBody(body.getBytes("UTF-8")); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
throw new AssertionError();
} // depends on control dependency: [catch], data = [none]
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.