code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
public static boolean[] values(Boolean[] array) {
boolean[] dest = new boolean[array.length];
for (int i = 0; i < array.length; i++) {
Boolean v = array[i];
if (v != null) {
dest[i] = v.booleanValue();
}
}
return dest;
} } | public class class_name {
public static boolean[] values(Boolean[] array) {
boolean[] dest = new boolean[array.length];
for (int i = 0; i < array.length; i++) {
Boolean v = array[i];
if (v != null) {
dest[i] = v.booleanValue(); // depends on control dependency: [if], data = [none]
}
}
return dest;
} } |
public class class_name {
private static String wordShapeChris2Short(String s, int len, Collection<String> knownLCWords) {
int sbLen = (knownLCWords != null) ? len + 1: len; // markKnownLC makes String 1 longer
final StringBuilder sb = new StringBuilder(sbLen);
boolean nonLetters = false;
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
char m = c;
if (Character.isDigit(c)) {
m = 'd';
} else if (Character.isLowerCase(c)) {
m = 'x';
} else if (Character.isUpperCase(c) || Character.isTitleCase(c)) {
m = 'X';
}
for (String gr : greek) {
if (s.startsWith(gr, i)) {
m = 'g';
//System.out.println(s + " :: " + s.substring(i+1));
i += gr.length() - 1;
// System.out.println("Position skips to " + i);
break;
}
}
if (m != 'x' && m != 'X') {
nonLetters = true;
}
sb.append(m);
}
if (knownLCWords != null) {
if ( ! nonLetters && knownLCWords.contains(s.toLowerCase())) {
sb.append('k');
}
}
// System.out.println(s + " became " + sb);
return sb.toString();
} } | public class class_name {
private static String wordShapeChris2Short(String s, int len, Collection<String> knownLCWords) {
int sbLen = (knownLCWords != null) ? len + 1: len; // markKnownLC makes String 1 longer
final StringBuilder sb = new StringBuilder(sbLen);
boolean nonLetters = false;
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
char m = c;
if (Character.isDigit(c)) {
m = 'd';
// depends on control dependency: [if], data = [none]
} else if (Character.isLowerCase(c)) {
m = 'x';
// depends on control dependency: [if], data = [none]
} else if (Character.isUpperCase(c) || Character.isTitleCase(c)) {
m = 'X';
// depends on control dependency: [if], data = [none]
}
for (String gr : greek) {
if (s.startsWith(gr, i)) {
m = 'g';
// depends on control dependency: [if], data = [none]
//System.out.println(s + " :: " + s.substring(i+1));
i += gr.length() - 1;
// depends on control dependency: [if], data = [none]
// System.out.println("Position skips to " + i);
break;
}
}
if (m != 'x' && m != 'X') {
nonLetters = true;
// depends on control dependency: [if], data = [none]
}
sb.append(m);
// depends on control dependency: [for], data = [none]
}
if (knownLCWords != null) {
if ( ! nonLetters && knownLCWords.contains(s.toLowerCase())) {
sb.append('k');
// depends on control dependency: [if], data = [none]
}
}
// System.out.println(s + " became " + sb);
return sb.toString();
} } |
public class class_name {
Statement generateReattachTable() {
final Expression readField = stateField.accessor(thisExpr);
final Statement defaultCase =
Statement.throwExpression(MethodRef.RUNTIME_UNEXPECTED_STATE_ERROR.invoke(readField));
return new Statement() {
@Override
protected void doGen(final CodeBuilder adapter) {
int[] keys = new int[reattaches.size()];
for (int i = 0; i < keys.length; i++) {
keys[i] = i;
}
readField.gen(adapter);
// Generate a switch table. Note, while it might be preferable to just 'goto state', Java
// doesn't allow computable gotos (probably because it makes verification impossible). So
// instead we emulate that with a jump table. And anyway we still need to execute 'restore'
// logic to repopulate the local variable tables, so the 'case' statements are a natural
// place for that logic to live.
adapter.tableSwitch(
keys,
new TableSwitchGenerator() {
@Override
public void generateCase(int key, Label end) {
if (key == 0) {
// State 0 is special, it means initial state, so we just jump to the very end
adapter.goTo(end);
return;
}
ReattachState reattachState = reattaches.get(key);
// restore and jump!
reattachState.restoreStatement().gen(adapter);
adapter.goTo(reattachState.reattachPoint());
}
@Override
public void generateDefault() {
defaultCase.gen(adapter);
}
},
// Use tableswitch instead of lookupswitch. TableSwitch is appropriate because our case
// labels are sequential integers in the range [0, N). This means that switch is O(1)
// and
// there are no 'holes' meaning that it is compact in the bytecode.
true);
}
};
} } | public class class_name {
Statement generateReattachTable() {
final Expression readField = stateField.accessor(thisExpr);
final Statement defaultCase =
Statement.throwExpression(MethodRef.RUNTIME_UNEXPECTED_STATE_ERROR.invoke(readField));
return new Statement() {
@Override
protected void doGen(final CodeBuilder adapter) {
int[] keys = new int[reattaches.size()];
for (int i = 0; i < keys.length; i++) {
keys[i] = i; // depends on control dependency: [for], data = [i]
}
readField.gen(adapter);
// Generate a switch table. Note, while it might be preferable to just 'goto state', Java
// doesn't allow computable gotos (probably because it makes verification impossible). So
// instead we emulate that with a jump table. And anyway we still need to execute 'restore'
// logic to repopulate the local variable tables, so the 'case' statements are a natural
// place for that logic to live.
adapter.tableSwitch(
keys,
new TableSwitchGenerator() {
@Override
public void generateCase(int key, Label end) {
if (key == 0) {
// State 0 is special, it means initial state, so we just jump to the very end
adapter.goTo(end); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
ReattachState reattachState = reattaches.get(key);
// restore and jump!
reattachState.restoreStatement().gen(adapter);
adapter.goTo(reattachState.reattachPoint());
}
@Override
public void generateDefault() {
defaultCase.gen(adapter);
}
},
// Use tableswitch instead of lookupswitch. TableSwitch is appropriate because our case
// labels are sequential integers in the range [0, N). This means that switch is O(1)
// and
// there are no 'holes' meaning that it is compact in the bytecode.
true);
}
};
} } |
public class class_name {
public JvmTypeReference typeRef(String typeName, JvmTypeReference... typeArgs) {
JvmType type = references.findDeclaredType(typeName, context);
if (type == null) {
return createUnknownTypeReference(typeName);
}
return typeRef(type, typeArgs);
} } | public class class_name {
public JvmTypeReference typeRef(String typeName, JvmTypeReference... typeArgs) {
JvmType type = references.findDeclaredType(typeName, context);
if (type == null) {
return createUnknownTypeReference(typeName); // depends on control dependency: [if], data = [(type]
}
return typeRef(type, typeArgs);
} } |
public class class_name {
public static Map<Transition, Collection<TileRef>> imports(Media config)
{
final Xml root = new Xml(config);
final Collection<Xml> nodesTransition = root.getChildren(NODE_TRANSITION);
final Map<Transition, Collection<TileRef>> transitions = new HashMap<>(nodesTransition.size());
for (final Xml nodeTransition : nodesTransition)
{
final String groupIn = nodeTransition.readString(ATTRIBUTE_GROUP_IN);
final String groupOut = nodeTransition.readString(ATTRIBUTE_GROUP_OUT);
final String transitionType = nodeTransition.readString(ATTRIBUTE_TRANSITION_TYPE);
final TransitionType type = TransitionType.from(transitionType);
final Transition transition = new Transition(type, groupIn, groupOut);
final Collection<Xml> nodesTileRef = nodeTransition.getChildren(TileConfig.NODE_TILE);
final Collection<TileRef> tilesRef = importTiles(nodesTileRef);
transitions.put(transition, tilesRef);
}
return transitions;
} } | public class class_name {
public static Map<Transition, Collection<TileRef>> imports(Media config)
{
final Xml root = new Xml(config);
final Collection<Xml> nodesTransition = root.getChildren(NODE_TRANSITION);
final Map<Transition, Collection<TileRef>> transitions = new HashMap<>(nodesTransition.size());
for (final Xml nodeTransition : nodesTransition)
{
final String groupIn = nodeTransition.readString(ATTRIBUTE_GROUP_IN);
final String groupOut = nodeTransition.readString(ATTRIBUTE_GROUP_OUT);
final String transitionType = nodeTransition.readString(ATTRIBUTE_TRANSITION_TYPE);
final TransitionType type = TransitionType.from(transitionType);
final Transition transition = new Transition(type, groupIn, groupOut);
final Collection<Xml> nodesTileRef = nodeTransition.getChildren(TileConfig.NODE_TILE);
final Collection<TileRef> tilesRef = importTiles(nodesTileRef);
transitions.put(transition, tilesRef);
// depends on control dependency: [for], data = [none]
}
return transitions;
} } |
public class class_name {
@Implementation
protected void prepare() {
checkStateException("prepare()", preparableStates);
MediaInfo info = getMediaInfo();
if (info.preparationDelay > 0) {
SystemClock.sleep(info.preparationDelay);
}
invokePreparedListener();
} } | public class class_name {
@Implementation
protected void prepare() {
checkStateException("prepare()", preparableStates);
MediaInfo info = getMediaInfo();
if (info.preparationDelay > 0) {
SystemClock.sleep(info.preparationDelay); // depends on control dependency: [if], data = [(info.preparationDelay]
}
invokePreparedListener();
} } |
public class class_name {
public static ArrayList<FileListItem> prepareFileListEntries(ArrayList<FileListItem> internalList, File inter, ExtensionFilter filter)
{ try {
//Check for each and every directory/file in 'inter' directory.
//Filter by extension using 'filter' reference.
for (File name : inter.listFiles(filter)) {
//If file/directory can be read by the Application
if (name.canRead()) {
//Create a row item for the directory list and define properties.
FileListItem item = new FileListItem();
item.setFilename(name.getName());
item.setDirectory(name.isDirectory());
item.setLocation(name.getAbsolutePath());
item.setTime(name.lastModified());
//Add row to the List of directories/files
internalList.add(item);
}
}
//Sort the files and directories in alphabetical order.
//See compareTo method in FileListItem class.
Collections.sort(internalList);
}
catch (NullPointerException e)
{ //Just dont worry, it rarely occurs.
e.printStackTrace();
internalList=new ArrayList<>();
}
return internalList;
} } | public class class_name {
public static ArrayList<FileListItem> prepareFileListEntries(ArrayList<FileListItem> internalList, File inter, ExtensionFilter filter)
{ try {
//Check for each and every directory/file in 'inter' directory.
//Filter by extension using 'filter' reference.
for (File name : inter.listFiles(filter)) {
//If file/directory can be read by the Application
if (name.canRead()) {
//Create a row item for the directory list and define properties.
FileListItem item = new FileListItem();
item.setFilename(name.getName()); // depends on control dependency: [if], data = [none]
item.setDirectory(name.isDirectory()); // depends on control dependency: [if], data = [none]
item.setLocation(name.getAbsolutePath()); // depends on control dependency: [if], data = [none]
item.setTime(name.lastModified()); // depends on control dependency: [if], data = [none]
//Add row to the List of directories/files
internalList.add(item); // depends on control dependency: [if], data = [none]
}
}
//Sort the files and directories in alphabetical order.
//See compareTo method in FileListItem class.
Collections.sort(internalList); // depends on control dependency: [try], data = [none]
}
catch (NullPointerException e)
{ //Just dont worry, it rarely occurs.
e.printStackTrace();
internalList=new ArrayList<>();
} // depends on control dependency: [catch], data = [none]
return internalList;
} } |
public class class_name {
protected SerializationPolicy doGetSerializationPolicy(HttpServletRequest request, String moduleBaseURL,
String strongName) {
if (getSerializationPolicyLocator() == null) {
return super.doGetSerializationPolicy(request, moduleBaseURL, strongName);
} else {
return getSerializationPolicyLocator().loadPolicy(request, moduleBaseURL, strongName);
}
} } | public class class_name {
protected SerializationPolicy doGetSerializationPolicy(HttpServletRequest request, String moduleBaseURL,
String strongName) {
if (getSerializationPolicyLocator() == null) {
return super.doGetSerializationPolicy(request, moduleBaseURL, strongName); // depends on control dependency: [if], data = [none]
} else {
return getSerializationPolicyLocator().loadPolicy(request, moduleBaseURL, strongName); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public CollectionAssert hasSizeBetween(int lowerBound, int higherBound) {
isNotNull();
int size = size(this.actual);
if (!(size >= lowerBound && size <= higherBound)) {
failWithMessage("The size <%s> is not between <%s> and <%s>", size,
lowerBound, higherBound);
}
return this;
} } | public class class_name {
public CollectionAssert hasSizeBetween(int lowerBound, int higherBound) {
isNotNull();
int size = size(this.actual);
if (!(size >= lowerBound && size <= higherBound)) {
failWithMessage("The size <%s> is not between <%s> and <%s>", size,
lowerBound, higherBound); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
} } | public class class_name {
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset]; // depends on control dependency: [if], data = [none]
}
return new Long(l);
} } |
public class class_name {
public static Map<String, String> lookupNamespaces(Node referenceNode) {
Map<String, String> namespaces = new HashMap<String, String>();
Node node;
if (referenceNode.getNodeType() == Node.DOCUMENT_NODE) {
node = referenceNode.getFirstChild();
} else {
node = referenceNode;
}
if (node != null && node.hasAttributes()) {
for (int i = 0; i < node.getAttributes().getLength(); i++) {
Node attribute = node.getAttributes().item(i);
if (attribute.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE + ":")) {
namespaces.put(attribute.getNodeName().substring((XMLConstants.XMLNS_ATTRIBUTE + ":").length()), attribute.getNodeValue());
} else if (attribute.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE)) {
//default namespace
namespaces.put(XMLConstants.DEFAULT_NS_PREFIX, attribute.getNodeValue());
}
}
}
return namespaces;
} } | public class class_name {
public static Map<String, String> lookupNamespaces(Node referenceNode) {
Map<String, String> namespaces = new HashMap<String, String>();
Node node;
if (referenceNode.getNodeType() == Node.DOCUMENT_NODE) {
node = referenceNode.getFirstChild(); // depends on control dependency: [if], data = [none]
} else {
node = referenceNode; // depends on control dependency: [if], data = [none]
}
if (node != null && node.hasAttributes()) {
for (int i = 0; i < node.getAttributes().getLength(); i++) {
Node attribute = node.getAttributes().item(i);
if (attribute.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE + ":")) {
namespaces.put(attribute.getNodeName().substring((XMLConstants.XMLNS_ATTRIBUTE + ":").length()), attribute.getNodeValue()); // depends on control dependency: [if], data = [none]
} else if (attribute.getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE)) {
//default namespace
namespaces.put(XMLConstants.DEFAULT_NS_PREFIX, attribute.getNodeValue()); // depends on control dependency: [if], data = [none]
}
}
}
return namespaces;
} } |
public class class_name {
public static FitData<Circle2D_F64> averageCircle_I32(List<Point2D_I32> points, GrowQueue_F64 optional,
FitData<Circle2D_F64> outputStorage) {
if( outputStorage == null ) {
outputStorage = new FitData<>(new Circle2D_F64());
}
if( optional == null ) {
optional = new GrowQueue_F64();
}
Circle2D_F64 circle = outputStorage.shape;
int N = points.size();
// find center of the circle by computing the mean x and y
int sumX=0,sumY=0;
for( int i = 0; i < N; i++ ) {
Point2D_I32 p = points.get(i);
sumX += p.x;
sumY += p.y;
}
optional.reset();
double centerX = circle.center.x = sumX/(double)N;
double centerY = circle.center.y = sumY/(double)N;
double meanR = 0;
for( int i = 0; i < N; i++ ) {
Point2D_I32 p = points.get(i);
double dx = p.x-centerX;
double dy = p.y-centerY;
double r = Math.sqrt(dx*dx + dy*dy);
optional.push(r);
meanR += r;
}
meanR /= N;
circle.radius = meanR;
// compute radius variance
double variance = 0;
for( int i = 0; i < N; i++ ) {
double diff = optional.get(i)-meanR;
variance += diff*diff;
}
outputStorage.error = variance/N;
return outputStorage;
} } | public class class_name {
public static FitData<Circle2D_F64> averageCircle_I32(List<Point2D_I32> points, GrowQueue_F64 optional,
FitData<Circle2D_F64> outputStorage) {
if( outputStorage == null ) {
outputStorage = new FitData<>(new Circle2D_F64()); // depends on control dependency: [if], data = [none]
}
if( optional == null ) {
optional = new GrowQueue_F64(); // depends on control dependency: [if], data = [none]
}
Circle2D_F64 circle = outputStorage.shape;
int N = points.size();
// find center of the circle by computing the mean x and y
int sumX=0,sumY=0;
for( int i = 0; i < N; i++ ) {
Point2D_I32 p = points.get(i);
sumX += p.x; // depends on control dependency: [for], data = [none]
sumY += p.y; // depends on control dependency: [for], data = [none]
}
optional.reset();
double centerX = circle.center.x = sumX/(double)N;
double centerY = circle.center.y = sumY/(double)N;
double meanR = 0;
for( int i = 0; i < N; i++ ) {
Point2D_I32 p = points.get(i);
double dx = p.x-centerX;
double dy = p.y-centerY;
double r = Math.sqrt(dx*dx + dy*dy);
optional.push(r); // depends on control dependency: [for], data = [none]
meanR += r; // depends on control dependency: [for], data = [none]
}
meanR /= N;
circle.radius = meanR;
// compute radius variance
double variance = 0;
for( int i = 0; i < N; i++ ) {
double diff = optional.get(i)-meanR;
variance += diff*diff; // depends on control dependency: [for], data = [none]
}
outputStorage.error = variance/N;
return outputStorage;
} } |
public class class_name {
private void inspectBinaryFile(byte[] bytes) {
for (int i = 0; i < bytes.length; i += width) {
out.print(String.format("0x%04X ", i));
// Print out databytes
for (int j = 0; j < width; ++j) {
if(j+i < bytes.length) {
out.print(String.format("%02X ", bytes[i+j]));
} else {
out.print(" ");
}
}
//
for (int j = 0; j < width; ++j) {
if(j+i < bytes.length) {
char c = (char) bytes[i+j];
if(c >= 32 && c < 128) {
out.print(c);
} else {
out.print(".");
}
}
}
//
out.println();
}
} } | public class class_name {
private void inspectBinaryFile(byte[] bytes) {
for (int i = 0; i < bytes.length; i += width) {
out.print(String.format("0x%04X ", i)); // depends on control dependency: [for], data = [i]
// Print out databytes
for (int j = 0; j < width; ++j) {
if(j+i < bytes.length) {
out.print(String.format("%02X ", bytes[i+j])); // depends on control dependency: [if], data = [none]
} else {
out.print(" "); // depends on control dependency: [if], data = [none]
}
}
//
for (int j = 0; j < width; ++j) {
if(j+i < bytes.length) {
char c = (char) bytes[i+j];
if(c >= 32 && c < 128) {
out.print(c); // depends on control dependency: [if], data = [(c]
} else {
out.print("."); // depends on control dependency: [if], data = [none]
}
}
}
//
out.println(); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public EClass getIfcBoundaryEdgeCondition() {
if (ifcBoundaryEdgeConditionEClass == null) {
ifcBoundaryEdgeConditionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(46);
}
return ifcBoundaryEdgeConditionEClass;
} } | public class class_name {
public EClass getIfcBoundaryEdgeCondition() {
if (ifcBoundaryEdgeConditionEClass == null) {
ifcBoundaryEdgeConditionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(46);
// depends on control dependency: [if], data = [none]
}
return ifcBoundaryEdgeConditionEClass;
} } |
public class class_name {
@SuppressWarnings("unchecked")
private static Method getMethodOrDie(
final Class clazz, final String name, final Class... params) {
try {
return clazz.getMethod(name, params);
} catch (NoSuchMethodException e) {
throw new RuntimeException(
"Generated message class \"" + clazz.getName() +
"\" missing method \"" + name + "\".", e);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
private static Method getMethodOrDie(
final Class clazz, final String name, final Class... params) {
try {
return clazz.getMethod(name, params); // depends on control dependency: [try], data = [none]
} catch (NoSuchMethodException e) {
throw new RuntimeException(
"Generated message class \"" + clazz.getName() +
"\" missing method \"" + name + "\".", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String getModuleName(URI uri) {
String name = uri.getPath();
if (name.endsWith("/")) { //$NON-NLS-1$
name = name.substring(0, name.length()-1);
}
int idx = name.lastIndexOf("/"); //$NON-NLS-1$
if (idx != -1) {
name = name.substring(idx+1);
}
if (name.endsWith(".js")) { //$NON-NLS-1$
name = name.substring(0, name.length()-3);
}
return name;
} } | public class class_name {
public static String getModuleName(URI uri) {
String name = uri.getPath();
if (name.endsWith("/")) { //$NON-NLS-1$
name = name.substring(0, name.length()-1);
// depends on control dependency: [if], data = [none]
}
int idx = name.lastIndexOf("/"); //$NON-NLS-1$
if (idx != -1) {
name = name.substring(idx+1);
// depends on control dependency: [if], data = [(idx]
}
if (name.endsWith(".js")) { //$NON-NLS-1$
name = name.substring(0, name.length()-3);
// depends on control dependency: [if], data = [none]
}
return name;
} } |
public class class_name {
public void marshall(ArchiveContainerSettings archiveContainerSettings, ProtocolMarshaller protocolMarshaller) {
if (archiveContainerSettings == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(archiveContainerSettings.getM2tsSettings(), M2TSSETTINGS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ArchiveContainerSettings archiveContainerSettings, ProtocolMarshaller protocolMarshaller) {
if (archiveContainerSettings == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(archiveContainerSettings.getM2tsSettings(), M2TSSETTINGS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static void wrap_undeclared_throwable(CodeEmitter e, Block handler, Type[] exceptions, Type wrapper) {
Set set = (exceptions == null) ? Collections.EMPTY_SET : new HashSet(Arrays.asList(exceptions));
if (set.contains(Constants.TYPE_THROWABLE))
return;
boolean needThrow = exceptions != null;
if (!set.contains(Constants.TYPE_RUNTIME_EXCEPTION)) {
e.catch_exception(handler, Constants.TYPE_RUNTIME_EXCEPTION);
needThrow = true;
}
if (!set.contains(Constants.TYPE_ERROR)) {
e.catch_exception(handler, Constants.TYPE_ERROR);
needThrow = true;
}
if (exceptions != null) {
for (int i = 0; i < exceptions.length; i++) {
e.catch_exception(handler, exceptions[i]);
}
}
if (needThrow) {
e.athrow();
}
// e -> eo -> oeo -> ooe -> o
e.catch_exception(handler, Constants.TYPE_THROWABLE);
e.new_instance(wrapper);
e.dup_x1();
e.swap();
e.invoke_constructor(wrapper, CSTRUCT_THROWABLE);
e.athrow();
} } | public class class_name {
public static void wrap_undeclared_throwable(CodeEmitter e, Block handler, Type[] exceptions, Type wrapper) {
Set set = (exceptions == null) ? Collections.EMPTY_SET : new HashSet(Arrays.asList(exceptions));
if (set.contains(Constants.TYPE_THROWABLE))
return;
boolean needThrow = exceptions != null;
if (!set.contains(Constants.TYPE_RUNTIME_EXCEPTION)) {
e.catch_exception(handler, Constants.TYPE_RUNTIME_EXCEPTION); // depends on control dependency: [if], data = [none]
needThrow = true; // depends on control dependency: [if], data = [none]
}
if (!set.contains(Constants.TYPE_ERROR)) {
e.catch_exception(handler, Constants.TYPE_ERROR); // depends on control dependency: [if], data = [none]
needThrow = true; // depends on control dependency: [if], data = [none]
}
if (exceptions != null) {
for (int i = 0; i < exceptions.length; i++) {
e.catch_exception(handler, exceptions[i]); // depends on control dependency: [for], data = [i]
}
}
if (needThrow) {
e.athrow(); // depends on control dependency: [if], data = [none]
}
// e -> eo -> oeo -> ooe -> o
e.catch_exception(handler, Constants.TYPE_THROWABLE);
e.new_instance(wrapper);
e.dup_x1();
e.swap();
e.invoke_constructor(wrapper, CSTRUCT_THROWABLE);
e.athrow();
} } |
public class class_name {
@SuppressWarnings("rawtypes")
public static boolean isEmpty(Object obj) {
if(null == obj) {
return true;
}
if(obj instanceof CharSequence) {
return StrUtil.isEmpty((CharSequence)obj);
}else if(obj instanceof Map) {
return MapUtil.isEmpty((Map)obj);
}else if(obj instanceof Iterable) {
return IterUtil.isEmpty((Iterable)obj);
}else if(obj instanceof Iterator) {
return IterUtil.isEmpty((Iterator)obj);
}else if(ArrayUtil.isArray(obj)) {
return ArrayUtil.isEmpty(obj);
}
return false;
} } | public class class_name {
@SuppressWarnings("rawtypes")
public static boolean isEmpty(Object obj) {
if(null == obj) {
return true;
// depends on control dependency: [if], data = [none]
}
if(obj instanceof CharSequence) {
return StrUtil.isEmpty((CharSequence)obj);
// depends on control dependency: [if], data = [none]
}else if(obj instanceof Map) {
return MapUtil.isEmpty((Map)obj);
// depends on control dependency: [if], data = [none]
}else if(obj instanceof Iterable) {
return IterUtil.isEmpty((Iterable)obj);
// depends on control dependency: [if], data = [none]
}else if(obj instanceof Iterator) {
return IterUtil.isEmpty((Iterator)obj);
// depends on control dependency: [if], data = [none]
}else if(ArrayUtil.isArray(obj)) {
return ArrayUtil.isEmpty(obj);
// depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public void cancel() {
try {
executorService.shutdown();
if (!executorService.awaitTermination(30, TimeUnit.MINUTES)) {
executorService.shutdownNow(); // Cancel currently executing tasks
if (!executorService.awaitTermination(30, TimeUnit.MINUTES)) {
LOGGER.error("Pool did not terminate... FATAL ERROR");
throw new RuntimeException("Parallel SAX pool did not terminate... FATAL ERROR");
}
}
else {
LOGGER.error("Parallel SAX was interrupted by a request");
}
}
catch (InterruptedException ie) {
LOGGER.error("Error while waiting interrupting.", ie);
// (Re-)Cancel if current thread also interrupted
executorService.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
} } | public class class_name {
public void cancel() {
try {
executorService.shutdown(); // depends on control dependency: [try], data = [none]
if (!executorService.awaitTermination(30, TimeUnit.MINUTES)) {
executorService.shutdownNow(); // Cancel currently executing tasks // depends on control dependency: [if], data = [none]
if (!executorService.awaitTermination(30, TimeUnit.MINUTES)) {
LOGGER.error("Pool did not terminate... FATAL ERROR"); // depends on control dependency: [if], data = [none]
throw new RuntimeException("Parallel SAX pool did not terminate... FATAL ERROR");
}
}
else {
LOGGER.error("Parallel SAX was interrupted by a request"); // depends on control dependency: [if], data = [none]
}
}
catch (InterruptedException ie) {
LOGGER.error("Error while waiting interrupting.", ie);
// (Re-)Cancel if current thread also interrupted
executorService.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public final DSLMapping mapping_file() throws RecognitionException {
mapping_file_stack.push(new mapping_file_scope());
DSLMapping mapping = null;
mapping_file_stack.peek().retval = new DefaultDSLMapping() ;
try {
// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:23:5: ( ^( VT_DSL_GRAMMAR ( valid_entry )* ) )
// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:23:7: ^( VT_DSL_GRAMMAR ( valid_entry )* )
{
match(input,VT_DSL_GRAMMAR,FOLLOW_VT_DSL_GRAMMAR_in_mapping_file63);
if ( input.LA(1)==Token.DOWN ) {
match(input, Token.DOWN, null);
// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:23:24: ( valid_entry )*
loop1:
while (true) {
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0==VT_ENTRY) ) {
alt1=1;
}
switch (alt1) {
case 1 :
// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:23:24: valid_entry
{
pushFollow(FOLLOW_valid_entry_in_mapping_file65);
valid_entry();
state._fsp--;
}
break;
default :
break loop1;
}
}
match(input, Token.UP, null);
}
mapping = mapping_file_stack.peek().retval;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
mapping_file_stack.pop();
}
return mapping;
} } | public class class_name {
public final DSLMapping mapping_file() throws RecognitionException {
mapping_file_stack.push(new mapping_file_scope());
DSLMapping mapping = null;
mapping_file_stack.peek().retval = new DefaultDSLMapping() ;
try {
// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:23:5: ( ^( VT_DSL_GRAMMAR ( valid_entry )* ) )
// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:23:7: ^( VT_DSL_GRAMMAR ( valid_entry )* )
{
match(input,VT_DSL_GRAMMAR,FOLLOW_VT_DSL_GRAMMAR_in_mapping_file63);
if ( input.LA(1)==Token.DOWN ) {
match(input, Token.DOWN, null); // depends on control dependency: [if], data = [none]
// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:23:24: ( valid_entry )*
loop1:
while (true) {
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0==VT_ENTRY) ) {
alt1=1; // depends on control dependency: [if], data = [none]
}
switch (alt1) {
case 1 :
// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:23:24: valid_entry
{
pushFollow(FOLLOW_valid_entry_in_mapping_file65);
valid_entry();
state._fsp--;
}
break;
default :
break loop1;
}
}
match(input, Token.UP, null); // depends on control dependency: [if], data = [none]
}
mapping = mapping_file_stack.peek().retval;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
mapping_file_stack.pop();
}
return mapping;
} } |
public class class_name {
public static void toastSafely(final Context context, final int resId, final int duration) {
Long lastToastTime = LAST_TOAST_TIME.get(resId);
if (lastToastTime != null && (lastToastTime + TOAST_MIN_REPEAT_DELAY) < System.currentTimeMillis()) {
return;
}
Looper mainLooper = Looper.getMainLooper();
if (Thread.currentThread().equals(mainLooper.getThread())) {
LAST_TOAST_TIME.put(resId, System.currentTimeMillis());
Toast.makeText(context, resId, duration).show();
} else {
Handler handler = new Handler(mainLooper);
handler.post(new Runnable() {
@Override
public void run() {
LAST_TOAST_TIME.put(resId, System.currentTimeMillis());
Toast.makeText(context, resId, duration).show();
}
});
}
} } | public class class_name {
public static void toastSafely(final Context context, final int resId, final int duration) {
Long lastToastTime = LAST_TOAST_TIME.get(resId);
if (lastToastTime != null && (lastToastTime + TOAST_MIN_REPEAT_DELAY) < System.currentTimeMillis()) {
return; // depends on control dependency: [if], data = [none]
}
Looper mainLooper = Looper.getMainLooper();
if (Thread.currentThread().equals(mainLooper.getThread())) {
LAST_TOAST_TIME.put(resId, System.currentTimeMillis()); // depends on control dependency: [if], data = [none]
Toast.makeText(context, resId, duration).show(); // depends on control dependency: [if], data = [none]
} else {
Handler handler = new Handler(mainLooper);
handler.post(new Runnable() {
@Override
public void run() {
LAST_TOAST_TIME.put(resId, System.currentTimeMillis());
Toast.makeText(context, resId, duration).show();
}
}); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private int parseLength() throws IOException {
int curLen = 0;
if (dataPos == dataSize)
return curLen;
int lenByte = data[dataPos++] & 0xff;
if (isIndefinite(lenByte)) {
ndefsList.add(new Integer(dataPos));
unresolved++;
return curLen;
}
if (isLongForm(lenByte)) {
lenByte &= LEN_MASK;
if (lenByte > 4) {
throw new IOException("Too much data");
}
if ((dataSize - dataPos) < (lenByte + 1)) {
throw new IOException("Too little data");
}
for (int i = 0; i < lenByte; i++) {
curLen = (curLen << 8) + (data[dataPos++] & 0xff);
}
if (curLen < 0) {
throw new IOException("Invalid length bytes");
}
} else {
curLen = (lenByte & LEN_MASK);
}
return curLen;
} } | public class class_name {
private int parseLength() throws IOException {
int curLen = 0;
if (dataPos == dataSize)
return curLen;
int lenByte = data[dataPos++] & 0xff;
if (isIndefinite(lenByte)) {
ndefsList.add(new Integer(dataPos));
unresolved++;
return curLen;
}
if (isLongForm(lenByte)) {
lenByte &= LEN_MASK;
if (lenByte > 4) {
throw new IOException("Too much data");
}
if ((dataSize - dataPos) < (lenByte + 1)) {
throw new IOException("Too little data");
}
for (int i = 0; i < lenByte; i++) {
curLen = (curLen << 8) + (data[dataPos++] & 0xff); // depends on control dependency: [for], data = [none]
}
if (curLen < 0) {
throw new IOException("Invalid length bytes");
}
} else {
curLen = (lenByte & LEN_MASK);
}
return curLen;
} } |
public class class_name {
public void addProducer(Broker broker) {
Properties props = new Properties();
props.put("host", broker.host);
props.put("port", "" + broker.port);
props.putAll(config.getProperties());
if (sync) {
SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));
logger.info("Creating sync producer for broker id = " + broker.id + " at " + broker.host + ":" + broker.port);
syncProducers.put(broker.id, producer);
} else {
AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//
new SyncProducer(new SyncProducerConfig(props)),//
serializer,//
eventHandler,//
config.getEventHandlerProperties(),//
this.callbackHandler, //
config.getCbkHandlerProperties());
producer.start();
logger.info("Creating async producer for broker id = " + broker.id + " at " + broker.host + ":" + broker.port);
asyncProducers.put(broker.id, producer);
}
} } | public class class_name {
public void addProducer(Broker broker) {
Properties props = new Properties();
props.put("host", broker.host);
props.put("port", "" + broker.port);
props.putAll(config.getProperties());
if (sync) {
SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));
logger.info("Creating sync producer for broker id = " + broker.id + " at " + broker.host + ":" + broker.port); // depends on control dependency: [if], data = [none]
syncProducers.put(broker.id, producer); // depends on control dependency: [if], data = [none]
} else {
AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//
new SyncProducer(new SyncProducerConfig(props)),//
serializer,//
eventHandler,//
config.getEventHandlerProperties(),//
this.callbackHandler, //
config.getCbkHandlerProperties());
producer.start(); // depends on control dependency: [if], data = [none]
logger.info("Creating async producer for broker id = " + broker.id + " at " + broker.host + ":" + broker.port); // depends on control dependency: [if], data = [none]
asyncProducers.put(broker.id, producer); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void render() {
removeMembers(getMembers());
// Then go over all layers, to draw styles:
for (Layer<?> layer : mapModel.getLayers()) {
if (staticLegend || layer.isShowing()) {
// Go over every truly visible layer:
if (layer instanceof VectorLayer) {
ClientVectorLayerInfo layerInfo = ((VectorLayer) layer).getLayerInfo();
// For vector layer; loop over the style definitions:
UserStyleInfo userStyle = layerInfo.getNamedStyleInfo().getUserStyle();
FeatureTypeStyleInfo info = userStyle.getFeatureTypeStyleList().get(0);
for (int i = 0; i < info.getRuleList().size(); i++) {
RuleInfo rule = info.getRuleList().get(i);
// use title if present, name if not
String title = (rule.getTitle() != null ? rule.getTitle() : rule.getName());
// fall back to style name
if (title == null) {
title = layerInfo.getNamedStyleInfo().getName();
}
addVector((VectorLayer) layer, i, title);
}
} else if (layer instanceof RasterLayer) {
addRaster((RasterLayer) layer);
}
}
}
} } | public class class_name {
public void render() {
removeMembers(getMembers());
// Then go over all layers, to draw styles:
for (Layer<?> layer : mapModel.getLayers()) {
if (staticLegend || layer.isShowing()) {
// Go over every truly visible layer:
if (layer instanceof VectorLayer) {
ClientVectorLayerInfo layerInfo = ((VectorLayer) layer).getLayerInfo();
// For vector layer; loop over the style definitions:
UserStyleInfo userStyle = layerInfo.getNamedStyleInfo().getUserStyle();
FeatureTypeStyleInfo info = userStyle.getFeatureTypeStyleList().get(0);
for (int i = 0; i < info.getRuleList().size(); i++) {
RuleInfo rule = info.getRuleList().get(i);
// use title if present, name if not
String title = (rule.getTitle() != null ? rule.getTitle() : rule.getName());
// fall back to style name
if (title == null) {
title = layerInfo.getNamedStyleInfo().getName(); // depends on control dependency: [if], data = [none]
}
addVector((VectorLayer) layer, i, title); // depends on control dependency: [for], data = [i]
}
} else if (layer instanceof RasterLayer) {
addRaster((RasterLayer) layer); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
protected void processLoginConfig(LoginConfig loginConfig) {
boolean authMethodDefaulted = false;
if (loginConfig != null) {
String authenticationMethod = loginConfig.getAuthMethod();
if (authenticationMethod != null) {
Map<String, ConfigItem<String>> authMethodMap = configurator.getConfigItemMap(AUTH_METHOD_KEY);
ConfigItem<String> existingAuthMethod = authMethodMap.get(LOGIN_CONFIG_KEY);
if (existingAuthMethod == null) {
authMethodMap.put(LOGIN_CONFIG_KEY, configurator.createConfigItem(authenticationMethod));
} else {
this.configurator.validateDuplicateConfiguration(LOGIN_CONFIG_KEY, AUTH_METHOD_KEY, authenticationMethod, existingAuthMethod);
}
} else {
//Default to BASIC
authenticationMethod = LoginConfiguration.BASIC;
authMethodDefaulted = true;
}
String realmName = loginConfig.getRealmName();
if (realmName != null) {
Map<String, ConfigItem<String>> realmNameMap = configurator.getConfigItemMap(REALM_NAME_KEY);
ConfigItem<String> existingRealmName = realmNameMap.get(LOGIN_CONFIG_KEY);
if (existingRealmName == null) {
realmNameMap.put(LOGIN_CONFIG_KEY, configurator.createConfigItem(realmName));
} else {
this.configurator.validateDuplicateConfiguration(LOGIN_CONFIG_KEY, REALM_NAME_KEY, realmName, existingRealmName);
}
}
FormLoginConfig formLoginConfig = loginConfig.getFormLoginConfig();
FormLoginConfiguration formLoginConfiguration = null;
if (formLoginConfig != null) {
Map<String, ConfigItem<FormLoginConfig>> formLoginConfigMap = configurator.getConfigItemMap(FORM_LOGIN_CONFIG_KEY);
ConfigItem<FormLoginConfig> existingFormLoginConfig = formLoginConfigMap.get(LOGIN_CONFIG_KEY);
if (existingFormLoginConfig == null) {
formLoginConfigMap.put(LOGIN_CONFIG_KEY, configurator.createConfigItem(loginConfig.getFormLoginConfig()));
formLoginConfiguration = createFormLoginConfiguration(loginConfig);
} else {
this.configurator.validateDuplicateConfiguration(LOGIN_CONFIG_KEY, FORM_LOGIN_CONFIG_KEY, formLoginConfig,
existingFormLoginConfig);
}
}
LoginConfigurationImpl lci = new LoginConfigurationImpl(authenticationMethod, realmName, formLoginConfiguration);
if (authMethodDefaulted) {
lci.setAuthenticationMethodDefaulted();
}
loginConfiguration = lci;
}
} } | public class class_name {
protected void processLoginConfig(LoginConfig loginConfig) {
boolean authMethodDefaulted = false;
if (loginConfig != null) {
String authenticationMethod = loginConfig.getAuthMethod();
if (authenticationMethod != null) {
Map<String, ConfigItem<String>> authMethodMap = configurator.getConfigItemMap(AUTH_METHOD_KEY);
ConfigItem<String> existingAuthMethod = authMethodMap.get(LOGIN_CONFIG_KEY);
if (existingAuthMethod == null) {
authMethodMap.put(LOGIN_CONFIG_KEY, configurator.createConfigItem(authenticationMethod)); // depends on control dependency: [if], data = [none]
} else {
this.configurator.validateDuplicateConfiguration(LOGIN_CONFIG_KEY, AUTH_METHOD_KEY, authenticationMethod, existingAuthMethod); // depends on control dependency: [if], data = [none]
}
} else {
//Default to BASIC
authenticationMethod = LoginConfiguration.BASIC; // depends on control dependency: [if], data = [none]
authMethodDefaulted = true; // depends on control dependency: [if], data = [none]
}
String realmName = loginConfig.getRealmName();
if (realmName != null) {
Map<String, ConfigItem<String>> realmNameMap = configurator.getConfigItemMap(REALM_NAME_KEY);
ConfigItem<String> existingRealmName = realmNameMap.get(LOGIN_CONFIG_KEY);
if (existingRealmName == null) {
realmNameMap.put(LOGIN_CONFIG_KEY, configurator.createConfigItem(realmName)); // depends on control dependency: [if], data = [none]
} else {
this.configurator.validateDuplicateConfiguration(LOGIN_CONFIG_KEY, REALM_NAME_KEY, realmName, existingRealmName); // depends on control dependency: [if], data = [none]
}
}
FormLoginConfig formLoginConfig = loginConfig.getFormLoginConfig();
FormLoginConfiguration formLoginConfiguration = null;
if (formLoginConfig != null) {
Map<String, ConfigItem<FormLoginConfig>> formLoginConfigMap = configurator.getConfigItemMap(FORM_LOGIN_CONFIG_KEY);
ConfigItem<FormLoginConfig> existingFormLoginConfig = formLoginConfigMap.get(LOGIN_CONFIG_KEY);
if (existingFormLoginConfig == null) {
formLoginConfigMap.put(LOGIN_CONFIG_KEY, configurator.createConfigItem(loginConfig.getFormLoginConfig())); // depends on control dependency: [if], data = [none]
formLoginConfiguration = createFormLoginConfiguration(loginConfig); // depends on control dependency: [if], data = [none]
} else {
this.configurator.validateDuplicateConfiguration(LOGIN_CONFIG_KEY, FORM_LOGIN_CONFIG_KEY, formLoginConfig,
existingFormLoginConfig); // depends on control dependency: [if], data = [none]
}
}
LoginConfigurationImpl lci = new LoginConfigurationImpl(authenticationMethod, realmName, formLoginConfiguration);
if (authMethodDefaulted) {
lci.setAuthenticationMethodDefaulted(); // depends on control dependency: [if], data = [none]
}
loginConfiguration = lci; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Maker from(Settable settable) {
Optional<Maker<?>> makerOptional = context.getPreferredValueMakers().getMaker(settable);
if (makerOptional.isPresent()) {
return makerOptional.get();
}
Type type = settable.getType();
Class<?> rawType = ClassUtil.getRawType(type);
if (ClassUtil.isPrimitive(type)) {
return new PrimitiveMaker(type);
}
if (type == String.class) {
return StringMaker.from(settable);
}
if (type == Date.class) {
return new DateMaker();
}
if (Number.class.isAssignableFrom(rawType)) {
return NumberMaker.from(settable);
}
if (ClassUtil.isArray(type)) {
log.trace("array type: {}", rawType.getComponentType());
return new NullMaker();
}
if (ClassUtil.isEnum(type)) {
log.trace("enum type: {}", type);
return new EnumMaker(rawType.getEnumConstants());
}
if (ClassUtil.isCollection(type)) {
log.trace("collection: {}", type);
return new NullMaker();
}
if (ClassUtil.isMap(type)) {
log.trace("map: {}", type);
return new NullMaker<Object>();
}
if (ClassUtil.isEntity(type)) {
log.trace("{} is entity type", type);
// we don't want to make unnecessary entities
// @see EntityMakerBuilder
return new ReuseOrNullMaker(context.getBeanValueHolder(), rawType);
}
log.debug("guessing this is a bean {}", type);
return new BeanMaker(rawType, context);
} } | public class class_name {
public Maker from(Settable settable) {
Optional<Maker<?>> makerOptional = context.getPreferredValueMakers().getMaker(settable);
if (makerOptional.isPresent()) {
return makerOptional.get(); // depends on control dependency: [if], data = [none]
}
Type type = settable.getType();
Class<?> rawType = ClassUtil.getRawType(type);
if (ClassUtil.isPrimitive(type)) {
return new PrimitiveMaker(type); // depends on control dependency: [if], data = [none]
}
if (type == String.class) {
return StringMaker.from(settable); // depends on control dependency: [if], data = [none]
}
if (type == Date.class) {
return new DateMaker(); // depends on control dependency: [if], data = [none]
}
if (Number.class.isAssignableFrom(rawType)) {
return NumberMaker.from(settable); // depends on control dependency: [if], data = [none]
}
if (ClassUtil.isArray(type)) {
log.trace("array type: {}", rawType.getComponentType()); // depends on control dependency: [if], data = [none]
return new NullMaker(); // depends on control dependency: [if], data = [none]
}
if (ClassUtil.isEnum(type)) {
log.trace("enum type: {}", type); // depends on control dependency: [if], data = [none]
return new EnumMaker(rawType.getEnumConstants()); // depends on control dependency: [if], data = [none]
}
if (ClassUtil.isCollection(type)) {
log.trace("collection: {}", type); // depends on control dependency: [if], data = [none]
return new NullMaker(); // depends on control dependency: [if], data = [none]
}
if (ClassUtil.isMap(type)) {
log.trace("map: {}", type); // depends on control dependency: [if], data = [none]
return new NullMaker<Object>(); // depends on control dependency: [if], data = [none]
}
if (ClassUtil.isEntity(type)) {
log.trace("{} is entity type", type); // depends on control dependency: [if], data = [none]
// we don't want to make unnecessary entities
// @see EntityMakerBuilder
return new ReuseOrNullMaker(context.getBeanValueHolder(), rawType); // depends on control dependency: [if], data = [none]
}
log.debug("guessing this is a bean {}", type);
return new BeanMaker(rawType, context);
} } |
public class class_name {
private static Node checkFollowedIdentifier(
final FormItemList formItemList,
final CreateFollowResponse createFollowResponse) {
final String followedId = formItemList
.getField(ProtocolConstants.Parameters.Create.Follow.FOLLOWED_IDENTIFIER);
if (followedId != null) {
final Node followed = NeoUtils.getUserByIdentifier(followedId);
if (followed != null) {
return followed;
}
createFollowResponse.followedIdentifierInvalid(followedId);
} else {
createFollowResponse.followedIdentifierMissing();
}
return null;
} } | public class class_name {
private static Node checkFollowedIdentifier(
final FormItemList formItemList,
final CreateFollowResponse createFollowResponse) {
final String followedId = formItemList
.getField(ProtocolConstants.Parameters.Create.Follow.FOLLOWED_IDENTIFIER);
if (followedId != null) {
final Node followed = NeoUtils.getUserByIdentifier(followedId);
if (followed != null) {
return followed; // depends on control dependency: [if], data = [none]
}
createFollowResponse.followedIdentifierInvalid(followedId); // depends on control dependency: [if], data = [(followedId]
} else {
createFollowResponse.followedIdentifierMissing(); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public Observable<ServiceResponse<Page<PermissionInner>>> listForResourceNextWithServiceResponseAsync(final String nextPageLink) {
return listForResourceNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<PermissionInner>>, Observable<ServiceResponse<Page<PermissionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PermissionInner>>> call(ServiceResponse<Page<PermissionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listForResourceNextWithServiceResponseAsync(nextPageLink));
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<PermissionInner>>> listForResourceNextWithServiceResponseAsync(final String nextPageLink) {
return listForResourceNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<PermissionInner>>, Observable<ServiceResponse<Page<PermissionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PermissionInner>>> call(ServiceResponse<Page<PermissionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page); // depends on control dependency: [if], data = [none]
}
return Observable.just(page).concatWith(listForResourceNextWithServiceResponseAsync(nextPageLink));
}
});
} } |
public class class_name {
private void open() {
for (Snapshot snapshot : loadSnapshots()) {
snapshots.put(snapshot.index(), snapshot);
}
if (!snapshots.isEmpty()) {
currentSnapshot = snapshots.lastEntry().getValue();
}
} } | public class class_name {
private void open() {
for (Snapshot snapshot : loadSnapshots()) {
snapshots.put(snapshot.index(), snapshot); // depends on control dependency: [for], data = [snapshot]
}
if (!snapshots.isEmpty()) {
currentSnapshot = snapshots.lastEntry().getValue(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static DoubleStream of(final Supplier<DoubleList> supplier) {
final DoubleIterator iter = new DoubleIteratorEx() {
private DoubleIterator iterator = null;
@Override
public boolean hasNext() {
if (iterator == null) {
init();
}
return iterator.hasNext();
}
@Override
public double nextDouble() {
if (iterator == null) {
init();
}
return iterator.nextDouble();
}
private void init() {
final DoubleList c = supplier.get();
if (N.isNullOrEmpty(c)) {
iterator = DoubleIterator.empty();
} else {
iterator = c.iterator();
}
}
};
return of(iter);
} } | public class class_name {
public static DoubleStream of(final Supplier<DoubleList> supplier) {
final DoubleIterator iter = new DoubleIteratorEx() {
private DoubleIterator iterator = null;
@Override
public boolean hasNext() {
if (iterator == null) {
init();
// depends on control dependency: [if], data = [none]
}
return iterator.hasNext();
}
@Override
public double nextDouble() {
if (iterator == null) {
init();
// depends on control dependency: [if], data = [none]
}
return iterator.nextDouble();
}
private void init() {
final DoubleList c = supplier.get();
if (N.isNullOrEmpty(c)) {
iterator = DoubleIterator.empty();
// depends on control dependency: [if], data = [none]
} else {
iterator = c.iterator();
// depends on control dependency: [if], data = [none]
}
}
};
return of(iter);
} } |
public class class_name {
public static String[] getTypeStrs(Class[] types, boolean javaStyle) {
if (CommonUtils.isEmpty(types)) {
return StringUtils.EMPTY_STRING_ARRAY;
} else {
String[] strings = new String[types.length];
for (int i = 0; i < types.length; i++) {
strings[i] = javaStyle ? types[i].getName() : getTypeStr(types[i]);
}
return strings;
}
} } | public class class_name {
public static String[] getTypeStrs(Class[] types, boolean javaStyle) {
if (CommonUtils.isEmpty(types)) {
return StringUtils.EMPTY_STRING_ARRAY; // depends on control dependency: [if], data = [none]
} else {
String[] strings = new String[types.length];
for (int i = 0; i < types.length; i++) {
strings[i] = javaStyle ? types[i].getName() : getTypeStr(types[i]); // depends on control dependency: [for], data = [i]
}
return strings; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("ConstantConditions")
public static NaaccrDictionary getDefaultUserDictionaryByVersion(String naaccrVersion) {
if (naaccrVersion == null)
throw new RuntimeException("Version is required for getting the default user dictionary.");
if (!NaaccrFormat.isVersionSupported(naaccrVersion))
throw new RuntimeException("Unsupported default user dictionary version: " + naaccrVersion);
NaaccrDictionary result = _INTERNAL_DICTIONARIES.get("user_" + naaccrVersion);
if (result == null) {
String resName = "user-defined-naaccr-dictionary-" + naaccrVersion + ".xml";
try (Reader reader = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResource(resName).openStream(), StandardCharsets.UTF_8)) {
result = readDictionary(reader);
_INTERNAL_DICTIONARIES.put("user_" + naaccrVersion, result);
}
catch (IOException e) {
throw new RuntimeException("Unable to get base dictionary for version " + naaccrVersion, e);
}
}
return result;
} } | public class class_name {
@SuppressWarnings("ConstantConditions")
public static NaaccrDictionary getDefaultUserDictionaryByVersion(String naaccrVersion) {
if (naaccrVersion == null)
throw new RuntimeException("Version is required for getting the default user dictionary.");
if (!NaaccrFormat.isVersionSupported(naaccrVersion))
throw new RuntimeException("Unsupported default user dictionary version: " + naaccrVersion);
NaaccrDictionary result = _INTERNAL_DICTIONARIES.get("user_" + naaccrVersion);
if (result == null) {
String resName = "user-defined-naaccr-dictionary-" + naaccrVersion + ".xml";
try (Reader reader = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResource(resName).openStream(), StandardCharsets.UTF_8)) {
result = readDictionary(reader);
_INTERNAL_DICTIONARIES.put("user_" + naaccrVersion, result); // depends on control dependency: [if], data = [none]
}
catch (IOException e) {
throw new RuntimeException("Unable to get base dictionary for version " + naaccrVersion, e);
}
}
return result;
} } |
public class class_name {
@Override
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (context == null) {
throw new NullPointerException();
}
Object result = null;
if (isResolvable(base)) {
if (params == null) {
params = new Object[0];
}
String name = method.toString();
Method target = findMethod(base, name, paramTypes, params.length);
if (target == null) {
throw new MethodNotFoundException("Cannot find method " + name + " with " + params.length + " parameters in " + base.getClass());
}
try {
result = target.invoke(base, coerceParams(getExpressionFactory(context), target, params));
} catch (InvocationTargetException e) {
throw new ELException(e.getCause());
} catch (IllegalAccessException e) {
throw new ELException(e);
}
context.setPropertyResolved(true);
}
return result;
} } | public class class_name {
@Override
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (context == null) {
throw new NullPointerException();
}
Object result = null;
if (isResolvable(base)) {
if (params == null) {
params = new Object[0]; // depends on control dependency: [if], data = [none]
}
String name = method.toString();
Method target = findMethod(base, name, paramTypes, params.length);
if (target == null) {
throw new MethodNotFoundException("Cannot find method " + name + " with " + params.length + " parameters in " + base.getClass());
}
try {
result = target.invoke(base, coerceParams(getExpressionFactory(context), target, params)); // depends on control dependency: [try], data = [none]
} catch (InvocationTargetException e) {
throw new ELException(e.getCause());
} catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none]
throw new ELException(e);
} // depends on control dependency: [catch], data = [none]
context.setPropertyResolved(true); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
@CheckReturnValue
public RoleAction setPermissions(Long permissions)
{
if (permissions != null)
{
Checks.notNegative(permissions, "Raw Permissions");
Checks.check(permissions <= Permission.ALL_PERMISSIONS, "Provided permissions may not be greater than a full permission set!");
for (Permission p : Permission.toEnumSet(permissions))
checkPermission(p);
}
this.permissions = permissions;
return this;
} } | public class class_name {
@CheckReturnValue
public RoleAction setPermissions(Long permissions)
{
if (permissions != null)
{
Checks.notNegative(permissions, "Raw Permissions"); // depends on control dependency: [if], data = [(permissions]
Checks.check(permissions <= Permission.ALL_PERMISSIONS, "Provided permissions may not be greater than a full permission set!"); // depends on control dependency: [if], data = [(permissions]
for (Permission p : Permission.toEnumSet(permissions))
checkPermission(p);
}
this.permissions = permissions;
return this;
} } |
public class class_name {
protected boolean taskStop()
{
try
{
task.stop();
return true;
}
catch (Throwable t)
{
log.warn("Unexpected error during 'stop' for task: " + taskString, t);
return false;
}
} } | public class class_name {
protected boolean taskStop()
{
try
{
task.stop(); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
}
catch (Throwable t)
{
log.warn("Unexpected error during 'stop' for task: " + taskString, t);
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void setInstanceNames(java.util.Collection<String> instanceNames) {
if (instanceNames == null) {
this.instanceNames = null;
return;
}
this.instanceNames = new java.util.ArrayList<String>(instanceNames);
} } | public class class_name {
public void setInstanceNames(java.util.Collection<String> instanceNames) {
if (instanceNames == null) {
this.instanceNames = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.instanceNames = new java.util.ArrayList<String>(instanceNames);
} } |
public class class_name {
public void registerTransformer(String namespace, String waivePattern, Class<?>... transformerClasses) {
ExtensionManager jem = extensionManager();
for (Class<?> extensionClass : transformerClasses) {
Transformer t = extensionClass.getAnnotation(Transformer.class);
boolean classAnnotated = null != t;
String nmsp = namespace;
boolean namespaceIsEmpty = S.empty(namespace);
if (classAnnotated && namespaceIsEmpty) {
nmsp = t.value();
}
String waive = waivePattern;
boolean waiveIsEmpty = S.empty(waive);
if (classAnnotated && waiveIsEmpty) {
waive = t.waivePattern();
}
boolean clsRequireTemplate = null == t ? false : t.requireTemplate();
boolean clsLastParam = null == t ? false : t.lastParam();
for (Method m : extensionClass.getDeclaredMethods()) {
int flag = m.getModifiers();
if (!Modifier.isPublic(flag) || !Modifier.isStatic(flag)) continue;
int len = m.getParameterTypes().length;
if (len <= 0) continue;
Transformer tm = m.getAnnotation(Transformer.class);
boolean methodAnnotated = null != tm;
if (!methodAnnotated && !classAnnotated) continue;
String mnmsp = nmsp;
if (methodAnnotated && namespaceIsEmpty) {
mnmsp = tm.value();
if (S.empty(mnmsp)) mnmsp = nmsp;
}
String mwaive = waive;
if (methodAnnotated && waiveIsEmpty) {
mwaive = tm.waivePattern();
if (S.empty(mwaive)) mwaive = waive;
}
String cn = extensionClass.getSimpleName();
if (S.empty(mwaive)) mwaive = cn;
boolean requireTemplate = clsRequireTemplate;
if (null != tm && tm.requireTemplate()) {
requireTemplate = true;
}
boolean lastParam = clsLastParam;
if (null != tm && tm.lastParam()) {
lastParam = true;
}
String cn0 = extensionClass.getName();
String mn = m.getName();
String fullName = String.format("%s.%s", cn0, mn);
if (S.notEmpty(mnmsp) && !"rythm".equals(mnmsp)) {
mn = mnmsp + "_" + mn;
}
if (len == 1) {
jem.registerJavaExtension(new IJavaExtension.VoidParameterExtension(mwaive, mn, fullName, requireTemplate));
} else {
jem.registerJavaExtension(new IJavaExtension.ParameterExtension(mwaive, mn, ".+", fullName, requireTemplate, lastParam));
}
}
}
} } | public class class_name {
public void registerTransformer(String namespace, String waivePattern, Class<?>... transformerClasses) {
ExtensionManager jem = extensionManager();
for (Class<?> extensionClass : transformerClasses) {
Transformer t = extensionClass.getAnnotation(Transformer.class);
boolean classAnnotated = null != t;
String nmsp = namespace;
boolean namespaceIsEmpty = S.empty(namespace);
if (classAnnotated && namespaceIsEmpty) {
nmsp = t.value(); // depends on control dependency: [if], data = [none]
}
String waive = waivePattern;
boolean waiveIsEmpty = S.empty(waive);
if (classAnnotated && waiveIsEmpty) {
waive = t.waivePattern(); // depends on control dependency: [if], data = [none]
}
boolean clsRequireTemplate = null == t ? false : t.requireTemplate();
boolean clsLastParam = null == t ? false : t.lastParam();
for (Method m : extensionClass.getDeclaredMethods()) {
int flag = m.getModifiers();
if (!Modifier.isPublic(flag) || !Modifier.isStatic(flag)) continue;
int len = m.getParameterTypes().length;
if (len <= 0) continue;
Transformer tm = m.getAnnotation(Transformer.class);
boolean methodAnnotated = null != tm;
if (!methodAnnotated && !classAnnotated) continue;
String mnmsp = nmsp;
if (methodAnnotated && namespaceIsEmpty) {
mnmsp = tm.value(); // depends on control dependency: [if], data = [none]
if (S.empty(mnmsp)) mnmsp = nmsp;
}
String mwaive = waive;
if (methodAnnotated && waiveIsEmpty) {
mwaive = tm.waivePattern(); // depends on control dependency: [if], data = [none]
if (S.empty(mwaive)) mwaive = waive;
}
String cn = extensionClass.getSimpleName();
if (S.empty(mwaive)) mwaive = cn;
boolean requireTemplate = clsRequireTemplate;
if (null != tm && tm.requireTemplate()) {
requireTemplate = true; // depends on control dependency: [if], data = [none]
}
boolean lastParam = clsLastParam;
if (null != tm && tm.lastParam()) {
lastParam = true; // depends on control dependency: [if], data = [none]
}
String cn0 = extensionClass.getName();
String mn = m.getName();
String fullName = String.format("%s.%s", cn0, mn);
if (S.notEmpty(mnmsp) && !"rythm".equals(mnmsp)) {
mn = mnmsp + "_" + mn; // depends on control dependency: [if], data = [none]
}
if (len == 1) {
jem.registerJavaExtension(new IJavaExtension.VoidParameterExtension(mwaive, mn, fullName, requireTemplate)); // depends on control dependency: [if], data = [none]
} else {
jem.registerJavaExtension(new IJavaExtension.ParameterExtension(mwaive, mn, ".+", fullName, requireTemplate, lastParam)); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
public Recording startRecording(String sessionId, RecordingProperties properties)
throws OpenViduJavaClientException, OpenViduHttpException {
HttpPost request = new HttpPost(OpenVidu.urlOpenViduServer + API_RECORDINGS + API_RECORDINGS_START);
JSONObject json = new JSONObject();
json.put("session", sessionId);
json.put("name", properties.name());
json.put("outputMode", properties.outputMode().name());
json.put("hasAudio", properties.hasAudio());
json.put("hasVideo", properties.hasVideo());
if (Recording.OutputMode.COMPOSED.equals(properties.outputMode()) && properties.hasVideo()) {
json.put("resolution", properties.resolution());
json.put("recordingLayout",
(properties.recordingLayout() != null) ? properties.recordingLayout().name() : "");
if (RecordingLayout.CUSTOM.equals(properties.recordingLayout())) {
json.put("customLayout", (properties.customLayout() != null) ? properties.customLayout() : "");
}
}
StringEntity params = null;
try {
params = new StringEntity(json.toString());
} catch (UnsupportedEncodingException e1) {
throw new OpenViduJavaClientException(e1.getMessage(), e1.getCause());
}
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
request.setEntity(params);
HttpResponse response;
try {
response = OpenVidu.httpClient.execute(request);
} catch (IOException e2) {
throw new OpenViduJavaClientException(e2.getMessage(), e2.getCause());
}
try {
int statusCode = response.getStatusLine().getStatusCode();
if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
Recording r = new Recording(httpResponseToJson(response));
Session activeSession = OpenVidu.activeSessions.get(r.getSessionId());
if (activeSession != null) {
activeSession.setIsBeingRecorded(true);
} else {
log.warn("No active session found for sessionId '" + r.getSessionId()
+ "'. This instance of OpenVidu Java Client didn't create this session");
}
return r;
} else {
throw new OpenViduHttpException(statusCode);
}
} finally {
EntityUtils.consumeQuietly(response.getEntity());
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public Recording startRecording(String sessionId, RecordingProperties properties)
throws OpenViduJavaClientException, OpenViduHttpException {
HttpPost request = new HttpPost(OpenVidu.urlOpenViduServer + API_RECORDINGS + API_RECORDINGS_START);
JSONObject json = new JSONObject();
json.put("session", sessionId);
json.put("name", properties.name());
json.put("outputMode", properties.outputMode().name());
json.put("hasAudio", properties.hasAudio());
json.put("hasVideo", properties.hasVideo());
if (Recording.OutputMode.COMPOSED.equals(properties.outputMode()) && properties.hasVideo()) {
json.put("resolution", properties.resolution());
json.put("recordingLayout",
(properties.recordingLayout() != null) ? properties.recordingLayout().name() : "");
if (RecordingLayout.CUSTOM.equals(properties.recordingLayout())) {
json.put("customLayout", (properties.customLayout() != null) ? properties.customLayout() : ""); // depends on control dependency: [if], data = [none]
}
}
StringEntity params = null;
try {
params = new StringEntity(json.toString());
} catch (UnsupportedEncodingException e1) {
throw new OpenViduJavaClientException(e1.getMessage(), e1.getCause());
}
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
request.setEntity(params);
HttpResponse response;
try {
response = OpenVidu.httpClient.execute(request);
} catch (IOException e2) {
throw new OpenViduJavaClientException(e2.getMessage(), e2.getCause());
}
try {
int statusCode = response.getStatusLine().getStatusCode();
if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
Recording r = new Recording(httpResponseToJson(response));
Session activeSession = OpenVidu.activeSessions.get(r.getSessionId());
if (activeSession != null) {
activeSession.setIsBeingRecorded(true); // depends on control dependency: [if], data = [none]
} else {
log.warn("No active session found for sessionId '" + r.getSessionId()
+ "'. This instance of OpenVidu Java Client didn't create this session"); // depends on control dependency: [if], data = [none]
}
return r; // depends on control dependency: [if], data = [none]
} else {
throw new OpenViduHttpException(statusCode);
}
} finally {
EntityUtils.consumeQuietly(response.getEntity());
}
} } |
public class class_name {
public final void stopCapture() {
synchronized (this) {
// make sure we are running
if ((state == STATE_STOPPED) || (state == STATE_ABOUT_TO_STOP))
//throw new StateException("The capture is about to stop");
return;
// update our state
state = STATE_ABOUT_TO_STOP;
}
if (thread.isAlive()) {
thread.interrupt();
// wait for thread to exit if the push thread is not the one
// trying to join
if (! Thread.currentThread().equals(thread)) {
while (state == STATE_ABOUT_TO_STOP) {
try {
// wait for thread to exit
thread.join();
//thread = null;
} catch (InterruptedException e) {
// interrupted while waiting for the thread to join
// keep waiting
// System.err.println("interrupted while waiting for frame pusher thread to complete");
// e.printStackTrace();
// throw new StateException("interrupted while waiting for frame pusher thread to complete", e);
}
}
}
}
} } | public class class_name {
public final void stopCapture() {
synchronized (this) {
// make sure we are running
if ((state == STATE_STOPPED) || (state == STATE_ABOUT_TO_STOP))
//throw new StateException("The capture is about to stop");
return;
// update our state
state = STATE_ABOUT_TO_STOP;
}
if (thread.isAlive()) {
thread.interrupt(); // depends on control dependency: [if], data = [none]
// wait for thread to exit if the push thread is not the one
// trying to join
if (! Thread.currentThread().equals(thread)) {
while (state == STATE_ABOUT_TO_STOP) {
try {
// wait for thread to exit
thread.join(); // depends on control dependency: [try], data = [none]
//thread = null;
} catch (InterruptedException e) {
// interrupted while waiting for the thread to join
// keep waiting
// System.err.println("interrupted while waiting for frame pusher thread to complete");
// e.printStackTrace();
// throw new StateException("interrupted while waiting for frame pusher thread to complete", e);
} // depends on control dependency: [catch], data = [none]
}
}
}
} } |
public class class_name {
PartitionReplica checkAndGetPrimaryReplicaOwner(int partitionId, int replicaIndex) {
InternalPartitionImpl partition = partitionStateManager.getPartitionImpl(partitionId);
PartitionReplica owner = partition.getOwnerReplicaOrNull();
if (owner == null) {
logger.info("Sync replica target is null, no need to sync -> partitionId=" + partitionId + ", replicaIndex="
+ replicaIndex);
return null;
}
PartitionReplica localReplica = PartitionReplica.from(nodeEngine.getLocalMember());
if (owner.equals(localReplica)) {
if (logger.isFinestEnabled()) {
logger.finest("This node is now owner of partition, cannot sync replica -> partitionId=" + partitionId
+ ", replicaIndex=" + replicaIndex + ", partition-info="
+ partitionStateManager.getPartitionImpl(partitionId));
}
return null;
}
if (!partition.isOwnerOrBackup(localReplica)) {
if (logger.isFinestEnabled()) {
logger.finest("This node is not backup replica of partitionId=" + partitionId
+ ", replicaIndex=" + replicaIndex + " anymore.");
}
return null;
}
return owner;
} } | public class class_name {
PartitionReplica checkAndGetPrimaryReplicaOwner(int partitionId, int replicaIndex) {
InternalPartitionImpl partition = partitionStateManager.getPartitionImpl(partitionId);
PartitionReplica owner = partition.getOwnerReplicaOrNull();
if (owner == null) {
logger.info("Sync replica target is null, no need to sync -> partitionId=" + partitionId + ", replicaIndex="
+ replicaIndex); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
PartitionReplica localReplica = PartitionReplica.from(nodeEngine.getLocalMember());
if (owner.equals(localReplica)) {
if (logger.isFinestEnabled()) {
logger.finest("This node is now owner of partition, cannot sync replica -> partitionId=" + partitionId
+ ", replicaIndex=" + replicaIndex + ", partition-info="
+ partitionStateManager.getPartitionImpl(partitionId)); // depends on control dependency: [if], data = [none]
}
return null; // depends on control dependency: [if], data = [none]
}
if (!partition.isOwnerOrBackup(localReplica)) {
if (logger.isFinestEnabled()) {
logger.finest("This node is not backup replica of partitionId=" + partitionId
+ ", replicaIndex=" + replicaIndex + " anymore."); // depends on control dependency: [if], data = [none]
}
return null; // depends on control dependency: [if], data = [none]
}
return owner;
} } |
public class class_name {
public String createInsertBeforeStr4ModelEntry(Map dbColMap0,Map<String,MicroDbModelEntry> modelEntryMap){
if(dbColMap0==null){
return null;
}
//add 201902 ning
Map dbColMap=new CaseInsensitiveKeyMap();
if(dbColMap0!=null){
dbColMap.putAll(dbColMap0);
}
Cobj crealValues=Cutil.createCobj();
Map metaMap=new HashMap();
Iterator it=dbColMap.keySet().iterator();
Set<String> metaFlagSet=new TreeSet();
while(it.hasNext()){
String key=(String) it.next();
String value=(String) dbColMap.get(key);
MicroDbModelEntry modelEntry=modelEntryMap.get(key);
if(modelEntry==null){
continue;
}
if(CheckModelTypeUtil.isRealCol(modelEntry)==false){
if(value!=null){
String metaName=modelEntry.getMetaContentId();
metaFlagSet.add(metaName);
}
}else {
crealValues.append(key,value!=null);
}
}
for(String metaName:metaFlagSet){
crealValues.append(metaName);
}
return crealValues.getStr();
} } | public class class_name {
public String createInsertBeforeStr4ModelEntry(Map dbColMap0,Map<String,MicroDbModelEntry> modelEntryMap){
if(dbColMap0==null){
return null;
// depends on control dependency: [if], data = [none]
}
//add 201902 ning
Map dbColMap=new CaseInsensitiveKeyMap();
if(dbColMap0!=null){
dbColMap.putAll(dbColMap0);
// depends on control dependency: [if], data = [(dbColMap0]
}
Cobj crealValues=Cutil.createCobj();
Map metaMap=new HashMap();
Iterator it=dbColMap.keySet().iterator();
Set<String> metaFlagSet=new TreeSet();
while(it.hasNext()){
String key=(String) it.next();
String value=(String) dbColMap.get(key);
MicroDbModelEntry modelEntry=modelEntryMap.get(key);
if(modelEntry==null){
continue;
}
if(CheckModelTypeUtil.isRealCol(modelEntry)==false){
if(value!=null){
String metaName=modelEntry.getMetaContentId();
metaFlagSet.add(metaName);
// depends on control dependency: [if], data = [none]
}
}else {
crealValues.append(key,value!=null);
// depends on control dependency: [if], data = [none]
}
}
for(String metaName:metaFlagSet){
crealValues.append(metaName);
// depends on control dependency: [for], data = [metaName]
}
return crealValues.getStr();
} } |
public class class_name {
static void closeQuietly(Connection connection) {
try {
if (connection != null && !connection.isClosed()) {
connection.close();
log.debug("closed {}", connection);
}
} catch (SQLException e) {
log.debug(e.getMessage(), e);
} catch (RuntimeException e) {
log.debug(e.getMessage(), e);
}
} } | public class class_name {
static void closeQuietly(Connection connection) {
try {
if (connection != null && !connection.isClosed()) {
connection.close(); // depends on control dependency: [if], data = [none]
log.debug("closed {}", connection); // depends on control dependency: [if], data = [none]
}
} catch (SQLException e) {
log.debug(e.getMessage(), e);
} catch (RuntimeException e) { // depends on control dependency: [catch], data = [none]
log.debug(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
try {
LOG.info("send to " + mailInfo.getFromAddress());
// 设置一些通用的数据
Message mailMessage = setCommon(mailInfo);
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
// 发送邮件
Transport.send(mailMessage);
LOG.info("send to " + mailInfo.getFromAddress() + " dnoe.");
return true;
} catch (MessagingException ex) {
LOG.error(ex.toString(), ex);
}
return false;
} } | public class class_name {
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
try {
LOG.info("send to " + mailInfo.getFromAddress()); // depends on control dependency: [try], data = [none]
// 设置一些通用的数据
Message mailMessage = setCommon(mailInfo);
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); // depends on control dependency: [try], data = [none]
mainPart.addBodyPart(html); // depends on control dependency: [try], data = [none]
// 将MiniMultipart对象设置为邮件内容
mailMessage.setContent(mainPart); // depends on control dependency: [try], data = [none]
// 发送邮件
Transport.send(mailMessage); // depends on control dependency: [try], data = [none]
LOG.info("send to " + mailInfo.getFromAddress() + " dnoe."); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
} catch (MessagingException ex) {
LOG.error(ex.toString(), ex);
} // depends on control dependency: [catch], data = [none]
return false;
} } |
public class class_name {
private List<HdfsStats> createFromScanResults(String cluster, String path,
Scan scan, int maxCount, boolean checkPath, long starttime, long endtime)
throws IOException {
Map<HdfsStatsKey, HdfsStats> hdfsStats =
new HashMap<HdfsStatsKey, HdfsStats>();
ResultScanner scanner = null;
Stopwatch timer = new Stopwatch().start();
int rowCount = 0;
long colCount = 0;
long resultSize = 0;
Table hdfsUsageTable = null;
try {
hdfsUsageTable = hbaseConnection
.getTable(TableName.valueOf(HdfsConstants.HDFS_USAGE_TABLE));
scanner = hdfsUsageTable.getScanner(scan);
for (Result result : scanner) {
if (result != null && !result.isEmpty()) {
colCount += result.size();
// TODO dogpiledays resultSize += result.getWritableSize();
rowCount = populateHdfsStats(result, hdfsStats, checkPath, path,
starttime, endtime, rowCount);
// return if we've already hit the limit
if (rowCount >= maxCount) {
break;
}
}
}
timer.stop();
LOG.info("In createFromScanResults For cluster " + cluster
+ " Fetched from hbase " + rowCount + " rows, " + colCount
+ " columns, " + resultSize + " bytes ( " + resultSize / (1024 * 1024)
+ ") MB, in total time of " + timer);
} finally {
try {
if (scanner != null) {
scanner.close();
}
} finally {
if (hdfsUsageTable != null) {
hdfsUsageTable.close();
}
}
}
List<HdfsStats> values = new ArrayList<HdfsStats>(hdfsStats.values());
// sort so that timestamps are arranged in descending order
Collections.sort(values);
return values;
} } | public class class_name {
private List<HdfsStats> createFromScanResults(String cluster, String path,
Scan scan, int maxCount, boolean checkPath, long starttime, long endtime)
throws IOException {
Map<HdfsStatsKey, HdfsStats> hdfsStats =
new HashMap<HdfsStatsKey, HdfsStats>();
ResultScanner scanner = null;
Stopwatch timer = new Stopwatch().start();
int rowCount = 0;
long colCount = 0;
long resultSize = 0;
Table hdfsUsageTable = null;
try {
hdfsUsageTable = hbaseConnection
.getTable(TableName.valueOf(HdfsConstants.HDFS_USAGE_TABLE));
scanner = hdfsUsageTable.getScanner(scan);
for (Result result : scanner) {
if (result != null && !result.isEmpty()) {
colCount += result.size(); // depends on control dependency: [if], data = [none]
// TODO dogpiledays resultSize += result.getWritableSize();
rowCount = populateHdfsStats(result, hdfsStats, checkPath, path,
starttime, endtime, rowCount); // depends on control dependency: [if], data = [none]
// return if we've already hit the limit
if (rowCount >= maxCount) {
break;
}
}
}
timer.stop();
LOG.info("In createFromScanResults For cluster " + cluster
+ " Fetched from hbase " + rowCount + " rows, " + colCount
+ " columns, " + resultSize + " bytes ( " + resultSize / (1024 * 1024)
+ ") MB, in total time of " + timer);
} finally {
try {
if (scanner != null) {
scanner.close(); // depends on control dependency: [if], data = [none]
}
} finally {
if (hdfsUsageTable != null) {
hdfsUsageTable.close(); // depends on control dependency: [if], data = [none]
}
}
}
List<HdfsStats> values = new ArrayList<HdfsStats>(hdfsStats.values());
// sort so that timestamps are arranged in descending order
Collections.sort(values);
return values;
} } |
public class class_name {
public void marshall(StartMonitoringMembersRequest startMonitoringMembersRequest, ProtocolMarshaller protocolMarshaller) {
if (startMonitoringMembersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startMonitoringMembersRequest.getAccountIds(), ACCOUNTIDS_BINDING);
protocolMarshaller.marshall(startMonitoringMembersRequest.getDetectorId(), DETECTORID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(StartMonitoringMembersRequest startMonitoringMembersRequest, ProtocolMarshaller protocolMarshaller) {
if (startMonitoringMembersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startMonitoringMembersRequest.getAccountIds(), ACCOUNTIDS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startMonitoringMembersRequest.getDetectorId(), DETECTORID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static int queryInt(PreparedStatement stmt, int def) throws SQLException {
ResultSet rs = null;
try {
rs = stmt.executeQuery();
if (rs.next()) {
int value = rs.getInt(1);
if (!rs.wasNull()) {
return value;
}
}
return def;
} finally {
close(rs);
}
} } | public class class_name {
public static int queryInt(PreparedStatement stmt, int def) throws SQLException {
ResultSet rs = null;
try {
rs = stmt.executeQuery();
if (rs.next()) {
int value = rs.getInt(1);
if (!rs.wasNull()) {
return value; // depends on control dependency: [if], data = [none]
}
}
return def;
} finally {
close(rs);
}
} } |
public class class_name {
private Map<Integer, Grib1Parameter> readParameterTableEcmwfEcCodes() throws IOException {
HashMap<Integer, Grib1Parameter> result = new HashMap<>();
try (InputStream is = GribResourceReader.getInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
String line = br.readLine();
if (line == null) {
throw new FileNotFoundException(path + " is empty");
}
// create table name from file name
String[] splitPath = path.split("/");
String tableNum = splitPath[splitPath.length - 1].replace(".table", "");
this.desc = "ECMWF GRIB API TABLE " + tableNum;
// skip header
while (line != null && !line.startsWith("#")) {
line = br.readLine(); // skip
}
// keep going until the end of the file is reached (line == null)
while (true) {
// exmaple: 251 atte [Adiabatic tendency of temperature] (K)
line = br.readLine();
if (line == null) {
break; // done with the file
}
if ((line.length() == 0) || line.startsWith("#")) {
continue;
}
// get unit - (K)
String[] tmpUnitArray = line.split("\\(");
String tmpUnit = tmpUnitArray[tmpUnitArray.length - 1];
int lastUnitIndex;
while ((lastUnitIndex = tmpUnit.lastIndexOf(")")) > 0) {
tmpUnit = tmpUnit.substring(0, lastUnitIndex).trim();
}
String unit = tmpUnit.trim();
// unit = Util.cleanUnit(unit); // fixes some common unit mistakes // jcaron - just use unit as it is
// get parameter number - 251
String[] lineArray = line.trim().split("\\s+"); // all and any white space
String num = lineArray[0];
// get shortName - atte
String name = lineArray[1].trim();
//if (name.equals("~")) {}; - todo create name from long name(?)
// get description. bracketed by [] - [Adiabatic Tendency of temperature]
int startDesc = line.indexOf("[");
int endDesc = line.indexOf("]");
String desc = line.substring(startDesc, endDesc).trim();
// stuff information into a Grib1Parameter object
int p1;
try {
p1 = Integer.parseInt(num);
} catch (Exception e) {
logger.warn("Cant parse " + num + " in file " + path);
continue;
}
Grib1Parameter parameter = new Grib1Parameter(this, p1, name, desc, unit);
result.put(parameter.getNumber(), parameter);
logger.debug(" %s%n", parameter);
}
return Collections.unmodifiableMap(result); // all at once - thread safe
}
} } | public class class_name {
private Map<Integer, Grib1Parameter> readParameterTableEcmwfEcCodes() throws IOException {
HashMap<Integer, Grib1Parameter> result = new HashMap<>();
try (InputStream is = GribResourceReader.getInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
String line = br.readLine();
if (line == null) {
throw new FileNotFoundException(path + " is empty");
}
// create table name from file name
String[] splitPath = path.split("/");
String tableNum = splitPath[splitPath.length - 1].replace(".table", "");
this.desc = "ECMWF GRIB API TABLE " + tableNum;
// skip header
while (line != null && !line.startsWith("#")) {
line = br.readLine(); // skip
}
// keep going until the end of the file is reached (line == null)
while (true) {
// exmaple: 251 atte [Adiabatic tendency of temperature] (K)
line = br.readLine();
if (line == null) {
break; // done with the file
}
if ((line.length() == 0) || line.startsWith("#")) {
continue;
}
// get unit - (K)
String[] tmpUnitArray = line.split("\\(");
String tmpUnit = tmpUnitArray[tmpUnitArray.length - 1];
int lastUnitIndex;
while ((lastUnitIndex = tmpUnit.lastIndexOf(")")) > 0) {
tmpUnit = tmpUnit.substring(0, lastUnitIndex).trim(); // depends on control dependency: [while], data = [none]
}
String unit = tmpUnit.trim();
// unit = Util.cleanUnit(unit); // fixes some common unit mistakes // jcaron - just use unit as it is
// get parameter number - 251
String[] lineArray = line.trim().split("\\s+"); // all and any white space
String num = lineArray[0];
// get shortName - atte
String name = lineArray[1].trim();
//if (name.equals("~")) {}; - todo create name from long name(?)
// get description. bracketed by [] - [Adiabatic Tendency of temperature]
int startDesc = line.indexOf("[");
int endDesc = line.indexOf("]");
String desc = line.substring(startDesc, endDesc).trim();
// stuff information into a Grib1Parameter object
int p1;
try {
p1 = Integer.parseInt(num); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.warn("Cant parse " + num + " in file " + path);
continue;
} // depends on control dependency: [catch], data = [none]
Grib1Parameter parameter = new Grib1Parameter(this, p1, name, desc, unit);
result.put(parameter.getNumber(), parameter);
logger.debug(" %s%n", parameter);
}
return Collections.unmodifiableMap(result); // all at once - thread safe
}
} } |
public class class_name {
public static String removeInvalidSeprator(String tmp) {
if (tmp != null && !tmp.isEmpty()) {
return tmp.replaceAll("[`~!@#$%^&*+=|{}':;',\\[\\]<>/?~! @#¥%……&*——+|{}【】‘;:”“’。,、?]",
"_").replaceAll("__", "_");
}
return tmp;
} } | public class class_name {
public static String removeInvalidSeprator(String tmp) {
if (tmp != null && !tmp.isEmpty()) {
return tmp.replaceAll("[`~!@#$%^&*+=|{}':;',\\[\\]<>/?~! @#¥%……&*——+|{}【】‘;:”“’。,、?]",
"_").replaceAll("__", "_"); // depends on control dependency: [if], data = [none]
}
return tmp;
} } |
public class class_name {
@Override
@Path("/{roleName}/users/{cuid}")
@ApiOperation(value="Create a role or add a user to an existing role",
notes="If users/{cuid} is present, user is added to role.", response=StatusMessage.class)
@ApiImplicitParams({
@ApiImplicitParam(name="Workgroup", paramType="body", dataType="com.centurylink.mdw.model.user.Role")})
public JSONObject post(String path, JSONObject content, Map<String,String> headers)
throws ServiceException, JSONException {
String name = getSegment(path, 1);
String rel = getSegment(path, 2);
UserServices userServices = ServiceLocator.getUserServices();
try {
Role existing = userServices.getRoles().get(name);
if (rel == null) {
if (existing != null)
throw new ServiceException(HTTP_409_CONFLICT, "Role name already exists: " + name);
Role role = new Role(content);
userServices.createRole(role);
}
else if (rel.equals("users")) {
String cuid = getSegment(path, 3);
User user = UserGroupCache.getUser(cuid);
if (user == null) {
throw new CachingException("Cannot find user: " + cuid);
}
if (user.hasRole(name)) // in case added elsewhere
throw new ServiceException(HTTP_409_CONFLICT, "User " + cuid + " already has role " + name);
userServices.addUserToRole(cuid, name);
}
else {
String msg = "Unsupported relationship for role " + name + ": " + rel;
throw new ServiceException(HTTP_400_BAD_REQUEST, msg);
}
return null;
}
catch (DataAccessException ex) {
throw new ServiceException(HTTP_500_INTERNAL_ERROR, ex.getMessage(), ex);
}
catch (CachingException ex) {
throw new ServiceException(HTTP_500_INTERNAL_ERROR, ex.getMessage(), ex);
}
} } | public class class_name {
@Override
@Path("/{roleName}/users/{cuid}")
@ApiOperation(value="Create a role or add a user to an existing role",
notes="If users/{cuid} is present, user is added to role.", response=StatusMessage.class)
@ApiImplicitParams({
@ApiImplicitParam(name="Workgroup", paramType="body", dataType="com.centurylink.mdw.model.user.Role")})
public JSONObject post(String path, JSONObject content, Map<String,String> headers)
throws ServiceException, JSONException {
String name = getSegment(path, 1);
String rel = getSegment(path, 2);
UserServices userServices = ServiceLocator.getUserServices();
try {
Role existing = userServices.getRoles().get(name);
if (rel == null) {
if (existing != null)
throw new ServiceException(HTTP_409_CONFLICT, "Role name already exists: " + name);
Role role = new Role(content);
userServices.createRole(role); // depends on control dependency: [if], data = [none]
}
else if (rel.equals("users")) {
String cuid = getSegment(path, 3);
User user = UserGroupCache.getUser(cuid);
if (user == null) {
throw new CachingException("Cannot find user: " + cuid);
}
if (user.hasRole(name)) // in case added elsewhere
throw new ServiceException(HTTP_409_CONFLICT, "User " + cuid + " already has role " + name);
userServices.addUserToRole(cuid, name); // depends on control dependency: [if], data = [none]
}
else {
String msg = "Unsupported relationship for role " + name + ": " + rel; // depends on control dependency: [if], data = [none]
throw new ServiceException(HTTP_400_BAD_REQUEST, msg);
}
return null;
}
catch (DataAccessException ex) {
throw new ServiceException(HTTP_500_INTERNAL_ERROR, ex.getMessage(), ex);
}
catch (CachingException ex) {
throw new ServiceException(HTTP_500_INTERNAL_ERROR, ex.getMessage(), ex);
}
} } |
public class class_name {
@Override
public EClass getIfcDistributionElement() {
if (ifcDistributionElementEClass == null) {
ifcDistributionElementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(183);
}
return ifcDistributionElementEClass;
} } | public class class_name {
@Override
public EClass getIfcDistributionElement() {
if (ifcDistributionElementEClass == null) {
ifcDistributionElementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(183);
// depends on control dependency: [if], data = [none]
}
return ifcDistributionElementEClass;
} } |
public class class_name {
public void add(final AbsAxis mAx) {
AbsAxis axis = mAx;
if (isDupOrd(axis)) {
axis = new DupFilterAxis(mRtx, axis);
DupState.nodup = true;
}
switch (mNumber) {
case 0:
mFirstAxis = axis;
mNumber++;
break;
case 1:
mExpr = new NestedAxis(mFirstAxis, axis, mRtx);
mNumber++;
break;
default:
final AbsAxis cache = mExpr;
mExpr = new NestedAxis(cache, axis, mRtx);
}
} } | public class class_name {
public void add(final AbsAxis mAx) {
AbsAxis axis = mAx;
if (isDupOrd(axis)) {
axis = new DupFilterAxis(mRtx, axis); // depends on control dependency: [if], data = [none]
DupState.nodup = true; // depends on control dependency: [if], data = [none]
}
switch (mNumber) {
case 0:
mFirstAxis = axis;
mNumber++;
break;
case 1:
mExpr = new NestedAxis(mFirstAxis, axis, mRtx);
mNumber++;
break;
default:
final AbsAxis cache = mExpr;
mExpr = new NestedAxis(cache, axis, mRtx);
}
} } |
public class class_name {
public static Point getCircumCenter(Geometry geometry) {
if(geometry == null || geometry.getNumPoints() == 0) {
return null;
}
return geometry.getFactory().createPoint(new MinimumBoundingCircle(geometry).getCentre());
} } | public class class_name {
public static Point getCircumCenter(Geometry geometry) {
if(geometry == null || geometry.getNumPoints() == 0) {
return null; // depends on control dependency: [if], data = [none]
}
return geometry.getFactory().createPoint(new MinimumBoundingCircle(geometry).getCentre());
} } |
public class class_name {
public static List<VectorTile.Tile.Feature> toFeatures(Collection<Geometry> flatGeoms,
MvtLayerProps layerProps,
IUserDataConverter userDataConverter) {
// Guard: empty geometry
if(flatGeoms.isEmpty()) {
return Collections.emptyList();
}
final List<VectorTile.Tile.Feature> features = new ArrayList<>();
final Vec2d cursor = new Vec2d();
VectorTile.Tile.Feature nextFeature;
for(Geometry nextGeom : flatGeoms) {
cursor.set(0d, 0d);
nextFeature = toFeature(nextGeom, cursor, layerProps, userDataConverter);
if(nextFeature != null) {
features.add(nextFeature);
}
}
return features;
} } | public class class_name {
public static List<VectorTile.Tile.Feature> toFeatures(Collection<Geometry> flatGeoms,
MvtLayerProps layerProps,
IUserDataConverter userDataConverter) {
// Guard: empty geometry
if(flatGeoms.isEmpty()) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
final List<VectorTile.Tile.Feature> features = new ArrayList<>();
final Vec2d cursor = new Vec2d();
VectorTile.Tile.Feature nextFeature;
for(Geometry nextGeom : flatGeoms) {
cursor.set(0d, 0d); // depends on control dependency: [for], data = [none]
nextFeature = toFeature(nextGeom, cursor, layerProps, userDataConverter); // depends on control dependency: [for], data = [nextGeom]
if(nextFeature != null) {
features.add(nextFeature); // depends on control dependency: [if], data = [(nextFeature]
}
}
return features;
} } |
public class class_name {
@Override
@LogarithmicTime
public AddressableHeap.Handle<K, V> deleteMin() {
if (size == 0) {
throw new NoSuchElementException();
}
Node oldRoot = root;
// easy special cases
if (size == 1) {
root = null;
size = 0;
return oldRoot;
} else if (size == 2) {
root = root.o_c;
root.o_c = null;
root.y_s = null;
size = 1;
oldRoot.o_c = null;
return oldRoot;
}
// remove last node
Node lastNodeParent = findParentNode(size);
Node lastNode = lastNodeParent.o_c;
if (lastNode.y_s != lastNodeParent) {
Node tmp = lastNode;
lastNode = tmp.y_s;
tmp.y_s = lastNodeParent;
} else {
lastNodeParent.o_c = null;
}
lastNode.y_s = null;
// decrease size
size--;
// place it as root
// (assumes root.o_c exists)
if (root.o_c.y_s == root) {
root.o_c.y_s = lastNode;
} else {
root.o_c.y_s.y_s = lastNode;
}
lastNode.o_c = root.o_c;
root = lastNode;
// fix priorities
fixdown(root);
oldRoot.o_c = null;
return oldRoot;
} } | public class class_name {
@Override
@LogarithmicTime
public AddressableHeap.Handle<K, V> deleteMin() {
if (size == 0) {
throw new NoSuchElementException();
}
Node oldRoot = root;
// easy special cases
if (size == 1) {
root = null; // depends on control dependency: [if], data = [none]
size = 0; // depends on control dependency: [if], data = [none]
return oldRoot; // depends on control dependency: [if], data = [none]
} else if (size == 2) {
root = root.o_c; // depends on control dependency: [if], data = [none]
root.o_c = null; // depends on control dependency: [if], data = [none]
root.y_s = null; // depends on control dependency: [if], data = [none]
size = 1; // depends on control dependency: [if], data = [none]
oldRoot.o_c = null; // depends on control dependency: [if], data = [none]
return oldRoot; // depends on control dependency: [if], data = [none]
}
// remove last node
Node lastNodeParent = findParentNode(size);
Node lastNode = lastNodeParent.o_c;
if (lastNode.y_s != lastNodeParent) {
Node tmp = lastNode;
lastNode = tmp.y_s; // depends on control dependency: [if], data = [none]
tmp.y_s = lastNodeParent; // depends on control dependency: [if], data = [none]
} else {
lastNodeParent.o_c = null; // depends on control dependency: [if], data = [none]
}
lastNode.y_s = null;
// decrease size
size--;
// place it as root
// (assumes root.o_c exists)
if (root.o_c.y_s == root) {
root.o_c.y_s = lastNode; // depends on control dependency: [if], data = [none]
} else {
root.o_c.y_s.y_s = lastNode; // depends on control dependency: [if], data = [none]
}
lastNode.o_c = root.o_c;
root = lastNode;
// fix priorities
fixdown(root);
oldRoot.o_c = null;
return oldRoot;
} } |
public class class_name {
@Override
public Double getUserItemPreference(U u, I i) {
if (userItemPreferences.containsKey(u) && userItemPreferences.get(u).containsKey(i)) {
return userItemPreferences.get(u).get(i);
}
return Double.NaN;
} } | public class class_name {
@Override
public Double getUserItemPreference(U u, I i) {
if (userItemPreferences.containsKey(u) && userItemPreferences.get(u).containsKey(i)) {
return userItemPreferences.get(u).get(i); // depends on control dependency: [if], data = [none]
}
return Double.NaN;
} } |
public class class_name {
private static WaveletTransform createDefaultShrinkTransform(ImageDataType imageType, int numLevels,
double minPixelValue , double maxPixelValue ) {
WaveletTransform descTran;
if( !imageType.isInteger()) {
WaveletDescription<WlCoef_F32> waveletDesc_F32 = FactoryWaveletDaub.daubJ_F32(4);
descTran = FactoryWaveletTransform.create_F32(waveletDesc_F32,numLevels,
(float)minPixelValue,(float)maxPixelValue);
} else {
WaveletDescription<WlCoef_I32> waveletDesc_I32 = FactoryWaveletDaub.biorthogonal_I32(5, BorderType.REFLECT);
descTran = FactoryWaveletTransform.create_I(waveletDesc_I32,numLevels,
(int)minPixelValue,(int)maxPixelValue,
ImageType.getImageClass(ImageType.Family.GRAY, imageType));
}
return descTran;
} } | public class class_name {
private static WaveletTransform createDefaultShrinkTransform(ImageDataType imageType, int numLevels,
double minPixelValue , double maxPixelValue ) {
WaveletTransform descTran;
if( !imageType.isInteger()) {
WaveletDescription<WlCoef_F32> waveletDesc_F32 = FactoryWaveletDaub.daubJ_F32(4);
descTran = FactoryWaveletTransform.create_F32(waveletDesc_F32,numLevels,
(float)minPixelValue,(float)maxPixelValue); // depends on control dependency: [if], data = [none]
} else {
WaveletDescription<WlCoef_I32> waveletDesc_I32 = FactoryWaveletDaub.biorthogonal_I32(5, BorderType.REFLECT);
descTran = FactoryWaveletTransform.create_I(waveletDesc_I32,numLevels,
(int)minPixelValue,(int)maxPixelValue,
ImageType.getImageClass(ImageType.Family.GRAY, imageType)); // depends on control dependency: [if], data = [none]
}
return descTran;
} } |
public class class_name {
public Namer getOneToManyIntermediateNamer(Namer fromEntityNamer, ColumnConfig pointsOnToEntity, Namer toEntityNamer) {
// new configuration
Namer result = getOneToManyNamerFromConf(pointsOnToEntity.getOneToManyConfig(), toEntityNamer);
// fallback
if (result == null) {
// NOTE: we use the many to many fallback as it is totally complient with intermediate m2o fallback expectations.
result = getManyToManyNamerFallBack(fromEntityNamer, pointsOnToEntity, toEntityNamer);
}
return result;
} } | public class class_name {
public Namer getOneToManyIntermediateNamer(Namer fromEntityNamer, ColumnConfig pointsOnToEntity, Namer toEntityNamer) {
// new configuration
Namer result = getOneToManyNamerFromConf(pointsOnToEntity.getOneToManyConfig(), toEntityNamer);
// fallback
if (result == null) {
// NOTE: we use the many to many fallback as it is totally complient with intermediate m2o fallback expectations.
result = getManyToManyNamerFallBack(fromEntityNamer, pointsOnToEntity, toEntityNamer); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public IFeatureAlphabet rebuildFeatureAlphabet(String name) {
IFeatureAlphabet alphabet = null;
if (maps.containsKey(name)) {
alphabet = (IFeatureAlphabet) maps.get(name);
alphabet.clear();
}else{
return buildFeatureAlphabet(name,defaultFeatureType);
}
return alphabet;
} } | public class class_name {
public IFeatureAlphabet rebuildFeatureAlphabet(String name) {
IFeatureAlphabet alphabet = null;
if (maps.containsKey(name)) {
alphabet = (IFeatureAlphabet) maps.get(name);
// depends on control dependency: [if], data = [none]
alphabet.clear();
// depends on control dependency: [if], data = [none]
}else{
return buildFeatureAlphabet(name,defaultFeatureType);
// depends on control dependency: [if], data = [none]
}
return alphabet;
} } |
public class class_name {
public static boolean isTopApplication(Context context) {
ComponentName activity = getTopActivity(context);
if (activity == null) {
return false;
}
return activity.getPackageName().equals(context.getApplicationInfo().packageName);
} } | public class class_name {
public static boolean isTopApplication(Context context) {
ComponentName activity = getTopActivity(context);
if (activity == null) {
return false; // depends on control dependency: [if], data = [none]
}
return activity.getPackageName().equals(context.getApplicationInfo().packageName);
} } |
public class class_name {
@Override
public void type(String text) throws WidgetException{
try{
if (getGUIDriver().isJavascriptTypeMode()) {
// Replaces apostrophes that have not been escaped with escaped variations
// Slashes need to be escaped multiple times. Once for Java's string escaping
// and again for the RegEx engine escaping.
final String theText = text.replaceAll("(\\\\')|(\\')", "\\\\'");
highlight( HIGHLIGHT_MODES.PUT);
try {
eval("arguments[0].value='" + theText + "';");
} catch (WidgetException we) {
throw new RuntimeException(we);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
} else {
// TODO Test this.
synchronized (InteractiveElement.class) {
getGUIDriver().focus();
click();
WebElement webElement = getWebElement();
highlight( HIGHLIGHT_MODES.PUT);
webElement.clear();
webElement.sendKeys(text);
}
}
}catch(Exception e){
throw new WidgetException("Error while trying to type at " + getByLocator(), getByLocator(), e);
}
} } | public class class_name {
@Override
public void type(String text) throws WidgetException{
try{
if (getGUIDriver().isJavascriptTypeMode()) {
// Replaces apostrophes that have not been escaped with escaped variations
// Slashes need to be escaped multiple times. Once for Java's string escaping
// and again for the RegEx engine escaping.
final String theText = text.replaceAll("(\\\\')|(\\')", "\\\\'");
highlight( HIGHLIGHT_MODES.PUT);
try {
eval("arguments[0].value='" + theText + "';"); // depends on control dependency: [try], data = [none]
} catch (WidgetException we) {
throw new RuntimeException(we);
} // depends on control dependency: [catch], data = [none]
try {
Thread.sleep(500); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
} // depends on control dependency: [catch], data = [none]
} else {
// TODO Test this.
synchronized (InteractiveElement.class) {
getGUIDriver().focus();
click();
WebElement webElement = getWebElement();
highlight( HIGHLIGHT_MODES.PUT);
webElement.clear();
webElement.sendKeys(text);
}
}
}catch(Exception e){
throw new WidgetException("Error while trying to type at " + getByLocator(), getByLocator(), e);
}
} } |
public class class_name {
public Node cloneNode(boolean deep) {
try {
if (isXMLDoc == UNKNOWN_TYPE) isXMLDoc = getDocumentType();
if (isXMLDoc == NON_XML) {
throw new UnsupportedOperationException(
"Text document cannot be cloned");
}
// initialize a new doc owner node
initClonedOwnerDoc();
} catch (ParserConfigurationException e) {
throw new RuntimeException("Internal Error:" + e);
}
if (deep) {
for (NodeImpl n = (NodeImpl) getFirstChild(); n != null; n = (NodeImpl) n
.getNextSibling()) {
ownerDocCloned.appendChild(n.cloneNode(ownerDocCloned, true));
}
}
return ownerDocCloned;
} } | public class class_name {
public Node cloneNode(boolean deep) {
try {
if (isXMLDoc == UNKNOWN_TYPE) isXMLDoc = getDocumentType();
if (isXMLDoc == NON_XML) {
throw new UnsupportedOperationException(
"Text document cannot be cloned");
}
// initialize a new doc owner node
initClonedOwnerDoc(); // depends on control dependency: [try], data = [none]
} catch (ParserConfigurationException e) {
throw new RuntimeException("Internal Error:" + e);
} // depends on control dependency: [catch], data = [none]
if (deep) {
for (NodeImpl n = (NodeImpl) getFirstChild(); n != null; n = (NodeImpl) n
.getNextSibling()) {
ownerDocCloned.appendChild(n.cloneNode(ownerDocCloned, true)); // depends on control dependency: [for], data = [n]
}
}
return ownerDocCloned;
} } |
public class class_name {
public boolean startsWithPackage(String... pkgs) {
for (String st : pkgs) {
if (!st.endsWith(".")) st += ".";
String className = getClassName();
if (className.startsWith(st)) {
return true;
}
}
return false;
} } | public class class_name {
public boolean startsWithPackage(String... pkgs) {
for (String st : pkgs) {
if (!st.endsWith(".")) st += ".";
String className = getClassName();
if (className.startsWith(st)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public <T> T get(Class<T> clazz, final String name)
{
JAXBNamedResourceFactory<T> cached = cachedReferences.get(name);
if (cached == null)
{
cached = new JAXBNamedResourceFactory<T>(this.config, this.factory, name, clazz);
cachedReferences.put(name, cached);
}
return cached.get();
} } | public class class_name {
public <T> T get(Class<T> clazz, final String name)
{
JAXBNamedResourceFactory<T> cached = cachedReferences.get(name);
if (cached == null)
{
cached = new JAXBNamedResourceFactory<T>(this.config, this.factory, name, clazz); // depends on control dependency: [if], data = [none]
cachedReferences.put(name, cached); // depends on control dependency: [if], data = [none]
}
return cached.get();
} } |
public class class_name {
public void setBoardTranslationX(float x) {
if (mListeners != null) {
for (StateListener l : mListeners) {
l.onBoardTranslationX(this, x);
}
}
mContentView.setTranslationX(x);
} } | public class class_name {
public void setBoardTranslationX(float x) {
if (mListeners != null) {
for (StateListener l : mListeners) {
l.onBoardTranslationX(this, x); // depends on control dependency: [for], data = [l]
}
}
mContentView.setTranslationX(x);
} } |
public class class_name {
@SuppressWarnings("unchecked")
private List<String> operations(Map<String, Object> ops) {
List<String> result = new LinkedList<>();
for (String operation : ops.keySet()) {
Object operationOrListOfOperations = ops.get(operation);
List<Map<String, Object>> toStringify;
if (operationOrListOfOperations instanceof List) {
toStringify = (List<Map<String, Object>>) operationOrListOfOperations;
} else {
toStringify = Collections.singletonList((Map<String, Object>) operationOrListOfOperations);
}
for (Map<String, Object> op : toStringify) {
List<Map<String, String>> args = (List<Map<String, String>>) op.get("args");
result.add(operation + "(" + argsToString(args) + ")");
}
}
return result;
} } | public class class_name {
@SuppressWarnings("unchecked")
private List<String> operations(Map<String, Object> ops) {
List<String> result = new LinkedList<>();
for (String operation : ops.keySet()) {
Object operationOrListOfOperations = ops.get(operation);
List<Map<String, Object>> toStringify;
if (operationOrListOfOperations instanceof List) {
toStringify = (List<Map<String, Object>>) operationOrListOfOperations; // depends on control dependency: [if], data = [none]
} else {
toStringify = Collections.singletonList((Map<String, Object>) operationOrListOfOperations); // depends on control dependency: [if], data = [none]
}
for (Map<String, Object> op : toStringify) {
List<Map<String, String>> args = (List<Map<String, String>>) op.get("args");
result.add(operation + "(" + argsToString(args) + ")"); // depends on control dependency: [for], data = [op]
}
}
return result;
} } |
public class class_name {
protected String getSetToField(String target, Field field, Class<?> cls, String express, boolean isList,
boolean isMap, boolean packed) {
StringBuilder ret = new StringBuilder();
if (isList || isMap) {
ret.append("if ((").append(getAccessByField(target, field, cls)).append(") == null) {").append(LINE_BREAK);
}
// if field of public modifier we can access directly
if (Modifier.isPublic(field.getModifiers())) {
if (isList) {
// should initialize list
ret.append(target).append(ClassHelper.PACKAGE_SEPARATOR).append(field.getName())
.append("= new ArrayList()").append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
if (express != null) {
if (packed) {
ret.append("while (input.getBytesUntilLimit() > 0) {").append(LINE_BREAK);
}
ret.append(target).append(ClassHelper.PACKAGE_SEPARATOR).append(field.getName()).append(".add(")
.append(express).append(")");
if (packed) {
ret.append(";}").append(LINE_BREAK);
}
}
return ret.toString();
} else if (isMap) {
ret.append(target).append(ClassHelper.PACKAGE_SEPARATOR).append(field.getName())
.append("= new HashMap()").append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
return ret.append(express).toString();
}
return target + ClassHelper.PACKAGE_SEPARATOR + field.getName() + "=" + express + LINE_BREAK;
}
String setter = "set" + CodedConstant.capitalize(field.getName());
// check method exist
try {
cls.getMethod(setter, new Class<?>[] { field.getType() });
if (isList) {
ret.append("List __list = new ArrayList()").append(JAVA_LINE_BREAK);
ret.append(target).append(ClassHelper.PACKAGE_SEPARATOR).append(setter).append("(__list)")
.append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
if (express != null) {
if (packed) {
ret.append("while (input.getBytesUntilLimit() > 0) {").append(LINE_BREAK);
}
ret.append("(").append(getAccessByField(target, field, cls)).append(").add(").append(express)
.append(")");
if (packed) {
ret.append(";}").append(LINE_BREAK);
}
}
return ret.toString();
} else if (isMap) {
ret.append("Map __map = new HashMap()").append(JAVA_LINE_BREAK);
ret.append(target).append(ClassHelper.PACKAGE_SEPARATOR).append(setter).append("(__map)")
.append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
return ret + express;
}
return target + ClassHelper.PACKAGE_SEPARATOR + setter + "(" + express + ")\n";
} catch (Exception e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(e.getMessage(), e);
}
}
if (isList) {
ret.append("List __list = new ArrayList()").append(JAVA_LINE_BREAK);
ret.append("FieldUtils.setField(").append(target).append(", \"").append(field.getName())
.append("\", __list)").append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
if (express != null) {
if (packed) {
ret.append("while (input.getBytesUntilLimit() > 0) {").append(LINE_BREAK);
}
ret.append("(").append(getAccessByField(target, field, cls)).append(").add(").append(express)
.append(")");
if (packed) {
ret.append(";}").append(LINE_BREAK);
}
}
return ret.toString();
} else if (isMap) {
ret.append("Map __map = new HashMap()").append(JAVA_LINE_BREAK);
ret.append("FieldUtils.setField(").append(target).append(", \"").append(field.getName())
.append("\", __map)").append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
return ret + express;
}
// use reflection to get value
String code = "";
if (express != null) {
code = "FieldUtils.setField(" + target + ", \"" + field.getName() + "\", " + express + ")" + LINE_BREAK;
}
return code;
} } | public class class_name {
protected String getSetToField(String target, Field field, Class<?> cls, String express, boolean isList,
boolean isMap, boolean packed) {
StringBuilder ret = new StringBuilder();
if (isList || isMap) {
ret.append("if ((").append(getAccessByField(target, field, cls)).append(") == null) {").append(LINE_BREAK);
// depends on control dependency: [if], data = [none]
}
// if field of public modifier we can access directly
if (Modifier.isPublic(field.getModifiers())) {
if (isList) {
// should initialize list
ret.append(target).append(ClassHelper.PACKAGE_SEPARATOR).append(field.getName())
.append("= new ArrayList()").append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
// depends on control dependency: [if], data = [none]
if (express != null) {
if (packed) {
ret.append("while (input.getBytesUntilLimit() > 0) {").append(LINE_BREAK);
// depends on control dependency: [if], data = [none]
}
ret.append(target).append(ClassHelper.PACKAGE_SEPARATOR).append(field.getName()).append(".add(")
.append(express).append(")");
// depends on control dependency: [if], data = [none]
if (packed) {
ret.append(";}").append(LINE_BREAK);
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
}
}
return ret.toString();
// depends on control dependency: [if], data = [none]
} else if (isMap) {
ret.append(target).append(ClassHelper.PACKAGE_SEPARATOR).append(field.getName())
.append("= new HashMap()").append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
// depends on control dependency: [if], data = [none]
return ret.append(express).toString();
// depends on control dependency: [if], data = [none]
}
return target + ClassHelper.PACKAGE_SEPARATOR + field.getName() + "=" + express + LINE_BREAK;
}
String setter = "set" + CodedConstant.capitalize(field.getName());
// check method exist
try {
cls.getMethod(setter, new Class<?>[] { field.getType() });
if (isList) {
ret.append("List __list = new ArrayList()").append(JAVA_LINE_BREAK);
// depends on control dependency: [if], data = [none]
ret.append(target).append(ClassHelper.PACKAGE_SEPARATOR).append(setter).append("(__list)")
.append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
// depends on control dependency: [if], data = [none]
if (express != null) {
if (packed) {
ret.append("while (input.getBytesUntilLimit() > 0) {").append(LINE_BREAK);
// depends on control dependency: [if], data = [none]
}
ret.append("(").append(getAccessByField(target, field, cls)).append(").add(").append(express)
.append(")");
// depends on control dependency: [if], data = [none]
if (packed) {
ret.append(";}").append(LINE_BREAK);
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
}
}
return ret.toString();
} else if (isMap) {
ret.append("Map __map = new HashMap()").append(JAVA_LINE_BREAK);
ret.append(target).append(ClassHelper.PACKAGE_SEPARATOR).append(setter).append("(__map)")
.append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
return ret + express;
}
return target + ClassHelper.PACKAGE_SEPARATOR + setter + "(" + express + ")\n";
} catch (Exception e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(e.getMessage(), e);
// depends on control dependency: [if], data = [none]
}
}
if (isList) {
ret.append("List __list = new ArrayList()").append(JAVA_LINE_BREAK);
ret.append("FieldUtils.setField(").append(target).append(", \"").append(field.getName())
.append("\", __list)").append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
if (express != null) {
if (packed) {
ret.append("while (input.getBytesUntilLimit() > 0) {").append(LINE_BREAK);
// depends on control dependency: [if], data = [none]
}
ret.append("(").append(getAccessByField(target, field, cls)).append(").add(").append(express)
.append(")");
// depends on control dependency: [if], data = [none]
if (packed) {
ret.append(";}").append(LINE_BREAK);
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
}
}
return ret.toString();
} else if (isMap) {
ret.append("Map __map = new HashMap()").append(JAVA_LINE_BREAK);
ret.append("FieldUtils.setField(").append(target).append(", \"").append(field.getName())
.append("\", __map)").append(JAVA_LINE_BREAK).append("}").append(LINE_BREAK);
return ret + express;
}
// use reflection to get value
String code = "";
if (express != null) {
code = "FieldUtils.setField(" + target + ", \"" + field.getName() + "\", " + express + ")" + LINE_BREAK;
}
return code;
} } |
public class class_name {
@Override
public void stop() {
synchronized (this) {
setStateAndNotify(State.STOPPING);
ArrayList<SubscriptionRecord> values = new ArrayList<>(subscriptions.values());
for (SubscriptionRecord subscription : values) {
doUnsubscribe(subscription.subscription);
}
disconnect(true);
}
} } | public class class_name {
@Override
public void stop() {
synchronized (this) {
setStateAndNotify(State.STOPPING);
ArrayList<SubscriptionRecord> values = new ArrayList<>(subscriptions.values());
for (SubscriptionRecord subscription : values) {
doUnsubscribe(subscription.subscription); // depends on control dependency: [for], data = [subscription]
}
disconnect(true);
}
} } |
public class class_name {
private boolean parameterIsAllowed(String name, String resourceType) {
switch (resourceType) {
case REMOTE_ACCEPTOR:
case HTTP_ACCEPTOR:
case REMOTE_CONNECTOR:
case HTTP_CONNECTOR:
// WFLY-5667 - for now remove only use-nio. Revisit this code when Artemis offers an API
// to know which parameters are ignored.
if ("use-nio".equals(name)) {
return false;
} else {
return true;
}
default:
// accept any parameter for other resources.
return true;
}
} } | public class class_name {
private boolean parameterIsAllowed(String name, String resourceType) {
switch (resourceType) {
case REMOTE_ACCEPTOR:
case HTTP_ACCEPTOR:
case REMOTE_CONNECTOR:
case HTTP_CONNECTOR:
// WFLY-5667 - for now remove only use-nio. Revisit this code when Artemis offers an API
// to know which parameters are ignored.
if ("use-nio".equals(name)) {
return false; // depends on control dependency: [if], data = [none]
} else {
return true; // depends on control dependency: [if], data = [none]
}
default:
// accept any parameter for other resources.
return true;
}
} } |
public class class_name {
public List<Attachment> getAttachmentsByForm(
Form formParam,
boolean includeAttachmentDataParam)
{
if(formParam != null && this.serviceTicket != null)
{
formParam.setServiceTicket(this.serviceTicket);
}
AttachmentListing returnedListing =
new AttachmentListing(postJson(
formParam, WS.Path.Attachment.Version1.getAllByFormContainer(
includeAttachmentDataParam,false)));
return (returnedListing == null) ? null :
returnedListing.getListing();
} } | public class class_name {
public List<Attachment> getAttachmentsByForm(
Form formParam,
boolean includeAttachmentDataParam)
{
if(formParam != null && this.serviceTicket != null)
{
formParam.setServiceTicket(this.serviceTicket); // depends on control dependency: [if], data = [none]
}
AttachmentListing returnedListing =
new AttachmentListing(postJson(
formParam, WS.Path.Attachment.Version1.getAllByFormContainer(
includeAttachmentDataParam,false)));
return (returnedListing == null) ? null :
returnedListing.getListing();
} } |
public class class_name {
public int getFieldsSendTotalByteSize(Object bean, Charset charset) {
if (!hasDynamicField()) {
return fieldsTotalSize;
} else {
return getDynamicTotalFieldSize(bean, charset);
}
} } | public class class_name {
public int getFieldsSendTotalByteSize(Object bean, Charset charset) {
if (!hasDynamicField()) {
return fieldsTotalSize; // depends on control dependency: [if], data = [none]
} else {
return getDynamicTotalFieldSize(bean, charset); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public int findIn(Source source) {
Matcher matcher = REGEX_AUTHORITY.matcher(source.subToEnd());
int offset = -1;
while (matcher.find()) {
int matcherPosition = source.getOffset() + matcher.start();
if (parseLength(source, matcherPosition, null) > 0) {
offset = matcherPosition;
break;
}
}
return offset;
} } | public class class_name {
@Override
public int findIn(Source source) {
Matcher matcher = REGEX_AUTHORITY.matcher(source.subToEnd());
int offset = -1;
while (matcher.find()) {
int matcherPosition = source.getOffset() + matcher.start();
if (parseLength(source, matcherPosition, null) > 0) {
offset = matcherPosition; // depends on control dependency: [if], data = [none]
break;
}
}
return offset;
} } |
public class class_name {
private void fillDensities(KNNQuery<O> knnq, DBIDs ids, WritableDoubleDataStore dens) {
FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Densities", ids.size(), LOG) : null;
for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
final KNNList neighbors = knnq.getKNNForDBID(iter, k);
dens.putDouble(iter, neighbors.getKNNDistance());
LOG.incrementProcessed(prog);
}
LOG.ensureCompleted(prog);
} } | public class class_name {
private void fillDensities(KNNQuery<O> knnq, DBIDs ids, WritableDoubleDataStore dens) {
FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Densities", ids.size(), LOG) : null;
for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
final KNNList neighbors = knnq.getKNNForDBID(iter, k);
dens.putDouble(iter, neighbors.getKNNDistance()); // depends on control dependency: [for], data = [iter]
LOG.incrementProcessed(prog); // depends on control dependency: [for], data = [none]
}
LOG.ensureCompleted(prog);
} } |
public class class_name {
protected void fireEvent(E event) {
for (L listener : this.listeners) {
try {
fireEvent(event, listener);
} catch (RuntimeException e) {
handleListenerError(listener, event, e);
}
}
} } | public class class_name {
protected void fireEvent(E event) {
for (L listener : this.listeners) {
try {
fireEvent(event, listener); // depends on control dependency: [try], data = [none]
} catch (RuntimeException e) {
handleListenerError(listener, event, e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private void extractFlags(GanttBarStyle style, GanttBarShowForTasks baseCriteria, long flagValue)
{
int index = 0;
long flag = 0x0001;
while (index < 64)
{
if ((flagValue & flag) != 0)
{
GanttBarShowForTasks enumValue = GanttBarShowForTasks.getInstance(baseCriteria.getValue() + index);
if (enumValue != null)
{
style.addShowForTasks(enumValue);
}
}
flag = flag << 1;
index++;
}
} } | public class class_name {
private void extractFlags(GanttBarStyle style, GanttBarShowForTasks baseCriteria, long flagValue)
{
int index = 0;
long flag = 0x0001;
while (index < 64)
{
if ((flagValue & flag) != 0)
{
GanttBarShowForTasks enumValue = GanttBarShowForTasks.getInstance(baseCriteria.getValue() + index);
if (enumValue != null)
{
style.addShowForTasks(enumValue); // depends on control dependency: [if], data = [(enumValue]
}
}
flag = flag << 1; // depends on control dependency: [while], data = [none]
index++; // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public void addTask(Object objJobDef)
{
synchronized (this)
{
if (objJobDef == CLEAR_JOBS)
{ // Dump all waiting jobs
m_vPrivateJobs.removeAllElements();
return;
}
m_vPrivateJobs.addElement(objJobDef);
if (m_bThreadSuspended)
{
synchronized(this)
{
m_bThreadSuspended = false; // Unsuspend this puppy
}
this.notify(); // Notify the job processor to continue
}
}
if (objJobDef == END_OF_JOBS)
Thread.yield(); // Give this task a chance to exit.
} } | public class class_name {
public void addTask(Object objJobDef)
{
synchronized (this)
{
if (objJobDef == CLEAR_JOBS)
{ // Dump all waiting jobs
m_vPrivateJobs.removeAllElements(); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
m_vPrivateJobs.addElement(objJobDef);
if (m_bThreadSuspended)
{
synchronized(this) // depends on control dependency: [if], data = [none]
{
m_bThreadSuspended = false; // Unsuspend this puppy
}
this.notify(); // Notify the job processor to continue // depends on control dependency: [if], data = [none]
}
}
if (objJobDef == END_OF_JOBS)
Thread.yield(); // Give this task a chance to exit.
} } |
public class class_name {
private final void checkForDeadConnections(final long now) {
final ArrayList<Pair<Connection, Integer>> connectionsToRemove = new ArrayList<Pair<Connection, Integer>>();
for (final ClientInterfaceHandleManager cihm : m_cihm.values()) {
// Internal connections don't implement calculatePendingWriteDelta(), so check for real connection first
if (VoltPort.class == cihm.connection.getClass()) {
final int delta = cihm.connection.writeStream().calculatePendingWriteDelta(now);
if (delta > CLIENT_HANGUP_TIMEOUT) {
connectionsToRemove.add(Pair.of(cihm.connection, delta));
}
}
}
for (final Pair<Connection, Integer> p : connectionsToRemove) {
Connection c = p.getFirst();
networkLog.warn("Closing connection to " + c +
" because it hasn't read a response that was pending for " + p.getSecond() + " milliseconds");
c.unregister();
}
} } | public class class_name {
private final void checkForDeadConnections(final long now) {
final ArrayList<Pair<Connection, Integer>> connectionsToRemove = new ArrayList<Pair<Connection, Integer>>();
for (final ClientInterfaceHandleManager cihm : m_cihm.values()) {
// Internal connections don't implement calculatePendingWriteDelta(), so check for real connection first
if (VoltPort.class == cihm.connection.getClass()) {
final int delta = cihm.connection.writeStream().calculatePendingWriteDelta(now);
if (delta > CLIENT_HANGUP_TIMEOUT) {
connectionsToRemove.add(Pair.of(cihm.connection, delta)); // depends on control dependency: [if], data = [none]
}
}
}
for (final Pair<Connection, Integer> p : connectionsToRemove) {
Connection c = p.getFirst();
networkLog.warn("Closing connection to " + c +
" because it hasn't read a response that was pending for " + p.getSecond() + " milliseconds"); // depends on control dependency: [for], data = [none]
c.unregister(); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public static CharSequence escapeMarkupId(final CharSequence markupId) {
Args.notNull(markupId, "markupId");
// create pattern for: !"#$%&'()*+,./:;<=>?@[\]^`{|}~
final StringCharacterIterator iterator = new StringCharacterIterator(markupId.toString());
final StringBuilder result = new StringBuilder((int) (markupId.length() * 1.5));
final String escape = "\\\\";
char c = iterator.current();
while (c != CharacterIterator.DONE) {
boolean escaped = false;
for (char x : ESCAPE_CHARS) {
if (x == c) {
result.append(escape).append(c);
escaped = true;
break;
}
}
if (!escaped) {
result.append(c);
}
c = iterator.next();
}
return result.toString();
} } | public class class_name {
public static CharSequence escapeMarkupId(final CharSequence markupId) {
Args.notNull(markupId, "markupId");
// create pattern for: !"#$%&'()*+,./:;<=>?@[\]^`{|}~
final StringCharacterIterator iterator = new StringCharacterIterator(markupId.toString());
final StringBuilder result = new StringBuilder((int) (markupId.length() * 1.5));
final String escape = "\\\\";
char c = iterator.current();
while (c != CharacterIterator.DONE) {
boolean escaped = false;
for (char x : ESCAPE_CHARS) {
if (x == c) {
result.append(escape).append(c); // depends on control dependency: [if], data = [c)]
escaped = true; // depends on control dependency: [if], data = [none]
break;
}
}
if (!escaped) {
result.append(c); // depends on control dependency: [if], data = [none]
}
c = iterator.next(); // depends on control dependency: [while], data = [none]
}
return result.toString();
} } |
public class class_name {
public static void generate(ConfigurationImpl configuration) {
HelpWriter helpgen;
DocPath filename = DocPath.empty;
try {
filename = DocPaths.HELP_DOC;
helpgen = new HelpWriter(configuration, filename);
helpgen.generateHelpFile();
helpgen.close();
} catch (IOException exc) {
configuration.standardmessage.error(
"doclet.exception_encountered",
exc.toString(), filename);
throw new DocletAbortException(exc);
}
} } | public class class_name {
public static void generate(ConfigurationImpl configuration) {
HelpWriter helpgen;
DocPath filename = DocPath.empty;
try {
filename = DocPaths.HELP_DOC; // depends on control dependency: [try], data = [none]
helpgen = new HelpWriter(configuration, filename); // depends on control dependency: [try], data = [none]
helpgen.generateHelpFile(); // depends on control dependency: [try], data = [none]
helpgen.close(); // depends on control dependency: [try], data = [none]
} catch (IOException exc) {
configuration.standardmessage.error(
"doclet.exception_encountered",
exc.toString(), filename);
throw new DocletAbortException(exc);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public java.util.List<String> getSnapshotIdentifierList() {
if (snapshotIdentifierList == null) {
snapshotIdentifierList = new com.amazonaws.internal.SdkInternalList<String>();
}
return snapshotIdentifierList;
} } | public class class_name {
public java.util.List<String> getSnapshotIdentifierList() {
if (snapshotIdentifierList == null) {
snapshotIdentifierList = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return snapshotIdentifierList;
} } |
public class class_name {
@Override
public void handle(ChangeConfigurationItemRequestedEvent event, CorrelationToken correlationToken) {
final boolean hasConfigurationChanged = chargingStationOcpp12Client.changeConfiguration(event.getChargingStationId(), event.getConfigurationItem());
if (hasConfigurationChanged) {
domainService.changeConfiguration(event.getChargingStationId(), event.getConfigurationItem(), correlationToken, addOnIdentity);
}
} } | public class class_name {
@Override
public void handle(ChangeConfigurationItemRequestedEvent event, CorrelationToken correlationToken) {
final boolean hasConfigurationChanged = chargingStationOcpp12Client.changeConfiguration(event.getChargingStationId(), event.getConfigurationItem());
if (hasConfigurationChanged) {
domainService.changeConfiguration(event.getChargingStationId(), event.getConfigurationItem(), correlationToken, addOnIdentity); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
protected void reserveInternal(int newCapacity) {
if (isArray() || type instanceof MapType) {
int[] newLengths = new int[newCapacity];
int[] newOffsets = new int[newCapacity];
if (this.arrayLengths != null) {
System.arraycopy(this.arrayLengths, 0, newLengths, 0, capacity);
System.arraycopy(this.arrayOffsets, 0, newOffsets, 0, capacity);
}
arrayLengths = newLengths;
arrayOffsets = newOffsets;
} else if (type instanceof BooleanType) {
if (byteData == null || byteData.length < newCapacity) {
byte[] newData = new byte[newCapacity];
if (byteData != null) System.arraycopy(byteData, 0, newData, 0, capacity);
byteData = newData;
}
} else if (type instanceof ByteType) {
if (byteData == null || byteData.length < newCapacity) {
byte[] newData = new byte[newCapacity];
if (byteData != null) System.arraycopy(byteData, 0, newData, 0, capacity);
byteData = newData;
}
} else if (type instanceof ShortType) {
if (shortData == null || shortData.length < newCapacity) {
short[] newData = new short[newCapacity];
if (shortData != null) System.arraycopy(shortData, 0, newData, 0, capacity);
shortData = newData;
}
} else if (type instanceof IntegerType || type instanceof DateType ||
DecimalType.is32BitDecimalType(type)) {
if (intData == null || intData.length < newCapacity) {
int[] newData = new int[newCapacity];
if (intData != null) System.arraycopy(intData, 0, newData, 0, capacity);
intData = newData;
}
} else if (type instanceof LongType || type instanceof TimestampType ||
DecimalType.is64BitDecimalType(type)) {
if (longData == null || longData.length < newCapacity) {
long[] newData = new long[newCapacity];
if (longData != null) System.arraycopy(longData, 0, newData, 0, capacity);
longData = newData;
}
} else if (type instanceof FloatType) {
if (floatData == null || floatData.length < newCapacity) {
float[] newData = new float[newCapacity];
if (floatData != null) System.arraycopy(floatData, 0, newData, 0, capacity);
floatData = newData;
}
} else if (type instanceof DoubleType) {
if (doubleData == null || doubleData.length < newCapacity) {
double[] newData = new double[newCapacity];
if (doubleData != null) System.arraycopy(doubleData, 0, newData, 0, capacity);
doubleData = newData;
}
} else if (childColumns != null) {
// Nothing to store.
} else {
throw new RuntimeException("Unhandled " + type);
}
byte[] newNulls = new byte[newCapacity];
if (nulls != null) System.arraycopy(nulls, 0, newNulls, 0, capacity);
nulls = newNulls;
capacity = newCapacity;
} } | public class class_name {
@Override
protected void reserveInternal(int newCapacity) {
if (isArray() || type instanceof MapType) {
int[] newLengths = new int[newCapacity];
int[] newOffsets = new int[newCapacity];
if (this.arrayLengths != null) {
System.arraycopy(this.arrayLengths, 0, newLengths, 0, capacity); // depends on control dependency: [if], data = [(this.arrayLengths]
System.arraycopy(this.arrayOffsets, 0, newOffsets, 0, capacity); // depends on control dependency: [if], data = [none]
}
arrayLengths = newLengths; // depends on control dependency: [if], data = [none]
arrayOffsets = newOffsets; // depends on control dependency: [if], data = [none]
} else if (type instanceof BooleanType) {
if (byteData == null || byteData.length < newCapacity) {
byte[] newData = new byte[newCapacity];
if (byteData != null) System.arraycopy(byteData, 0, newData, 0, capacity);
byteData = newData; // depends on control dependency: [if], data = [none]
}
} else if (type instanceof ByteType) {
if (byteData == null || byteData.length < newCapacity) {
byte[] newData = new byte[newCapacity];
if (byteData != null) System.arraycopy(byteData, 0, newData, 0, capacity);
byteData = newData; // depends on control dependency: [if], data = [none]
}
} else if (type instanceof ShortType) {
if (shortData == null || shortData.length < newCapacity) {
short[] newData = new short[newCapacity];
if (shortData != null) System.arraycopy(shortData, 0, newData, 0, capacity);
shortData = newData; // depends on control dependency: [if], data = [none]
}
} else if (type instanceof IntegerType || type instanceof DateType ||
DecimalType.is32BitDecimalType(type)) {
if (intData == null || intData.length < newCapacity) {
int[] newData = new int[newCapacity];
if (intData != null) System.arraycopy(intData, 0, newData, 0, capacity);
intData = newData; // depends on control dependency: [if], data = [none]
}
} else if (type instanceof LongType || type instanceof TimestampType ||
DecimalType.is64BitDecimalType(type)) {
if (longData == null || longData.length < newCapacity) {
long[] newData = new long[newCapacity];
if (longData != null) System.arraycopy(longData, 0, newData, 0, capacity);
longData = newData; // depends on control dependency: [if], data = [none]
}
} else if (type instanceof FloatType) {
if (floatData == null || floatData.length < newCapacity) {
float[] newData = new float[newCapacity];
if (floatData != null) System.arraycopy(floatData, 0, newData, 0, capacity);
floatData = newData; // depends on control dependency: [if], data = [none]
}
} else if (type instanceof DoubleType) {
if (doubleData == null || doubleData.length < newCapacity) {
double[] newData = new double[newCapacity];
if (doubleData != null) System.arraycopy(doubleData, 0, newData, 0, capacity);
doubleData = newData; // depends on control dependency: [if], data = [none]
}
} else if (childColumns != null) {
// Nothing to store.
} else {
throw new RuntimeException("Unhandled " + type);
}
byte[] newNulls = new byte[newCapacity];
if (nulls != null) System.arraycopy(nulls, 0, newNulls, 0, capacity);
nulls = newNulls;
capacity = newCapacity;
} } |
public class class_name {
protected void trackConnectionFinalizer(ConnectionHandle connectionHandle) {
if (!this.disableTracking){
// assert !connectionHandle.getPool().getFinalizableRefs().containsKey(connectionHandle) : "Already tracking this handle";
Connection con = connectionHandle.getInternalConnection();
if (con != null && con instanceof Proxy && Proxy.getInvocationHandler(con) instanceof MemorizeTransactionProxy){
try {
// if this is a proxy, get the correct target so that when we call close we're actually calling close on the database
// handle and not a proxy-based close.
con = (Connection) Proxy.getInvocationHandler(con).invoke(con, ConnectionHandle.class.getMethod("getProxyTarget"), null);
} catch (Throwable t) {
logger.error("Error while attempting to track internal db connection", t); // should never happen
}
}
final Connection internalDBConnection = con;
final BoneCP pool = connectionHandle.getPool();
connectionHandle.getPool().getFinalizableRefs().put(internalDBConnection, new FinalizableWeakReference<ConnectionHandle>(connectionHandle, connectionHandle.getPool().getFinalizableRefQueue()) {
@SuppressWarnings("synthetic-access")
public void finalizeReferent() {
try {
pool.getFinalizableRefs().remove(internalDBConnection);
if (internalDBConnection != null && !internalDBConnection.isClosed()){ // safety!
logger.warn("BoneCP detected an unclosed connection "+ConnectionPartition.this.poolName + "and will now attempt to close it for you. " +
"You should be closing this connection in your application - enable connectionWatch for additional debugging assistance or set disableConnectionTracking to true to disable this feature entirely.");
internalDBConnection.close();
updateCreatedConnections(-1);
}
} catch (Throwable t) {
logger.error("Error while closing off internal db connection", t);
}
}
});
}
} } | public class class_name {
protected void trackConnectionFinalizer(ConnectionHandle connectionHandle) {
if (!this.disableTracking){
// assert !connectionHandle.getPool().getFinalizableRefs().containsKey(connectionHandle) : "Already tracking this handle";
Connection con = connectionHandle.getInternalConnection();
if (con != null && con instanceof Proxy && Proxy.getInvocationHandler(con) instanceof MemorizeTransactionProxy){
try {
// if this is a proxy, get the correct target so that when we call close we're actually calling close on the database
// handle and not a proxy-based close.
con = (Connection) Proxy.getInvocationHandler(con).invoke(con, ConnectionHandle.class.getMethod("getProxyTarget"), null);
// depends on control dependency: [try], data = [none]
} catch (Throwable t) {
logger.error("Error while attempting to track internal db connection", t); // should never happen
}
// depends on control dependency: [catch], data = [none]
}
final Connection internalDBConnection = con;
final BoneCP pool = connectionHandle.getPool();
connectionHandle.getPool().getFinalizableRefs().put(internalDBConnection, new FinalizableWeakReference<ConnectionHandle>(connectionHandle, connectionHandle.getPool().getFinalizableRefQueue()) {
@SuppressWarnings("synthetic-access")
public void finalizeReferent() {
try {
pool.getFinalizableRefs().remove(internalDBConnection);
// depends on control dependency: [try], data = [none]
if (internalDBConnection != null && !internalDBConnection.isClosed()){ // safety!
logger.warn("BoneCP detected an unclosed connection "+ConnectionPartition.this.poolName + "and will now attempt to close it for you. " +
"You should be closing this connection in your application - enable connectionWatch for additional debugging assistance or set disableConnectionTracking to true to disable this feature entirely.");
// depends on control dependency: [if], data = [none]
internalDBConnection.close();
// depends on control dependency: [if], data = [none]
updateCreatedConnections(-1);
// depends on control dependency: [if], data = [none]
}
} catch (Throwable t) {
logger.error("Error while closing off internal db connection", t);
}
// depends on control dependency: [catch], data = [none]
}
});
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean process(Field onField, Object fieldOwnedBy, Set<Object> mockCandidates) {
if(processInjection(onField, fieldOwnedBy, mockCandidates)) {
return true;
}
return relayProcessToNextStrategy(onField, fieldOwnedBy, mockCandidates);
} } | public class class_name {
public boolean process(Field onField, Object fieldOwnedBy, Set<Object> mockCandidates) {
if(processInjection(onField, fieldOwnedBy, mockCandidates)) {
return true; // depends on control dependency: [if], data = [none]
}
return relayProcessToNextStrategy(onField, fieldOwnedBy, mockCandidates);
} } |
public class class_name {
public void dischargeAsEmpty(BitmapStorage container) {
while (size() > 0) {
container.addStreamOfEmptyWords(false, size());
discardFirstWords(size());
}
} } | public class class_name {
public void dischargeAsEmpty(BitmapStorage container) {
while (size() > 0) {
container.addStreamOfEmptyWords(false, size()); // depends on control dependency: [while], data = [none]
discardFirstWords(size()); // depends on control dependency: [while], data = [(size()]
}
} } |
public class class_name {
public void ensureCapacity(@NonNegative long maximumSize) {
requireArgument(maximumSize >= 0);
int maximum = (int) Math.min(maximumSize, Integer.MAX_VALUE >>> 1);
if ((table != null) && (table.length >= maximum)) {
return;
}
table = new long[(maximum == 0) ? 1 : ceilingNextPowerOfTwo(maximum)];
tableMask = Math.max(0, table.length - 1);
sampleSize = (maximumSize == 0) ? 10 : (10 * maximum);
if (sampleSize <= 0) {
sampleSize = Integer.MAX_VALUE;
}
size = 0;
} } | public class class_name {
public void ensureCapacity(@NonNegative long maximumSize) {
requireArgument(maximumSize >= 0);
int maximum = (int) Math.min(maximumSize, Integer.MAX_VALUE >>> 1);
if ((table != null) && (table.length >= maximum)) {
return; // depends on control dependency: [if], data = [none]
}
table = new long[(maximum == 0) ? 1 : ceilingNextPowerOfTwo(maximum)];
tableMask = Math.max(0, table.length - 1);
sampleSize = (maximumSize == 0) ? 10 : (10 * maximum);
if (sampleSize <= 0) {
sampleSize = Integer.MAX_VALUE; // depends on control dependency: [if], data = [none]
}
size = 0;
} } |
public class class_name {
public void ancestorAdded (AncestorEvent e)
{
gainedFocus();
if (_window == null) {
_window = SwingUtilities.getWindowAncestor(_target);
_window.addWindowFocusListener(this);
}
} } | public class class_name {
public void ancestorAdded (AncestorEvent e)
{
gainedFocus();
if (_window == null) {
_window = SwingUtilities.getWindowAncestor(_target); // depends on control dependency: [if], data = [none]
_window.addWindowFocusListener(this); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static final void translate (Structure structure, Vector3d v) {
for (int n=0; n<structure.nrModels();n++) {
for (Chain c : structure.getChains(n)) {
translate(c, v);
}
}
} } | public class class_name {
public static final void translate (Structure structure, Vector3d v) {
for (int n=0; n<structure.nrModels();n++) {
for (Chain c : structure.getChains(n)) {
translate(c, v); // depends on control dependency: [for], data = [c]
}
}
} } |
public class class_name {
public void flip(long startIndex, long endIndex)
{
if (endIndex <= startIndex) return;
int startWord = (int) (startIndex >> 6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = expandingWordNum(endIndex - 1);
long startmask = -1L << startIndex;
long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex
// due to wrap
if (startWord == endWord)
{
bits[startWord] ^= (startmask & endmask);
return;
}
bits[startWord] ^= startmask;
for (int i = startWord + 1; i < endWord; i++)
{
bits[i] = ~bits[i];
}
bits[endWord] ^= endmask;
} } | public class class_name {
public void flip(long startIndex, long endIndex)
{
if (endIndex <= startIndex) return;
int startWord = (int) (startIndex >> 6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = expandingWordNum(endIndex - 1);
long startmask = -1L << startIndex;
long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex
// due to wrap
if (startWord == endWord)
{
bits[startWord] ^= (startmask & endmask); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
bits[startWord] ^= startmask;
for (int i = startWord + 1; i < endWord; i++)
{
bits[i] = ~bits[i]; // depends on control dependency: [for], data = [i]
}
bits[endWord] ^= endmask;
} } |
public class class_name {
public static HSQLDDLInfo preprocessHSQLDDL(String ddl) {
ddl = SQLLexer.stripComments(ddl);
Matcher matcher = HSQL_DDL_PREPROCESSOR.matcher(ddl);
if (matcher.find()) {
String verbString = matcher.group("verb");
HSQLDDLInfo.Verb verb = HSQLDDLInfo.Verb.get(verbString);
if (verb == null) {
return null;
}
String nounString = matcher.group("object");
HSQLDDLInfo.Noun noun = HSQLDDLInfo.Noun.get(nounString);
if (noun == null) {
return null;
}
boolean createStream = verb.equals(HSQLDDLInfo.Verb.CREATE) &&
noun.equals(HSQLDDLInfo.Noun.STREAM);
String name = matcher.group("name");
if (name == null) {
return null;
}
String secondName = matcher.group("subject");
if (secondName != null) {
secondName = secondName.toLowerCase();
}
// cascade/if exists are interesting on alters and drops
boolean cascade = false;
boolean ifexists = false;
if (verb != HSQLDDLInfo.Verb.CREATE) {
matcher = DDL_IFEXISTS_OR_CASCADE_CHECK.matcher(ddl);
if (matcher.matches()) {
// Don't be too sensitive to regex specifics by assuming null always
// indicates a missing clause. Look for empty too.
String existsClause = matcher.group("exists");
String cascadeClause = matcher.group("cascade");
ifexists = existsClause != null && !existsClause.isEmpty();
cascade = cascadeClause != null && !cascadeClause.isEmpty();
}
}
return new HSQLDDLInfo(verb, noun, name.toLowerCase(), secondName, cascade, ifexists, createStream);
}
return null;
} } | public class class_name {
public static HSQLDDLInfo preprocessHSQLDDL(String ddl) {
ddl = SQLLexer.stripComments(ddl);
Matcher matcher = HSQL_DDL_PREPROCESSOR.matcher(ddl);
if (matcher.find()) {
String verbString = matcher.group("verb");
HSQLDDLInfo.Verb verb = HSQLDDLInfo.Verb.get(verbString);
if (verb == null) {
return null; // depends on control dependency: [if], data = [none]
}
String nounString = matcher.group("object");
HSQLDDLInfo.Noun noun = HSQLDDLInfo.Noun.get(nounString);
if (noun == null) {
return null; // depends on control dependency: [if], data = [none]
}
boolean createStream = verb.equals(HSQLDDLInfo.Verb.CREATE) &&
noun.equals(HSQLDDLInfo.Noun.STREAM);
String name = matcher.group("name");
if (name == null) {
return null; // depends on control dependency: [if], data = [none]
}
String secondName = matcher.group("subject");
if (secondName != null) {
secondName = secondName.toLowerCase(); // depends on control dependency: [if], data = [none]
}
// cascade/if exists are interesting on alters and drops
boolean cascade = false;
boolean ifexists = false;
if (verb != HSQLDDLInfo.Verb.CREATE) {
matcher = DDL_IFEXISTS_OR_CASCADE_CHECK.matcher(ddl); // depends on control dependency: [if], data = [none]
if (matcher.matches()) {
// Don't be too sensitive to regex specifics by assuming null always
// indicates a missing clause. Look for empty too.
String existsClause = matcher.group("exists");
String cascadeClause = matcher.group("cascade");
ifexists = existsClause != null && !existsClause.isEmpty(); // depends on control dependency: [if], data = [none]
cascade = cascadeClause != null && !cascadeClause.isEmpty(); // depends on control dependency: [if], data = [none]
}
}
return new HSQLDDLInfo(verb, noun, name.toLowerCase(), secondName, cascade, ifexists, createStream); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public JBBPOut Byte(final String str, final JBBPBitOrder bitOrder) throws IOException {
assertNotEnded();
assertStringNotNull(str);
if (this.processCommands) {
for (int i = 0; i < str.length(); i++) {
byte value = (byte) str.charAt(i);
if (bitOrder == JBBPBitOrder.MSB0) {
value = JBBPUtils.reverseBitsInByte(value);
}
this.outStream.write(value);
}
}
return this;
} } | public class class_name {
public JBBPOut Byte(final String str, final JBBPBitOrder bitOrder) throws IOException {
assertNotEnded();
assertStringNotNull(str);
if (this.processCommands) {
for (int i = 0; i < str.length(); i++) {
byte value = (byte) str.charAt(i);
if (bitOrder == JBBPBitOrder.MSB0) {
value = JBBPUtils.reverseBitsInByte(value); // depends on control dependency: [if], data = [none]
}
this.outStream.write(value); // depends on control dependency: [for], data = [none]
}
}
return this;
} } |
public class class_name {
private void buildSheetConfigMapFromFormCommand(final Sheet sheet,
final Map<String, SheetConfiguration> sheetConfigMap, final List<ConfigCommand> commandList,
final List<String> formList, final int sheetRightCol) {
boolean foundForm = false;
int minRowNum = sheet.getLastRowNum();
int maxRowNum = sheet.getFirstRowNum();
for (Command command : commandList) {
// check whether is form command
if (command.getCommandTypeName().equalsIgnoreCase(TieConstants.COMMAND_FORM)) {
foundForm = true;
FormCommand fcommand = (FormCommand) command;
sheetConfigMap.put(fcommand.getName(),
getSheetConfigurationFromConfigCommand(sheet, fcommand, sheetRightCol));
formList.add(fcommand.getName());
if (fcommand.getTopRow() < minRowNum) {
minRowNum = fcommand.getTopRow();
}
if (fcommand.getLastRow() > maxRowNum) {
maxRowNum = fcommand.getLastRow();
}
}
}
// if no form found, then use the whole sheet as form
if (!foundForm) {
WebSheetUtility.clearHiddenColumns(sheet);
String formName = sheet.getSheetName();
SheetConfiguration sheetConfig = getSheetConfiguration(sheet, formName, sheetRightCol);
FormCommand fcommand = buildFormCommandFromSheetConfig(sheetConfig, sheet);
commandList.add(fcommand);
sheetConfig.setFormCommand(fcommand);
sheetConfigMap.put(formName, sheetConfig);
formList.add(formName);
minRowNum = sheet.getFirstRowNum();
maxRowNum = sheet.getLastRowNum();
}
// if skip config then return.
if (parent.isSkipConfiguration()) {
return;
}
SaveAttrsUtility.setSaveAttrsForSheet(sheet, minRowNum, maxRowNum,
parent.getCellAttributesMap().getTemplateCommentMap().get(TieConstants.SAVE_COMMENT_KEY_IN_MAP));
} } | public class class_name {
private void buildSheetConfigMapFromFormCommand(final Sheet sheet,
final Map<String, SheetConfiguration> sheetConfigMap, final List<ConfigCommand> commandList,
final List<String> formList, final int sheetRightCol) {
boolean foundForm = false;
int minRowNum = sheet.getLastRowNum();
int maxRowNum = sheet.getFirstRowNum();
for (Command command : commandList) {
// check whether is form command
if (command.getCommandTypeName().equalsIgnoreCase(TieConstants.COMMAND_FORM)) {
foundForm = true;
// depends on control dependency: [if], data = [none]
FormCommand fcommand = (FormCommand) command;
sheetConfigMap.put(fcommand.getName(),
getSheetConfigurationFromConfigCommand(sheet, fcommand, sheetRightCol));
// depends on control dependency: [if], data = [none]
formList.add(fcommand.getName());
// depends on control dependency: [if], data = [none]
if (fcommand.getTopRow() < minRowNum) {
minRowNum = fcommand.getTopRow();
// depends on control dependency: [if], data = [none]
}
if (fcommand.getLastRow() > maxRowNum) {
maxRowNum = fcommand.getLastRow();
// depends on control dependency: [if], data = [none]
}
}
}
// if no form found, then use the whole sheet as form
if (!foundForm) {
WebSheetUtility.clearHiddenColumns(sheet);
// depends on control dependency: [if], data = [none]
String formName = sheet.getSheetName();
SheetConfiguration sheetConfig = getSheetConfiguration(sheet, formName, sheetRightCol);
FormCommand fcommand = buildFormCommandFromSheetConfig(sheetConfig, sheet);
commandList.add(fcommand);
// depends on control dependency: [if], data = [none]
sheetConfig.setFormCommand(fcommand);
// depends on control dependency: [if], data = [none]
sheetConfigMap.put(formName, sheetConfig);
// depends on control dependency: [if], data = [none]
formList.add(formName);
// depends on control dependency: [if], data = [none]
minRowNum = sheet.getFirstRowNum();
// depends on control dependency: [if], data = [none]
maxRowNum = sheet.getLastRowNum();
// depends on control dependency: [if], data = [none]
}
// if skip config then return.
if (parent.isSkipConfiguration()) {
return;
// depends on control dependency: [if], data = [none]
}
SaveAttrsUtility.setSaveAttrsForSheet(sheet, minRowNum, maxRowNum,
parent.getCellAttributesMap().getTemplateCommentMap().get(TieConstants.SAVE_COMMENT_KEY_IN_MAP));
} } |
public class class_name {
public boolean addAll(Collection<? extends E> c)
{
Iterator<? extends E> cIterator = c.iterator();
while(cIterator.hasNext())
{
this.add(cIterator.next());
}
return true;
} } | public class class_name {
public boolean addAll(Collection<? extends E> c)
{
Iterator<? extends E> cIterator = c.iterator();
while(cIterator.hasNext())
{
this.add(cIterator.next()); // depends on control dependency: [while], data = [none]
}
return true;
} } |
public class class_name {
public void applyIndexes(VocabCache<? extends SequenceElement> cache) {
if (!buildTrigger)
build();
for (int a = 0; a < words.size(); a++) {
if (words.get(a).getLabel() != null) {
cache.addWordToIndex(a, words.get(a).getLabel());
} else {
cache.addWordToIndex(a, words.get(a).getStorageId());
}
words.get(a).setIndex(a);
}
} } | public class class_name {
public void applyIndexes(VocabCache<? extends SequenceElement> cache) {
if (!buildTrigger)
build();
for (int a = 0; a < words.size(); a++) {
if (words.get(a).getLabel() != null) {
cache.addWordToIndex(a, words.get(a).getLabel()); // depends on control dependency: [if], data = [none]
} else {
cache.addWordToIndex(a, words.get(a).getStorageId()); // depends on control dependency: [if], data = [none]
}
words.get(a).setIndex(a); // depends on control dependency: [for], data = [a]
}
} } |
public class class_name {
StringVector processSTRINGLIST(StylesheetHandler handler, String uri,
String name, String rawName, String value)
{
StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
int nStrings = tokenizer.countTokens();
StringVector strings = new StringVector(nStrings);
for (int i = 0; i < nStrings; i++)
{
strings.addElement(tokenizer.nextToken());
}
return strings;
} } | public class class_name {
StringVector processSTRINGLIST(StylesheetHandler handler, String uri,
String name, String rawName, String value)
{
StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f");
int nStrings = tokenizer.countTokens();
StringVector strings = new StringVector(nStrings);
for (int i = 0; i < nStrings; i++)
{
strings.addElement(tokenizer.nextToken()); // depends on control dependency: [for], data = [none]
}
return strings;
} } |
public class class_name {
public ServiceCall<Collection> createCollection(CreateCollectionOptions createCollectionOptions) {
Validator.notNull(createCollectionOptions, "createCollectionOptions cannot be null");
String[] pathSegments = { "v1/environments", "collections" };
String[] pathParameters = { createCollectionOptions.environmentId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("discovery", "v1", "createCollection");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
final JsonObject contentJson = new JsonObject();
contentJson.addProperty("name", createCollectionOptions.name());
if (createCollectionOptions.description() != null) {
contentJson.addProperty("description", createCollectionOptions.description());
}
if (createCollectionOptions.configurationId() != null) {
contentJson.addProperty("configuration_id", createCollectionOptions.configurationId());
}
if (createCollectionOptions.language() != null) {
contentJson.addProperty("language", createCollectionOptions.language());
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Collection.class));
} } | public class class_name {
public ServiceCall<Collection> createCollection(CreateCollectionOptions createCollectionOptions) {
Validator.notNull(createCollectionOptions, "createCollectionOptions cannot be null");
String[] pathSegments = { "v1/environments", "collections" };
String[] pathParameters = { createCollectionOptions.environmentId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("discovery", "v1", "createCollection");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue()); // depends on control dependency: [for], data = [header]
}
builder.header("Accept", "application/json");
final JsonObject contentJson = new JsonObject();
contentJson.addProperty("name", createCollectionOptions.name());
if (createCollectionOptions.description() != null) {
contentJson.addProperty("description", createCollectionOptions.description()); // depends on control dependency: [if], data = [none]
}
if (createCollectionOptions.configurationId() != null) {
contentJson.addProperty("configuration_id", createCollectionOptions.configurationId()); // depends on control dependency: [if], data = [none]
}
if (createCollectionOptions.language() != null) {
contentJson.addProperty("language", createCollectionOptions.language()); // depends on control dependency: [if], data = [none]
}
builder.bodyJson(contentJson);
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Collection.class));
} } |
public class class_name {
public static String getMajorName(String path) {
int len = path.length();
int l = 0;
int r = len;
for (int i = r - 1; i > 0; i--) {
if (r == len)
if (path.charAt(i) == '.') {
r = i;
}
if (path.charAt(i) == '/' || path.charAt(i) == '\\') {
l = i + 1;
break;
}
}
return path.substring(l, r);
} } | public class class_name {
public static String getMajorName(String path) {
int len = path.length();
int l = 0;
int r = len;
for (int i = r - 1; i > 0; i--) {
if (r == len)
if (path.charAt(i) == '.') {
r = i;
// depends on control dependency: [if], data = [none]
}
if (path.charAt(i) == '/' || path.charAt(i) == '\\') {
l = i + 1;
// depends on control dependency: [if], data = [none]
break;
}
}
return path.substring(l, r);
} } |
public class class_name {
@Override
public IRoSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientRoSession.class)) {
ClientRoSessionDataReplicatedImpl data =
new ClientRoSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
return data;
}
else if (clazz.equals(ServerRoSession.class)) {
ServerRoSessionDataReplicatedImpl data = new ServerRoSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
throw new IllegalArgumentException();
} } | public class class_name {
@Override
public IRoSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientRoSession.class)) {
ClientRoSessionDataReplicatedImpl data =
new ClientRoSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
return data;
// depends on control dependency: [if], data = [none]
}
else if (clazz.equals(ServerRoSession.class)) {
ServerRoSessionDataReplicatedImpl data = new ServerRoSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
// depends on control dependency: [if], data = [none]
}
throw new IllegalArgumentException();
} } |
public class class_name {
private Pair<List<DCTree>, List<DCTree>> splitBody(Collection<? extends DocTree> list) {
// pos is modified as we create trees, therefore
// we save the pos and restore it later.
final int savedpos = this.pos;
try {
ListBuffer<DCTree> body = new ListBuffer<>();
// split body into first sentence and body
ListBuffer<DCTree> fs = new ListBuffer<>();
if (list.isEmpty()) {
return new Pair<>(fs.toList(), body.toList());
}
boolean foundFirstSentence = false;
ArrayList<DocTree> alist = new ArrayList<>(list);
ListIterator<DocTree> itr = alist.listIterator();
while (itr.hasNext()) {
boolean isFirst = !itr.hasPrevious();
DocTree dt = itr.next();
int spos = ((DCTree) dt).pos;
if (foundFirstSentence) {
body.add((DCTree) dt);
continue;
}
switch (dt.getKind()) {
case TEXT:
DCText tt = (DCText) dt;
String s = tt.getBody();
DocTree peekedNext = itr.hasNext()
? alist.get(itr.nextIndex())
: null;
int sbreak = getSentenceBreak(s, peekedNext);
if (sbreak > 0) {
s = removeTrailingWhitespace(s.substring(0, sbreak));
DCText text = this.at(spos).newTextTree(s);
fs.add(text);
foundFirstSentence = true;
int nwPos = skipWhiteSpace(tt.getBody(), sbreak);
if (nwPos > 0) {
DCText text2 = this.at(spos + nwPos).newTextTree(tt.getBody().substring(nwPos));
body.add(text2);
}
continue;
} else if (itr.hasNext()) {
// if the next doctree is a break, remove trailing spaces
peekedNext = alist.get(itr.nextIndex());
boolean sbrk = isSentenceBreak(peekedNext, false);
if (sbrk) {
DocTree next = itr.next();
s = removeTrailingWhitespace(s);
DCText text = this.at(spos).newTextTree(s);
fs.add(text);
body.add((DCTree) next);
foundFirstSentence = true;
continue;
}
}
break;
default:
if (isSentenceBreak(dt, isFirst)) {
body.add((DCTree) dt);
foundFirstSentence = true;
continue;
}
break;
}
fs.add((DCTree) dt);
}
return new Pair<>(fs.toList(), body.toList());
} finally {
this.pos = savedpos;
}
} } | public class class_name {
private Pair<List<DCTree>, List<DCTree>> splitBody(Collection<? extends DocTree> list) {
// pos is modified as we create trees, therefore
// we save the pos and restore it later.
final int savedpos = this.pos;
try {
ListBuffer<DCTree> body = new ListBuffer<>();
// split body into first sentence and body
ListBuffer<DCTree> fs = new ListBuffer<>();
if (list.isEmpty()) {
return new Pair<>(fs.toList(), body.toList()); // depends on control dependency: [if], data = [none]
}
boolean foundFirstSentence = false;
ArrayList<DocTree> alist = new ArrayList<>(list);
ListIterator<DocTree> itr = alist.listIterator();
while (itr.hasNext()) {
boolean isFirst = !itr.hasPrevious();
DocTree dt = itr.next();
int spos = ((DCTree) dt).pos;
if (foundFirstSentence) {
body.add((DCTree) dt); // depends on control dependency: [if], data = [none]
continue;
}
switch (dt.getKind()) {
case TEXT:
DCText tt = (DCText) dt;
String s = tt.getBody();
DocTree peekedNext = itr.hasNext()
? alist.get(itr.nextIndex())
: null;
int sbreak = getSentenceBreak(s, peekedNext);
if (sbreak > 0) {
s = removeTrailingWhitespace(s.substring(0, sbreak)); // depends on control dependency: [if], data = [none]
DCText text = this.at(spos).newTextTree(s);
fs.add(text); // depends on control dependency: [if], data = [none]
foundFirstSentence = true; // depends on control dependency: [if], data = [none]
int nwPos = skipWhiteSpace(tt.getBody(), sbreak);
if (nwPos > 0) {
DCText text2 = this.at(spos + nwPos).newTextTree(tt.getBody().substring(nwPos));
body.add(text2); // depends on control dependency: [if], data = [none]
}
continue;
} else if (itr.hasNext()) {
// if the next doctree is a break, remove trailing spaces
peekedNext = alist.get(itr.nextIndex()); // depends on control dependency: [if], data = [none]
boolean sbrk = isSentenceBreak(peekedNext, false);
if (sbrk) {
DocTree next = itr.next();
s = removeTrailingWhitespace(s); // depends on control dependency: [if], data = [none]
DCText text = this.at(spos).newTextTree(s);
fs.add(text); // depends on control dependency: [if], data = [none]
body.add((DCTree) next); // depends on control dependency: [if], data = [none]
foundFirstSentence = true; // depends on control dependency: [if], data = [none]
continue;
}
}
break;
default:
if (isSentenceBreak(dt, isFirst)) {
body.add((DCTree) dt); // depends on control dependency: [if], data = [none]
foundFirstSentence = true; // depends on control dependency: [if], data = [none]
continue;
}
break;
}
fs.add((DCTree) dt); // depends on control dependency: [try], data = [none]
}
return new Pair<>(fs.toList(), body.toList());
} finally {
this.pos = savedpos;
}
} } |
public class class_name {
private boolean remoteViewerActive() {
if (remoteQueue == null) {
return false;
}
if (!remoteQueue.isAlive()) {
remoteQueue = null;
return false;
}
return true;
} } | public class class_name {
private boolean remoteViewerActive() {
if (remoteQueue == null) {
return false; // depends on control dependency: [if], data = [none]
}
if (!remoteQueue.isAlive()) {
remoteQueue = null; // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.