code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
@PropertySetter("allowCustom")
public void setAllowCustom(boolean allowCustom) {
customItem.setVisible(allowCustom);
if (!allowCustom) {
BaseComponent sibling;
while ((sibling = customItem.getNextSibling()) != null) {
sibling.destroy();
}
}
} } | public class class_name {
@PropertySetter("allowCustom")
public void setAllowCustom(boolean allowCustom) {
customItem.setVisible(allowCustom);
if (!allowCustom) {
BaseComponent sibling;
while ((sibling = customItem.getNextSibling()) != null) {
sibling.destroy(); // depends on control dependency: [while], data = [none]
}
}
} } |
public class class_name {
public static void copyFromTo(Object from, Object to, String fieldName) {
if (from == null || to == null) {
log.info("object deep copy : from or to is null ");
return;
}
try {
Method getter = getGetterMethod(from.getClass(), fieldName);
if (getter == null) {
//log.info("getter method not found : " + fieldName);
return;
}
Method setter = getSetterMethod(to.getClass(), fieldName, getter.getReturnType());
if (setter == null) {
//log.info("setter method not found : " + fieldName);
return;
}
setter.invoke(to, getter.invoke(from, EMPTY_CLASS));
} catch (IllegalAccessException | InvocationTargetException e) {
log.info("set method invoke error : " + fieldName);
}
} } | public class class_name {
public static void copyFromTo(Object from, Object to, String fieldName) {
if (from == null || to == null) {
log.info("object deep copy : from or to is null "); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
try {
Method getter = getGetterMethod(from.getClass(), fieldName);
if (getter == null) {
//log.info("getter method not found : " + fieldName);
return; // depends on control dependency: [if], data = [none]
}
Method setter = getSetterMethod(to.getClass(), fieldName, getter.getReturnType());
if (setter == null) {
//log.info("setter method not found : " + fieldName);
return; // depends on control dependency: [if], data = [none]
}
setter.invoke(to, getter.invoke(from, EMPTY_CLASS));
} catch (IllegalAccessException | InvocationTargetException e) {
log.info("set method invoke error : " + fieldName);
}
} } |
public class class_name {
@Override
protected int pruneCache() {
if (!isPruneExpiredActive()) {
return 0;
}
int count = 0;
Iterator<CacheObject<K,V>> values = cacheMap.values().iterator();
while (values.hasNext()) {
CacheObject<K,V> co = values.next();
if (co.isExpired()) {
values.remove();
onRemove(co.key, co.cachedObject);
count++;
}
}
return count;
} } | public class class_name {
@Override
protected int pruneCache() {
if (!isPruneExpiredActive()) {
return 0; // depends on control dependency: [if], data = [none]
}
int count = 0;
Iterator<CacheObject<K,V>> values = cacheMap.values().iterator();
while (values.hasNext()) {
CacheObject<K,V> co = values.next();
if (co.isExpired()) {
values.remove(); // depends on control dependency: [if], data = [none]
onRemove(co.key, co.cachedObject); // depends on control dependency: [if], data = [none]
count++; // depends on control dependency: [if], data = [none]
}
}
return count;
} } |
public class class_name {
@Override
public CPInstance fetchByLtD_S_First(Date displayDate, int status,
OrderByComparator<CPInstance> orderByComparator) {
List<CPInstance> list = findByLtD_S(displayDate, status, 0, 1,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
} } | public class class_name {
@Override
public CPInstance fetchByLtD_S_First(Date displayDate, int status,
OrderByComparator<CPInstance> orderByComparator) {
List<CPInstance> list = findByLtD_S(displayDate, status, 0, 1,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static boolean allJSONArrays(JSONArray array) throws JSONException {
for (int i = 0; i < array.length(); ++i) {
if (!(array.get(i) instanceof JSONArray)) {
return false;
}
}
return true;
} } | public class class_name {
public static boolean allJSONArrays(JSONArray array) throws JSONException {
for (int i = 0; i < array.length(); ++i) {
if (!(array.get(i) instanceof JSONArray)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
@Override
protected Statement visitMsgFallbackGroupNode(MsgFallbackGroupNode node) {
MsgNode msg = node.getMsg();
MsgPartsAndIds idAndParts = MsgUtils.buildMsgPartsAndComputeMsgIdForDualFormat(msg);
ImmutableList<SoyPrintDirective> escapingDirectives = node.getEscapingDirectives();
Statement renderDefault = getMsgCompiler().compileMessage(idAndParts, msg, escapingDirectives);
// fallback groups have 1 or 2 children. if there are 2 then the second is a fallback and we
// need to check for presence.
if (node.hasFallbackMsg()) {
MsgNode fallback = node.getFallbackMsg();
MsgPartsAndIds fallbackIdAndParts =
MsgUtils.buildMsgPartsAndComputeMsgIdForDualFormat(fallback);
// TODO(lukes): consider changing the control flow here by 'inlining' the usePrimaryMsg logic
// it would save some lookups. Right now we will do to 2- 3 calls to
// SoyMsgBundle.getMsgParts (each of which requires a binary search). We could reduce that
// to 1-2 in the worse case by inlining and storing the lists in local variables.
IfBlock ifAvailableRenderDefault =
IfBlock.create(
parameterLookup
.getRenderContext()
.usePrimaryMsg(idAndParts.id, fallbackIdAndParts.id),
renderDefault);
return ControlFlow.ifElseChain(
ImmutableList.of(ifAvailableRenderDefault),
Optional.of(
getMsgCompiler().compileMessage(fallbackIdAndParts, fallback, escapingDirectives)));
} else {
return renderDefault;
}
} } | public class class_name {
@Override
protected Statement visitMsgFallbackGroupNode(MsgFallbackGroupNode node) {
MsgNode msg = node.getMsg();
MsgPartsAndIds idAndParts = MsgUtils.buildMsgPartsAndComputeMsgIdForDualFormat(msg);
ImmutableList<SoyPrintDirective> escapingDirectives = node.getEscapingDirectives();
Statement renderDefault = getMsgCompiler().compileMessage(idAndParts, msg, escapingDirectives);
// fallback groups have 1 or 2 children. if there are 2 then the second is a fallback and we
// need to check for presence.
if (node.hasFallbackMsg()) {
MsgNode fallback = node.getFallbackMsg();
MsgPartsAndIds fallbackIdAndParts =
MsgUtils.buildMsgPartsAndComputeMsgIdForDualFormat(fallback);
// TODO(lukes): consider changing the control flow here by 'inlining' the usePrimaryMsg logic
// it would save some lookups. Right now we will do to 2- 3 calls to
// SoyMsgBundle.getMsgParts (each of which requires a binary search). We could reduce that
// to 1-2 in the worse case by inlining and storing the lists in local variables.
IfBlock ifAvailableRenderDefault =
IfBlock.create(
parameterLookup
.getRenderContext()
.usePrimaryMsg(idAndParts.id, fallbackIdAndParts.id),
renderDefault);
return ControlFlow.ifElseChain(
ImmutableList.of(ifAvailableRenderDefault),
Optional.of(
getMsgCompiler().compileMessage(fallbackIdAndParts, fallback, escapingDirectives))); // depends on control dependency: [if], data = [none]
} else {
return renderDefault; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static Object digIn(Object target, String field) {
if (target instanceof List) {
// The 'field' will tell us what type of objects belong in the list.
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) target;
return digInList(list, field);
} else if (target instanceof Map) {
// The 'field' will tell us what type of objects belong in the map.
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) target;
return digInMap(map, field);
} else {
return digInObject(target, field);
}
} } | public class class_name {
private static Object digIn(Object target, String field) {
if (target instanceof List) {
// The 'field' will tell us what type of objects belong in the list.
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) target;
return digInList(list, field); // depends on control dependency: [if], data = [none]
} else if (target instanceof Map) {
// The 'field' will tell us what type of objects belong in the map.
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) target;
return digInMap(map, field); // depends on control dependency: [if], data = [none]
} else {
return digInObject(target, field); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public DERObject toASN1Object()
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(base);
if (minimum != null)
{
v.add(new DERTaggedObject(false, 0, minimum));
}
if (maximum != null)
{
v.add(new DERTaggedObject(false, 1, maximum));
}
return new DERSequence(v);
} } | public class class_name {
public DERObject toASN1Object()
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(base);
if (minimum != null)
{
v.add(new DERTaggedObject(false, 0, minimum)); // depends on control dependency: [if], data = [none]
}
if (maximum != null)
{
v.add(new DERTaggedObject(false, 1, maximum)); // depends on control dependency: [if], data = [none]
}
return new DERSequence(v);
} } |
public class class_name {
public static String[] segmentTags(String qualifiedSegmentName) {
Preconditions.checkNotNull(qualifiedSegmentName);
String[] tags = {TAG_SCOPE, null, TAG_STREAM, null, TAG_SEGMENT, null, TAG_EPOCH, null};
if (qualifiedSegmentName.contains(TABLE_SEGMENT_DELIMITER)) {
String[] tokens = qualifiedSegmentName.split(TABLE_SEGMENT_DELIMITER);
tags[1] = tokens[0];
tags[3] = TABLES;
tags[5] = tokens[1];
tags[7] = "0";
return tags;
}
String segmentBaseName = getSegmentBaseName(qualifiedSegmentName);
String[] tokens = segmentBaseName.split("[/]");
int segmentIdIndex = tokens.length == 2 ? 1 : 2;
if (tokens[segmentIdIndex].contains(EPOCH_DELIMITER)) {
String[] segmentIdTokens = tokens[segmentIdIndex].split(EPOCH_DELIMITER);
tags[5] = segmentIdTokens[0];
tags[7] = segmentIdTokens[1];
} else {
tags[5] = tokens[segmentIdIndex];
tags[7] = "0";
}
if (tokens.length == 3) {
tags[1] = tokens[0];
tags[3] = tokens[1];
} else {
tags[1] = "default";
tags[3] = tokens[0];
}
return tags;
} } | public class class_name {
public static String[] segmentTags(String qualifiedSegmentName) {
Preconditions.checkNotNull(qualifiedSegmentName);
String[] tags = {TAG_SCOPE, null, TAG_STREAM, null, TAG_SEGMENT, null, TAG_EPOCH, null};
if (qualifiedSegmentName.contains(TABLE_SEGMENT_DELIMITER)) {
String[] tokens = qualifiedSegmentName.split(TABLE_SEGMENT_DELIMITER);
tags[1] = tokens[0]; // depends on control dependency: [if], data = [none]
tags[3] = TABLES; // depends on control dependency: [if], data = [none]
tags[5] = tokens[1]; // depends on control dependency: [if], data = [none]
tags[7] = "0"; // depends on control dependency: [if], data = [none]
return tags; // depends on control dependency: [if], data = [none]
}
String segmentBaseName = getSegmentBaseName(qualifiedSegmentName);
String[] tokens = segmentBaseName.split("[/]");
int segmentIdIndex = tokens.length == 2 ? 1 : 2;
if (tokens[segmentIdIndex].contains(EPOCH_DELIMITER)) {
String[] segmentIdTokens = tokens[segmentIdIndex].split(EPOCH_DELIMITER);
tags[5] = segmentIdTokens[0]; // depends on control dependency: [if], data = [none]
tags[7] = segmentIdTokens[1]; // depends on control dependency: [if], data = [none]
} else {
tags[5] = tokens[segmentIdIndex]; // depends on control dependency: [if], data = [none]
tags[7] = "0"; // depends on control dependency: [if], data = [none]
}
if (tokens.length == 3) {
tags[1] = tokens[0]; // depends on control dependency: [if], data = [none]
tags[3] = tokens[1]; // depends on control dependency: [if], data = [none]
} else {
tags[1] = "default"; // depends on control dependency: [if], data = [none]
tags[3] = tokens[0]; // depends on control dependency: [if], data = [none]
}
return tags;
} } |
public class class_name {
private static boolean hasSameVersionOfCglib(ClassLoader classLoader) {
Class<?> fc = net.sf.cglib.reflect.FastClass.class;
try {
return classLoader.loadClass(fc.getName()) == fc;
} catch (ClassNotFoundException e) {
return false;
}
} } | public class class_name {
private static boolean hasSameVersionOfCglib(ClassLoader classLoader) {
Class<?> fc = net.sf.cglib.reflect.FastClass.class;
try {
return classLoader.loadClass(fc.getName()) == fc; // depends on control dependency: [try], data = [none]
} catch (ClassNotFoundException e) {
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setInternetGatewayIds(java.util.Collection<String> internetGatewayIds) {
if (internetGatewayIds == null) {
this.internetGatewayIds = null;
return;
}
this.internetGatewayIds = new com.amazonaws.internal.SdkInternalList<String>(internetGatewayIds);
} } | public class class_name {
public void setInternetGatewayIds(java.util.Collection<String> internetGatewayIds) {
if (internetGatewayIds == null) {
this.internetGatewayIds = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.internetGatewayIds = new com.amazonaws.internal.SdkInternalList<String>(internetGatewayIds);
} } |
public class class_name {
public static DependencyHintsInfo getHints(String filename) {
DependencyHintsInfo hints = null;
if (StringUtils.isNotBlank(filename)) {
if (filename.matches(PORTABLE_EXECUTABLES_PATTERN)) {
hints = getPortableExecutableHints(filename);
}
}
return hints;
} } | public class class_name {
public static DependencyHintsInfo getHints(String filename) {
DependencyHintsInfo hints = null;
if (StringUtils.isNotBlank(filename)) {
if (filename.matches(PORTABLE_EXECUTABLES_PATTERN)) {
hints = getPortableExecutableHints(filename); // depends on control dependency: [if], data = [none]
}
}
return hints;
} } |
public class class_name {
public void setZoom(int zoom)
{
if (zoom == this.zoomLevel)
{
return;
}
TileFactoryInfo info = getTileFactory().getInfo();
// don't repaint if we are out of the valid zoom levels
if (info != null && (zoom < info.getMinimumZoomLevel() || zoom > info.getMaximumZoomLevel()))
{
return;
}
// if(zoom >= 0 && zoom <= 15 && zoom != this.zoom) {
int oldzoom = this.zoomLevel;
Point2D oldCenter = getCenter();
Dimension oldMapSize = getTileFactory().getMapSize(oldzoom);
this.zoomLevel = zoom;
this.firePropertyChange("zoom", oldzoom, zoom);
Dimension mapSize = getTileFactory().getMapSize(zoom);
setCenter(new Point2D.Double(oldCenter.getX() * (mapSize.getWidth() / oldMapSize.getWidth()), oldCenter.getY()
* (mapSize.getHeight() / oldMapSize.getHeight())));
repaint();
} } | public class class_name {
public void setZoom(int zoom)
{
if (zoom == this.zoomLevel)
{
return;
// depends on control dependency: [if], data = [none]
}
TileFactoryInfo info = getTileFactory().getInfo();
// don't repaint if we are out of the valid zoom levels
if (info != null && (zoom < info.getMinimumZoomLevel() || zoom > info.getMaximumZoomLevel()))
{
return;
// depends on control dependency: [if], data = [none]
}
// if(zoom >= 0 && zoom <= 15 && zoom != this.zoom) {
int oldzoom = this.zoomLevel;
Point2D oldCenter = getCenter();
Dimension oldMapSize = getTileFactory().getMapSize(oldzoom);
this.zoomLevel = zoom;
this.firePropertyChange("zoom", oldzoom, zoom);
Dimension mapSize = getTileFactory().getMapSize(zoom);
setCenter(new Point2D.Double(oldCenter.getX() * (mapSize.getWidth() / oldMapSize.getWidth()), oldCenter.getY()
* (mapSize.getHeight() / oldMapSize.getHeight())));
repaint();
} } |
public class class_name {
@Deprecated
public Object getOptionObject(String opt)
{
try
{
return getParsedOptionValue(opt);
}
catch (ParseException pe)
{
System.err.println("Exception found converting " + opt + " to desired type: " + pe.getMessage());
return null;
}
} } | public class class_name {
@Deprecated
public Object getOptionObject(String opt)
{
try
{
return getParsedOptionValue(opt); // depends on control dependency: [try], data = [none]
}
catch (ParseException pe)
{
System.err.println("Exception found converting " + opt + " to desired type: " + pe.getMessage());
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static BufferedImage createThumbnail(BufferedImage image,
int newSize) {
int width = image.getWidth();
int height = image.getHeight();
boolean isTranslucent = image.getTransparency() != Transparency.OPAQUE;
boolean isWidthGreater = width > height;
if (isWidthGreater) {
if (newSize >= width) {
throw new IllegalArgumentException("newSize must be lower than" +
" the image width");
}
} else if (newSize >= height) {
throw new IllegalArgumentException("newSize must be lower than" +
" the image height");
}
if (newSize <= 0) {
throw new IllegalArgumentException("newSize must" +
" be greater than 0");
}
float ratioWH = (float) width / (float) height;
float ratioHW = (float) height / (float) width;
BufferedImage thumb = image;
BufferedImage temp = null;
Graphics2D g2 = null;
try {
int previousWidth = width;
int previousHeight = height;
do {
if (isWidthGreater) {
width /= 2;
if (width < newSize) {
width = newSize;
}
height = (int) (width / ratioWH);
} else {
height /= 2;
if (height < newSize) {
height = newSize;
}
width = (int) (height / ratioHW);
}
if (temp == null || isTranslucent) {
if (g2 != null) {
//do not need to wrap with finally
//outer finally block will ensure
//that resources are properly reclaimed
g2.dispose();
}
temp = createCompatibleImage(image, width, height);
g2 = temp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
}
if (g2 != null) // always the case
g2.drawImage(thumb, 0, 0, width, height,
0, 0, previousWidth, previousHeight, null);
previousWidth = width;
previousHeight = height;
thumb = temp;
} while (newSize != (isWidthGreater ? width : height));
} finally {
if (g2 != null) {
g2.dispose();
}
}
if (width != thumb.getWidth() || height != thumb.getHeight()) {
temp = createCompatibleImage(image, width, height);
g2 = temp.createGraphics();
try {
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(thumb, 0, 0, width, height, 0, 0, width, height, null);
} finally {
g2.dispose();
}
thumb = temp;
}
return thumb;
} } | public class class_name {
public static BufferedImage createThumbnail(BufferedImage image,
int newSize) {
int width = image.getWidth();
int height = image.getHeight();
boolean isTranslucent = image.getTransparency() != Transparency.OPAQUE;
boolean isWidthGreater = width > height;
if (isWidthGreater) {
if (newSize >= width) {
throw new IllegalArgumentException("newSize must be lower than" +
" the image width");
}
} else if (newSize >= height) {
throw new IllegalArgumentException("newSize must be lower than" +
" the image height");
}
if (newSize <= 0) {
throw new IllegalArgumentException("newSize must" +
" be greater than 0");
}
float ratioWH = (float) width / (float) height;
float ratioHW = (float) height / (float) width;
BufferedImage thumb = image;
BufferedImage temp = null;
Graphics2D g2 = null;
try {
int previousWidth = width;
int previousHeight = height;
do {
if (isWidthGreater) {
width /= 2; // depends on control dependency: [if], data = [none]
if (width < newSize) {
width = newSize; // depends on control dependency: [if], data = [none]
}
height = (int) (width / ratioWH); // depends on control dependency: [if], data = [none]
} else {
height /= 2; // depends on control dependency: [if], data = [none]
if (height < newSize) {
height = newSize; // depends on control dependency: [if], data = [none]
}
width = (int) (height / ratioHW); // depends on control dependency: [if], data = [none]
}
if (temp == null || isTranslucent) {
if (g2 != null) {
//do not need to wrap with finally
//outer finally block will ensure
//that resources are properly reclaimed
g2.dispose(); // depends on control dependency: [if], data = [none]
}
temp = createCompatibleImage(image, width, height); // depends on control dependency: [if], data = [none]
g2 = temp.createGraphics(); // depends on control dependency: [if], data = [none]
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR); // depends on control dependency: [if], data = [none]
}
if (g2 != null) // always the case
g2.drawImage(thumb, 0, 0, width, height,
0, 0, previousWidth, previousHeight, null);
previousWidth = width;
previousHeight = height;
thumb = temp;
} while (newSize != (isWidthGreater ? width : height));
} finally {
if (g2 != null) {
g2.dispose(); // depends on control dependency: [if], data = [none]
}
}
if (width != thumb.getWidth() || height != thumb.getHeight()) {
temp = createCompatibleImage(image, width, height); // depends on control dependency: [if], data = [none]
g2 = temp.createGraphics(); // depends on control dependency: [if], data = [none]
try {
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR); // depends on control dependency: [try], data = [none]
g2.drawImage(thumb, 0, 0, width, height, 0, 0, width, height, null); // depends on control dependency: [try], data = [none]
} finally {
g2.dispose();
}
thumb = temp; // depends on control dependency: [if], data = [none]
}
return thumb;
} } |
public class class_name {
public String getEncodeType() {
String contentType = header.get("Content-Type");
if (null != contentType) {
for (String tmp : contentType.split(";")) {
if (tmp == null)
continue;
tmp = tmp.trim();
if (tmp.startsWith("charset=")) {
tmp = Strings.trim(tmp.substring(8)).trim();
if (tmp.contains(","))
tmp = tmp.substring(0, tmp.indexOf(',')).trim();
return tmp;
}
}
}
return Encoding.UTF8;
} } | public class class_name {
public String getEncodeType() {
String contentType = header.get("Content-Type");
if (null != contentType) {
for (String tmp : contentType.split(";")) {
if (tmp == null)
continue;
tmp = tmp.trim();
// depends on control dependency: [for], data = [tmp]
if (tmp.startsWith("charset=")) {
tmp = Strings.trim(tmp.substring(8)).trim();
// depends on control dependency: [if], data = [none]
if (tmp.contains(","))
tmp = tmp.substring(0, tmp.indexOf(',')).trim();
return tmp;
// depends on control dependency: [if], data = [none]
}
}
}
return Encoding.UTF8;
} } |
public class class_name {
public DescribeConditionalForwardersRequest withRemoteDomainNames(String... remoteDomainNames) {
if (this.remoteDomainNames == null) {
setRemoteDomainNames(new com.amazonaws.internal.SdkInternalList<String>(remoteDomainNames.length));
}
for (String ele : remoteDomainNames) {
this.remoteDomainNames.add(ele);
}
return this;
} } | public class class_name {
public DescribeConditionalForwardersRequest withRemoteDomainNames(String... remoteDomainNames) {
if (this.remoteDomainNames == null) {
setRemoteDomainNames(new com.amazonaws.internal.SdkInternalList<String>(remoteDomainNames.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : remoteDomainNames) {
this.remoteDomainNames.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
protected final boolean isValidEndTypeForPattern() {
if (getEndType() == null) {
return false;
}
switch (getPatternType()) {
case DAILY:
case WEEKLY:
case MONTHLY:
case YEARLY:
return (getEndType().equals(EndType.DATE) || getEndType().equals(EndType.TIMES));
case INDIVIDUAL:
case NONE:
return getEndType().equals(EndType.SINGLE);
default:
return false;
}
} } | public class class_name {
protected final boolean isValidEndTypeForPattern() {
if (getEndType() == null) {
return false; // depends on control dependency: [if], data = [none]
}
switch (getPatternType()) {
case DAILY:
case WEEKLY:
case MONTHLY:
case YEARLY:
return (getEndType().equals(EndType.DATE) || getEndType().equals(EndType.TIMES));
case INDIVIDUAL:
case NONE:
return getEndType().equals(EndType.SINGLE);
default:
return false;
}
} } |
public class class_name {
@Override
public void removeByCommerceCountryId(long commerceCountryId) {
for (CommerceRegion commerceRegion : findByCommerceCountryId(
commerceCountryId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceRegion);
}
} } | public class class_name {
@Override
public void removeByCommerceCountryId(long commerceCountryId) {
for (CommerceRegion commerceRegion : findByCommerceCountryId(
commerceCountryId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceRegion); // depends on control dependency: [for], data = [commerceRegion]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
protected I getIdFromEntity(EntityManager em, Object entity, ResourceField idField) {
Object pk = em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(entity);
PreconditionUtil.verify(pk != null, "pk not available for entity %s", entity);
if (pk != null && primaryKeyAttribute.getName().equals(idField.getUnderlyingName()) && idField.getElementType().isAssignableFrom(pk.getClass())) {
return (I) pk;
}
return null;
} } | public class class_name {
@SuppressWarnings("unchecked")
protected I getIdFromEntity(EntityManager em, Object entity, ResourceField idField) {
Object pk = em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(entity);
PreconditionUtil.verify(pk != null, "pk not available for entity %s", entity);
if (pk != null && primaryKeyAttribute.getName().equals(idField.getUnderlyingName()) && idField.getElementType().isAssignableFrom(pk.getClass())) {
return (I) pk; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static <Value extends Comparable<Value>> int nullSafeCompare(final Value first, final Value second) {
if (first == null) {
return second == null ? EQUAL_COMPARE_RESULT : LOWER_THAN_COMPARE_RESULT;
}
return second == null ? GREATER_THAN_COMPARE_RESULT : first.compareTo(second);
} } | public class class_name {
public static <Value extends Comparable<Value>> int nullSafeCompare(final Value first, final Value second) {
if (first == null) {
return second == null ? EQUAL_COMPARE_RESULT : LOWER_THAN_COMPARE_RESULT; // depends on control dependency: [if], data = [none]
}
return second == null ? GREATER_THAN_COMPARE_RESULT : first.compareTo(second);
} } |
public class class_name {
public static XMLGregorianCalendar parseXMLGregorianCalendar(final String calendar, final String format, final TimeZone timeZone) {
if (N.isNullOrEmpty(calendar) || (calendar.length() == 4 && "null".equalsIgnoreCase(calendar))) {
return null;
}
return createXMLGregorianCalendar(parse(calendar, format, timeZone));
} } | public class class_name {
public static XMLGregorianCalendar parseXMLGregorianCalendar(final String calendar, final String format, final TimeZone timeZone) {
if (N.isNullOrEmpty(calendar) || (calendar.length() == 4 && "null".equalsIgnoreCase(calendar))) {
return null;
// depends on control dependency: [if], data = [none]
}
return createXMLGregorianCalendar(parse(calendar, format, timeZone));
} } |
public class class_name {
CommitLogSegment recycle()
{
try
{
sync();
}
catch (FSWriteError e)
{
logger.error("I/O error flushing {} {}", this, e.getMessage());
throw e;
}
close();
return new CommitLogSegment(getPath());
} } | public class class_name {
CommitLogSegment recycle()
{
try
{
sync(); // depends on control dependency: [try], data = [none]
}
catch (FSWriteError e)
{
logger.error("I/O error flushing {} {}", this, e.getMessage());
throw e;
} // depends on control dependency: [catch], data = [none]
close();
return new CommitLogSegment(getPath());
} } |
public class class_name {
Method getSetter(Method getter) {
synchronized (setterCache) {
if ( !setterCache.containsKey(getter) ) {
String attributeName = null;
if ( getter.getName().startsWith("get") ) {
attributeName = getter.getName().substring("get".length());
} else if ( getter.getName().startsWith("is") ) {
attributeName = getter.getName().substring("is".length());
} else {
// should be impossible to reach this exception
throw new RuntimeException("Getter method must start with 'is' or 'get'");
}
String setterName = "set" + attributeName;
Method setter = null;
try {
setter = getter.getDeclaringClass().getMethod(setterName, getter.getReturnType());
} catch ( NoSuchMethodException e ) {
throw new DynamoDBMappingException("Expected a public, one-argument method called " + setterName
+ " on class " + getter.getDeclaringClass(), e);
} catch ( SecurityException e ) {
throw new DynamoDBMappingException("No access to public, one-argument method called " + setterName
+ " on class " + getter.getDeclaringClass(), e);
}
setterCache.put(getter, setter);
}
}
return setterCache.get(getter);
} } | public class class_name {
Method getSetter(Method getter) {
synchronized (setterCache) {
if ( !setterCache.containsKey(getter) ) {
String attributeName = null;
if ( getter.getName().startsWith("get") ) {
attributeName = getter.getName().substring("get".length()); // depends on control dependency: [if], data = [none]
} else if ( getter.getName().startsWith("is") ) {
attributeName = getter.getName().substring("is".length()); // depends on control dependency: [if], data = [none]
} else {
// should be impossible to reach this exception
throw new RuntimeException("Getter method must start with 'is' or 'get'");
}
String setterName = "set" + attributeName;
Method setter = null;
try {
setter = getter.getDeclaringClass().getMethod(setterName, getter.getReturnType()); // depends on control dependency: [try], data = [none]
} catch ( NoSuchMethodException e ) {
throw new DynamoDBMappingException("Expected a public, one-argument method called " + setterName
+ " on class " + getter.getDeclaringClass(), e);
} catch ( SecurityException e ) { // depends on control dependency: [catch], data = [none]
throw new DynamoDBMappingException("No access to public, one-argument method called " + setterName
+ " on class " + getter.getDeclaringClass(), e);
} // depends on control dependency: [catch], data = [none]
setterCache.put(getter, setter); // depends on control dependency: [if], data = [none]
}
}
return setterCache.get(getter);
} } |
public class class_name {
synchronized public boolean release(DTM dtm, boolean shouldHardDelete)
{
if(DEBUG)
{
System.out.println("Releasing "+
(shouldHardDelete ? "HARD" : "soft")+
" dtm="+
// Following shouldn't need a nodeHandle, but does...
// and doesn't seem to report the intended value
dtm.getDocumentBaseURI()
);
}
if (dtm instanceof SAX2DTM)
{
((SAX2DTM) dtm).clearCoRoutine();
}
// Multiple DTM IDs may be assigned to a single DTM.
// The Right Answer is to ask which (if it supports
// extension, the DTM will need a list anyway). The
// Wrong Answer, applied if the DTM can't help us,
// is to linearly search them all; this may be very
// painful.
//
// %REVIEW% Should the lookup move up into the basic DTM API?
if(dtm instanceof DTMDefaultBase)
{
org.apache.xml.utils.SuballocatedIntVector ids=((DTMDefaultBase)dtm).getDTMIDs();
for(int i=ids.size()-1;i>=0;--i)
m_dtms[ids.elementAt(i)>>>DTMManager.IDENT_DTM_NODE_BITS]=null;
}
else
{
int i = getDTMIdentity(dtm);
if (i >= 0)
{
m_dtms[i >>> DTMManager.IDENT_DTM_NODE_BITS] = null;
}
}
dtm.documentRelease();
return true;
} } | public class class_name {
synchronized public boolean release(DTM dtm, boolean shouldHardDelete)
{
if(DEBUG)
{
System.out.println("Releasing "+
(shouldHardDelete ? "HARD" : "soft")+
" dtm="+
// Following shouldn't need a nodeHandle, but does...
// and doesn't seem to report the intended value
dtm.getDocumentBaseURI()
); // depends on control dependency: [if], data = [none]
}
if (dtm instanceof SAX2DTM)
{
((SAX2DTM) dtm).clearCoRoutine(); // depends on control dependency: [if], data = [none]
}
// Multiple DTM IDs may be assigned to a single DTM.
// The Right Answer is to ask which (if it supports
// extension, the DTM will need a list anyway). The
// Wrong Answer, applied if the DTM can't help us,
// is to linearly search them all; this may be very
// painful.
//
// %REVIEW% Should the lookup move up into the basic DTM API?
if(dtm instanceof DTMDefaultBase)
{
org.apache.xml.utils.SuballocatedIntVector ids=((DTMDefaultBase)dtm).getDTMIDs();
for(int i=ids.size()-1;i>=0;--i)
m_dtms[ids.elementAt(i)>>>DTMManager.IDENT_DTM_NODE_BITS]=null;
}
else
{
int i = getDTMIdentity(dtm);
if (i >= 0)
{
m_dtms[i >>> DTMManager.IDENT_DTM_NODE_BITS] = null; // depends on control dependency: [if], data = [none]
}
}
dtm.documentRelease();
return true;
} } |
public class class_name {
public String getCaption() {
if (item.captionCode().isEmpty()) {
return item.caption();
} else {
return i18n.get(item.captionCode());
}
} } | public class class_name {
public String getCaption() {
if (item.captionCode().isEmpty()) {
return item.caption(); // depends on control dependency: [if], data = [none]
} else {
return i18n.get(item.captionCode()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Collection<Class> getClassSimpleDependencies(Class c)
{
HashSet<Class> result = new HashSet<Class>();
result.add(c); //add the own class
//declared subclasses
Class[] declaredClasses = c.getDeclaredClasses();
for(Class cl : declaredClasses) {
result.add(cl);
}
//fields
Field[] declaredFields = c.getDeclaredFields();
for(Field f : declaredFields) {
if (!BASETYPES.contains(f.getType().getName()))
result.add(f.getType());
}
//method arguments/return
Method[] declaredMethods = c.getDeclaredMethods();
for(Method m : declaredMethods) {
result.add(m.getReturnType());
for(Class pc : m.getParameterTypes()) {
if (!BASETYPES.contains(pc.getName()))
result.add(pc);
}
}
return result;
} } | public class class_name {
public static Collection<Class> getClassSimpleDependencies(Class c)
{
HashSet<Class> result = new HashSet<Class>();
result.add(c); //add the own class
//declared subclasses
Class[] declaredClasses = c.getDeclaredClasses();
for(Class cl : declaredClasses) {
result.add(cl); // depends on control dependency: [for], data = [cl]
}
//fields
Field[] declaredFields = c.getDeclaredFields();
for(Field f : declaredFields) {
if (!BASETYPES.contains(f.getType().getName()))
result.add(f.getType());
}
//method arguments/return
Method[] declaredMethods = c.getDeclaredMethods();
for(Method m : declaredMethods) {
result.add(m.getReturnType()); // depends on control dependency: [for], data = [m]
for(Class pc : m.getParameterTypes()) {
if (!BASETYPES.contains(pc.getName()))
result.add(pc);
}
}
return result;
} } |
public class class_name {
@Override
public void onViewReady(View view, Bundle savedInstanceState, Reason reason) {
super.onViewReady(view, savedInstanceState, reason);
if (reason.isFirstTime()) {
CounterMasterInsideView f = new CounterMasterInsideView();
getChildFragmentManager().beginTransaction()
.replace(R.id.screen_master_anotherFragmentContainer, f).commit();
}
} } | public class class_name {
@Override
public void onViewReady(View view, Bundle savedInstanceState, Reason reason) {
super.onViewReady(view, savedInstanceState, reason);
if (reason.isFirstTime()) {
CounterMasterInsideView f = new CounterMasterInsideView();
getChildFragmentManager().beginTransaction()
.replace(R.id.screen_master_anotherFragmentContainer, f).commit(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void close() {
synchronized (lock) {
if (closed) {
return;
}
closed = true;
tokenSource.unregister(this);
tokenSource = null;
action = null;
}
} } | public class class_name {
@Override
public void close() {
synchronized (lock) {
if (closed) {
return; // depends on control dependency: [if], data = [none]
}
closed = true;
tokenSource.unregister(this);
tokenSource = null;
action = null;
}
} } |
public class class_name {
static String maybeEscapeElementValue(final String pValue) {
int startEscape = needsEscapeElement(pValue);
if (startEscape < 0) {
// If no escaping is needed, simply return original
return pValue;
}
else {
// Otherwise, start replacing
StringBuilder builder = new StringBuilder(pValue.substring(0, startEscape));
builder.ensureCapacity(pValue.length() + 30);
int pos = startEscape;
for (int i = pos; i < pValue.length(); i++) {
switch (pValue.charAt(i)) {
case '&':
pos = appendAndEscape(pValue, pos, i, builder, "&");
break;
case '<':
pos = appendAndEscape(pValue, pos, i, builder, "<");
break;
case '>':
pos = appendAndEscape(pValue, pos, i, builder, ">");
break;
//case '\'':
//case '"':
default:
break;
}
}
builder.append(pValue.substring(pos));
return builder.toString();
}
} } | public class class_name {
static String maybeEscapeElementValue(final String pValue) {
int startEscape = needsEscapeElement(pValue);
if (startEscape < 0) {
// If no escaping is needed, simply return original
return pValue; // depends on control dependency: [if], data = [none]
}
else {
// Otherwise, start replacing
StringBuilder builder = new StringBuilder(pValue.substring(0, startEscape));
builder.ensureCapacity(pValue.length() + 30); // depends on control dependency: [if], data = [0)]
int pos = startEscape;
for (int i = pos; i < pValue.length(); i++) {
switch (pValue.charAt(i)) { // depends on control dependency: [for], data = [i]
case '&':
pos = appendAndEscape(pValue, pos, i, builder, "&");
break;
case '<':
pos = appendAndEscape(pValue, pos, i, builder, "<");
break;
case '>':
pos = appendAndEscape(pValue, pos, i, builder, ">");
break;
//case '\'':
//case '"':
default:
break;
}
}
builder.append(pValue.substring(pos)); // depends on control dependency: [if], data = [none]
return builder.toString(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public synchronized void add(PmiModule instance) {
if (instance == null)
return;
// no need to add instance to instanceList - to be removed.
/*
* if(!instanceList.contains(instance)) {
* instanceList.add(instance);
* }
*/
// removing add(spddata[]) - customPmi
//add(instance.listData());
PmiModuleConfig instanceModCfg = null;
boolean bSameSubMod = true;
// Check if instance and aggregate are same type
if (!instance.getModuleID().equals(getModuleID())) {
bSameSubMod = false;
addModuleID(instance.getModuleID());
instanceModCfg = PerfModules.getConfig(instance.getModuleID());
// can't aggregate data from different modules (different xml files)
// customPMI limitation - fixed in VELA
//return;
} else {
instanceModCfg = moduleConfig;
}
SpdData[] dataList = instance.listData();
if (dataList == null || instanceModCfg == null)
return;
for (int i = 0; i < dataList.length; i++) {
int dataId = dataList[i].getId();
// Always creating aggregate data in ModuleAggregate
// fg: check if dataId is enabled in the parent before adding
//if (bSameSubMod && !isEnabled (dataId))
// continue;
// if different sub module then create the sub-module aggregate data
// in parent even if its not enabled.
PmiDataInfo info = instanceModCfg.getDataInfo(dataId);
if (info == null) {
// wrong data id, ignore it. - This should not happen
continue;
} else if (!info.isAggregatable())
continue;
// Check if aggregateData is already available. If not create it.
SpdGroup aggregateData = (SpdGroup) dataTable.get(new Integer(dataId));
if (aggregateData == null) {
aggregateData = (SpdGroup) createAggregateData(info);
if (aggregateData != null)
putToTable((SpdData) aggregateData);
//if (!bSameSubMod)
//{
// enable of parent level is
if (currentLevel == LEVEL_FINEGRAIN) {
//if( !isEnabledInConfig (dataId) )
if (!isEnabled(dataId))
((SpdData) aggregateData).disable();
} else if (info.getLevel() > currentLevel)
((SpdData) aggregateData).disable();
//}
// FINE GRAINED
/*
* if(info.getLevel() > currentLevel)
* ((SpdData)aggregateData).disable();
*/
}
aggregateData.add(dataList[i]);
}
} } | public class class_name {
public synchronized void add(PmiModule instance) {
if (instance == null)
return;
// no need to add instance to instanceList - to be removed.
/*
* if(!instanceList.contains(instance)) {
* instanceList.add(instance);
* }
*/
// removing add(spddata[]) - customPmi
//add(instance.listData());
PmiModuleConfig instanceModCfg = null;
boolean bSameSubMod = true;
// Check if instance and aggregate are same type
if (!instance.getModuleID().equals(getModuleID())) {
bSameSubMod = false; // depends on control dependency: [if], data = [none]
addModuleID(instance.getModuleID()); // depends on control dependency: [if], data = [none]
instanceModCfg = PerfModules.getConfig(instance.getModuleID()); // depends on control dependency: [if], data = [none]
// can't aggregate data from different modules (different xml files)
// customPMI limitation - fixed in VELA
//return;
} else {
instanceModCfg = moduleConfig; // depends on control dependency: [if], data = [none]
}
SpdData[] dataList = instance.listData();
if (dataList == null || instanceModCfg == null)
return;
for (int i = 0; i < dataList.length; i++) {
int dataId = dataList[i].getId();
// Always creating aggregate data in ModuleAggregate
// fg: check if dataId is enabled in the parent before adding
//if (bSameSubMod && !isEnabled (dataId))
// continue;
// if different sub module then create the sub-module aggregate data
// in parent even if its not enabled.
PmiDataInfo info = instanceModCfg.getDataInfo(dataId);
if (info == null) {
// wrong data id, ignore it. - This should not happen
continue;
} else if (!info.isAggregatable())
continue;
// Check if aggregateData is already available. If not create it.
SpdGroup aggregateData = (SpdGroup) dataTable.get(new Integer(dataId));
if (aggregateData == null) {
aggregateData = (SpdGroup) createAggregateData(info); // depends on control dependency: [if], data = [none]
if (aggregateData != null)
putToTable((SpdData) aggregateData);
//if (!bSameSubMod)
//{
// enable of parent level is
if (currentLevel == LEVEL_FINEGRAIN) {
//if( !isEnabledInConfig (dataId) )
if (!isEnabled(dataId))
((SpdData) aggregateData).disable();
} else if (info.getLevel() > currentLevel)
((SpdData) aggregateData).disable();
//}
// FINE GRAINED
/*
* if(info.getLevel() > currentLevel)
* ((SpdData)aggregateData).disable();
*/
}
aggregateData.add(dataList[i]); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
@Override
public long getLong(TemporalField field) {
if (field instanceof ChronoField) {
switch ((ChronoField) field) {
case ALIGNED_DAY_OF_WEEK_IN_MONTH:
return month == 0 ? 0 : super.getLong(field);
case ALIGNED_DAY_OF_WEEK_IN_YEAR:
return getDayOfWeek();
case ALIGNED_WEEK_OF_MONTH:
return month == 0 ? 0 : super.getLong(field);
case ALIGNED_WEEK_OF_YEAR:
if (month == 0) {
return 0;
} else {
return ((getDayOfYear() - (getDayOfYear() >= ST_TIBS_OFFSET && isLeapYear() ? 1 : 0) - 1) / DAYS_IN_WEEK) + 1;
}
default:
break;
}
}
return super.getLong(field);
} } | public class class_name {
@Override
public long getLong(TemporalField field) {
if (field instanceof ChronoField) {
switch ((ChronoField) field) {
case ALIGNED_DAY_OF_WEEK_IN_MONTH:
return month == 0 ? 0 : super.getLong(field);
case ALIGNED_DAY_OF_WEEK_IN_YEAR:
return getDayOfWeek();
case ALIGNED_WEEK_OF_MONTH:
return month == 0 ? 0 : super.getLong(field);
case ALIGNED_WEEK_OF_YEAR:
if (month == 0) {
return 0; // depends on control dependency: [if], data = [none]
} else {
return ((getDayOfYear() - (getDayOfYear() >= ST_TIBS_OFFSET && isLeapYear() ? 1 : 0) - 1) / DAYS_IN_WEEK) + 1; // depends on control dependency: [if], data = [0)]
}
default:
break;
}
}
return super.getLong(field);
} } |
public class class_name {
final static protected void addInputPathRecursively(List<FileStatus> result,
FileSystem fs, Path path, PathFilter inputFilter)
throws IOException {
for(FileStatus stat: fs.listStatus(path, inputFilter)) {
if (stat.isDir()) {
addInputPathRecursively(result, fs, stat.getPath(), inputFilter);
} else {
result.add(stat);
}
}
} } | public class class_name {
final static protected void addInputPathRecursively(List<FileStatus> result,
FileSystem fs, Path path, PathFilter inputFilter)
throws IOException {
for(FileStatus stat: fs.listStatus(path, inputFilter)) {
if (stat.isDir()) {
addInputPathRecursively(result, fs, stat.getPath(), inputFilter); // depends on control dependency: [if], data = [none]
} else {
result.add(stat); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
synchronized void cleanUpOverMemoryTask(TaskAttemptID tid, boolean wasFailure,
String diagnosticMsg) {
TaskInProgress tip = runningTasks.get(tid);
if (tip != null) {
tip.reportDiagnosticInfo(diagnosticMsg);
try {
purgeTask(tip, wasFailure); // Marking it as failed/killed.
} catch (IOException ioe) {
LOG.warn("Couldn't purge the task of " + tid + ". Error : " + ioe);
}
}
} } | public class class_name {
synchronized void cleanUpOverMemoryTask(TaskAttemptID tid, boolean wasFailure,
String diagnosticMsg) {
TaskInProgress tip = runningTasks.get(tid);
if (tip != null) {
tip.reportDiagnosticInfo(diagnosticMsg); // depends on control dependency: [if], data = [none]
try {
purgeTask(tip, wasFailure); // Marking it as failed/killed. // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
LOG.warn("Couldn't purge the task of " + tid + ". Error : " + ioe);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public void isFalse(final boolean expression, final String message, final Object... values) {
if (expression) {
fail(String.format(message, values));
}
} } | public class class_name {
public void isFalse(final boolean expression, final String message, final Object... values) {
if (expression) {
fail(String.format(message, values)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
Schema stripOptionalTypeUnion(Schema schema) {
if(schema.getType() == Schema.Type.UNION && schema.getTypes().size() == 2
&& schema.getTypes().contains(NULL_TYPE_SCHEMA)) {
return schema.getTypes().get(0).equals(NULL_TYPE_SCHEMA) ? schema.getTypes().get(1)
: schema.getTypes().get(0);
}
return schema;
} } | public class class_name {
Schema stripOptionalTypeUnion(Schema schema) {
if(schema.getType() == Schema.Type.UNION && schema.getTypes().size() == 2
&& schema.getTypes().contains(NULL_TYPE_SCHEMA)) {
return schema.getTypes().get(0).equals(NULL_TYPE_SCHEMA) ? schema.getTypes().get(1)
: schema.getTypes().get(0); // depends on control dependency: [if], data = [none]
}
return schema;
} } |
public class class_name {
public static List<Method> findMethods(Class<?> type,
Class<? extends Annotation> annotation) {
List<Method> list = new ArrayList<Method>();
while (type != null) {
for (Method method : type.getDeclaredMethods()) {
if (method.getAnnotation(annotation) != null) {
list.add(method);
}
}
type = type.getSuperclass();
}
return list;
} } | public class class_name {
public static List<Method> findMethods(Class<?> type,
Class<? extends Annotation> annotation) {
List<Method> list = new ArrayList<Method>();
while (type != null) {
for (Method method : type.getDeclaredMethods()) {
if (method.getAnnotation(annotation) != null) {
list.add(method); // depends on control dependency: [if], data = [none]
}
}
type = type.getSuperclass(); // depends on control dependency: [while], data = [none]
}
return list;
} } |
public class class_name {
@SafeVarargs
static public <T> MutableRrbt<T> mutableRrb(T... items) {
if ( (items == null) || (items.length < 1) ) { return RrbTree.emptyMutable(); }
return RrbTree.<T>emptyMutable()
.concat(Arrays.asList(items));
} } | public class class_name {
@SafeVarargs
static public <T> MutableRrbt<T> mutableRrb(T... items) {
if ( (items == null) || (items.length < 1) ) { return RrbTree.emptyMutable(); } // depends on control dependency: [if], data = [none]
return RrbTree.<T>emptyMutable()
.concat(Arrays.asList(items));
} } |
public class class_name {
private final void setFlagValue(byte flagBit, boolean value) {
if (value) {
flags = (byte) (getFlags() | flagBit);
}
else {
flags = (byte) (getFlags() & (~flagBit));
}
} } | public class class_name {
private final void setFlagValue(byte flagBit, boolean value) {
if (value) {
flags = (byte) (getFlags() | flagBit); // depends on control dependency: [if], data = [none]
}
else {
flags = (byte) (getFlags() & (~flagBit)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected void onRender() {
MarkupStream markupStream = findMarkupStream();
try {
final ComponentTag openTag = markupStream.getTag();
final ComponentTag tag = openTag.mutable();
final IValueMap attributes = tag.getAttributes();
String src = (String) attributes.get("src");
boolean base64 = Boolean.valueOf((String) attributes.get("base64"))
.booleanValue();
// src is mandatory
if (null == src) {
throw new IllegalStateException(
"The src attribute is mandatory for this Jawr tag. ");
}
// Retrieve the image resource handler
ServletWebRequest servletWebRequest = (ServletWebRequest) getRequest();
HttpServletRequest request = servletWebRequest
.getContainerRequest();
BinaryResourcesHandler binaryRsHandler = (BinaryResourcesHandler) WebApplication
.get().getServletContext()
.getAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE);
if (null == binaryRsHandler)
throw new IllegalStateException(
"You are using a Jawr image tag while the Jawr Image servlet has not been initialized. Initialization of Jawr Image servlet either failed or never occurred.");
final Response response = getResponse();
src = ImageTagUtils.getImageUrl(src, base64, binaryRsHandler, request,
getHttpServletResponseUrlEncoder(response));
Writer writer = new RedirectWriter(response);
this.renderer = RendererFactory.getImgRenderer(
binaryRsHandler.getConfig(), isPlainImage());
this.renderer.renderImage(src, attributes, writer);
} catch (IOException ex) {
LOGGER.error("onRender() error : ", ex);
} finally {
// Reset the Thread local for the Jawr context
ThreadLocalJawrContext.reset();
}
markupStream.skipComponent();
} } | public class class_name {
protected void onRender() {
MarkupStream markupStream = findMarkupStream();
try {
final ComponentTag openTag = markupStream.getTag();
final ComponentTag tag = openTag.mutable();
final IValueMap attributes = tag.getAttributes();
String src = (String) attributes.get("src");
boolean base64 = Boolean.valueOf((String) attributes.get("base64"))
.booleanValue();
// src is mandatory
if (null == src) {
throw new IllegalStateException(
"The src attribute is mandatory for this Jawr tag. ");
}
// Retrieve the image resource handler
ServletWebRequest servletWebRequest = (ServletWebRequest) getRequest();
HttpServletRequest request = servletWebRequest
.getContainerRequest();
BinaryResourcesHandler binaryRsHandler = (BinaryResourcesHandler) WebApplication
.get().getServletContext()
.getAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE);
if (null == binaryRsHandler)
throw new IllegalStateException(
"You are using a Jawr image tag while the Jawr Image servlet has not been initialized. Initialization of Jawr Image servlet either failed or never occurred.");
final Response response = getResponse();
src = ImageTagUtils.getImageUrl(src, base64, binaryRsHandler, request,
getHttpServletResponseUrlEncoder(response)); // depends on control dependency: [try], data = [none]
Writer writer = new RedirectWriter(response);
this.renderer = RendererFactory.getImgRenderer(
binaryRsHandler.getConfig(), isPlainImage()); // depends on control dependency: [try], data = [none]
this.renderer.renderImage(src, attributes, writer); // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
LOGGER.error("onRender() error : ", ex);
} finally { // depends on control dependency: [catch], data = [none]
// Reset the Thread local for the Jawr context
ThreadLocalJawrContext.reset();
}
markupStream.skipComponent();
} } |
public class class_name {
@Override
public void visitInsn(int inst) {
processPendingExceptionHandlerEntry(-1);
// List of opcodes taken from visitInsn documentation
if (waitingForSuper) {
// Visit the instruction
super.visitInsn(inst);
switch (inst) {
case NOP:
break;
// One slot constants
case ACONST_NULL:
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(OTHER, 1);
break;
// Two slot constants
case DCONST_0:
case DCONST_1:
case LCONST_0:
case LCONST_1:
push(OTHER, 2);
break;
// One slot array load
case IALOAD:
case FALOAD:
case AALOAD:
case BALOAD:
case CALOAD:
case SALOAD:
pop(1); // pop(2); push(OTHER, 1);
break;
// Two slot array load
case DALOAD:
case LALOAD:
// pop(2); push(OTHER, 2);
break;
// One slot array store
case IASTORE:
case FASTORE:
case AASTORE:
case BASTORE:
case CASTORE:
case SASTORE:
pop(3);
break;
// Two slot array store
case DASTORE:
case LASTORE:
pop(4);
break;
// Basic pop instructions
case POP:
pop(1);
break;
case POP2:
pop(2);
break;
// Stack manipulation instructions
case DUP: {
Object top = currentStack.get(currentStack.size() - 1);
push(top, 1);
break;
}
case DUP_X1: {
Object top = currentStack.get(currentStack.size() - 1);
int addPosition = currentStack.size() - 2;
currentStack.add(addPosition, top);
break;
}
case DUP_X2: {
Object top = currentStack.get(currentStack.size() - 1);
int addPosition = currentStack.size() - 3;
currentStack.add(addPosition, top);
break;
}
case DUP2: {
int position = currentStack.size() - 2;
currentStack.add(currentStack.get(position));
currentStack.add(currentStack.get(position + 1));
break;
}
case DUP2_X1: {
int addPosition = currentStack.size() - 3;
currentStack.add(addPosition, currentStack.get(currentStack.size() - 1));
currentStack.add(addPosition, currentStack.get(currentStack.size() - 2));
break;
}
case DUP2_X2: {
int addPosition = currentStack.size() - 4;
currentStack.add(addPosition, currentStack.get(currentStack.size() - 1));
currentStack.add(addPosition, currentStack.get(currentStack.size() - 2));
break;
}
case SWAP: {
Object o = currentStack.remove(currentStack.size() - 2);
currentStack.add(o);
break;
}
// One slot arithmetic and logical instructions
case IADD:
case FADD:
case ISUB:
case FSUB:
case IMUL:
case FMUL:
case IDIV:
case FDIV:
case IREM:
case FREM:
case INEG:
case FNEG:
case ISHL:
case ISHR:
case IUSHR:
case IAND:
case IOR:
case IXOR:
pop(1);
break;
// Two slot arithmetic and logical instructions
case DADD:
case LADD:
case DSUB:
case LSUB:
case DMUL:
case LMUL:
case DDIV:
case LDIV:
case DREM:
case LREM:
case DNEG:
case LNEG:
case LSHL:
case LSHR:
case LUSHR:
case LAND:
case LOR:
case LXOR:
pop(2);
break;
// One slot to two slot conversions
case I2D:
case I2L:
case F2D:
case F2L:
push(OTHER, 1);
break;
// One slot to one slot conversions
case F2I:
case I2B:
case I2C:
case I2F:
case I2S:
break;
// Two slot to one slot conversions
case D2F:
case D2I:
case L2I:
case L2F:
pop(1);
break;
// Two slot to two slot conversions
case L2D:
case D2L:
break;
// Two slot compare
case DCMPL:
case DCMPG:
case LCMP:
pop(3);
break;
// One slot compare
case FCMPL:
case FCMPG:
pop(1);
break;
// One slot return
case IRETURN:
case FRETURN:
case ARETURN:
pop(1);
break;
// Two slot return
case DRETURN:
case LRETURN:
pop(2);
break;
// Zero slot return
case RETURN:
break;
// Get array length
case ARRAYLENGTH:
break;
// Throw an exception
case ATHROW:
pop(1);
break;
// Enter or leave a monitor
case MONITORENTER:
case MONITOREXIT:
pop(1);
break;
default:
}
} else {
// Handle return and throw instructions
switch (inst) {
case RETURN:
case ARETURN:
case DRETURN:
case FRETURN:
case IRETURN:
case LRETURN:
if (onMethodReturn()) {
visitFrameAfterMethodReturnCallback();
}
break;
case ATHROW:
if (onThrowInstruction()) {
visitFrameAfterOnThrowCallback();
}
break;
}
super.visitInsn(inst);
}
} } | public class class_name {
@Override
public void visitInsn(int inst) {
processPendingExceptionHandlerEntry(-1);
// List of opcodes taken from visitInsn documentation
if (waitingForSuper) {
// Visit the instruction
super.visitInsn(inst); // depends on control dependency: [if], data = [none]
switch (inst) {
case NOP:
break;
// One slot constants
case ACONST_NULL:
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(OTHER, 1);
break;
// Two slot constants
case DCONST_0:
case DCONST_1:
case LCONST_0:
case LCONST_1:
push(OTHER, 2);
break;
// One slot array load
case IALOAD:
case FALOAD:
case AALOAD:
case BALOAD:
case CALOAD:
case SALOAD:
pop(1); // pop(2); push(OTHER, 1);
break;
// Two slot array load
case DALOAD:
case LALOAD:
// pop(2); push(OTHER, 2);
break;
// One slot array store
case IASTORE:
case FASTORE:
case AASTORE:
case BASTORE:
case CASTORE:
case SASTORE:
pop(3);
break;
// Two slot array store
case DASTORE:
case LASTORE:
pop(4);
break;
// Basic pop instructions
case POP:
pop(1);
break;
case POP2:
pop(2);
break;
// Stack manipulation instructions
case DUP: {
Object top = currentStack.get(currentStack.size() - 1);
push(top, 1);
break;
}
case DUP_X1: {
Object top = currentStack.get(currentStack.size() - 1);
int addPosition = currentStack.size() - 2;
currentStack.add(addPosition, top); // depends on control dependency: [if], data = [none]
break;
}
case DUP_X2: {
Object top = currentStack.get(currentStack.size() - 1);
int addPosition = currentStack.size() - 3;
currentStack.add(addPosition, top);
break;
}
case DUP2: {
int position = currentStack.size() - 2;
currentStack.add(currentStack.get(position));
currentStack.add(currentStack.get(position + 1));
break;
}
case DUP2_X1: {
int addPosition = currentStack.size() - 3;
currentStack.add(addPosition, currentStack.get(currentStack.size() - 1));
currentStack.add(addPosition, currentStack.get(currentStack.size() - 2));
break;
}
case DUP2_X2: {
int addPosition = currentStack.size() - 4;
currentStack.add(addPosition, currentStack.get(currentStack.size() - 1));
currentStack.add(addPosition, currentStack.get(currentStack.size() - 2));
break;
}
case SWAP: {
Object o = currentStack.remove(currentStack.size() - 2);
currentStack.add(o);
break;
}
// One slot arithmetic and logical instructions
case IADD:
case FADD:
case ISUB:
case FSUB:
case IMUL:
case FMUL:
case IDIV:
case FDIV:
case IREM:
case FREM:
case INEG:
case FNEG:
case ISHL:
case ISHR:
case IUSHR:
case IAND:
case IOR:
case IXOR:
pop(1);
break;
// Two slot arithmetic and logical instructions
case DADD:
case LADD:
case DSUB:
case LSUB:
case DMUL:
case LMUL:
case DDIV:
case LDIV:
case DREM:
case LREM:
case DNEG:
case LNEG:
case LSHL:
case LSHR:
case LUSHR:
case LAND:
case LOR:
case LXOR:
pop(2);
break;
// One slot to two slot conversions
case I2D:
case I2L:
case F2D:
case F2L:
push(OTHER, 1);
break;
// One slot to one slot conversions
case F2I:
case I2B:
case I2C:
case I2F:
case I2S:
break;
// Two slot to one slot conversions
case D2F:
case D2I:
case L2I:
case L2F:
pop(1);
break;
// Two slot to two slot conversions
case L2D:
case D2L:
break;
// Two slot compare
case DCMPL:
case DCMPG:
case LCMP:
pop(3);
break;
// One slot compare
case FCMPL:
case FCMPG:
pop(1);
break;
// One slot return
case IRETURN:
case FRETURN:
case ARETURN:
pop(1);
break;
// Two slot return
case DRETURN:
case LRETURN:
pop(2);
break;
// Zero slot return
case RETURN:
break;
// Get array length
case ARRAYLENGTH:
break;
// Throw an exception
case ATHROW:
pop(1);
break;
// Enter or leave a monitor
case MONITORENTER:
case MONITOREXIT:
pop(1);
break;
default:
}
} else {
// Handle return and throw instructions
switch (inst) {
case RETURN:
case ARETURN:
case DRETURN:
case FRETURN:
case IRETURN:
case LRETURN:
if (onMethodReturn()) {
visitFrameAfterMethodReturnCallback();
}
break;
case ATHROW:
if (onThrowInstruction()) {
visitFrameAfterOnThrowCallback();
}
break;
}
super.visitInsn(inst);
}
} } |
public class class_name {
@SuppressWarnings("PMD.AssignmentInOperand")
private static byte[] asBytes(final InputStream input) throws IOException {
input.reset();
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
// @checkstyle MagicNumberCheck (1 line)
final byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer, 0, buffer.length)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
return output.toByteArray();
}
} } | public class class_name {
@SuppressWarnings("PMD.AssignmentInOperand")
private static byte[] asBytes(final InputStream input) throws IOException {
input.reset();
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
// @checkstyle MagicNumberCheck (1 line)
final byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer, 0, buffer.length)) != -1) {
output.write(buffer, 0, read); // depends on control dependency: [while], data = [none]
}
output.flush();
return output.toByteArray();
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
public <T> Set<T> getContextSet(String key) {
Set<T> set = (Set<T>) attributes.get(key);
if (set == null) {
set = new HashSet<T>();
attributes.put(key, set);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "ConfigContext create set instance for {0}", key);
}
}
return set;
} } | public class class_name {
@SuppressWarnings("unchecked")
public <T> Set<T> getContextSet(String key) {
Set<T> set = (Set<T>) attributes.get(key);
if (set == null) {
set = new HashSet<T>(); // depends on control dependency: [if], data = [none]
attributes.put(key, set); // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "ConfigContext create set instance for {0}", key); // depends on control dependency: [if], data = [none]
}
}
return set;
} } |
public class class_name {
public String formatISO(
IsoDateStyle dateStyle,
InfinityStyle infinityStyle
) {
DateInterval interval = this.toCanonical();
StringBuilder buffer = new StringBuilder(21);
ChronoPrinter<PlainDate> printer = Iso8601Format.ofDate(dateStyle);
if (interval.getStart().isInfinite()) {
buffer.append(infinityStyle.displayPast(printer, PlainDate.axis()));
} else {
printer.print(interval.getStartAsCalendarDate(), buffer);
}
buffer.append('/');
if (interval.getEnd().isInfinite()) {
buffer.append(infinityStyle.displayFuture(printer, PlainDate.axis()));
} else {
printer.print(interval.getEndAsCalendarDate(), buffer);
}
return buffer.toString();
} } | public class class_name {
public String formatISO(
IsoDateStyle dateStyle,
InfinityStyle infinityStyle
) {
DateInterval interval = this.toCanonical();
StringBuilder buffer = new StringBuilder(21);
ChronoPrinter<PlainDate> printer = Iso8601Format.ofDate(dateStyle);
if (interval.getStart().isInfinite()) {
buffer.append(infinityStyle.displayPast(printer, PlainDate.axis())); // depends on control dependency: [if], data = [none]
} else {
printer.print(interval.getStartAsCalendarDate(), buffer); // depends on control dependency: [if], data = [none]
}
buffer.append('/');
if (interval.getEnd().isInfinite()) {
buffer.append(infinityStyle.displayFuture(printer, PlainDate.axis())); // depends on control dependency: [if], data = [none]
} else {
printer.print(interval.getEndAsCalendarDate(), buffer); // depends on control dependency: [if], data = [none]
}
return buffer.toString();
} } |
public class class_name {
public static boolean isEventMetadataRequired(ObserverMethod<?> observer) {
if (observer instanceof EventMetadataAwareObserverMethod) {
EventMetadataAwareObserverMethod<?> eventMetadataAware = (EventMetadataAwareObserverMethod<?>) observer;
return eventMetadataAware.isEventMetadataRequired();
} else {
return true;
}
} } | public class class_name {
public static boolean isEventMetadataRequired(ObserverMethod<?> observer) {
if (observer instanceof EventMetadataAwareObserverMethod) {
EventMetadataAwareObserverMethod<?> eventMetadataAware = (EventMetadataAwareObserverMethod<?>) observer;
return eventMetadataAware.isEventMetadataRequired(); // depends on control dependency: [if], data = [none]
} else {
return true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void printBeans(final int width) {
final Print print = new Print();
print.line("Beans", width);
final List<BeanDefinition> beanDefinitionList = new ArrayList<>();
final String appName = appNameSupplier.get();
final String prefix = appName + ".";
petiteContainer.forEachBean(beanDefinitionList::add);
beanDefinitionList.stream()
.sorted((bd1, bd2) -> {
if (bd1.name().startsWith(prefix)) {
if (bd2.name().startsWith(prefix)) {
return bd1.name().compareTo(bd2.name());
}
return 1;
}
if (bd2.name().startsWith(prefix)) {
if (bd1.name().startsWith(prefix)) {
return bd1.name().compareTo(bd2.name());
}
return -1;
}
return bd1.name().compareTo(bd2.name());
})
.forEach(beanDefinition -> {
print.out(Chalk256.chalk().yellow(), scopeName(beanDefinition), 10);
print.space();
print.outLeftRightNewLine(
Chalk256.chalk().green(), beanDefinition.name(),
Chalk256.chalk().blue(), ClassUtil.getShortClassName(beanDefinition.type(), 2),
width - 10 - 1
);
});
print.line(width);
} } | public class class_name {
public void printBeans(final int width) {
final Print print = new Print();
print.line("Beans", width);
final List<BeanDefinition> beanDefinitionList = new ArrayList<>();
final String appName = appNameSupplier.get();
final String prefix = appName + ".";
petiteContainer.forEachBean(beanDefinitionList::add);
beanDefinitionList.stream()
.sorted((bd1, bd2) -> {
if (bd1.name().startsWith(prefix)) {
if (bd2.name().startsWith(prefix)) {
return bd1.name().compareTo(bd2.name()); // depends on control dependency: [if], data = [none]
}
return 1; // depends on control dependency: [if], data = [none]
}
if (bd2.name().startsWith(prefix)) {
if (bd1.name().startsWith(prefix)) {
return bd1.name().compareTo(bd2.name()); // depends on control dependency: [if], data = [none]
}
return -1; // depends on control dependency: [if], data = [none]
}
return bd1.name().compareTo(bd2.name());
})
.forEach(beanDefinition -> {
print.out(Chalk256.chalk().yellow(), scopeName(beanDefinition), 10);
print.space();
print.outLeftRightNewLine(
Chalk256.chalk().green(), beanDefinition.name(),
Chalk256.chalk().blue(), ClassUtil.getShortClassName(beanDefinition.type(), 2),
width - 10 - 1
);
});
print.line(width);
} } |
public class class_name {
public static Optimizer<DifferentiableFunction> getRegularizedOptimizer(final Optimizer<DifferentiableFunction> opt,
final double l1Lambda, final double l2Lambda) {
if (l1Lambda == 0 && l2Lambda == 0) {
return opt;
}
return new Optimizer<DifferentiableFunction>() {
@Override
public boolean minimize(DifferentiableFunction objective, IntDoubleVector point) {
DifferentiableFunction fn = getRegularizedFn(objective, false, l1Lambda, l2Lambda);
return opt.minimize(fn, point);
}
};
} } | public class class_name {
public static Optimizer<DifferentiableFunction> getRegularizedOptimizer(final Optimizer<DifferentiableFunction> opt,
final double l1Lambda, final double l2Lambda) {
if (l1Lambda == 0 && l2Lambda == 0) {
return opt; // depends on control dependency: [if], data = [none]
}
return new Optimizer<DifferentiableFunction>() {
@Override
public boolean minimize(DifferentiableFunction objective, IntDoubleVector point) {
DifferentiableFunction fn = getRegularizedFn(objective, false, l1Lambda, l2Lambda);
return opt.minimize(fn, point);
}
};
} } |
public class class_name {
private void checkAtMost(int i) throws ContradictionException {
ISet ker = target.getMandSet(g, i);
ISet env = target.getPotSet(g, i);
int size = ker.size();
if (size > degrees[i]) {
g.removeNode(i, this);
} else if (size == degrees[i] && env.size() > size) {
for (int other : env) {
if (!ker.contains(other)) {
target.remove(g, i, other, this);
}
}
}
} } | public class class_name {
private void checkAtMost(int i) throws ContradictionException {
ISet ker = target.getMandSet(g, i);
ISet env = target.getPotSet(g, i);
int size = ker.size();
if (size > degrees[i]) {
g.removeNode(i, this);
} else if (size == degrees[i] && env.size() > size) {
for (int other : env) {
if (!ker.contains(other)) {
target.remove(g, i, other, this); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
private String substitute(String uri) {
List<String> params = extractRequiredParamsInURI(uri);
for (String param: params) {
if (param.equals(PARAMS)) {
uri = uri.replace("{" + PARAMS +"}", Utils.urlEncode(getParamsURI()));
}
else {
uri = uri.replace("{" + param + "}", (String)commandParams.get(param));
}
}
return uri;
} } | public class class_name {
private String substitute(String uri) {
List<String> params = extractRequiredParamsInURI(uri);
for (String param: params) {
if (param.equals(PARAMS)) {
uri = uri.replace("{" + PARAMS +"}", Utils.urlEncode(getParamsURI())); // depends on control dependency: [if], data = [none]
}
else {
uri = uri.replace("{" + param + "}", (String)commandParams.get(param)); // depends on control dependency: [if], data = [none]
}
}
return uri;
} } |
public class class_name {
public static <T extends TextView> List<T> filterViewsByText(Iterable<T> views, Pattern regex) {
final ArrayList<T> filteredViews = new ArrayList<T>();
for (T view : views) {
if (view != null && regex.matcher(view.getText()).matches()) {
filteredViews.add(view);
}
}
return filteredViews;
} } | public class class_name {
public static <T extends TextView> List<T> filterViewsByText(Iterable<T> views, Pattern regex) {
final ArrayList<T> filteredViews = new ArrayList<T>();
for (T view : views) {
if (view != null && regex.matcher(view.getText()).matches()) {
filteredViews.add(view); // depends on control dependency: [if], data = [(view]
}
}
return filteredViews;
} } |
public class class_name {
public void marshall(DescribeDRTAccessRequest describeDRTAccessRequest, ProtocolMarshaller protocolMarshaller) {
if (describeDRTAccessRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DescribeDRTAccessRequest describeDRTAccessRequest, ProtocolMarshaller protocolMarshaller) {
if (describeDRTAccessRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
} 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 DerValue findMostSpecificAttribute(ObjectIdentifier attribute) {
if (names != null) {
for (int i = names.length - 1; i >= 0; i--) {
DerValue value = names[i].findAttribute(attribute);
if (value != null) {
return value;
}
}
}
return null;
} } | public class class_name {
public DerValue findMostSpecificAttribute(ObjectIdentifier attribute) {
if (names != null) {
for (int i = names.length - 1; i >= 0; i--) {
DerValue value = names[i].findAttribute(attribute);
if (value != null) {
return value; // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
public static final Color hex2RGB(final String hex)
{
String r, g, b;
final int len = hex.length();
if (len == 7)
{
r = hex.substring(1, 3);
g = hex.substring(3, 5);
b = hex.substring(5, 7);
}
else if (len == 4)
{
r = hex.substring(1, 2);
g = hex.substring(2, 3);
b = hex.substring(3, 4);
r = r + r;
g = g + g;
b = b + b;
}
else
{
return null;// error - invalid length
}
try
{
return new Color(Integer.valueOf(r, 16), Integer.valueOf(g, 16), Integer.valueOf(b, 16));
}
catch (final NumberFormatException ignored)
{
return null;
}
} } | public class class_name {
public static final Color hex2RGB(final String hex)
{
String r, g, b;
final int len = hex.length();
if (len == 7)
{
r = hex.substring(1, 3); // depends on control dependency: [if], data = [none]
g = hex.substring(3, 5); // depends on control dependency: [if], data = [none]
b = hex.substring(5, 7); // depends on control dependency: [if], data = [7)]
}
else if (len == 4)
{
r = hex.substring(1, 2); // depends on control dependency: [if], data = [none]
g = hex.substring(2, 3); // depends on control dependency: [if], data = [none]
b = hex.substring(3, 4); // depends on control dependency: [if], data = [4)]
r = r + r; // depends on control dependency: [if], data = [none]
g = g + g; // depends on control dependency: [if], data = [none]
b = b + b; // depends on control dependency: [if], data = [none]
}
else
{
return null;// error - invalid length // depends on control dependency: [if], data = [none]
}
try
{
return new Color(Integer.valueOf(r, 16), Integer.valueOf(g, 16), Integer.valueOf(b, 16)); // depends on control dependency: [try], data = [none]
}
catch (final NumberFormatException ignored)
{
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public List<ProteinType.Component> getComponent() {
if (component == null) {
component = new ArrayList<ProteinType.Component>();
}
return this.component;
} } | public class class_name {
public List<ProteinType.Component> getComponent() {
if (component == null) {
component = new ArrayList<ProteinType.Component>(); // depends on control dependency: [if], data = [none]
}
return this.component;
} } |
public class class_name {
private void updateCurrentToolTipText() {
String toolTipText;
final boolean disabled = !isEnabled();
final boolean selected = isSelected();
if (disabled && selected && disabledSelectedToolTipText != null) {
toolTipText = disabledSelectedToolTipText;
} else if (disabled && disabledToolTipText != null) {
toolTipText = disabledToolTipText;
} else if (selected && selectedToolTipText != null) {
toolTipText = selectedToolTipText;
} else {
toolTipText = defaultToolTipText;
}
super.setToolTipText(toolTipText);
} } | public class class_name {
private void updateCurrentToolTipText() {
String toolTipText;
final boolean disabled = !isEnabled();
final boolean selected = isSelected();
if (disabled && selected && disabledSelectedToolTipText != null) {
toolTipText = disabledSelectedToolTipText; // depends on control dependency: [if], data = [none]
} else if (disabled && disabledToolTipText != null) {
toolTipText = disabledToolTipText; // depends on control dependency: [if], data = [none]
} else if (selected && selectedToolTipText != null) {
toolTipText = selectedToolTipText; // depends on control dependency: [if], data = [none]
} else {
toolTipText = defaultToolTipText; // depends on control dependency: [if], data = [none]
}
super.setToolTipText(toolTipText);
} } |
public class class_name {
@Nullable
public String getServiceId() {
String serviceId = getString(SERVICE_KEY);
if (serviceId == null) {
serviceId = getString(MODULE_KEY);
}
return serviceId;
} } | public class class_name {
@Nullable
public String getServiceId() {
String serviceId = getString(SERVICE_KEY);
if (serviceId == null) {
serviceId = getString(MODULE_KEY); // depends on control dependency: [if], data = [none]
}
return serviceId;
} } |
public class class_name {
public Object value(int i, String key) {
Object data = getData();
if (data instanceof List) {
List list = (List) data;
if (list.size() > 0) {
Map map = (Map) list.get(i);
return map.get(key);
}
} else if (data instanceof Map) {
return ((Map) data).get(key);
}
return null;
} } | public class class_name {
public Object value(int i, String key) {
Object data = getData();
if (data instanceof List) {
List list = (List) data;
if (list.size() > 0) {
Map map = (Map) list.get(i);
return map.get(key); // depends on control dependency: [if], data = [none]
}
} else if (data instanceof Map) {
return ((Map) data).get(key); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public java.util.List<EventSubscription> getEventSubscriptionsList() {
if (eventSubscriptionsList == null) {
eventSubscriptionsList = new com.amazonaws.internal.SdkInternalList<EventSubscription>();
}
return eventSubscriptionsList;
} } | public class class_name {
public java.util.List<EventSubscription> getEventSubscriptionsList() {
if (eventSubscriptionsList == null) {
eventSubscriptionsList = new com.amazonaws.internal.SdkInternalList<EventSubscription>(); // depends on control dependency: [if], data = [none]
}
return eventSubscriptionsList;
} } |
public class class_name {
public void setAttributes(FaceletContext ctx, Object obj)
{
super.setAttributes(ctx, obj);
NumberConverter c = (NumberConverter) obj;
if (this.locale != null)
{
c.setLocale(ComponentSupport.getLocale(ctx, this.locale));
}
} } | public class class_name {
public void setAttributes(FaceletContext ctx, Object obj)
{
super.setAttributes(ctx, obj);
NumberConverter c = (NumberConverter) obj;
if (this.locale != null)
{
c.setLocale(ComponentSupport.getLocale(ctx, this.locale)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void removeEndPoint(String name) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Deleting endpoint: " + name);
}
synchronized (this.endpoints) {
if (this.endpoints.remove(name) != null) {
unregisterMBeanInService(name);
}
}
} } | public class class_name {
@Override
public void removeEndPoint(String name) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Deleting endpoint: " + name); // depends on control dependency: [if], data = [none]
}
synchronized (this.endpoints) {
if (this.endpoints.remove(name) != null) {
unregisterMBeanInService(name); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public java.lang.String getJavaClass() {
java.lang.Object ref = javaClass_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
javaClass_ = s;
}
return s;
}
} } | public class class_name {
public java.lang.String getJavaClass() {
java.lang.Object ref = javaClass_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref; // depends on control dependency: [if], data = [none]
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
javaClass_ = s; // depends on control dependency: [if], data = [none]
}
return s; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void manage(int workersCount)
{
this.workers.clear();
WorkerThread worker = null;
for (int i = 0; i <workersCount; i++)
{
worker = new WorkerThread(this); //TODO expensive use thread pool
this.manage(worker);
}
} } | public class class_name {
public void manage(int workersCount)
{
this.workers.clear();
WorkerThread worker = null;
for (int i = 0; i <workersCount; i++)
{
worker = new WorkerThread(this); //TODO expensive use thread pool
// depends on control dependency: [for], data = [none]
this.manage(worker);
// depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public void setInstanceProfileList(java.util.Collection<InstanceProfile> instanceProfileList) {
if (instanceProfileList == null) {
this.instanceProfileList = null;
return;
}
this.instanceProfileList = new com.amazonaws.internal.SdkInternalList<InstanceProfile>(instanceProfileList);
} } | public class class_name {
public void setInstanceProfileList(java.util.Collection<InstanceProfile> instanceProfileList) {
if (instanceProfileList == null) {
this.instanceProfileList = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.instanceProfileList = new com.amazonaws.internal.SdkInternalList<InstanceProfile>(instanceProfileList);
} } |
public class class_name {
private void pushInitialEventsAsync() {
postAsyncSafely("CleverTapAPI#pushInitialEventsAsync", new Runnable() {
@Override
public void run() {
try {
getConfigLogger().verbose(getAccountId(), "Queuing daily events");
pushBasicProfile(null);
} catch (Throwable t) {
getConfigLogger().verbose(getAccountId(), "Daily profile sync failed", t);
}
}
});
} } | public class class_name {
private void pushInitialEventsAsync() {
postAsyncSafely("CleverTapAPI#pushInitialEventsAsync", new Runnable() {
@Override
public void run() {
try {
getConfigLogger().verbose(getAccountId(), "Queuing daily events"); // depends on control dependency: [try], data = [none]
pushBasicProfile(null); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
getConfigLogger().verbose(getAccountId(), "Daily profile sync failed", t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public Timecode resample(final Timebase toRate, final boolean toDropFrame)
{
if (toDropFrame && !toRate.canBeDropFrame())
throw new IllegalArgumentException(
"Resample cannot convert to a drop-frame version of a Timebase that does not support drop frame: " + toRate);
final Timebase fromRate = getTimebase();
if (!fromRate.equals(toRate))
{
// Changing framerate
if (isDropFrame() || toDropFrame)
{
final SampleCount samples = getSampleCount().resample(toRate);
return TimecodeBuilder.fromSamples(samples, toDropFrame).build();
}
else
{
// No drop frames to worry about, proceed with simple resample of just the frames part
// Resample the frames part (N.B. may round up to 1 whole second)
final long resampled = toRate.resample(this.getFramesPart(), fromRate);
// Take the fast approach if the number of samples is < 1 second, otherwise take the slow route
if (resampled < toRate.getSamplesPerSecond())
return new Timecode(negative, days, hours, minutes, seconds, resampled, toRate, toDropFrame);
else
return new Timecode(negative,
days,
hours,
minutes,
seconds,
0,
toRate,
toDropFrame).add(new SampleCount(resampled, toRate));
}
}
else if (toDropFrame != isDropFrame())
{
// Changing drop frame flag
return Timecode.getInstance(getSampleCount(), toDropFrame);
}
else
{
// Changing nothing
return this;
}
} } | public class class_name {
public Timecode resample(final Timebase toRate, final boolean toDropFrame)
{
if (toDropFrame && !toRate.canBeDropFrame())
throw new IllegalArgumentException(
"Resample cannot convert to a drop-frame version of a Timebase that does not support drop frame: " + toRate);
final Timebase fromRate = getTimebase();
if (!fromRate.equals(toRate))
{
// Changing framerate
if (isDropFrame() || toDropFrame)
{
final SampleCount samples = getSampleCount().resample(toRate);
return TimecodeBuilder.fromSamples(samples, toDropFrame).build(); // depends on control dependency: [if], data = [toDropFrame)]
}
else
{
// No drop frames to worry about, proceed with simple resample of just the frames part
// Resample the frames part (N.B. may round up to 1 whole second)
final long resampled = toRate.resample(this.getFramesPart(), fromRate);
// Take the fast approach if the number of samples is < 1 second, otherwise take the slow route
if (resampled < toRate.getSamplesPerSecond())
return new Timecode(negative, days, hours, minutes, seconds, resampled, toRate, toDropFrame);
else
return new Timecode(negative,
days,
hours,
minutes,
seconds,
0,
toRate,
toDropFrame).add(new SampleCount(resampled, toRate));
}
}
else if (toDropFrame != isDropFrame())
{
// Changing drop frame flag
return Timecode.getInstance(getSampleCount(), toDropFrame); // depends on control dependency: [if], data = [none]
}
else
{
// Changing nothing
return this; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String addStart(String str, String add) {
if (isNullOrEmpty(add)) {
return str;
}
if (isNullOrEmpty(str)) {
return add;
}
if (!str.startsWith(add)) {
return add + str;
}
return str;
} } | public class class_name {
public static String addStart(String str, String add) {
if (isNullOrEmpty(add)) {
return str; // depends on control dependency: [if], data = [none]
}
if (isNullOrEmpty(str)) {
return add; // depends on control dependency: [if], data = [none]
}
if (!str.startsWith(add)) {
return add + str; // depends on control dependency: [if], data = [none]
}
return str;
} } |
public class class_name {
public void setNoteUpdatedBy(java.util.Collection<StringFilter> noteUpdatedBy) {
if (noteUpdatedBy == null) {
this.noteUpdatedBy = null;
return;
}
this.noteUpdatedBy = new java.util.ArrayList<StringFilter>(noteUpdatedBy);
} } | public class class_name {
public void setNoteUpdatedBy(java.util.Collection<StringFilter> noteUpdatedBy) {
if (noteUpdatedBy == null) {
this.noteUpdatedBy = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.noteUpdatedBy = new java.util.ArrayList<StringFilter>(noteUpdatedBy);
} } |
public class class_name {
public DERObject toASN1Object()
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(policyIdentifier);
if (policyQualifiers != null)
{
v.add(policyQualifiers);
}
return new DERSequence(v);
} } | public class class_name {
public DERObject toASN1Object()
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(policyIdentifier);
if (policyQualifiers != null)
{
v.add(policyQualifiers); // depends on control dependency: [if], data = [(policyQualifiers]
}
return new DERSequence(v);
} } |
public class class_name {
public AwsSecurityFindingFilters withResourceAwsIamAccessKeyStatus(StringFilter... resourceAwsIamAccessKeyStatus) {
if (this.resourceAwsIamAccessKeyStatus == null) {
setResourceAwsIamAccessKeyStatus(new java.util.ArrayList<StringFilter>(resourceAwsIamAccessKeyStatus.length));
}
for (StringFilter ele : resourceAwsIamAccessKeyStatus) {
this.resourceAwsIamAccessKeyStatus.add(ele);
}
return this;
} } | public class class_name {
public AwsSecurityFindingFilters withResourceAwsIamAccessKeyStatus(StringFilter... resourceAwsIamAccessKeyStatus) {
if (this.resourceAwsIamAccessKeyStatus == null) {
setResourceAwsIamAccessKeyStatus(new java.util.ArrayList<StringFilter>(resourceAwsIamAccessKeyStatus.length)); // depends on control dependency: [if], data = [none]
}
for (StringFilter ele : resourceAwsIamAccessKeyStatus) {
this.resourceAwsIamAccessKeyStatus.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private void processRangeOptions(final Map<String, String> properties) {
final String featuresRange = properties.get("range");
final String[] rangeArray = Flags
.processTokenClassFeaturesRange(featuresRange);
if (rangeArray[0].equalsIgnoreCase("lower")) {
this.isLower = true;
}
if (rangeArray[1].equalsIgnoreCase("wac")) {
this.isWordAndClassFeature = true;
}
} } | public class class_name {
private void processRangeOptions(final Map<String, String> properties) {
final String featuresRange = properties.get("range");
final String[] rangeArray = Flags
.processTokenClassFeaturesRange(featuresRange);
if (rangeArray[0].equalsIgnoreCase("lower")) {
this.isLower = true; // depends on control dependency: [if], data = [none]
}
if (rangeArray[1].equalsIgnoreCase("wac")) {
this.isWordAndClassFeature = true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void stop()
{
if (! getLifecycle().toStop()) {
return;
}
ArrayList<EnvLoaderListener> listeners = getEnvironmentListeners();
Thread thread = Thread.currentThread();
ClassLoader oldLoader = thread.getContextClassLoader();
thread.setContextClassLoader(this);
try {
// closing down in reverse
if (listeners != null) {
for (int i = listeners.size() - 1; i >= 0; i--) {
EnvLoaderListener listener = listeners.get(i);
try {
listener.environmentStop(this);
} catch (Throwable e) {
log().log(Level.WARNING, e.toString(), e);
}
}
}
super.stop();
} finally {
thread.setContextClassLoader(oldLoader);
// drain the thread pool for GC
// XXX: ExecutorThreadPoolBaratine.getThreadPool().stopEnvironment(this);
}
} } | public class class_name {
@Override
public void stop()
{
if (! getLifecycle().toStop()) {
return; // depends on control dependency: [if], data = [none]
}
ArrayList<EnvLoaderListener> listeners = getEnvironmentListeners();
Thread thread = Thread.currentThread();
ClassLoader oldLoader = thread.getContextClassLoader();
thread.setContextClassLoader(this);
try {
// closing down in reverse
if (listeners != null) {
for (int i = listeners.size() - 1; i >= 0; i--) {
EnvLoaderListener listener = listeners.get(i);
try {
listener.environmentStop(this); // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
log().log(Level.WARNING, e.toString(), e);
} // depends on control dependency: [catch], data = [none]
}
}
super.stop(); // depends on control dependency: [try], data = [none]
} finally {
thread.setContextClassLoader(oldLoader);
// drain the thread pool for GC
// XXX: ExecutorThreadPoolBaratine.getThreadPool().stopEnvironment(this);
}
} } |
public class class_name {
public void addMainHandler(Object handler, String prefix) {
if (handler == null) {
throw new NullPointerException();
}
allHandlers.add(handler);
addDeclaredMethods(handler, prefix);
inputConverter.addDeclaredConverters(handler);
outputConverter.addDeclaredConverters(handler);
if (handler instanceof ShellDependent) {
((ShellDependent)handler).cliSetShell(this);
}
} } | public class class_name {
public void addMainHandler(Object handler, String prefix) {
if (handler == null) {
throw new NullPointerException();
}
allHandlers.add(handler);
addDeclaredMethods(handler, prefix);
inputConverter.addDeclaredConverters(handler);
outputConverter.addDeclaredConverters(handler);
if (handler instanceof ShellDependent) {
((ShellDependent)handler).cliSetShell(this); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Result run(Database database, Relation<O> relation) {
if(queries == null) {
throw new AbortException("A query set is required for this 'run' method.");
}
// Get a distance and kNN query instance.
DistanceQuery<O> distQuery = database.getDistanceQuery(relation, getDistanceFunction());
RangeQuery<O> rangeQuery = database.getRangeQuery(distQuery);
NumberVector.Factory<O> ofactory = RelationUtil.getNumberVectorFactory(relation);
int dim = RelationUtil.dimensionality(relation);
// Separate query set.
TypeInformation res = VectorFieldTypeInformation.typeRequest(NumberVector.class, dim + 1, dim + 1);
MultipleObjectsBundle bundle = queries.loadData();
int col = -1;
for(int i = 0; i < bundle.metaLength(); i++) {
if(res.isAssignableFromType(bundle.meta(i))) {
col = i;
break;
}
}
if(col < 0) {
StringBuilder buf = new StringBuilder();
buf.append("No compatible data type in query input was found. Expected: ");
buf.append(res.toString());
buf.append(" have: ");
for(int i = 0; i < bundle.metaLength(); i++) {
if(i > 0) {
buf.append(' ');
}
buf.append(bundle.meta(i).toString());
}
throw new IncompatibleDataException(buf.toString());
}
// Random sampling is a bit of hack, sorry.
// But currently, we don't (yet) have an "integer random sample" function.
DBIDRange sids = DBIDUtil.generateStaticDBIDRange(bundle.dataLength());
final DBIDs sample = DBIDUtil.randomSample(sids, sampling, random);
FiniteProgress prog = LOG.isVeryVerbose() ? new FiniteProgress("kNN queries", sample.size(), LOG) : null;
int hash = 0;
MeanVariance mv = new MeanVariance();
double[] buf = new double[dim];
for(DBIDIter iditer = sample.iter(); iditer.valid(); iditer.advance()) {
int off = sids.binarySearch(iditer);
assert (off >= 0);
NumberVector o = (NumberVector) bundle.data(off, col);
for(int i = 0; i < dim; i++) {
buf[i] = o.doubleValue(i);
}
O v = ofactory.newNumberVector(buf);
double r = o.doubleValue(dim);
DoubleDBIDList rres = rangeQuery.getRangeForObject(v, r);
int ichecksum = 0;
for(DBIDIter it = rres.iter(); it.valid(); it.advance()) {
ichecksum += DBIDUtil.asInteger(it);
}
hash = Util.mixHashCodes(hash, ichecksum);
mv.put(rres.size());
LOG.incrementProcessed(prog);
}
LOG.ensureCompleted(prog);
if(LOG.isStatistics()) {
LOG.statistics("Result hashcode: " + hash);
LOG.statistics("Mean number of results: " + mv.getMean() + " +- " + mv.getNaiveStddev());
}
return null;
} } | public class class_name {
public Result run(Database database, Relation<O> relation) {
if(queries == null) {
throw new AbortException("A query set is required for this 'run' method.");
}
// Get a distance and kNN query instance.
DistanceQuery<O> distQuery = database.getDistanceQuery(relation, getDistanceFunction());
RangeQuery<O> rangeQuery = database.getRangeQuery(distQuery);
NumberVector.Factory<O> ofactory = RelationUtil.getNumberVectorFactory(relation);
int dim = RelationUtil.dimensionality(relation);
// Separate query set.
TypeInformation res = VectorFieldTypeInformation.typeRequest(NumberVector.class, dim + 1, dim + 1);
MultipleObjectsBundle bundle = queries.loadData();
int col = -1;
for(int i = 0; i < bundle.metaLength(); i++) {
if(res.isAssignableFromType(bundle.meta(i))) {
col = i; // depends on control dependency: [if], data = [none]
break;
}
}
if(col < 0) {
StringBuilder buf = new StringBuilder();
buf.append("No compatible data type in query input was found. Expected: "); // depends on control dependency: [if], data = [none]
buf.append(res.toString()); // depends on control dependency: [if], data = [none]
buf.append(" have: "); // depends on control dependency: [if], data = [none]
for(int i = 0; i < bundle.metaLength(); i++) {
if(i > 0) {
buf.append(' '); // depends on control dependency: [if], data = [none]
}
buf.append(bundle.meta(i).toString()); // depends on control dependency: [for], data = [i]
}
throw new IncompatibleDataException(buf.toString());
}
// Random sampling is a bit of hack, sorry.
// But currently, we don't (yet) have an "integer random sample" function.
DBIDRange sids = DBIDUtil.generateStaticDBIDRange(bundle.dataLength());
final DBIDs sample = DBIDUtil.randomSample(sids, sampling, random);
FiniteProgress prog = LOG.isVeryVerbose() ? new FiniteProgress("kNN queries", sample.size(), LOG) : null;
int hash = 0;
MeanVariance mv = new MeanVariance();
double[] buf = new double[dim];
for(DBIDIter iditer = sample.iter(); iditer.valid(); iditer.advance()) {
int off = sids.binarySearch(iditer);
assert (off >= 0); // depends on control dependency: [for], data = [none]
NumberVector o = (NumberVector) bundle.data(off, col);
for(int i = 0; i < dim; i++) {
buf[i] = o.doubleValue(i); // depends on control dependency: [for], data = [i]
}
O v = ofactory.newNumberVector(buf);
double r = o.doubleValue(dim);
DoubleDBIDList rres = rangeQuery.getRangeForObject(v, r);
int ichecksum = 0;
for(DBIDIter it = rres.iter(); it.valid(); it.advance()) {
ichecksum += DBIDUtil.asInteger(it); // depends on control dependency: [for], data = [it]
}
hash = Util.mixHashCodes(hash, ichecksum); // depends on control dependency: [for], data = [none]
mv.put(rres.size()); // depends on control dependency: [for], data = [none]
LOG.incrementProcessed(prog); // depends on control dependency: [for], data = [none]
}
LOG.ensureCompleted(prog);
if(LOG.isStatistics()) {
LOG.statistics("Result hashcode: " + hash); // depends on control dependency: [if], data = [none]
LOG.statistics("Mean number of results: " + mv.getMean() + " +- " + mv.getNaiveStddev()); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Override
protected void nibble(Queue<BitIntegrityMorsel> queue) {
BitIntegrityMorsel morsel = queue.peek();
String storeId = morsel.getStoreId();
String account = morsel.getAccount();
StorageProvider store;
try {
store = getStorageProvider(account, storeId);
} catch (Exception ex) {
if (morsel.getMarker() != null) {
throw new DuraCloudRuntimeException(
"Failed to get storage provider for " + morsel + ". Morsel has already been nibbled. " +
"Likely cause: a storage provider was removed in the middle of processing the morsel. " +
"Further investigation and clean up recommended before restarting the run." +
"In most cases you should be able to remove the state file and restart the run.", ex);
} else {
//remove morsel.
queue.poll();
String message =
MessageFormat.format("Failed to get storage provider for {0}. Likely cause: A storage " +
"provider was removed after the bit integrity run was started. Since no " +
"tasks have been added yet for this morsel, we will simply skip it. " +
"No further action required.", morsel);
log.warn(message, morsel);
sendEmail("Failed to get storage provider for " + morsel, message);
return;
}
}
int maxTaskQueueSize = getMaxTaskQueueSize();
int taskQueueSize = getTaskQueue().size();
while (taskQueueSize < maxTaskQueueSize) {
if (taskQueueSize >= maxTaskQueueSize) {
log.info("Task queue size ({}) has reached or exceeded max size ({}).",
taskQueueSize, maxTaskQueueSize);
} else {
if (addTasks(morsel, store, 1000)) {
log.info("All bit integrity tasks that could be created were created for account={}, storeId={}, " +
"spaceId={}. getTaskQueue().size = {}",
morsel.getAccount(), storeId, morsel.getSpaceId(), getTaskQueue().size());
log.info("{} completely nibbled.", morsel);
// check if queue is empty after waiting a few moments: It is possible that AWS will not have
// registered a new task that was added in the previous step (or even is pending). I observed
// this problem while debugging this code.
// If I put the breakpoint on the if statement and I ran the task producer against a space with a
// single content item then size would be reported as 0. However if I put the breakpoint a line
// above on "long size = ..." then the size variable was evaluating to 1. At 5 seconds, I was
// still seeing the inconsistency. At 10 seconds the matter seems to be resolved.
// Makes me a little nervous. --dbernstein
log.debug("delay before checking the queue size in ms: {}", waitTimeInMsBeforeQueueSizeCheck);
sleep(waitTimeInMsBeforeQueueSizeCheck);
long size = getTaskQueue().sizeIncludingInvisibleAndDelayed();
if (size == 0) {
addReportTaskProcessorTask(queue.poll());
} else {
log.info("{} (queue) is not empty: {} items remain to be processed before " +
"creating report generation task.", getTaskQueue().getName(), size);
}
break;
} else {
log.info("morsel nibbled down: {}", morsel);
}
}
taskQueueSize = getTaskQueue().size();
}
} } | public class class_name {
@Override
protected void nibble(Queue<BitIntegrityMorsel> queue) {
BitIntegrityMorsel morsel = queue.peek();
String storeId = morsel.getStoreId();
String account = morsel.getAccount();
StorageProvider store;
try {
store = getStorageProvider(account, storeId); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
if (morsel.getMarker() != null) {
throw new DuraCloudRuntimeException(
"Failed to get storage provider for " + morsel + ". Morsel has already been nibbled. " +
"Likely cause: a storage provider was removed in the middle of processing the morsel. " +
"Further investigation and clean up recommended before restarting the run." +
"In most cases you should be able to remove the state file and restart the run.", ex);
} else {
//remove morsel.
queue.poll(); // depends on control dependency: [if], data = [none]
String message =
MessageFormat.format("Failed to get storage provider for {0}. Likely cause: A storage " +
"provider was removed after the bit integrity run was started. Since no " +
"tasks have been added yet for this morsel, we will simply skip it. " +
"No further action required.", morsel);
log.warn(message, morsel); // depends on control dependency: [if], data = [none]
sendEmail("Failed to get storage provider for " + morsel, message); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
int maxTaskQueueSize = getMaxTaskQueueSize();
int taskQueueSize = getTaskQueue().size();
while (taskQueueSize < maxTaskQueueSize) {
if (taskQueueSize >= maxTaskQueueSize) {
log.info("Task queue size ({}) has reached or exceeded max size ({}).",
taskQueueSize, maxTaskQueueSize); // depends on control dependency: [if], data = [none]
} else {
if (addTasks(morsel, store, 1000)) {
log.info("All bit integrity tasks that could be created were created for account={}, storeId={}, " +
"spaceId={}. getTaskQueue().size = {}",
morsel.getAccount(), storeId, morsel.getSpaceId(), getTaskQueue().size()); // depends on control dependency: [if], data = [none]
log.info("{} completely nibbled.", morsel); // depends on control dependency: [if], data = [none]
// check if queue is empty after waiting a few moments: It is possible that AWS will not have
// registered a new task that was added in the previous step (or even is pending). I observed
// this problem while debugging this code.
// If I put the breakpoint on the if statement and I ran the task producer against a space with a
// single content item then size would be reported as 0. However if I put the breakpoint a line
// above on "long size = ..." then the size variable was evaluating to 1. At 5 seconds, I was
// still seeing the inconsistency. At 10 seconds the matter seems to be resolved.
// Makes me a little nervous. --dbernstein
log.debug("delay before checking the queue size in ms: {}", waitTimeInMsBeforeQueueSizeCheck); // depends on control dependency: [if], data = [none]
sleep(waitTimeInMsBeforeQueueSizeCheck); // depends on control dependency: [if], data = [none]
long size = getTaskQueue().sizeIncludingInvisibleAndDelayed();
if (size == 0) {
addReportTaskProcessorTask(queue.poll()); // depends on control dependency: [if], data = [none]
} else {
log.info("{} (queue) is not empty: {} items remain to be processed before " +
"creating report generation task.", getTaskQueue().getName(), size); // depends on control dependency: [if], data = [none]
}
break;
} else {
log.info("morsel nibbled down: {}", morsel); // depends on control dependency: [if], data = [none]
}
}
taskQueueSize = getTaskQueue().size(); // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public void setStatusBarVisible(boolean statusBarVisible) {
if (this.statusBarVisible == statusBarVisible) return;
if (statusBar!=null) {
if (statusBarVisible)
panel.add(statusBar.getComponent(), BorderLayout.SOUTH);
else
panel.remove(statusBar.getComponent());
panel.revalidate();
panel.repaint();
}
boolean prev = this.statusBarVisible;
this.statusBarVisible = statusBarVisible;
synchronizer.statusBarVisibilityChanged(this);
propertyChangeSupport.firePropertyChange("statusBarVisible", prev, statusBarVisible);
} } | public class class_name {
public void setStatusBarVisible(boolean statusBarVisible) {
if (this.statusBarVisible == statusBarVisible) return;
if (statusBar!=null) {
if (statusBarVisible)
panel.add(statusBar.getComponent(), BorderLayout.SOUTH);
else
panel.remove(statusBar.getComponent());
panel.revalidate(); // depends on control dependency: [if], data = [none]
panel.repaint(); // depends on control dependency: [if], data = [none]
}
boolean prev = this.statusBarVisible;
this.statusBarVisible = statusBarVisible;
synchronizer.statusBarVisibilityChanged(this);
propertyChangeSupport.firePropertyChange("statusBarVisible", prev, statusBarVisible);
} } |
public class class_name {
public void marshall(DisassociateNodeRequest disassociateNodeRequest, ProtocolMarshaller protocolMarshaller) {
if (disassociateNodeRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(disassociateNodeRequest.getServerName(), SERVERNAME_BINDING);
protocolMarshaller.marshall(disassociateNodeRequest.getNodeName(), NODENAME_BINDING);
protocolMarshaller.marshall(disassociateNodeRequest.getEngineAttributes(), ENGINEATTRIBUTES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DisassociateNodeRequest disassociateNodeRequest, ProtocolMarshaller protocolMarshaller) {
if (disassociateNodeRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(disassociateNodeRequest.getServerName(), SERVERNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(disassociateNodeRequest.getNodeName(), NODENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(disassociateNodeRequest.getEngineAttributes(), ENGINEATTRIBUTES_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void removeDeleted(CmsClientSitemapEntry entry) {
for (CmsClientSitemapEntry child : entry.getSubEntries()) {
removeDeleted(child);
}
m_treeItems.remove(entry.getId());
} } | public class class_name {
public void removeDeleted(CmsClientSitemapEntry entry) {
for (CmsClientSitemapEntry child : entry.getSubEntries()) {
removeDeleted(child); // depends on control dependency: [for], data = [child]
}
m_treeItems.remove(entry.getId());
} } |
public class class_name {
public boolean isNew(String name, String artist, String album, byte[] albumCover, String albumCoverFormat, String id, String year, String genre, String bmp, long duration) {
if (name == null && artist == null && album == null && albumCover == null && id == null)
return true;
BiPredicate<String, String> compareStrings = (newString, oldString) ->
oldString != null && newString != null && !oldString.equals(newString);
if (compareStrings.test(name, this.name)) {
return true;
}
if (compareStrings.test(artist, this.artist)) {
return true;
}
if (compareStrings.test(album, this.album)) {
return true;
}
if (compareStrings.test(id, this.data)) {
return true;
}
if (compareStrings.test(albumCoverFormat, this.albumCoverFormat)) {
return true;
}
if (compareStrings.test(year, this.year)) {
return true;
}
if (compareStrings.test(genre, this.genre)) {
return true;
}
if (this.duration > 0 && duration > 0 && this.duration == duration) {
return true;
}
if (compareStrings.test(bmp, this.bmp)) {
return true;
}
if (albumCover != null) {
if (this.albumCover == null || !Arrays.equals(albumCover, this.albumCover))
return true;
}
return false;
} } | public class class_name {
public boolean isNew(String name, String artist, String album, byte[] albumCover, String albumCoverFormat, String id, String year, String genre, String bmp, long duration) {
if (name == null && artist == null && album == null && albumCover == null && id == null)
return true;
BiPredicate<String, String> compareStrings = (newString, oldString) ->
oldString != null && newString != null && !oldString.equals(newString);
if (compareStrings.test(name, this.name)) {
return true; // depends on control dependency: [if], data = [none]
}
if (compareStrings.test(artist, this.artist)) {
return true; // depends on control dependency: [if], data = [none]
}
if (compareStrings.test(album, this.album)) {
return true; // depends on control dependency: [if], data = [none]
}
if (compareStrings.test(id, this.data)) {
return true; // depends on control dependency: [if], data = [none]
}
if (compareStrings.test(albumCoverFormat, this.albumCoverFormat)) {
return true; // depends on control dependency: [if], data = [none]
}
if (compareStrings.test(year, this.year)) {
return true; // depends on control dependency: [if], data = [none]
}
if (compareStrings.test(genre, this.genre)) {
return true; // depends on control dependency: [if], data = [none]
}
if (this.duration > 0 && duration > 0 && this.duration == duration) {
return true; // depends on control dependency: [if], data = [none]
}
if (compareStrings.test(bmp, this.bmp)) {
return true; // depends on control dependency: [if], data = [none]
}
if (albumCover != null) {
if (this.albumCover == null || !Arrays.equals(albumCover, this.albumCover))
return true;
}
return false;
} } |
public class class_name {
public static Long getLong(long pValue) {
if (pValue >= LONG_LOWER_BOUND &&
pValue <= LONG_UPPER_BOUND) {
return mLongs[((int) pValue) - LONG_LOWER_BOUND];
} else {
return new Long(pValue);
}
} } | public class class_name {
public static Long getLong(long pValue) {
if (pValue >= LONG_LOWER_BOUND &&
pValue <= LONG_UPPER_BOUND) {
return mLongs[((int) pValue) - LONG_LOWER_BOUND]; // depends on control dependency: [if], data = [none]
} else {
return new Long(pValue); // depends on control dependency: [if], data = [(pValue]
}
} } |
public class class_name {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
Date date = triggerContext.lastCompletionTime();
if (date != null) {
Date scheduled = triggerContext.lastScheduledExecutionTime();
if (scheduled != null && date.before(scheduled)) {
// Previous task apparently executed too early...
// Let's simply use the last calculated execution time then,
// in order to prevent accidental re-fires in the same second.
date = scheduled;
}
} else {
date = new Date();
}
return this.sequenceGenerator.next(date);
} } | public class class_name {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
Date date = triggerContext.lastCompletionTime();
if (date != null) {
Date scheduled = triggerContext.lastScheduledExecutionTime();
if (scheduled != null && date.before(scheduled)) {
// Previous task apparently executed too early...
// Let's simply use the last calculated execution time then,
// in order to prevent accidental re-fires in the same second.
date = scheduled; // depends on control dependency: [if], data = [none]
}
} else {
date = new Date(); // depends on control dependency: [if], data = [none]
}
return this.sequenceGenerator.next(date);
} } |
public class class_name {
public void setBonusPayments(java.util.Collection<BonusPayment> bonusPayments) {
if (bonusPayments == null) {
this.bonusPayments = null;
return;
}
this.bonusPayments = new java.util.ArrayList<BonusPayment>(bonusPayments);
} } | public class class_name {
public void setBonusPayments(java.util.Collection<BonusPayment> bonusPayments) {
if (bonusPayments == null) {
this.bonusPayments = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.bonusPayments = new java.util.ArrayList<BonusPayment>(bonusPayments);
} } |
public class class_name {
public Object getSessionAttr(final String attrName) {
final HttpSession sess = request.getSession(false);
if (sess == null) {
return null;
}
return sess.getAttribute(attrName);
} } | public class class_name {
public Object getSessionAttr(final String attrName) {
final HttpSession sess = request.getSession(false);
if (sess == null) {
return null; // depends on control dependency: [if], data = [none]
}
return sess.getAttribute(attrName);
} } |
public class class_name {
protected CDI11Deployment createDeployment(ServletContext context, CDI11Bootstrap bootstrap) {
ImmutableSet.Builder<Metadata<Extension>> extensionsBuilder = ImmutableSet.builder();
extensionsBuilder.addAll(bootstrap.loadExtensions(WeldResourceLoader.getClassLoader()));
if (isDevModeEnabled) {
extensionsBuilder.add(new MetadataImpl<Extension>(DevelopmentMode.getProbeExtension(resourceLoader), "N/A"));
}
final Iterable<Metadata<Extension>> extensions = extensionsBuilder.build();
final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(extensions);
final EEModuleDescriptor eeModule = new EEModuleDescriptorImpl(context.getContextPath(), ModuleType.WEB);
final DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration.getKnownBeanDefiningAnnotations(),
Boolean.parseBoolean(context.getInitParameter(Jandex.DISABLE_JANDEX_DISCOVERY_STRATEGY)));
if (Jandex.isJandexAvailable(resourceLoader)) {
try {
Class<? extends BeanArchiveHandler> handlerClass = Reflections.loadClass(resourceLoader, JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER);
strategy.registerHandler((SecurityActions.newConstructorInstance(handlerClass, new Class<?>[] { ServletContext.class }, context)));
} catch (Exception e) {
throw CommonLogger.LOG.unableToInstantiate(JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER, Arrays.toString(new Object[] { context }), e);
}
} else {
strategy.registerHandler(new ServletContextBeanArchiveHandler(context));
}
strategy.setScanner(new WebAppBeanArchiveScanner(resourceLoader, bootstrap, context));
Set<WeldBeanDeploymentArchive> beanDeploymentArchives = strategy.performDiscovery();
String isolation = context.getInitParameter(CONTEXT_PARAM_ARCHIVE_ISOLATION);
if (isolation == null || Boolean.valueOf(isolation)) {
CommonLogger.LOG.archiveIsolationEnabled();
} else {
CommonLogger.LOG.archiveIsolationDisabled();
Set<WeldBeanDeploymentArchive> flatDeployment = new HashSet<WeldBeanDeploymentArchive>();
flatDeployment.add(WeldBeanDeploymentArchive.merge(bootstrap, beanDeploymentArchives));
beanDeploymentArchives = flatDeployment;
}
for (BeanDeploymentArchive archive : beanDeploymentArchives) {
archive.getServices().add(EEModuleDescriptor.class, eeModule);
}
CDI11Deployment deployment = new WeldDeployment(resourceLoader, bootstrap, beanDeploymentArchives, extensions) {
@Override
protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {
WeldBeanDeploymentArchive archive = super.createAdditionalBeanDeploymentArchive();
archive.getServices().add(EEModuleDescriptor.class, eeModule);
return archive;
}
};
if (strategy.getClassFileServices() != null) {
deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices());
}
return deployment;
} } | public class class_name {
protected CDI11Deployment createDeployment(ServletContext context, CDI11Bootstrap bootstrap) {
ImmutableSet.Builder<Metadata<Extension>> extensionsBuilder = ImmutableSet.builder();
extensionsBuilder.addAll(bootstrap.loadExtensions(WeldResourceLoader.getClassLoader()));
if (isDevModeEnabled) {
extensionsBuilder.add(new MetadataImpl<Extension>(DevelopmentMode.getProbeExtension(resourceLoader), "N/A")); // depends on control dependency: [if], data = [none]
}
final Iterable<Metadata<Extension>> extensions = extensionsBuilder.build();
final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(extensions);
final EEModuleDescriptor eeModule = new EEModuleDescriptorImpl(context.getContextPath(), ModuleType.WEB);
final DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration.getKnownBeanDefiningAnnotations(),
Boolean.parseBoolean(context.getInitParameter(Jandex.DISABLE_JANDEX_DISCOVERY_STRATEGY)));
if (Jandex.isJandexAvailable(resourceLoader)) {
try {
Class<? extends BeanArchiveHandler> handlerClass = Reflections.loadClass(resourceLoader, JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER);
strategy.registerHandler((SecurityActions.newConstructorInstance(handlerClass, new Class<?>[] { ServletContext.class }, context)));
} catch (Exception e) {
throw CommonLogger.LOG.unableToInstantiate(JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER, Arrays.toString(new Object[] { context }), e);
}
} else {
strategy.registerHandler(new ServletContextBeanArchiveHandler(context));
}
strategy.setScanner(new WebAppBeanArchiveScanner(resourceLoader, bootstrap, context)); // depends on control dependency: [if], data = [none]
Set<WeldBeanDeploymentArchive> beanDeploymentArchives = strategy.performDiscovery();
String isolation = context.getInitParameter(CONTEXT_PARAM_ARCHIVE_ISOLATION);
if (isolation == null || Boolean.valueOf(isolation)) {
CommonLogger.LOG.archiveIsolationEnabled(); // depends on control dependency: [if], data = [none]
} else {
CommonLogger.LOG.archiveIsolationDisabled(); // depends on control dependency: [if], data = [none]
Set<WeldBeanDeploymentArchive> flatDeployment = new HashSet<WeldBeanDeploymentArchive>();
flatDeployment.add(WeldBeanDeploymentArchive.merge(bootstrap, beanDeploymentArchives)); // depends on control dependency: [if], data = [none]
beanDeploymentArchives = flatDeployment; // depends on control dependency: [if], data = [none]
}
for (BeanDeploymentArchive archive : beanDeploymentArchives) {
archive.getServices().add(EEModuleDescriptor.class, eeModule); // depends on control dependency: [for], data = [archive]
}
CDI11Deployment deployment = new WeldDeployment(resourceLoader, bootstrap, beanDeploymentArchives, extensions) {
@Override
protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() {
WeldBeanDeploymentArchive archive = super.createAdditionalBeanDeploymentArchive();
archive.getServices().add(EEModuleDescriptor.class, eeModule);
return archive;
}
};
if (strategy.getClassFileServices() != null) {
deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices()); // depends on control dependency: [if], data = [none]
}
return deployment; // depends on control dependency: [if], data = [none]
} } |
public class class_name {
public static final Controller.RetentionPolicy decode(final RetentionPolicy policyModel) {
if (policyModel != null) {
return Controller.RetentionPolicy.newBuilder()
.setRetentionType(Controller.RetentionPolicy.RetentionPolicyType.valueOf(policyModel.getRetentionType().name()))
.setRetentionParam(policyModel.getRetentionParam())
.build();
} else {
return null;
}
} } | public class class_name {
public static final Controller.RetentionPolicy decode(final RetentionPolicy policyModel) {
if (policyModel != null) {
return Controller.RetentionPolicy.newBuilder()
.setRetentionType(Controller.RetentionPolicy.RetentionPolicyType.valueOf(policyModel.getRetentionType().name()))
.setRetentionParam(policyModel.getRetentionParam())
.build(); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
void appendHex( int value, int digits ) {
if( digits > 1 ) {
appendHex( value >>> 4, digits-1 );
}
output.append( DIGITS[ value & 0xF ] );
} } | public class class_name {
void appendHex( int value, int digits ) {
if( digits > 1 ) {
appendHex( value >>> 4, digits-1 ); // depends on control dependency: [if], data = [1 )]
}
output.append( DIGITS[ value & 0xF ] );
} } |
public class class_name {
private boolean checkForKnownValue(Instruction obj) {
if (trackValueNumbers) {
try {
// See if the value number loaded here is a known value
ValueNumberFrame vnaFrameAfter = vnaDataflow.getFactAfterLocation(getLocation());
if (vnaFrameAfter.isValid()) {
ValueNumber tosVN = vnaFrameAfter.getTopValue();
IsNullValue knownValue = getFrame().getKnownValue(tosVN);
if (knownValue != null) {
// System.out.println("Produce known value!");
// The value produced by this instruction is known.
// Push the known value.
modelNormalInstruction(obj, getNumWordsConsumed(obj), 0);
produce(knownValue);
return true;
}
}
} catch (DataflowAnalysisException e) {
// Ignore...
}
}
return false;
} } | public class class_name {
private boolean checkForKnownValue(Instruction obj) {
if (trackValueNumbers) {
try {
// See if the value number loaded here is a known value
ValueNumberFrame vnaFrameAfter = vnaDataflow.getFactAfterLocation(getLocation());
if (vnaFrameAfter.isValid()) {
ValueNumber tosVN = vnaFrameAfter.getTopValue();
IsNullValue knownValue = getFrame().getKnownValue(tosVN);
if (knownValue != null) {
// System.out.println("Produce known value!");
// The value produced by this instruction is known.
// Push the known value.
modelNormalInstruction(obj, getNumWordsConsumed(obj), 0); // depends on control dependency: [if], data = [none]
produce(knownValue); // depends on control dependency: [if], data = [(knownValue]
return true; // depends on control dependency: [if], data = [none]
}
}
} catch (DataflowAnalysisException e) {
// Ignore...
} // depends on control dependency: [catch], data = [none]
}
return false;
} } |
public class class_name {
public static final synchronized Date parseDateTime(String dateTime) {
try {
return dateTimeFormat.parse(dateTime);
} catch(ParseException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static final synchronized Date parseDateTime(String dateTime) {
try {
return dateTimeFormat.parse(dateTime); // depends on control dependency: [try], data = [none]
} catch(ParseException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(Endpoint endpoint, ProtocolMarshaller protocolMarshaller) {
if (endpoint == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(endpoint.getAddress(), ADDRESS_BINDING);
protocolMarshaller.marshall(endpoint.getCachePeriodInMinutes(), CACHEPERIODINMINUTES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(Endpoint endpoint, ProtocolMarshaller protocolMarshaller) {
if (endpoint == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(endpoint.getAddress(), ADDRESS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(endpoint.getCachePeriodInMinutes(), CACHEPERIODINMINUTES_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 String decodeFormFields (final String content, final String charset) {
if (content == null) {
return null;
}
return urldecode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, true);
} } | public class class_name {
private static String decodeFormFields (final String content, final String charset) {
if (content == null) {
return null; // depends on control dependency: [if], data = [none]
}
return urldecode(content, charset != null ? Charset.forName(charset) : Consts.UTF_8, true);
} } |
public class class_name {
private static String validateDestination(
final JsMessagingEngine messagingEngine, final String busName,
final String destinationName, final DestinationType destinationType)
throws NotSupportedException, ResourceAdapterInternalException {
final String methodName = "validateDestination";
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(TRACE, methodName, new Object[] { messagingEngine,
busName, destinationName, destinationType });
}
/*
* The destination may contain a null bus name so, for clarity in
* messages, use the name from the messaging engine if this is the case
*/
final String resolvedBusName = (((busName == null) || ""
.equals(busName)) ? messagingEngine.getBusName() : busName);
final String uuid;
try {
/*
* Obtain destination definition
*/
final BaseDestinationDefinition destinationDefinition = messagingEngine
.getSIBDestination(busName, destinationName);
/*
* Foreign destinations are not supported
*/
if (destinationDefinition.isForeign()) {
throw new NotSupportedException(NLS.getFormattedMessage(
("FOREIGN_DESTINATION_CWSIV0754"), new Object[] {
destinationName, resolvedBusName }, null));
}
if (destinationDefinition.isLocal()) {
/*
* Local destinations must be of the correct type
*/
final DestinationDefinition localDefinition = (DestinationDefinition) destinationDefinition;
if (destinationType
.equals(localDefinition.getDestinationType())) {
uuid = destinationDefinition.getUUID().toString();
} else {
/*
* The destination resolved to the wrong type
*/
throw new NotSupportedException(NLS.getFormattedMessage(
("INCORRECT_TYPE_CWSIV0755"), new Object[] {
destinationName, resolvedBusName,
destinationType,
localDefinition.getDestinationType() },
null));
}
} else if (destinationDefinition.isAlias()) {
/*
* Recursively check an alias destination
*/
final DestinationAliasDefinition aliasDefinition = (DestinationAliasDefinition) destinationDefinition;
uuid = validateDestination(messagingEngine, aliasDefinition
.getTargetBus(), aliasDefinition.getTargetName(),
destinationType);
} else {
/*
* Unknown destination type
*/
throw new ResourceAdapterInternalException(
NLS
.getFormattedMessage(
("UNKNOWN_TYPE_CWSIV0756"),
new Object[] { destinationName,
resolvedBusName }, null));
}
} catch (final SIBExceptionDestinationNotFound exception) {
FFDCFilter.processException(exception, CLASS_NAME + "."
+ methodName, FFDC_PROBE_1);
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEventEnabled()) {
SibTr.exception(TRACE, exception);
}
throw new NotSupportedException(NLS.getFormattedMessage(
("NOT_FOUND_CWSIV0757"), new Object[] { destinationName,
resolvedBusName }, null), exception);
} catch (final SIBExceptionBase exception) {
FFDCFilter.processException(exception, CLASS_NAME + "."
+ methodName, FFDC_PROBE_2);
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEventEnabled()) {
SibTr.exception(TRACE, exception);
}
throw new ResourceAdapterInternalException(NLS
.getFormattedMessage(("UNEXPECTED_EXCEPTION_CWSIV0758"),
new Object[] { destinationName, resolvedBusName,
exception }, null), exception);
}
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.exit(TRACE, methodName, uuid);
}
return uuid;
} } | public class class_name {
private static String validateDestination(
final JsMessagingEngine messagingEngine, final String busName,
final String destinationName, final DestinationType destinationType)
throws NotSupportedException, ResourceAdapterInternalException {
final String methodName = "validateDestination";
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(TRACE, methodName, new Object[] { messagingEngine,
busName, destinationName, destinationType });
}
/*
* The destination may contain a null bus name so, for clarity in
* messages, use the name from the messaging engine if this is the case
*/
final String resolvedBusName = (((busName == null) || ""
.equals(busName)) ? messagingEngine.getBusName() : busName);
final String uuid;
try {
/*
* Obtain destination definition
*/
final BaseDestinationDefinition destinationDefinition = messagingEngine
.getSIBDestination(busName, destinationName);
/*
* Foreign destinations are not supported
*/
if (destinationDefinition.isForeign()) {
throw new NotSupportedException(NLS.getFormattedMessage(
("FOREIGN_DESTINATION_CWSIV0754"), new Object[] {
destinationName, resolvedBusName }, null));
}
if (destinationDefinition.isLocal()) {
/*
* Local destinations must be of the correct type
*/
final DestinationDefinition localDefinition = (DestinationDefinition) destinationDefinition;
if (destinationType
.equals(localDefinition.getDestinationType())) {
uuid = destinationDefinition.getUUID().toString(); // depends on control dependency: [if], data = [none]
} else {
/*
* The destination resolved to the wrong type
*/
throw new NotSupportedException(NLS.getFormattedMessage(
("INCORRECT_TYPE_CWSIV0755"), new Object[] {
destinationName, resolvedBusName,
destinationType,
localDefinition.getDestinationType() },
null));
}
} else if (destinationDefinition.isAlias()) {
/*
* Recursively check an alias destination
*/
final DestinationAliasDefinition aliasDefinition = (DestinationAliasDefinition) destinationDefinition;
uuid = validateDestination(messagingEngine, aliasDefinition
.getTargetBus(), aliasDefinition.getTargetName(),
destinationType); // depends on control dependency: [if], data = [none]
} else {
/*
* Unknown destination type
*/
throw new ResourceAdapterInternalException(
NLS
.getFormattedMessage(
("UNKNOWN_TYPE_CWSIV0756"),
new Object[] { destinationName,
resolvedBusName }, null));
}
} catch (final SIBExceptionDestinationNotFound exception) {
FFDCFilter.processException(exception, CLASS_NAME + "."
+ methodName, FFDC_PROBE_1);
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEventEnabled()) {
SibTr.exception(TRACE, exception); // depends on control dependency: [if], data = [none]
}
throw new NotSupportedException(NLS.getFormattedMessage(
("NOT_FOUND_CWSIV0757"), new Object[] { destinationName,
resolvedBusName }, null), exception);
} catch (final SIBExceptionBase exception) {
FFDCFilter.processException(exception, CLASS_NAME + "."
+ methodName, FFDC_PROBE_2);
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEventEnabled()) {
SibTr.exception(TRACE, exception); // depends on control dependency: [if], data = [none]
}
throw new ResourceAdapterInternalException(NLS
.getFormattedMessage(("UNEXPECTED_EXCEPTION_CWSIV0758"),
new Object[] { destinationName, resolvedBusName,
exception }, null), exception);
}
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.exit(TRACE, methodName, uuid);
}
return uuid;
} } |
public class class_name {
protected void setMethodStubSelection(boolean createConstructors, boolean createInherited,
boolean createEventHandlers, boolean createLifecycleFunctions, boolean canBeModified) {
if (this.methodStubsButtons != null) {
int idx = 0;
if (this.isConstructorCreationEnabled) {
this.methodStubsButtons.setSelection(idx, createConstructors);
++idx;
}
if (this.isInheritedCreationEnabled) {
this.methodStubsButtons.setSelection(idx, createInherited);
++idx;
}
if (this.isDefaultEventGenerated) {
this.methodStubsButtons.setSelection(idx, createEventHandlers);
++idx;
}
if (this.isDefaultLifecycleFunctionsGenerated) {
this.methodStubsButtons.setSelection(idx, createLifecycleFunctions);
++idx;
}
this.methodStubsButtons.setEnabled(canBeModified);
}
} } | public class class_name {
protected void setMethodStubSelection(boolean createConstructors, boolean createInherited,
boolean createEventHandlers, boolean createLifecycleFunctions, boolean canBeModified) {
if (this.methodStubsButtons != null) {
int idx = 0;
if (this.isConstructorCreationEnabled) {
this.methodStubsButtons.setSelection(idx, createConstructors); // depends on control dependency: [if], data = [none]
++idx; // depends on control dependency: [if], data = [none]
}
if (this.isInheritedCreationEnabled) {
this.methodStubsButtons.setSelection(idx, createInherited); // depends on control dependency: [if], data = [none]
++idx; // depends on control dependency: [if], data = [none]
}
if (this.isDefaultEventGenerated) {
this.methodStubsButtons.setSelection(idx, createEventHandlers); // depends on control dependency: [if], data = [none]
++idx; // depends on control dependency: [if], data = [none]
}
if (this.isDefaultLifecycleFunctionsGenerated) {
this.methodStubsButtons.setSelection(idx, createLifecycleFunctions); // depends on control dependency: [if], data = [none]
++idx; // depends on control dependency: [if], data = [none]
}
this.methodStubsButtons.setEnabled(canBeModified); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public synchronized static Session getSession() {
if(session == null){
Properties properties = IOUtil.loadProperties("jdbc.properties");
session = getSession(properties);
}
return session;
} } | public class class_name {
public synchronized static Session getSession() {
if(session == null){
Properties properties = IOUtil.loadProperties("jdbc.properties");
session = getSession(properties);
// depends on control dependency: [if], data = [none]
}
return session;
} } |
public class class_name {
public Date getNextDate(final int pSize, final String pPattern, final boolean pUseBcd) {
Date date = null;
// create date formatter
SimpleDateFormat sdf = new SimpleDateFormat(pPattern);
// get String
String dateTxt = null;
if (pUseBcd) {
dateTxt = getNextHexaString(pSize);
} else {
dateTxt = getNextString(pSize);
}
try {
date = sdf.parse(dateTxt);
} catch (ParseException e) {
LOGGER.error("Parsing date error. date:" + dateTxt + " pattern:" + pPattern, e);
}
return date;
} } | public class class_name {
public Date getNextDate(final int pSize, final String pPattern, final boolean pUseBcd) {
Date date = null;
// create date formatter
SimpleDateFormat sdf = new SimpleDateFormat(pPattern);
// get String
String dateTxt = null;
if (pUseBcd) {
dateTxt = getNextHexaString(pSize);
// depends on control dependency: [if], data = [none]
} else {
dateTxt = getNextString(pSize);
// depends on control dependency: [if], data = [none]
}
try {
date = sdf.parse(dateTxt);
// depends on control dependency: [try], data = [none]
} catch (ParseException e) {
LOGGER.error("Parsing date error. date:" + dateTxt + " pattern:" + pPattern, e);
}
// depends on control dependency: [catch], data = [none]
return date;
} } |
public class class_name {
@Override
public void setCallback(SourceCallback callback) {
try {
mCallbackLock.lock();
mCallback = callback;
mCallbackChanged.signal();
} finally {
mCallbackLock.unlock();
}
} } | public class class_name {
@Override
public void setCallback(SourceCallback callback) {
try {
mCallbackLock.lock(); // depends on control dependency: [try], data = [none]
mCallback = callback; // depends on control dependency: [try], data = [none]
mCallbackChanged.signal(); // depends on control dependency: [try], data = [none]
} finally {
mCallbackLock.unlock();
}
} } |
public class class_name {
private void addParent(MavenPomDescriptor pomDescriptor, Model model, ScannerContext context) {
Parent parent = model.getParent();
if (null != parent) {
ArtifactResolver resolver = getArtifactResolver(context);
MavenArtifactDescriptor parentDescriptor = resolver.resolve(new ParentCoordinates(parent), context);
pomDescriptor.setParent(parentDescriptor);
}
} } | public class class_name {
private void addParent(MavenPomDescriptor pomDescriptor, Model model, ScannerContext context) {
Parent parent = model.getParent();
if (null != parent) {
ArtifactResolver resolver = getArtifactResolver(context);
MavenArtifactDescriptor parentDescriptor = resolver.resolve(new ParentCoordinates(parent), context);
pomDescriptor.setParent(parentDescriptor); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public DataModelIF<Long, Long> parseData(final File f) throws IOException {
DataModelIF<Long, Long> dataset = DataModelFactory.getDefaultModel();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
try {
String line = null;
while ((line = br.readLine()) != null) {
parseLine(line, dataset);
}
} finally {
br.close();
}
return dataset;
} } | public class class_name {
@Override
public DataModelIF<Long, Long> parseData(final File f) throws IOException {
DataModelIF<Long, Long> dataset = DataModelFactory.getDefaultModel();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
try {
String line = null;
while ((line = br.readLine()) != null) {
parseLine(line, dataset); // depends on control dependency: [while], data = [none]
}
} finally {
br.close();
}
return dataset;
} } |
public class class_name {
@SuppressWarnings("unchecked")
@Override
protected void performValidation(String path, Object value, List<ValidationResult> results) {
String name = path != null ? path : "value";
value = ObjectReader.getValue(value);
super.performValidation(path, value, results);
if (value == null)
return;
if (value instanceof Map<?, ?>) {
Map<Object, Object> map = (Map<Object, Object>) value;
for (Object key : map.keySet()) {
String elementPath = path == null || path.length() == 0 ? key.toString() : path + "." + key;
performTypeValidation(elementPath, _keyType, key, results);
performTypeValidation(elementPath, _valueType, map.get(key), results);
}
} else {
results.add(new ValidationResult(path, ValidationResultType.Error, "VALUE_ISNOT_MAP",
name + " type must be Map", "Map", value.getClass()));
}
} } | public class class_name {
@SuppressWarnings("unchecked")
@Override
protected void performValidation(String path, Object value, List<ValidationResult> results) {
String name = path != null ? path : "value";
value = ObjectReader.getValue(value);
super.performValidation(path, value, results);
if (value == null)
return;
if (value instanceof Map<?, ?>) {
Map<Object, Object> map = (Map<Object, Object>) value;
for (Object key : map.keySet()) {
String elementPath = path == null || path.length() == 0 ? key.toString() : path + "." + key;
performTypeValidation(elementPath, _keyType, key, results); // depends on control dependency: [for], data = [key]
performTypeValidation(elementPath, _valueType, map.get(key), results); // depends on control dependency: [for], data = [key]
}
} else {
results.add(new ValidationResult(path, ValidationResultType.Error, "VALUE_ISNOT_MAP",
name + " type must be Map", "Map", value.getClass())); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void removeChildren(String key) {
super.remove(key);
if ( !key.endsWith("/") ) {
key = key + "/";
}
Set<String> keys = super.keySet();
for ( String k : keys) {
if ( (k).startsWith(key) ) {
super.remove(k);
}
}
} } | public class class_name {
public void removeChildren(String key) {
super.remove(key);
if ( !key.endsWith("/") ) {
key = key + "/"; // depends on control dependency: [if], data = [none]
}
Set<String> keys = super.keySet();
for ( String k : keys) {
if ( (k).startsWith(key) ) {
super.remove(k); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public List<Post> blogPosts(String blogName, Map<String, ?> options) {
if (options == null) {
options = Collections.emptyMap();
}
Map<String, Object> soptions = JumblrClient.safeOptionMap(options);
soptions.put("api_key", apiKey);
String path = "/posts";
if (soptions.containsKey("type")) {
path += "/" + soptions.get("type").toString();
soptions.remove("type");
}
return requestBuilder.get(JumblrClient.blogPath(blogName, path), soptions).getPosts();
} } | public class class_name {
public List<Post> blogPosts(String blogName, Map<String, ?> options) {
if (options == null) {
options = Collections.emptyMap(); // depends on control dependency: [if], data = [none]
}
Map<String, Object> soptions = JumblrClient.safeOptionMap(options);
soptions.put("api_key", apiKey);
String path = "/posts";
if (soptions.containsKey("type")) {
path += "/" + soptions.get("type").toString(); // depends on control dependency: [if], data = [none]
soptions.remove("type"); // depends on control dependency: [if], data = [none]
}
return requestBuilder.get(JumblrClient.blogPath(blogName, path), soptions).getPosts();
} } |
public class class_name {
public void marshall(UpdateWebhookRequest updateWebhookRequest, ProtocolMarshaller protocolMarshaller) {
if (updateWebhookRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateWebhookRequest.getProjectName(), PROJECTNAME_BINDING);
protocolMarshaller.marshall(updateWebhookRequest.getBranchFilter(), BRANCHFILTER_BINDING);
protocolMarshaller.marshall(updateWebhookRequest.getRotateSecret(), ROTATESECRET_BINDING);
protocolMarshaller.marshall(updateWebhookRequest.getFilterGroups(), FILTERGROUPS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UpdateWebhookRequest updateWebhookRequest, ProtocolMarshaller protocolMarshaller) {
if (updateWebhookRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateWebhookRequest.getProjectName(), PROJECTNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateWebhookRequest.getBranchFilter(), BRANCHFILTER_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateWebhookRequest.getRotateSecret(), ROTATESECRET_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateWebhookRequest.getFilterGroups(), FILTERGROUPS_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]
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.