code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
public static Pair<? extends UndoAction, TheHashinator> updateHashinator(
Class<? extends TheHashinator> hashinatorImplementation,
long version,
byte configBytes[],
boolean cooked) {
//Use a cached/canonical hashinator if possible
TheHashinator existingHashinator = m_cachedHashinators.get(version);
if (existingHashinator == null) {
existingHashinator = constructHashinator(hashinatorImplementation, configBytes, cooked);
TheHashinator tempVal = m_cachedHashinators.putIfAbsent( version, existingHashinator);
if (tempVal != null) {
existingHashinator = tempVal;
}
}
//Do a CAS loop to maintain a global instance
while (true) {
final Pair<Long, ? extends TheHashinator> snapshot = instance.get();
if (version > snapshot.getFirst()) {
final Pair<Long, ? extends TheHashinator> update =
Pair.of(version, existingHashinator);
if (instance.compareAndSet(snapshot, update)) {
if (!m_elasticallyModified) {
if (!update.getSecond().pIsPristine()) {
// This is not a lock protected (atomic) but it should be fine because
// release() should only be called by the one thread that successfully
// updated the hashinator
hostLogger.debug("The Hashinator has been elastically modified.");
m_elasticallyModified = true;
}
}
// Note: Only undo is ever called and only from a failure in @BalancePartitions
return Pair.of(new UndoAction() {
@Override
public void release() {}
@Override
public void undo() {
boolean rolledBack = instance.compareAndSet(update, snapshot);
if (!rolledBack) {
hostLogger.info(
"Didn't roll back hashinator because it wasn't set to expected hashinator");
}
}
}, existingHashinator);
}
} else {
return Pair.of(new UndoAction() {
@Override
public void release() {}
@Override
public void undo() {}
}, existingHashinator);
}
}
} } | public class class_name {
public static Pair<? extends UndoAction, TheHashinator> updateHashinator(
Class<? extends TheHashinator> hashinatorImplementation,
long version,
byte configBytes[],
boolean cooked) {
//Use a cached/canonical hashinator if possible
TheHashinator existingHashinator = m_cachedHashinators.get(version);
if (existingHashinator == null) {
existingHashinator = constructHashinator(hashinatorImplementation, configBytes, cooked); // depends on control dependency: [if], data = [none]
TheHashinator tempVal = m_cachedHashinators.putIfAbsent( version, existingHashinator);
if (tempVal != null) {
existingHashinator = tempVal; // depends on control dependency: [if], data = [none]
}
}
//Do a CAS loop to maintain a global instance
while (true) {
final Pair<Long, ? extends TheHashinator> snapshot = instance.get();
if (version > snapshot.getFirst()) {
final Pair<Long, ? extends TheHashinator> update =
Pair.of(version, existingHashinator);
if (instance.compareAndSet(snapshot, update)) {
if (!m_elasticallyModified) {
if (!update.getSecond().pIsPristine()) {
// This is not a lock protected (atomic) but it should be fine because
// release() should only be called by the one thread that successfully
// updated the hashinator
hostLogger.debug("The Hashinator has been elastically modified."); // depends on control dependency: [if], data = [none]
m_elasticallyModified = true; // depends on control dependency: [if], data = [none]
}
}
// Note: Only undo is ever called and only from a failure in @BalancePartitions
return Pair.of(new UndoAction() {
@Override
public void release() {}
@Override
public void undo() {
boolean rolledBack = instance.compareAndSet(update, snapshot);
if (!rolledBack) {
hostLogger.info(
"Didn't roll back hashinator because it wasn't set to expected hashinator"); // depends on control dependency: [if], data = [none]
}
}
}, existingHashinator); // depends on control dependency: [if], data = [none]
}
} else {
return Pair.of(new UndoAction() {
@Override
public void release() {}
@Override
public void undo() {}
}, existingHashinator); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private HamtPMap<K, V> minus(K key, int hash, V[] value) {
if (hash == this.hash && key.equals(this.key)) {
HamtPMap<K, V> result = deleteRoot(mask, children);
if (value != null) {
value[0] = this.value;
}
return result != null ? result : empty();
}
int bucket = bucket(hash);
int bucketMask = 1 << bucket;
if ((mask & bucketMask) == 0) {
// not present, stop looking
return this;
}
hash = shift(hash);
int index = index(bucketMask);
HamtPMap<K, V> child = children[index];
HamtPMap<K, V> newChild = child.minus(key, hash, value);
if (newChild == child) {
return this;
} else if (newChild == EMPTY) {
return withChildren(mask & ~bucketMask, deleteChild(children, index));
} else {
return withChildren(mask, replaceChild(children, index, newChild));
}
} } | public class class_name {
private HamtPMap<K, V> minus(K key, int hash, V[] value) {
if (hash == this.hash && key.equals(this.key)) {
HamtPMap<K, V> result = deleteRoot(mask, children);
if (value != null) {
value[0] = this.value; // depends on control dependency: [if], data = [none]
}
return result != null ? result : empty(); // depends on control dependency: [if], data = [none]
}
int bucket = bucket(hash);
int bucketMask = 1 << bucket;
if ((mask & bucketMask) == 0) {
// not present, stop looking
return this; // depends on control dependency: [if], data = [none]
}
hash = shift(hash);
int index = index(bucketMask);
HamtPMap<K, V> child = children[index];
HamtPMap<K, V> newChild = child.minus(key, hash, value);
if (newChild == child) {
return this; // depends on control dependency: [if], data = [none]
} else if (newChild == EMPTY) {
return withChildren(mask & ~bucketMask, deleteChild(children, index)); // depends on control dependency: [if], data = [none]
} else {
return withChildren(mask, replaceChild(children, index, newChild)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected void ensureInflated() {
if (compressed != null) {
try {
ByteArrayInputStream deflated = new ByteArrayInputStream(compressed);
DataInput inflater =
new DataInputStream(new InflaterInputStream(deflated));
readFieldsCompressed(inflater);
compressed = null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} } | public class class_name {
protected void ensureInflated() {
if (compressed != null) {
try {
ByteArrayInputStream deflated = new ByteArrayInputStream(compressed);
DataInput inflater =
new DataInputStream(new InflaterInputStream(deflated));
readFieldsCompressed(inflater); // depends on control dependency: [try], data = [none]
compressed = null; // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public static SymbolTable initialSymtab(_Private_LocalSymbolTableFactory lstFactory,
SymbolTable defaultSystemSymtab,
SymbolTable... imports)
{
if (imports == null || imports.length == 0)
{
return defaultSystemSymtab;
}
if (imports.length == 1 && imports[0].isSystemTable())
{
return imports[0];
}
return lstFactory.newLocalSymtab(defaultSystemSymtab, imports);
} } | public class class_name {
public static SymbolTable initialSymtab(_Private_LocalSymbolTableFactory lstFactory,
SymbolTable defaultSystemSymtab,
SymbolTable... imports)
{
if (imports == null || imports.length == 0)
{
return defaultSystemSymtab; // depends on control dependency: [if], data = [none]
}
if (imports.length == 1 && imports[0].isSystemTable())
{
return imports[0]; // depends on control dependency: [if], data = [none]
}
return lstFactory.newLocalSymtab(defaultSystemSymtab, imports);
} } |
public class class_name {
@Override
public CommerceTaxFixedRate fetchByC_C(long CPTaxCategoryId,
long commerceTaxMethodId, boolean retrieveFromCache) {
Object[] finderArgs = new Object[] { CPTaxCategoryId, commerceTaxMethodId };
Object result = null;
if (retrieveFromCache) {
result = finderCache.getResult(FINDER_PATH_FETCH_BY_C_C,
finderArgs, this);
}
if (result instanceof CommerceTaxFixedRate) {
CommerceTaxFixedRate commerceTaxFixedRate = (CommerceTaxFixedRate)result;
if ((CPTaxCategoryId != commerceTaxFixedRate.getCPTaxCategoryId()) ||
(commerceTaxMethodId != commerceTaxFixedRate.getCommerceTaxMethodId())) {
result = null;
}
}
if (result == null) {
StringBundler query = new StringBundler(4);
query.append(_SQL_SELECT_COMMERCETAXFIXEDRATE_WHERE);
query.append(_FINDER_COLUMN_C_C_CPTAXCATEGORYID_2);
query.append(_FINDER_COLUMN_C_C_COMMERCETAXMETHODID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(CPTaxCategoryId);
qPos.add(commerceTaxMethodId);
List<CommerceTaxFixedRate> list = q.list();
if (list.isEmpty()) {
finderCache.putResult(FINDER_PATH_FETCH_BY_C_C, finderArgs,
list);
}
else {
CommerceTaxFixedRate commerceTaxFixedRate = list.get(0);
result = commerceTaxFixedRate;
cacheResult(commerceTaxFixedRate);
}
}
catch (Exception e) {
finderCache.removeResult(FINDER_PATH_FETCH_BY_C_C, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
if (result instanceof List<?>) {
return null;
}
else {
return (CommerceTaxFixedRate)result;
}
} } | public class class_name {
@Override
public CommerceTaxFixedRate fetchByC_C(long CPTaxCategoryId,
long commerceTaxMethodId, boolean retrieveFromCache) {
Object[] finderArgs = new Object[] { CPTaxCategoryId, commerceTaxMethodId };
Object result = null;
if (retrieveFromCache) {
result = finderCache.getResult(FINDER_PATH_FETCH_BY_C_C,
finderArgs, this); // depends on control dependency: [if], data = [none]
}
if (result instanceof CommerceTaxFixedRate) {
CommerceTaxFixedRate commerceTaxFixedRate = (CommerceTaxFixedRate)result;
if ((CPTaxCategoryId != commerceTaxFixedRate.getCPTaxCategoryId()) ||
(commerceTaxMethodId != commerceTaxFixedRate.getCommerceTaxMethodId())) {
result = null; // depends on control dependency: [if], data = [none]
}
}
if (result == null) {
StringBundler query = new StringBundler(4);
query.append(_SQL_SELECT_COMMERCETAXFIXEDRATE_WHERE); // depends on control dependency: [if], data = [none]
query.append(_FINDER_COLUMN_C_C_CPTAXCATEGORYID_2); // depends on control dependency: [if], data = [none]
query.append(_FINDER_COLUMN_C_C_COMMERCETAXMETHODID_2); // depends on control dependency: [if], data = [none]
String sql = query.toString();
Session session = null;
try {
session = openSession(); // depends on control dependency: [try], data = [none]
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(CPTaxCategoryId); // depends on control dependency: [try], data = [none]
qPos.add(commerceTaxMethodId); // depends on control dependency: [try], data = [none]
List<CommerceTaxFixedRate> list = q.list();
if (list.isEmpty()) {
finderCache.putResult(FINDER_PATH_FETCH_BY_C_C, finderArgs,
list); // depends on control dependency: [if], data = [none]
}
else {
CommerceTaxFixedRate commerceTaxFixedRate = list.get(0);
result = commerceTaxFixedRate; // depends on control dependency: [if], data = [none]
cacheResult(commerceTaxFixedRate); // depends on control dependency: [if], data = [none]
}
}
catch (Exception e) {
finderCache.removeResult(FINDER_PATH_FETCH_BY_C_C, finderArgs);
throw processException(e);
} // depends on control dependency: [catch], data = [none]
finally {
closeSession(session);
}
}
if (result instanceof List<?>) {
return null; // depends on control dependency: [if], data = [none]
}
else {
return (CommerceTaxFixedRate)result; // depends on control dependency: [if], data = [)]
}
} } |
public class class_name {
@Override
public Collection<String> getAppliesToMinimumVersions() {
Collection<String> versions = new HashSet<String>();
try {
List<AppliesToFilterInfo> entries = generateAppliesToFilterInfoList(false);
if (entries != null) {
for (AppliesToFilterInfo appliesToFilterInfo : entries) {
FilterVersion minVersion = appliesToFilterInfo.getMinVersion();
if (minVersion != null) {
versions.add(minVersion.toString());
}
}
}
} catch (RepositoryResourceCreationException e) {
// Impossible as we don't validate the applies to
}
return versions;
} } | public class class_name {
@Override
public Collection<String> getAppliesToMinimumVersions() {
Collection<String> versions = new HashSet<String>();
try {
List<AppliesToFilterInfo> entries = generateAppliesToFilterInfoList(false);
if (entries != null) {
for (AppliesToFilterInfo appliesToFilterInfo : entries) {
FilterVersion minVersion = appliesToFilterInfo.getMinVersion();
if (minVersion != null) {
versions.add(minVersion.toString()); // depends on control dependency: [if], data = [(minVersion]
}
}
}
} catch (RepositoryResourceCreationException e) {
// Impossible as we don't validate the applies to
} // depends on control dependency: [catch], data = [none]
return versions;
} } |
public class class_name {
public JBBPTextWriter DelExtras(final Extra... extras) {
JBBPUtils.assertNotNull(extras, "Extras must not be null");
for (final Extra e : extras) {
JBBPUtils.assertNotNull(e, "Extras must not be null");
this.extras.remove(e);
}
return this;
} } | public class class_name {
public JBBPTextWriter DelExtras(final Extra... extras) {
JBBPUtils.assertNotNull(extras, "Extras must not be null");
for (final Extra e : extras) {
JBBPUtils.assertNotNull(e, "Extras must not be null"); // depends on control dependency: [for], data = [e]
this.extras.remove(e); // depends on control dependency: [for], data = [e]
}
return this;
} } |
public class class_name {
public Command get(String commandName, boolean forceCreate) {
Command command = commands.get(commandName);
if (command == null && forceCreate) {
command = new Command(commandName);
add(command);
}
return command;
} } | public class class_name {
public Command get(String commandName, boolean forceCreate) {
Command command = commands.get(commandName);
if (command == null && forceCreate) {
command = new Command(commandName); // depends on control dependency: [if], data = [(command]
add(command); // depends on control dependency: [if], data = [(command]
}
return command;
} } |
public class class_name {
protected boolean addSortColumn( QueryContext context,
PlanNode node,
Column sortColumn ) {
boolean added = false;
if (node.getSelectors().contains(sortColumn.selectorName())) {
// Get the existing projected columns ...
List<Column> columns = node.getPropertyAsList(Property.PROJECT_COLUMNS, Column.class);
List<String> types = node.getPropertyAsList(Property.PROJECT_COLUMN_TYPES, String.class);
if (columns != null && addIfMissing(context, sortColumn, columns, types)) {
node.setProperty(Property.PROJECT_COLUMNS, columns);
node.setProperty(Property.PROJECT_COLUMN_TYPES, types);
added = true;
}
}
// Apply recursively ...
for (PlanNode child : node) {
addSortColumn(context, child, sortColumn);
}
if (node.is(Type.SORT)) {
// Get the child node, which should be a PROJECT ...
PlanNode child = node.findAtOrBelow(Type.PROJECT);
if (child != null && !child.getSelectors().contains(sortColumn.selectorName())) {
// Make sure the PROJECT includes the missing columns, even when the selector is not included ...
List<Column> columns = child.getPropertyAsList(Property.PROJECT_COLUMNS, Column.class);
List<String> types = child.getPropertyAsList(Property.PROJECT_COLUMN_TYPES, String.class);
if (columns != null && addIfMissing(context, sortColumn, columns, types)) {
child.setProperty(Property.PROJECT_COLUMNS, columns);
child.setProperty(Property.PROJECT_COLUMN_TYPES, types);
added = true;
}
}
}
return added;
} } | public class class_name {
protected boolean addSortColumn( QueryContext context,
PlanNode node,
Column sortColumn ) {
boolean added = false;
if (node.getSelectors().contains(sortColumn.selectorName())) {
// Get the existing projected columns ...
List<Column> columns = node.getPropertyAsList(Property.PROJECT_COLUMNS, Column.class);
List<String> types = node.getPropertyAsList(Property.PROJECT_COLUMN_TYPES, String.class);
if (columns != null && addIfMissing(context, sortColumn, columns, types)) {
node.setProperty(Property.PROJECT_COLUMNS, columns); // depends on control dependency: [if], data = [none]
node.setProperty(Property.PROJECT_COLUMN_TYPES, types); // depends on control dependency: [if], data = [none]
added = true; // depends on control dependency: [if], data = [none]
}
}
// Apply recursively ...
for (PlanNode child : node) {
addSortColumn(context, child, sortColumn); // depends on control dependency: [for], data = [child]
}
if (node.is(Type.SORT)) {
// Get the child node, which should be a PROJECT ...
PlanNode child = node.findAtOrBelow(Type.PROJECT);
if (child != null && !child.getSelectors().contains(sortColumn.selectorName())) {
// Make sure the PROJECT includes the missing columns, even when the selector is not included ...
List<Column> columns = child.getPropertyAsList(Property.PROJECT_COLUMNS, Column.class);
List<String> types = child.getPropertyAsList(Property.PROJECT_COLUMN_TYPES, String.class);
if (columns != null && addIfMissing(context, sortColumn, columns, types)) {
child.setProperty(Property.PROJECT_COLUMNS, columns); // depends on control dependency: [if], data = [none]
child.setProperty(Property.PROJECT_COLUMN_TYPES, types); // depends on control dependency: [if], data = [none]
added = true; // depends on control dependency: [if], data = [none]
}
}
}
return added;
} } |
public class class_name {
public SerIterable createIterable(MetaProperty<?> prop, Class<?> beanClass, boolean allowPrimitiveArrays) {
if (allowPrimitiveArrays &&
prop.propertyType().isArray() &&
prop.propertyType().getComponentType().isPrimitive() &&
prop.propertyType().getComponentType() != byte.class) {
return arrayPrimitive(prop.propertyType().getComponentType());
}
return createIterable(prop, beanClass);
} } | public class class_name {
public SerIterable createIterable(MetaProperty<?> prop, Class<?> beanClass, boolean allowPrimitiveArrays) {
if (allowPrimitiveArrays &&
prop.propertyType().isArray() &&
prop.propertyType().getComponentType().isPrimitive() &&
prop.propertyType().getComponentType() != byte.class) {
return arrayPrimitive(prop.propertyType().getComponentType()); // depends on control dependency: [if], data = [none]
}
return createIterable(prop, beanClass);
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static Object coerceToSAM(Closure argument, Method method, Class clazz, boolean isInterface) {
if (argument!=null && clazz.isAssignableFrom(argument.getClass())) {
return argument;
}
if (isInterface) {
if (Traits.isTrait(clazz)) {
Map<String,Closure> impl = Collections.singletonMap(
method.getName(),
argument
);
return ProxyGenerator.INSTANCE.instantiateAggregate(impl,Collections.singletonList(clazz));
}
return Proxy.newProxyInstance(
clazz.getClassLoader(),
new Class[]{clazz},
new ConvertedClosure(argument));
} else {
Map<String, Object> m = new HashMap<String,Object>();
m.put(method.getName(), argument);
return ProxyGenerator.INSTANCE.
instantiateAggregateFromBaseClass(m, clazz);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public static Object coerceToSAM(Closure argument, Method method, Class clazz, boolean isInterface) {
if (argument!=null && clazz.isAssignableFrom(argument.getClass())) {
return argument; // depends on control dependency: [if], data = [none]
}
if (isInterface) {
if (Traits.isTrait(clazz)) {
Map<String,Closure> impl = Collections.singletonMap(
method.getName(),
argument
);
return ProxyGenerator.INSTANCE.instantiateAggregate(impl,Collections.singletonList(clazz)); // depends on control dependency: [if], data = [none]
}
return Proxy.newProxyInstance(
clazz.getClassLoader(),
new Class[]{clazz},
new ConvertedClosure(argument)); // depends on control dependency: [if], data = [none]
} else {
Map<String, Object> m = new HashMap<String,Object>();
m.put(method.getName(), argument); // depends on control dependency: [if], data = [none]
return ProxyGenerator.INSTANCE.
instantiateAggregateFromBaseClass(m, clazz); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public EClass getIfcFontWeight() {
if (ifcFontWeightEClass == null) {
ifcFontWeightEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(678);
}
return ifcFontWeightEClass;
} } | public class class_name {
public EClass getIfcFontWeight() {
if (ifcFontWeightEClass == null) {
ifcFontWeightEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(678);
// depends on control dependency: [if], data = [none]
}
return ifcFontWeightEClass;
} } |
public class class_name {
public void updatePermissions() {
final String[] accessViewerList =
this.accessViewer.trim().split(ACCESS_LIST_SPLIT_REGEX);
final String[] accessExecutorList =
this.accessExecutor.trim().split(ACCESS_LIST_SPLIT_REGEX);
final String[] accessOwnerList =
this.accessOwner.trim().split(ACCESS_LIST_SPLIT_REGEX);
// Prepare permission types
final Permission admin = new Permission();
admin.addPermission(Type.READ);
admin.addPermission(Type.EXECUTE);
admin.addPermission(Type.ADMIN);
final Permission executor = new Permission();
executor.addPermission(Type.READ);
executor.addPermission(Type.EXECUTE);
final Permission viewer = new Permission();
viewer.addPermission(Type.READ);
// Sets the permissions
this.project.clearUserPermission();
for (String user : accessViewerList) {
user = user.trim();
if (!user.isEmpty()) {
this.project.setUserPermission(user, viewer);
}
}
for (String user : accessExecutorList) {
user = user.trim();
if (!user.isEmpty()) {
this.project.setUserPermission(user, executor);
}
}
for (String user : accessOwnerList) {
user = user.trim();
if (!user.isEmpty()) {
this.project.setUserPermission(user, admin);
}
}
this.project.setUserPermission(this.reportalUser, admin);
} } | public class class_name {
public void updatePermissions() {
final String[] accessViewerList =
this.accessViewer.trim().split(ACCESS_LIST_SPLIT_REGEX);
final String[] accessExecutorList =
this.accessExecutor.trim().split(ACCESS_LIST_SPLIT_REGEX);
final String[] accessOwnerList =
this.accessOwner.trim().split(ACCESS_LIST_SPLIT_REGEX);
// Prepare permission types
final Permission admin = new Permission();
admin.addPermission(Type.READ);
admin.addPermission(Type.EXECUTE);
admin.addPermission(Type.ADMIN);
final Permission executor = new Permission();
executor.addPermission(Type.READ);
executor.addPermission(Type.EXECUTE);
final Permission viewer = new Permission();
viewer.addPermission(Type.READ);
// Sets the permissions
this.project.clearUserPermission();
for (String user : accessViewerList) {
user = user.trim(); // depends on control dependency: [for], data = [user]
if (!user.isEmpty()) {
this.project.setUserPermission(user, viewer); // depends on control dependency: [if], data = [none]
}
}
for (String user : accessExecutorList) {
user = user.trim(); // depends on control dependency: [for], data = [user]
if (!user.isEmpty()) {
this.project.setUserPermission(user, executor); // depends on control dependency: [if], data = [none]
}
}
for (String user : accessOwnerList) {
user = user.trim(); // depends on control dependency: [for], data = [user]
if (!user.isEmpty()) {
this.project.setUserPermission(user, admin); // depends on control dependency: [if], data = [none]
}
}
this.project.setUserPermission(this.reportalUser, admin);
} } |
public class class_name {
public java.util.List<String> getServiceNames() {
if (serviceNames == null) {
serviceNames = new com.amazonaws.internal.SdkInternalList<String>();
}
return serviceNames;
} } | public class class_name {
public java.util.List<String> getServiceNames() {
if (serviceNames == null) {
serviceNames = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return serviceNames;
} } |
public class class_name {
public void analyseWC(final WComponent comp) {
if (comp == null) {
return;
}
statsByWCTree.put(comp, createWCTreeStats(comp));
} } | public class class_name {
public void analyseWC(final WComponent comp) {
if (comp == null) {
return; // depends on control dependency: [if], data = [none]
}
statsByWCTree.put(comp, createWCTreeStats(comp));
} } |
public class class_name {
public static <T, U> JavaPairRDD<T, U>[] balancedRandomSplit(int totalObjectCount, int numObjectsPerSplit,
JavaPairRDD<T, U> data, long rngSeed) {
JavaPairRDD<T, U>[] splits;
if (totalObjectCount <= numObjectsPerSplit) {
splits = (JavaPairRDD<T, U>[]) Array.newInstance(JavaPairRDD.class, 1);
splits[0] = data;
} else {
int numSplits = totalObjectCount / numObjectsPerSplit; //Intentional round down
splits = (JavaPairRDD<T, U>[]) Array.newInstance(JavaPairRDD.class, numSplits);
for (int i = 0; i < numSplits; i++) {
//What we really need is a .mapPartitionsToPairWithIndex function
//but, of course Spark doesn't provide this
//So we need to do a two-step process here...
JavaRDD<Tuple2<T, U>> split = data.mapPartitionsWithIndex(
new SplitPartitionsFunction2<T, U>(i, numSplits, rngSeed), true);
splits[i] = split.mapPartitionsToPair(new MapTupleToPairFlatMap<T, U>(), true);
}
}
return splits;
} } | public class class_name {
public static <T, U> JavaPairRDD<T, U>[] balancedRandomSplit(int totalObjectCount, int numObjectsPerSplit,
JavaPairRDD<T, U> data, long rngSeed) {
JavaPairRDD<T, U>[] splits;
if (totalObjectCount <= numObjectsPerSplit) {
splits = (JavaPairRDD<T, U>[]) Array.newInstance(JavaPairRDD.class, 1); // depends on control dependency: [if], data = [none]
splits[0] = data; // depends on control dependency: [if], data = [none]
} else {
int numSplits = totalObjectCount / numObjectsPerSplit; //Intentional round down
splits = (JavaPairRDD<T, U>[]) Array.newInstance(JavaPairRDD.class, numSplits); // depends on control dependency: [if], data = [none]
for (int i = 0; i < numSplits; i++) {
//What we really need is a .mapPartitionsToPairWithIndex function
//but, of course Spark doesn't provide this
//So we need to do a two-step process here...
JavaRDD<Tuple2<T, U>> split = data.mapPartitionsWithIndex(
new SplitPartitionsFunction2<T, U>(i, numSplits, rngSeed), true);
splits[i] = split.mapPartitionsToPair(new MapTupleToPairFlatMap<T, U>(), true); // depends on control dependency: [for], data = [i]
}
}
return splits;
} } |
public class class_name {
public XMLGregorianCalendar newXMLGregorianCalendar(
final int year,
final int month,
final int day,
final int hour,
final int minute,
final int second,
final int millisecond,
final int timezone) {
// year may be undefined
BigInteger realYear = (year != DatatypeConstants.FIELD_UNDEFINED) ? BigInteger.valueOf((long) year) : null;
// millisecond may be undefined
// millisecond must be >= 0 millisecond <= 1000
BigDecimal realMillisecond = null; // undefined value
if (millisecond != DatatypeConstants.FIELD_UNDEFINED) {
if (millisecond < 0 || millisecond > 1000) {
throw new IllegalArgumentException(
"javax.xml.datatype.DatatypeFactory#newXMLGregorianCalendar("
+ "int year, int month, int day, int hour, int minute, int second, int millisecond, int timezone)"
+ "with invalid millisecond: " + millisecond
);
}
realMillisecond = BigDecimal.valueOf((long) millisecond, 3);
}
return newXMLGregorianCalendar(
realYear,
month,
day,
hour,
minute,
second,
realMillisecond,
timezone
);
} } | public class class_name {
public XMLGregorianCalendar newXMLGregorianCalendar(
final int year,
final int month,
final int day,
final int hour,
final int minute,
final int second,
final int millisecond,
final int timezone) {
// year may be undefined
BigInteger realYear = (year != DatatypeConstants.FIELD_UNDEFINED) ? BigInteger.valueOf((long) year) : null;
// millisecond may be undefined
// millisecond must be >= 0 millisecond <= 1000
BigDecimal realMillisecond = null; // undefined value
if (millisecond != DatatypeConstants.FIELD_UNDEFINED) {
if (millisecond < 0 || millisecond > 1000) {
throw new IllegalArgumentException(
"javax.xml.datatype.DatatypeFactory#newXMLGregorianCalendar("
+ "int year, int month, int day, int hour, int minute, int second, int millisecond, int timezone)"
+ "with invalid millisecond: " + millisecond
);
}
realMillisecond = BigDecimal.valueOf((long) millisecond, 3); // depends on control dependency: [if], data = [none]
}
return newXMLGregorianCalendar(
realYear,
month,
day,
hour,
minute,
second,
realMillisecond,
timezone
);
} } |
public class class_name {
@MustBeLocked (ELockType.WRITE)
protected final void internalMarkItemDeleted (@Nonnull final IMPLTYPE aItem, final boolean bInvokeCallbacks)
{
// Trigger save changes
super.markAsChanged (aItem, EDAOActionType.UPDATE);
if (bInvokeCallbacks)
{
// Invoke callbacks
m_aCallbacks.forEach (aCB -> aCB.onMarkItemDeleted (aItem));
}
} } | public class class_name {
@MustBeLocked (ELockType.WRITE)
protected final void internalMarkItemDeleted (@Nonnull final IMPLTYPE aItem, final boolean bInvokeCallbacks)
{
// Trigger save changes
super.markAsChanged (aItem, EDAOActionType.UPDATE);
if (bInvokeCallbacks)
{
// Invoke callbacks
m_aCallbacks.forEach (aCB -> aCB.onMarkItemDeleted (aItem)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(CreateUserRequest createUserRequest, ProtocolMarshaller protocolMarshaller) {
if (createUserRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createUserRequest.getOrganizationId(), ORGANIZATIONID_BINDING);
protocolMarshaller.marshall(createUserRequest.getUsername(), USERNAME_BINDING);
protocolMarshaller.marshall(createUserRequest.getEmailAddress(), EMAILADDRESS_BINDING);
protocolMarshaller.marshall(createUserRequest.getGivenName(), GIVENNAME_BINDING);
protocolMarshaller.marshall(createUserRequest.getSurname(), SURNAME_BINDING);
protocolMarshaller.marshall(createUserRequest.getPassword(), PASSWORD_BINDING);
protocolMarshaller.marshall(createUserRequest.getTimeZoneId(), TIMEZONEID_BINDING);
protocolMarshaller.marshall(createUserRequest.getStorageRule(), STORAGERULE_BINDING);
protocolMarshaller.marshall(createUserRequest.getAuthenticationToken(), AUTHENTICATIONTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateUserRequest createUserRequest, ProtocolMarshaller protocolMarshaller) {
if (createUserRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createUserRequest.getOrganizationId(), ORGANIZATIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createUserRequest.getUsername(), USERNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createUserRequest.getEmailAddress(), EMAILADDRESS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createUserRequest.getGivenName(), GIVENNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createUserRequest.getSurname(), SURNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createUserRequest.getPassword(), PASSWORD_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createUserRequest.getTimeZoneId(), TIMEZONEID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createUserRequest.getStorageRule(), STORAGERULE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createUserRequest.getAuthenticationToken(), AUTHENTICATIONTOKEN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String[] toStringArray(final Object value) {
if (value == null) {
return new String[0];
}
Class<?> type = value.getClass();
if (!type.isArray()) {
return new String[] {value.toString()};
}
Class componentType = type.getComponentType();
if (componentType.isPrimitive()) {
if (componentType == int.class) {
return ArraysUtil.toStringArray((int[]) value);
}
else if (componentType == long.class) {
return ArraysUtil.toStringArray((long[]) value);
}
else if (componentType == double.class) {
return ArraysUtil.toStringArray((double[]) value);
}
else if (componentType == float.class) {
return ArraysUtil.toStringArray((float[]) value);
}
else if (componentType == boolean.class) {
return ArraysUtil.toStringArray((boolean[]) value);
}
else if (componentType == short.class) {
return ArraysUtil.toStringArray((short[]) value);
}
else if (componentType == byte.class) {
return ArraysUtil.toStringArray((byte[]) value);
}
else {
throw new IllegalArgumentException();
}
}
else {
return ArraysUtil.toStringArray((Object[]) value);
}
} } | public class class_name {
public static String[] toStringArray(final Object value) {
if (value == null) {
return new String[0]; // depends on control dependency: [if], data = [none]
}
Class<?> type = value.getClass();
if (!type.isArray()) {
return new String[] {value.toString()}; // depends on control dependency: [if], data = [none]
}
Class componentType = type.getComponentType();
if (componentType.isPrimitive()) {
if (componentType == int.class) {
return ArraysUtil.toStringArray((int[]) value); // depends on control dependency: [if], data = [none]
}
else if (componentType == long.class) {
return ArraysUtil.toStringArray((long[]) value); // depends on control dependency: [if], data = [none]
}
else if (componentType == double.class) {
return ArraysUtil.toStringArray((double[]) value); // depends on control dependency: [if], data = [none]
}
else if (componentType == float.class) {
return ArraysUtil.toStringArray((float[]) value); // depends on control dependency: [if], data = [none]
}
else if (componentType == boolean.class) {
return ArraysUtil.toStringArray((boolean[]) value); // depends on control dependency: [if], data = [none]
}
else if (componentType == short.class) {
return ArraysUtil.toStringArray((short[]) value); // depends on control dependency: [if], data = [none]
}
else if (componentType == byte.class) {
return ArraysUtil.toStringArray((byte[]) value); // depends on control dependency: [if], data = [none]
}
else {
throw new IllegalArgumentException();
}
}
else {
return ArraysUtil.toStringArray((Object[]) value); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private String processCatalogName(String dbProvideName, String userName, String catalogName) {
String result = null;
if (catalogName != null) {
result = catalogName.toUpperCase();
} else {
if ("Oracle".equals(dbProvideName) == true) {
// SPRING: Oracle uses catalog name for package name or an empty string if no package
result = "";
}
}
return result;
} } | public class class_name {
private String processCatalogName(String dbProvideName, String userName, String catalogName) {
String result = null;
if (catalogName != null) {
result = catalogName.toUpperCase();
// depends on control dependency: [if], data = [none]
} else {
if ("Oracle".equals(dbProvideName) == true) {
// SPRING: Oracle uses catalog name for package name or an empty string if no package
result = "";
// depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
protected synchronized Collection<T> findAllInstances() {
if (this.allInstances == null) {
this.allInstances = new ArrayList<>();
ServiceLocator serviceLocator = Scope.getCurrentScope().getServiceLocator();
this.allInstances.addAll(serviceLocator.findInstances(getPluginClass()));
}
return this.allInstances;
} } | public class class_name {
protected synchronized Collection<T> findAllInstances() {
if (this.allInstances == null) {
this.allInstances = new ArrayList<>(); // depends on control dependency: [if], data = [none]
ServiceLocator serviceLocator = Scope.getCurrentScope().getServiceLocator();
this.allInstances.addAll(serviceLocator.findInstances(getPluginClass())); // depends on control dependency: [if], data = [none]
}
return this.allInstances;
} } |
public class class_name {
public final void arrayInitializer() throws RecognitionException {
try {
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:5: ( LEFT_CURLY ( variableInitializer ( COMMA variableInitializer )* ( COMMA )? )? RIGHT_CURLY )
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:7: LEFT_CURLY ( variableInitializer ( COMMA variableInitializer )* ( COMMA )? )? RIGHT_CURLY
{
match(input,LEFT_CURLY,FOLLOW_LEFT_CURLY_in_arrayInitializer3669); if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:18: ( variableInitializer ( COMMA variableInitializer )* ( COMMA )? )?
int alt79=2;
int LA79_0 = input.LA(1);
if ( (LA79_0==BOOL||(LA79_0 >= DECIMAL && LA79_0 <= DECR)||LA79_0==FLOAT||LA79_0==HEX||(LA79_0 >= ID && LA79_0 <= INCR)||(LA79_0 >= LEFT_CURLY && LA79_0 <= LESS)||LA79_0==MINUS||LA79_0==NEGATION||LA79_0==NULL||LA79_0==PLUS||(LA79_0 >= STAR && LA79_0 <= TIME_INTERVAL)) ) {
alt79=1;
}
switch (alt79) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:19: variableInitializer ( COMMA variableInitializer )* ( COMMA )?
{
pushFollow(FOLLOW_variableInitializer_in_arrayInitializer3672);
variableInitializer();
state._fsp--;
if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:39: ( COMMA variableInitializer )*
loop77:
while (true) {
int alt77=2;
int LA77_0 = input.LA(1);
if ( (LA77_0==COMMA) ) {
int LA77_1 = input.LA(2);
if ( (LA77_1==BOOL||(LA77_1 >= DECIMAL && LA77_1 <= DECR)||LA77_1==FLOAT||LA77_1==HEX||(LA77_1 >= ID && LA77_1 <= INCR)||(LA77_1 >= LEFT_CURLY && LA77_1 <= LESS)||LA77_1==MINUS||LA77_1==NEGATION||LA77_1==NULL||LA77_1==PLUS||(LA77_1 >= STAR && LA77_1 <= TIME_INTERVAL)) ) {
alt77=1;
}
}
switch (alt77) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:40: COMMA variableInitializer
{
match(input,COMMA,FOLLOW_COMMA_in_arrayInitializer3675); if (state.failed) return;
pushFollow(FOLLOW_variableInitializer_in_arrayInitializer3677);
variableInitializer();
state._fsp--;
if (state.failed) return;
}
break;
default :
break loop77;
}
}
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:68: ( COMMA )?
int alt78=2;
int LA78_0 = input.LA(1);
if ( (LA78_0==COMMA) ) {
alt78=1;
}
switch (alt78) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:69: COMMA
{
match(input,COMMA,FOLLOW_COMMA_in_arrayInitializer3682); if (state.failed) return;
}
break;
}
}
break;
}
match(input,RIGHT_CURLY,FOLLOW_RIGHT_CURLY_in_arrayInitializer3689); if (state.failed) return;
}
}
catch (RecognitionException re) {
throw re;
}
finally {
// do for sure before leaving
}
} } | public class class_name {
public final void arrayInitializer() throws RecognitionException {
try {
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:5: ( LEFT_CURLY ( variableInitializer ( COMMA variableInitializer )* ( COMMA )? )? RIGHT_CURLY )
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:7: LEFT_CURLY ( variableInitializer ( COMMA variableInitializer )* ( COMMA )? )? RIGHT_CURLY
{
match(input,LEFT_CURLY,FOLLOW_LEFT_CURLY_in_arrayInitializer3669); if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:18: ( variableInitializer ( COMMA variableInitializer )* ( COMMA )? )?
int alt79=2;
int LA79_0 = input.LA(1);
if ( (LA79_0==BOOL||(LA79_0 >= DECIMAL && LA79_0 <= DECR)||LA79_0==FLOAT||LA79_0==HEX||(LA79_0 >= ID && LA79_0 <= INCR)||(LA79_0 >= LEFT_CURLY && LA79_0 <= LESS)||LA79_0==MINUS||LA79_0==NEGATION||LA79_0==NULL||LA79_0==PLUS||(LA79_0 >= STAR && LA79_0 <= TIME_INTERVAL)) ) {
alt79=1;
}
switch (alt79) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:19: variableInitializer ( COMMA variableInitializer )* ( COMMA )?
{
pushFollow(FOLLOW_variableInitializer_in_arrayInitializer3672);
variableInitializer();
state._fsp--;
if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:39: ( COMMA variableInitializer )*
loop77:
while (true) {
int alt77=2;
int LA77_0 = input.LA(1);
if ( (LA77_0==COMMA) ) {
int LA77_1 = input.LA(2);
if ( (LA77_1==BOOL||(LA77_1 >= DECIMAL && LA77_1 <= DECR)||LA77_1==FLOAT||LA77_1==HEX||(LA77_1 >= ID && LA77_1 <= INCR)||(LA77_1 >= LEFT_CURLY && LA77_1 <= LESS)||LA77_1==MINUS||LA77_1==NEGATION||LA77_1==NULL||LA77_1==PLUS||(LA77_1 >= STAR && LA77_1 <= TIME_INTERVAL)) ) {
alt77=1; // depends on control dependency: [if], data = [none]
}
}
switch (alt77) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:40: COMMA variableInitializer
{
match(input,COMMA,FOLLOW_COMMA_in_arrayInitializer3675); if (state.failed) return;
pushFollow(FOLLOW_variableInitializer_in_arrayInitializer3677);
variableInitializer();
state._fsp--;
if (state.failed) return;
}
break;
default :
break loop77;
}
}
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:68: ( COMMA )?
int alt78=2;
int LA78_0 = input.LA(1);
if ( (LA78_0==COMMA) ) {
alt78=1; // depends on control dependency: [if], data = [none]
}
switch (alt78) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:631:69: COMMA
{
match(input,COMMA,FOLLOW_COMMA_in_arrayInitializer3682); if (state.failed) return;
}
break;
}
}
break;
}
match(input,RIGHT_CURLY,FOLLOW_RIGHT_CURLY_in_arrayInitializer3689); if (state.failed) return;
}
}
catch (RecognitionException re) {
throw re;
}
finally {
// do for sure before leaving
}
} } |
public class class_name {
public Item withAttributes(Attribute... attributes) {
if (this.attributes == null) {
setAttributes(new com.amazonaws.internal.SdkInternalList<Attribute>(attributes.length));
}
for (Attribute ele : attributes) {
this.attributes.add(ele);
}
return this;
} } | public class class_name {
public Item withAttributes(Attribute... attributes) {
if (this.attributes == null) {
setAttributes(new com.amazonaws.internal.SdkInternalList<Attribute>(attributes.length)); // depends on control dependency: [if], data = [none]
}
for (Attribute ele : attributes) {
this.attributes.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private void processWebModulePersistenceXml(JPAApplInfo applInfo, ContainerInfo warContainerInfo, ClassLoader warClassLoader) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled()) {
Tr.entry(tc, "processWebModulePersistenceXml : " + applInfo.getApplName() + "#" + warContainerInfo);
}
String archiveName = warContainerInfo.getName();
Container warContainer = warContainerInfo.getContainer();
// ------------------------------------------------------------------------
// JPA 2.0 Specification - 8.2 Persistence Unit Packaging
//
// A persistence unit is defined by a persistence.xml file. The jar file or
// directory whose META-INF directory contains the persistence.xml file is
// termed the root of the persistence unit. In Java EE environments, the
// root of a persistence unit may be one of the following:
//
// -> the WEB-INF/classes directory of a WAR file
// -> a jar file in the WEB-INF/lib directory of a WAR file
// ------------------------------------------------------------------------
// Obtain any persistence.xml in WEB-INF/classes/META-INF
Entry pxml = warContainer.getEntry("WEB-INF/classes/META-INF/persistence.xml");
if (pxml != null) {
String appName = applInfo.getApplName();
URL puRoot = getPXmlRootURL(appName, archiveName, pxml);
applInfo.addPersistenceUnits(new OSGiJPAPXml(applInfo, archiveName, JPAPuScope.Web_Scope, puRoot, warClassLoader, pxml));
}
// Obtain any persistenc.xml in WEB-INF/lib/*.jar. This includes 'utility'
// jars and web fragments. Any PUs found are WEB scoped and considered to
// be in the WAR, so just use the WAR archiveName (don't use a root prefix
// that is prepended to the jar/fragment name).
Entry webInfLib = warContainer.getEntry("WEB-INF/lib/");
if (webInfLib != null) {
try {
Container webInfLibContainer = webInfLib.adapt(Container.class);
processLibraryJarPersistenceXml(applInfo, webInfLibContainer, archiveName, null, JPAPuScope.Web_Scope, warClassLoader);
} catch (UnableToAdaptException ex) {
// Should never occur... just propagate failure
throw new RuntimeException("Failure locating persistence.xml", ex);
}
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "processWebModulePersistenceXml : " + applInfo.getApplName() +
"#" + warContainer);
} } | public class class_name {
private void processWebModulePersistenceXml(JPAApplInfo applInfo, ContainerInfo warContainerInfo, ClassLoader warClassLoader) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled()) {
Tr.entry(tc, "processWebModulePersistenceXml : " + applInfo.getApplName() + "#" + warContainerInfo); // depends on control dependency: [if], data = [none]
}
String archiveName = warContainerInfo.getName();
Container warContainer = warContainerInfo.getContainer();
// ------------------------------------------------------------------------
// JPA 2.0 Specification - 8.2 Persistence Unit Packaging
//
// A persistence unit is defined by a persistence.xml file. The jar file or
// directory whose META-INF directory contains the persistence.xml file is
// termed the root of the persistence unit. In Java EE environments, the
// root of a persistence unit may be one of the following:
//
// -> the WEB-INF/classes directory of a WAR file
// -> a jar file in the WEB-INF/lib directory of a WAR file
// ------------------------------------------------------------------------
// Obtain any persistence.xml in WEB-INF/classes/META-INF
Entry pxml = warContainer.getEntry("WEB-INF/classes/META-INF/persistence.xml");
if (pxml != null) {
String appName = applInfo.getApplName();
URL puRoot = getPXmlRootURL(appName, archiveName, pxml);
applInfo.addPersistenceUnits(new OSGiJPAPXml(applInfo, archiveName, JPAPuScope.Web_Scope, puRoot, warClassLoader, pxml));
}
// Obtain any persistenc.xml in WEB-INF/lib/*.jar. This includes 'utility'
// jars and web fragments. Any PUs found are WEB scoped and considered to
// be in the WAR, so just use the WAR archiveName (don't use a root prefix
// that is prepended to the jar/fragment name).
Entry webInfLib = warContainer.getEntry("WEB-INF/lib/");
if (webInfLib != null) {
try {
Container webInfLibContainer = webInfLib.adapt(Container.class);
processLibraryJarPersistenceXml(applInfo, webInfLibContainer, archiveName, null, JPAPuScope.Web_Scope, warClassLoader);
} catch (UnableToAdaptException ex) {
// Should never occur... just propagate failure
throw new RuntimeException("Failure locating persistence.xml", ex);
}
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "processWebModulePersistenceXml : " + applInfo.getApplName() +
"#" + warContainer);
} } |
public class class_name {
@Override
public boolean booleanValue(CssFormatter formatter) {
Expression leftOp = operands.get( 0 );
switch( operator ) {
case '&':
case '|':
boolean value = leftOp.booleanValue( formatter );
for( int i = 1; i < operands.size(); i++ ) {
boolean right = operands.get( i ).booleanValue( formatter );
switch( operator ) {
case '&':
value &= right;
break;
case '|':
value |= right;
break;
}
}
return value;
case '!':
return !leftOp.booleanValue( formatter );
case ' ':
if( leftOp instanceof ValueExpression && "not".equals( leftOp.toString() ) ) {
return !operands.get( 1 ).booleanValue( formatter );
}
if( operands.size() == 3 ) {
Expression op = operands.get( 1 );
if( op instanceof ValueExpression ) {
Expression rightOp = operands.get( 2 );
switch( op.toString() ) {
case "and":
return leftOp.booleanValue( formatter ) & rightOp.booleanValue( formatter );
case "or":
return leftOp.booleanValue( formatter ) | rightOp.booleanValue( formatter );
}
}
}
break;
case '>':
case '<':
case '=':
case '≥':
case '≤':
int type = maxOperadType( formatter );
switch( type ) {
case LIST:
case STRING: {
// need to differ between keyword without quotes and strings with quotes. The type of quote is ignored
String left = normlizeQuotes( leftOp.stringValue( formatter ) );
String right = normlizeQuotes( operands.get( 1 ).stringValue( formatter ) );
switch( operator ) {
case '>':
return left.compareTo( right ) > 0;
case '<':
return left.compareTo( right ) < 0;
case '=':
return left.compareTo( right ) == 0;
case '≥':
return left.compareTo( right ) >= 0;
case '≤':
return left.compareTo( right ) <= 0;
}
break;
}
case COLOR:
case RGBA:{
long left = Double.doubleToRawLongBits( leftOp.doubleValue( formatter ) );
long right = Double.doubleToRawLongBits( operands.get( 1 ).doubleValue( formatter ) );
// colors can not be greater or lesser
switch( operator ) {
case '>':
case '<':
return false;
case '=':
case '≥':
case '≤':
return left == right;
}
}
//$FALL-THROUGH$
default: {
double left = leftOp.doubleValue( formatter );
Expression rightOp = operands.get( 1 );
double right = rightOp.doubleValue( formatter );
try {
right /= unitFactor( leftOp.unit( formatter ), rightOp.unit( formatter ), true );
switch( operator ) {
case '>':
return left > right;
case '<':
return left < right;
case '=':
return left == right;
case '≥':
return left >= right;
case '≤':
return left <= right;
}
} catch (LessException ex ) {
return false;
}
}
}
//$FALL-THROUGH$
default:
}
throw createException( "Not supported Oprator '" + operator + "' for Expression '" + toString() + '\'' );
} } | public class class_name {
@Override
public boolean booleanValue(CssFormatter formatter) {
Expression leftOp = operands.get( 0 );
switch( operator ) {
case '&':
case '|':
boolean value = leftOp.booleanValue( formatter );
for( int i = 1; i < operands.size(); i++ ) {
boolean right = operands.get( i ).booleanValue( formatter );
switch( operator ) {
case '&':
value &= right;
break;
case '|':
value |= right;
break;
}
}
return value;
case '!':
return !leftOp.booleanValue( formatter );
case ' ':
if( leftOp instanceof ValueExpression && "not".equals( leftOp.toString() ) ) {
return !operands.get( 1 ).booleanValue( formatter );
}
if( operands.size() == 3 ) {
Expression op = operands.get( 1 );
if( op instanceof ValueExpression ) {
Expression rightOp = operands.get( 2 );
switch( op.toString() ) { // depends on control dependency: [if], data = [none]
case "and":
return leftOp.booleanValue( formatter ) & rightOp.booleanValue( formatter );
case "or":
return leftOp.booleanValue( formatter ) | rightOp.booleanValue( formatter );
}
}
}
break;
case '>':
case '<':
case '=':
case '≥':
case '≤':
int type = maxOperadType( formatter );
switch( type ) {
case LIST:
case STRING: {
// need to differ between keyword without quotes and strings with quotes. The type of quote is ignored
String left = normlizeQuotes( leftOp.stringValue( formatter ) );
String right = normlizeQuotes( operands.get( 1 ).stringValue( formatter ) );
switch( operator ) {
case '>':
return left.compareTo( right ) > 0;
case '<':
return left.compareTo( right ) < 0;
case '=':
return left.compareTo( right ) == 0;
case '≥':
return left.compareTo( right ) >= 0;
case '≤':
return left.compareTo( right ) <= 0;
}
break;
}
case COLOR:
case RGBA:{
long left = Double.doubleToRawLongBits( leftOp.doubleValue( formatter ) );
long right = Double.doubleToRawLongBits( operands.get( 1 ).doubleValue( formatter ) );
// colors can not be greater or lesser
switch( operator ) {
case '>':
case '<':
return false;
case '=':
case '≥':
case '≤':
return left == right;
}
}
//$FALL-THROUGH$
default: {
double left = leftOp.doubleValue( formatter );
Expression rightOp = operands.get( 1 );
double right = rightOp.doubleValue( formatter );
try {
right /= unitFactor( leftOp.unit( formatter ), rightOp.unit( formatter ), true ); // depends on control dependency: [try], data = [none]
switch( operator ) {
case '>':
return left > right;
case '<':
return left < right;
case '=':
return left == right;
case '≥':
return left >= right;
case '≤':
return left <= right;
}
} catch (LessException ex ) {
return false;
} // depends on control dependency: [catch], data = [none]
}
}
//$FALL-THROUGH$
default:
}
throw createException( "Not supported Oprator '" + operator + "' for Expression '" + toString() + '\'' );
} } |
public class class_name {
@Override
public void start(BundleContext context) throws Exception {
this.bundleContext = context;
this.bundle = context.getBundle();
try {
// check if another version of the bundle exists
long myId = this.bundle.getBundleId();
String myName = this.bundle.getSymbolicName();
Bundle[] currentBundles = this.bundleContext.getBundles();
for (Bundle bundle : currentBundles) {
if (myId != bundle.getBundleId() && myName.equals(bundle.getSymbolicName())) {
// found another version of me
handleAnotherVersionAtStartup(bundle);
}
}
// set bundle's user-defined properties
this.properties = new Properties();
properties.put(Constants.LOOKUP_PROP_VERSION, bundle.getVersion().toString());
String alias = alias();
if (!StringUtils.isEmpty(alias)) {
properties.put(Constants.LOOKUP_PROP_MODULE, alias);
}
init();
} catch (Exception e) {
_destroy();
throw e;
}
} } | public class class_name {
@Override
public void start(BundleContext context) throws Exception {
this.bundleContext = context;
this.bundle = context.getBundle();
try {
// check if another version of the bundle exists
long myId = this.bundle.getBundleId();
String myName = this.bundle.getSymbolicName();
Bundle[] currentBundles = this.bundleContext.getBundles();
for (Bundle bundle : currentBundles) {
if (myId != bundle.getBundleId() && myName.equals(bundle.getSymbolicName())) {
// found another version of me
handleAnotherVersionAtStartup(bundle); // depends on control dependency: [if], data = [none]
}
}
// set bundle's user-defined properties
this.properties = new Properties();
properties.put(Constants.LOOKUP_PROP_VERSION, bundle.getVersion().toString());
String alias = alias();
if (!StringUtils.isEmpty(alias)) {
properties.put(Constants.LOOKUP_PROP_MODULE, alias); // depends on control dependency: [if], data = [none]
}
init();
} catch (Exception e) {
_destroy();
throw e;
}
} } |
public class class_name {
public static Map<String,Set<Writable>> getUniqueSequence(List<String> columnNames, Schema schema,
SequenceRecordReader sequenceData) {
Map<String,Set<Writable>> m = new HashMap<>();
for(String s : columnNames){
m.put(s, new HashSet<>());
}
while(sequenceData.hasNext()){
List<List<Writable>> next = sequenceData.sequenceRecord();
for(List<Writable> step : next) {
for (String s : columnNames) {
int idx = schema.getIndexOfColumn(s);
m.get(s).add(step.get(idx));
}
}
}
return m;
} } | public class class_name {
public static Map<String,Set<Writable>> getUniqueSequence(List<String> columnNames, Schema schema,
SequenceRecordReader sequenceData) {
Map<String,Set<Writable>> m = new HashMap<>();
for(String s : columnNames){
m.put(s, new HashSet<>()); // depends on control dependency: [for], data = [s]
}
while(sequenceData.hasNext()){
List<List<Writable>> next = sequenceData.sequenceRecord();
for(List<Writable> step : next) {
for (String s : columnNames) {
int idx = schema.getIndexOfColumn(s);
m.get(s).add(step.get(idx)); // depends on control dependency: [for], data = [s]
}
}
}
return m;
} } |
public class class_name {
private void emitCurrentOrLeftover(ByteBuffer key, List<ByteBuffer> values) {
if (leftover != null) {
int leftOverCompare = LexicographicalComparator.compareBuffers(leftover.getKey(), key);
if (leftOverCompare <= 0) {
emit(leftover.getKey(), leftover.getValue());
leftover = null;
}
}
if (!values.isEmpty()) {
emit(key, values);
values.clear();
}
} } | public class class_name {
private void emitCurrentOrLeftover(ByteBuffer key, List<ByteBuffer> values) {
if (leftover != null) {
int leftOverCompare = LexicographicalComparator.compareBuffers(leftover.getKey(), key);
if (leftOverCompare <= 0) {
emit(leftover.getKey(), leftover.getValue()); // depends on control dependency: [if], data = [none]
leftover = null; // depends on control dependency: [if], data = [none]
}
}
if (!values.isEmpty()) {
emit(key, values); // depends on control dependency: [if], data = [none]
values.clear(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setRelatedResources(java.util.Collection<RelatedResource> relatedResources) {
if (relatedResources == null) {
this.relatedResources = null;
return;
}
this.relatedResources = new java.util.ArrayList<RelatedResource>(relatedResources);
} } | public class class_name {
public void setRelatedResources(java.util.Collection<RelatedResource> relatedResources) {
if (relatedResources == null) {
this.relatedResources = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.relatedResources = new java.util.ArrayList<RelatedResource>(relatedResources);
} } |
public class class_name {
public static void shutdown() {
if (orbStart != null) {
orbStart.shutdown();
}
if (orb != null) {
orb.shutdown(true);
LOGGER.debug("ORB shutdown");
}
} } | public class class_name {
public static void shutdown() {
if (orbStart != null) {
orbStart.shutdown(); // depends on control dependency: [if], data = [none]
}
if (orb != null) {
orb.shutdown(true); // depends on control dependency: [if], data = [none]
LOGGER.debug("ORB shutdown"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void drawLegend(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
setRenderingHints(g2);
g2.setColor(Color.BLACK);
Font font = g2.getFont();
Font f = new Font(font.getFontName(), Font.BOLD, font.getSize());
g2.setFont(f);
fm = getFontMetrics(f);
int fontHeight = fm.getHeight();
for (int i = 0; i < title.size(); i++) {
if (fm.stringWidth(title.get(i)) > .8 * this.getWidth()) {
f = new Font(font.getFontName(), Font.BOLD, 10);
g2.setFont(f);
fm = getFontMetrics(f);
}
g2.drawString(title.get(i), (getSize().width - fm.stringWidth(title.get(i))) / 2, ((i + 1) * fontHeight));
// g2.setFont(font);
}
// draw the maxPercentage and minPercentage values
String label = df.format(minPercentage);
g2.drawString(label, left - 5 - (fm.stringWidth(label)), bottom + titleHeight / 6);
g2.drawLine(left - 5, bottom, left, bottom);
double d = minPercentage + kmfi.yaxisPercentIncrement;
//double graphHeight = top - bottom;
while (d < maxPercentage) {
int yvalue = bottom - (int) (d * (bottom - top));
label = df.format(d * 100);
g2.drawString(label, left - 5 - (fm.stringWidth(label)), yvalue + titleHeight / 6); //
g2.drawLine(left - 5, yvalue, left, yvalue);
d = d + kmfi.yaxisPercentIncrement;
}
label = df.format(maxPercentage * 100);
g2.drawString(label, left - 5 - (fm.stringWidth(label)), top + (titleHeight) / 6);
g2.drawLine(left - 5, top, left, top);
// Create a rotation transformation for the font.
AffineTransform fontAT = new AffineTransform();
// Derive a new font using a rotatation transform
fontAT.rotate(270 * java.lang.Math.PI / 180);
Font theDerivedFont = f.deriveFont(fontAT);
// set the derived font in the Graphics2D context
g2.setFont(theDerivedFont);
// Render a string using the derived font
int yaxisHeight = fm.stringWidth(kmfi.yAxisLegend);
g2.drawString(kmfi.yAxisLegend, yaxisLabel, (bottom - (int) (.5 * (bottom - top))) + yaxisHeight / 2);
// put the original font back
g2.setFont(f);
double timeDistance = maxTime - minTime;
double timeIncrement = timeDistance * kmfi.xaxisPercentIncrement;
double timeInt = (int) Math.floor(timeIncrement);
if (timeInt < 1.0) {
timeInt = 1.0;
}
adjustedPercentIncrement = timeInt / timeDistance;
d = adjustedPercentIncrement; //kmfi.xaxisPercentIncrement;
xAxisTimeValues.clear();
xAxisTimeCoordinates.clear();
//if we don't have time values then use percentage to set time. Not perfect but allows different tics
if (kmfi.xAxisLabels.isEmpty()) {
xAxisTimeValues.add(minTime);
xAxisTimeCoordinates.add(left);
while (d <= 1.0) {
double xaxisTime = ((minTime * kmfi.timeScale) + d * ((maxTime - minTime) * kmfi.timeScale)); //
xAxisTimeValues.add(xaxisTime);
Integer coordinate = left + (int) (d * (right - left));
xAxisTimeCoordinates.add(coordinate);
// System.out.println(d + " " + left + " " + right + " " + coordinate + " " + minTime + " " + maxTime);
d = d + adjustedPercentIncrement; //kmfi.xaxisPercentIncrement;
}
} else {
minTime = kmfi.xAxisLabels.get(0);
maxTime = kmfi.xAxisLabels.get(kmfi.xAxisLabels.size() - 1);
for (Double xaxisTime : kmfi.xAxisLabels) {
xAxisTimeValues.add(xaxisTime);
d = (xaxisTime - minTime) / (maxTime - minTime);
Integer coordinate = left + (int) (d * (right - left));
xAxisTimeCoordinates.add(coordinate);
}
}
for (int i = 0; i < xAxisTimeValues.size(); i++) {
Double xaxisTime = xAxisTimeValues.get(i);
Integer xCoordinate = xAxisTimeCoordinates.get(i);
label = df.format(xaxisTime);
if (i == xAxisTimeValues.size() - 1) {
g2.drawString(label, xCoordinate - (fm.stringWidth(label)), bottom + fm.getHeight() + 5);
} else {
g2.drawString(label, xCoordinate - (fm.stringWidth(label) / 2), bottom + fm.getHeight() + 5);
}
g2.drawLine(xCoordinate, bottom, xCoordinate, bottom + 5);
}
// draw the vertical and horizontal lines
g2.setStroke(kmfi.axisStroke);
g2.drawLine(left, top, left, bottom);
g2.drawLine(left, bottom, right, bottom);
// draw xAxis legend
g2.drawString(kmfi.xAxisLegend, getSize().width / 2 - (fm.stringWidth(kmfi.xAxisLegend) / 2), bottom + 2 * fm.getHeight() + 10);
} } | public class class_name {
private void drawLegend(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
setRenderingHints(g2);
g2.setColor(Color.BLACK);
Font font = g2.getFont();
Font f = new Font(font.getFontName(), Font.BOLD, font.getSize());
g2.setFont(f);
fm = getFontMetrics(f);
int fontHeight = fm.getHeight();
for (int i = 0; i < title.size(); i++) {
if (fm.stringWidth(title.get(i)) > .8 * this.getWidth()) {
f = new Font(font.getFontName(), Font.BOLD, 10); // depends on control dependency: [if], data = [none]
g2.setFont(f); // depends on control dependency: [if], data = [none]
fm = getFontMetrics(f); // depends on control dependency: [if], data = [none]
}
g2.drawString(title.get(i), (getSize().width - fm.stringWidth(title.get(i))) / 2, ((i + 1) * fontHeight)); // depends on control dependency: [for], data = [i]
// g2.setFont(font);
}
// draw the maxPercentage and minPercentage values
String label = df.format(minPercentage);
g2.drawString(label, left - 5 - (fm.stringWidth(label)), bottom + titleHeight / 6);
g2.drawLine(left - 5, bottom, left, bottom);
double d = minPercentage + kmfi.yaxisPercentIncrement;
//double graphHeight = top - bottom;
while (d < maxPercentage) {
int yvalue = bottom - (int) (d * (bottom - top));
label = df.format(d * 100); // depends on control dependency: [while], data = [(d]
g2.drawString(label, left - 5 - (fm.stringWidth(label)), yvalue + titleHeight / 6); // // depends on control dependency: [while], data = [none]
g2.drawLine(left - 5, yvalue, left, yvalue); // depends on control dependency: [while], data = [none]
d = d + kmfi.yaxisPercentIncrement; // depends on control dependency: [while], data = [none]
}
label = df.format(maxPercentage * 100);
g2.drawString(label, left - 5 - (fm.stringWidth(label)), top + (titleHeight) / 6);
g2.drawLine(left - 5, top, left, top);
// Create a rotation transformation for the font.
AffineTransform fontAT = new AffineTransform();
// Derive a new font using a rotatation transform
fontAT.rotate(270 * java.lang.Math.PI / 180);
Font theDerivedFont = f.deriveFont(fontAT);
// set the derived font in the Graphics2D context
g2.setFont(theDerivedFont);
// Render a string using the derived font
int yaxisHeight = fm.stringWidth(kmfi.yAxisLegend);
g2.drawString(kmfi.yAxisLegend, yaxisLabel, (bottom - (int) (.5 * (bottom - top))) + yaxisHeight / 2);
// put the original font back
g2.setFont(f);
double timeDistance = maxTime - minTime;
double timeIncrement = timeDistance * kmfi.xaxisPercentIncrement;
double timeInt = (int) Math.floor(timeIncrement);
if (timeInt < 1.0) {
timeInt = 1.0; // depends on control dependency: [if], data = [none]
}
adjustedPercentIncrement = timeInt / timeDistance;
d = adjustedPercentIncrement; //kmfi.xaxisPercentIncrement;
xAxisTimeValues.clear();
xAxisTimeCoordinates.clear();
//if we don't have time values then use percentage to set time. Not perfect but allows different tics
if (kmfi.xAxisLabels.isEmpty()) {
xAxisTimeValues.add(minTime); // depends on control dependency: [if], data = [none]
xAxisTimeCoordinates.add(left); // depends on control dependency: [if], data = [none]
while (d <= 1.0) {
double xaxisTime = ((minTime * kmfi.timeScale) + d * ((maxTime - minTime) * kmfi.timeScale)); //
xAxisTimeValues.add(xaxisTime); // depends on control dependency: [while], data = [none]
Integer coordinate = left + (int) (d * (right - left));
xAxisTimeCoordinates.add(coordinate); // depends on control dependency: [while], data = [none]
// System.out.println(d + " " + left + " " + right + " " + coordinate + " " + minTime + " " + maxTime);
d = d + adjustedPercentIncrement; //kmfi.xaxisPercentIncrement; // depends on control dependency: [while], data = [none]
}
} else {
minTime = kmfi.xAxisLabels.get(0); // depends on control dependency: [if], data = [none]
maxTime = kmfi.xAxisLabels.get(kmfi.xAxisLabels.size() - 1); // depends on control dependency: [if], data = [none]
for (Double xaxisTime : kmfi.xAxisLabels) {
xAxisTimeValues.add(xaxisTime); // depends on control dependency: [for], data = [xaxisTime]
d = (xaxisTime - minTime) / (maxTime - minTime); // depends on control dependency: [for], data = [xaxisTime]
Integer coordinate = left + (int) (d * (right - left));
xAxisTimeCoordinates.add(coordinate); // depends on control dependency: [for], data = [none]
}
}
for (int i = 0; i < xAxisTimeValues.size(); i++) {
Double xaxisTime = xAxisTimeValues.get(i);
Integer xCoordinate = xAxisTimeCoordinates.get(i);
label = df.format(xaxisTime); // depends on control dependency: [for], data = [none]
if (i == xAxisTimeValues.size() - 1) {
g2.drawString(label, xCoordinate - (fm.stringWidth(label)), bottom + fm.getHeight() + 5); // depends on control dependency: [if], data = [none]
} else {
g2.drawString(label, xCoordinate - (fm.stringWidth(label) / 2), bottom + fm.getHeight() + 5); // depends on control dependency: [if], data = [none]
}
g2.drawLine(xCoordinate, bottom, xCoordinate, bottom + 5); // depends on control dependency: [for], data = [none]
}
// draw the vertical and horizontal lines
g2.setStroke(kmfi.axisStroke);
g2.drawLine(left, top, left, bottom);
g2.drawLine(left, bottom, right, bottom);
// draw xAxis legend
g2.drawString(kmfi.xAxisLegend, getSize().width / 2 - (fm.stringWidth(kmfi.xAxisLegend) / 2), bottom + 2 * fm.getHeight() + 10);
} } |
public class class_name {
@Override
public void setVisible( boolean bVisible )
{
super.setVisible( bVisible );
if( bVisible )
{
registerListeners();
}
else
{
unregisterListeners();
_editor.getEditor().requestFocus();
}
} } | public class class_name {
@Override
public void setVisible( boolean bVisible )
{
super.setVisible( bVisible );
if( bVisible )
{
registerListeners(); // depends on control dependency: [if], data = [none]
}
else
{
unregisterListeners(); // depends on control dependency: [if], data = [none]
_editor.getEditor().requestFocus(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Map<String, Set<ServiceDefinition>> getNamespaceServiceDefinitionMap() {
Map<String, Set<ServiceDefinition>> namespaceServiceDefinitionMap = new HashMap<String, Set<ServiceDefinition>>();
for (String namespace : serviceImplementationMap.keySet()) {
Set<ServiceDefinition> serviceDefinitions = new HashSet<ServiceDefinition>();
namespaceServiceDefinitionMap.put(namespace, serviceDefinitions);
for (ServiceDefinition sd : serviceImplementationMap.get(namespace).keySet()) {
serviceDefinitions.add(sd);
}
}
return Collections.unmodifiableMap(namespaceServiceDefinitionMap);
} } | public class class_name {
public Map<String, Set<ServiceDefinition>> getNamespaceServiceDefinitionMap() {
Map<String, Set<ServiceDefinition>> namespaceServiceDefinitionMap = new HashMap<String, Set<ServiceDefinition>>();
for (String namespace : serviceImplementationMap.keySet()) {
Set<ServiceDefinition> serviceDefinitions = new HashSet<ServiceDefinition>();
namespaceServiceDefinitionMap.put(namespace, serviceDefinitions); // depends on control dependency: [for], data = [namespace]
for (ServiceDefinition sd : serviceImplementationMap.get(namespace).keySet()) {
serviceDefinitions.add(sd); // depends on control dependency: [for], data = [sd]
}
}
return Collections.unmodifiableMap(namespaceServiceDefinitionMap);
} } |
public class class_name {
private boolean refineWithBundleAdjustment(SceneObservations observations) {
if( scaleSBA ) {
scaler.applyScale(structure,observations);
}
sba.setVerbose(verbose,verboseLevel);
sba.setParameters(structure,observations);
sba.configure(converge.ftol,converge.gtol,converge.maxIterations);
if( !sba.optimize(structure) ) {
return false;
}
if( scaleSBA ) {
// only undo scaling on camera matrices since observations are discarded
for (int i = 0; i < structure.views.length; i++) {
DMatrixRMaj P = structure.views[i].worldToView;
scaler.pixelScaling.get(i).remove(P,P);
}
scaler.undoScale(structure,observations);
}
return true;
} } | public class class_name {
private boolean refineWithBundleAdjustment(SceneObservations observations) {
if( scaleSBA ) {
scaler.applyScale(structure,observations); // depends on control dependency: [if], data = [none]
}
sba.setVerbose(verbose,verboseLevel);
sba.setParameters(structure,observations);
sba.configure(converge.ftol,converge.gtol,converge.maxIterations);
if( !sba.optimize(structure) ) {
return false; // depends on control dependency: [if], data = [none]
}
if( scaleSBA ) {
// only undo scaling on camera matrices since observations are discarded
for (int i = 0; i < structure.views.length; i++) {
DMatrixRMaj P = structure.views[i].worldToView;
scaler.pixelScaling.get(i).remove(P,P); // depends on control dependency: [for], data = [i]
}
scaler.undoScale(structure,observations); // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
@Override
public void start() {
initLogger();
log.info("PETITE start ----------");
petiteContainer = createPetiteContainer();
if (externalsCache) {
petiteContainer.setExternalsCache(TypeCache.createDefault());
}
log.info("Web application? " + isWebApplication);
if (!isWebApplication) {
// make session scope to act as singleton scope
// if this is not a web application (and http session is not available).
petiteContainer.registerScope(SessionScope.class, new SingletonScope(petiteContainer));
}
// load parameters from properties files
petiteContainer.defineParameters(joyPropsSupplier.get().getProps());
// automagic configuration
if (autoConfiguration) {
final AutomagicPetiteConfigurator automagicPetiteConfigurator =
new AutomagicPetiteConfigurator(petiteContainer);
automagicPetiteConfigurator.registerAsConsumer(joyScannerSupplier.get().getClassScanner());
}
petiteContainerConsumers.accept(this.petiteContainer);
log.info("PETITE OK!");
} } | public class class_name {
@Override
public void start() {
initLogger();
log.info("PETITE start ----------");
petiteContainer = createPetiteContainer();
if (externalsCache) {
petiteContainer.setExternalsCache(TypeCache.createDefault()); // depends on control dependency: [if], data = [none]
}
log.info("Web application? " + isWebApplication);
if (!isWebApplication) {
// make session scope to act as singleton scope
// if this is not a web application (and http session is not available).
petiteContainer.registerScope(SessionScope.class, new SingletonScope(petiteContainer)); // depends on control dependency: [if], data = [none]
}
// load parameters from properties files
petiteContainer.defineParameters(joyPropsSupplier.get().getProps());
// automagic configuration
if (autoConfiguration) {
final AutomagicPetiteConfigurator automagicPetiteConfigurator =
new AutomagicPetiteConfigurator(petiteContainer);
automagicPetiteConfigurator.registerAsConsumer(joyScannerSupplier.get().getClassScanner()); // depends on control dependency: [if], data = [none]
}
petiteContainerConsumers.accept(this.petiteContainer);
log.info("PETITE OK!");
} } |
public class class_name {
@SuppressWarnings("unchecked")
protected MessageListener createCaseEventReceiver() {
try {
Class<MessageListener> caseEventReceiverClass = (Class<MessageListener>) Class.forName("org.jbpm.casemgmt.impl.jms.AsyncCaseInstanceAuditEventReceiver");
return caseEventReceiverClass.getConstructor(EntityManagerFactory.class).newInstance(entityManagerFactory);
} catch (Exception e) {
logger.debug("No message listener found for case instance event receiver", e);
return null;
}
} } | public class class_name {
@SuppressWarnings("unchecked")
protected MessageListener createCaseEventReceiver() {
try {
Class<MessageListener> caseEventReceiverClass = (Class<MessageListener>) Class.forName("org.jbpm.casemgmt.impl.jms.AsyncCaseInstanceAuditEventReceiver"); // depends on control dependency: [try], data = [none]
return caseEventReceiverClass.getConstructor(EntityManagerFactory.class).newInstance(entityManagerFactory); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.debug("No message listener found for case instance event receiver", e);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public boolean appendUnitSeparator(TimeUnit unit, boolean longSep,
boolean afterFirst, boolean beforeLast,
StringBuffer sb) {
// long seps
// false, false "...b', '...d"
// false, true "...', and 'c"
// true, false - "a', '...c"
// true, true - "a' and 'b"
if ((longSep && dr.unitSep != null) || dr.shortUnitSep != null) {
if (longSep && dr.unitSep != null) {
int ix = (afterFirst ? 2 : 0) + (beforeLast ? 1 : 0);
sb.append(dr.unitSep[ix]);
return dr.unitSepRequiresDP != null && dr.unitSepRequiresDP[ix];
}
sb.append(dr.shortUnitSep); // todo: investigate whether DP is required
}
return false;
} } | public class class_name {
public boolean appendUnitSeparator(TimeUnit unit, boolean longSep,
boolean afterFirst, boolean beforeLast,
StringBuffer sb) {
// long seps
// false, false "...b', '...d"
// false, true "...', and 'c"
// true, false - "a', '...c"
// true, true - "a' and 'b"
if ((longSep && dr.unitSep != null) || dr.shortUnitSep != null) {
if (longSep && dr.unitSep != null) {
int ix = (afterFirst ? 2 : 0) + (beforeLast ? 1 : 0);
sb.append(dr.unitSep[ix]); // depends on control dependency: [if], data = [none]
return dr.unitSepRequiresDP != null && dr.unitSepRequiresDP[ix]; // depends on control dependency: [if], data = [none]
}
sb.append(dr.shortUnitSep); // todo: investigate whether DP is required // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public Observable<ServiceResponse<Page<AvailableServiceSkuInner>>> listSkusNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listSkusNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<AvailableServiceSkuInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AvailableServiceSkuInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<AvailableServiceSkuInner>> result = listSkusNextDelegate(response);
return Observable.just(new ServiceResponse<Page<AvailableServiceSkuInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<AvailableServiceSkuInner>>> listSkusNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listSkusNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<AvailableServiceSkuInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AvailableServiceSkuInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<AvailableServiceSkuInner>> result = listSkusNextDelegate(response);
return Observable.just(new ServiceResponse<Page<AvailableServiceSkuInner>>(result.body(), result.response())); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public SbbComponent getComponentByID(SbbID id) {
// get from repository
SbbComponent component = componentRepository.getComponentByID(id);
if (component == null) {
// not found in repository, get it from deployable unit
component = deployableUnit.getSbbComponents().get(id);
}
return component;
} } | public class class_name {
public SbbComponent getComponentByID(SbbID id) {
// get from repository
SbbComponent component = componentRepository.getComponentByID(id);
if (component == null) {
// not found in repository, get it from deployable unit
component = deployableUnit.getSbbComponents().get(id); // depends on control dependency: [if], data = [none]
}
return component;
} } |
public class class_name {
protected ResourceEntry findResourceInternal(File file, String path){
ResourceEntry entry = new ResourceEntry();
try {
entry.source = getURI(new File(file, path));
entry.codeBase = getURL(new File(file, path), false);
} catch (MalformedURLException e) {
return null;
}
return entry;
} } | public class class_name {
protected ResourceEntry findResourceInternal(File file, String path){
ResourceEntry entry = new ResourceEntry();
try {
entry.source = getURI(new File(file, path)); // depends on control dependency: [try], data = [none]
entry.codeBase = getURL(new File(file, path), false); // depends on control dependency: [try], data = [none]
} catch (MalformedURLException e) {
return null;
} // depends on control dependency: [catch], data = [none]
return entry;
} } |
public class class_name {
@Override
public void injectionMetaDataCreated(InjectionMetaData injectionMetaData) throws InjectionException {
ReferenceContext referenceContext = injectionMetaData.getReferenceContext();
if (referenceContext != null) {
ApplicationMetaData appMetaData = injectionMetaData.getComponentNameSpaceConfiguration().getApplicationMetaData();
WebSphereCDIDeployment deployment = getDeployment(appMetaData);
if (deployment != null) {
deployment.addReferenceContext(referenceContext);
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "injectionMetaDataCreated()", "Could not find a CDI Deployment for ReferenceContext " + injectionMetaData.getJ2EEName());
}
}
}
} } | public class class_name {
@Override
public void injectionMetaDataCreated(InjectionMetaData injectionMetaData) throws InjectionException {
ReferenceContext referenceContext = injectionMetaData.getReferenceContext();
if (referenceContext != null) {
ApplicationMetaData appMetaData = injectionMetaData.getComponentNameSpaceConfiguration().getApplicationMetaData();
WebSphereCDIDeployment deployment = getDeployment(appMetaData);
if (deployment != null) {
deployment.addReferenceContext(referenceContext);
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "injectionMetaDataCreated()", "Could not find a CDI Deployment for ReferenceContext " + injectionMetaData.getJ2EEName()); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
private void appendVersion(StringBuilder sb, long ver) {
if (sb.length() > 0) {
sb.append(".");
}
sb.append(ver);
} } | public class class_name {
private void appendVersion(StringBuilder sb, long ver) {
if (sb.length() > 0) {
sb.append("."); // depends on control dependency: [if], data = [none]
}
sb.append(ver);
} } |
public class class_name {
public Map<String, List<String>> parseCSV(final String headers,
final String file, final String separator, final String encoding)
throws IOException {
LOG.info("Parsing CSVs from file: " + file + " with headers: "
+ headers + " separator: " + separator);
Map<String, List<String>> result = new HashMap<String, List<String>>();
BufferedReader reader = null;
try {
String[] headersArr = headers.split(",");
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), encoding));
String line = null;
while ((line = reader.readLine()) != null) {
String[] lines = line.split(separator);
if (lines.length != headersArr.length) {
throw new IOException("Too many or too little theaders!");
}
for (int i = 0; i < lines.length; i++) {
List<String> currentHeader = result.get(headersArr[i]
.trim());
if (currentHeader == null) {
currentHeader = new ArrayList<String>();
result.put(headersArr[i].trim(), currentHeader);
}
currentHeader.add(lines[i].trim());
}
}
} finally {
if (reader != null) {
reader.close();
}
}
LOG.info("Result of parsing CSV: " + result);
return result;
} } | public class class_name {
public Map<String, List<String>> parseCSV(final String headers,
final String file, final String separator, final String encoding)
throws IOException {
LOG.info("Parsing CSVs from file: " + file + " with headers: "
+ headers + " separator: " + separator);
Map<String, List<String>> result = new HashMap<String, List<String>>();
BufferedReader reader = null;
try {
String[] headersArr = headers.split(",");
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), encoding));
String line = null;
while ((line = reader.readLine()) != null) {
String[] lines = line.split(separator);
if (lines.length != headersArr.length) {
throw new IOException("Too many or too little theaders!");
}
for (int i = 0; i < lines.length; i++) {
List<String> currentHeader = result.get(headersArr[i]
.trim());
if (currentHeader == null) {
currentHeader = new ArrayList<String>(); // depends on control dependency: [if], data = [none]
result.put(headersArr[i].trim(), currentHeader); // depends on control dependency: [if], data = [none]
}
currentHeader.add(lines[i].trim()); // depends on control dependency: [for], data = [i]
}
}
} finally {
if (reader != null) {
reader.close(); // depends on control dependency: [if], data = [none]
}
}
LOG.info("Result of parsing CSV: " + result);
return result;
} } |
public class class_name {
public Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>> getWithServiceResponseAsync(final String vaultName, final String resourceGroupName, final String filter, final String skipToken) {
return getSinglePageAsync(vaultName, resourceGroupName, filter, skipToken)
.concatMap(new Func1<ServiceResponse<Page<BackupEngineBaseResourceInner>>, Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>> call(ServiceResponse<Page<BackupEngineBaseResourceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(getNextWithServiceResponseAsync(nextPageLink));
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>> getWithServiceResponseAsync(final String vaultName, final String resourceGroupName, final String filter, final String skipToken) {
return getSinglePageAsync(vaultName, resourceGroupName, filter, skipToken)
.concatMap(new Func1<ServiceResponse<Page<BackupEngineBaseResourceInner>>, Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<BackupEngineBaseResourceInner>>> call(ServiceResponse<Page<BackupEngineBaseResourceInner>> 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(getNextWithServiceResponseAsync(nextPageLink));
}
});
} } |
public class class_name {
@Override
public void removeByUuid(String uuid) {
for (CPDefinitionGroupedEntry cpDefinitionGroupedEntry : findByUuid(
uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(cpDefinitionGroupedEntry);
}
} } | public class class_name {
@Override
public void removeByUuid(String uuid) {
for (CPDefinitionGroupedEntry cpDefinitionGroupedEntry : findByUuid(
uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(cpDefinitionGroupedEntry); // depends on control dependency: [for], data = [cpDefinitionGroupedEntry]
}
} } |
public class class_name {
public static IDifference difference(IChemObject first, IChemObject second) {
if (!(first instanceof IBond && second instanceof IBond)) {
return null;
}
IBond firstB = (IBond) first;
IBond secondB = (IBond) second;
IDifferenceList totalDiff = new ChemObjectDifference("BondDiff");
totalDiff.addChild(BondOrderDifference.construct("order", firstB.getOrder(), secondB.getOrder()));
totalDiff.addChild(IntegerDifference.construct("atomCount", firstB.getAtomCount(), secondB.getAtomCount()));
if (firstB.getAtomCount() == secondB.getAtomCount()) {
totalDiff.addChild(AtomDiff.difference(firstB.getBegin(), secondB.getBegin()));
totalDiff.addChild(AtomDiff.difference(firstB.getEnd(), secondB.getEnd()));
for (int i = 2; i < firstB.getAtomCount(); i++) {
totalDiff.addChild(AtomDiff.difference(firstB.getAtom(i), secondB.getAtom(i)));
}
}
totalDiff.addChild(ElectronContainerDiff.difference(first, second));
if (totalDiff.childCount() > 0) {
return totalDiff;
} else {
return null;
}
} } | public class class_name {
public static IDifference difference(IChemObject first, IChemObject second) {
if (!(first instanceof IBond && second instanceof IBond)) {
return null; // depends on control dependency: [if], data = [none]
}
IBond firstB = (IBond) first;
IBond secondB = (IBond) second;
IDifferenceList totalDiff = new ChemObjectDifference("BondDiff");
totalDiff.addChild(BondOrderDifference.construct("order", firstB.getOrder(), secondB.getOrder()));
totalDiff.addChild(IntegerDifference.construct("atomCount", firstB.getAtomCount(), secondB.getAtomCount()));
if (firstB.getAtomCount() == secondB.getAtomCount()) {
totalDiff.addChild(AtomDiff.difference(firstB.getBegin(), secondB.getBegin())); // depends on control dependency: [if], data = [none]
totalDiff.addChild(AtomDiff.difference(firstB.getEnd(), secondB.getEnd())); // depends on control dependency: [if], data = [none]
for (int i = 2; i < firstB.getAtomCount(); i++) {
totalDiff.addChild(AtomDiff.difference(firstB.getAtom(i), secondB.getAtom(i))); // depends on control dependency: [for], data = [i]
}
}
totalDiff.addChild(ElectronContainerDiff.difference(first, second));
if (totalDiff.childCount() > 0) {
return totalDiff; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public List<String> tokenize(String text) {
// TODO: find a cleaner implementation, this is a hack
String replaced = text.replaceAll(
"(?<!')\\b([a-zA-ZĉĝĥĵŝŭĈĜĤĴŜŬ]+)'(?![a-zA-ZĉĝĥĵŝŭĈĜĤĴŜŬ-])",
"$1\u0001\u0001EO@APOS1\u0001\u0001").replaceAll(
"(?<!')\\b([a-zA-ZĉĝĥĵŝŭĈĜĤĴŜŬ]+)'(?=[a-zA-ZĉĝĥĵŝŭĈĜĤĴŜŬ-])",
"$1\u0001\u0001EO@APOS2\u0001\u0001 ");
List<String> tokenList = super.tokenize(replaced);
List<String> tokens = new ArrayList<>();
// Put back apostrophes and remove spurious spaces.
Iterator<String> itr = tokenList.iterator();
while (itr.hasNext()) {
String word = itr.next();
if (word.endsWith("\u0001\u0001EO@APOS2\u0001\u0001")) {
itr.next(); // Skip the next spurious white space.
}
word = word.replace("\u0001\u0001EO@APOS1\u0001\u0001", "'")
.replace("\u0001\u0001EO@APOS2\u0001\u0001", "'");
tokens.add(word);
}
return tokens;
} } | public class class_name {
@Override
public List<String> tokenize(String text) {
// TODO: find a cleaner implementation, this is a hack
String replaced = text.replaceAll(
"(?<!')\\b([a-zA-ZĉĝĥĵŝŭĈĜĤĴŜŬ]+)'(?![a-zA-ZĉĝĥĵŝŭĈĜĤĴŜŬ-])",
"$1\u0001\u0001EO@APOS1\u0001\u0001").replaceAll(
"(?<!')\\b([a-zA-ZĉĝĥĵŝŭĈĜĤĴŜŬ]+)'(?=[a-zA-ZĉĝĥĵŝŭĈĜĤĴŜŬ-])",
"$1\u0001\u0001EO@APOS2\u0001\u0001 ");
List<String> tokenList = super.tokenize(replaced);
List<String> tokens = new ArrayList<>();
// Put back apostrophes and remove spurious spaces.
Iterator<String> itr = tokenList.iterator();
while (itr.hasNext()) {
String word = itr.next();
if (word.endsWith("\u0001\u0001EO@APOS2\u0001\u0001")) {
itr.next(); // Skip the next spurious white space. // depends on control dependency: [if], data = [none]
}
word = word.replace("\u0001\u0001EO@APOS1\u0001\u0001", "'")
.replace("\u0001\u0001EO@APOS2\u0001\u0001", "'"); // depends on control dependency: [while], data = [none]
tokens.add(word); // depends on control dependency: [while], data = [none]
}
return tokens;
} } |
public class class_name {
@Override
public RetryContext open(RetryContext parent) {
List<RetryContext> list = new ArrayList<RetryContext>();
for (RetryPolicy policy : this.policies) {
list.add(policy.open(parent));
}
return new CompositeRetryContext(parent, list, this.policies);
} } | public class class_name {
@Override
public RetryContext open(RetryContext parent) {
List<RetryContext> list = new ArrayList<RetryContext>();
for (RetryPolicy policy : this.policies) {
list.add(policy.open(parent)); // depends on control dependency: [for], data = [policy]
}
return new CompositeRetryContext(parent, list, this.policies);
} } |
public class class_name {
private List<CmsNewResourceInfo> getNewResourceInfos(CmsObject cms, CmsADEConfigData configData, Locale locale) {
List<CmsNewResourceInfo> result = new ArrayList<CmsNewResourceInfo>();
for (CmsModelPageConfig modelConfig : configData.getModelPages()) {
try {
CmsNewResourceInfo info = createNewResourceInfo(cms, modelConfig.getResource(), locale);
info.setDefault(modelConfig.isDefault());
result.add(info);
} catch (CmsException e) {
LOG.debug(e.getLocalizedMessage(), e);
}
}
Collections.sort(result, new Comparator<CmsNewResourceInfo>() {
public int compare(CmsNewResourceInfo a, CmsNewResourceInfo b) {
return ComparisonChain.start().compareTrueFirst(a.isDefault(), b.isDefault()).compare(
a.getNavPos(),
b.getNavPos(),
Ordering.natural().nullsLast()).result();
}
});
return result;
} } | public class class_name {
private List<CmsNewResourceInfo> getNewResourceInfos(CmsObject cms, CmsADEConfigData configData, Locale locale) {
List<CmsNewResourceInfo> result = new ArrayList<CmsNewResourceInfo>();
for (CmsModelPageConfig modelConfig : configData.getModelPages()) {
try {
CmsNewResourceInfo info = createNewResourceInfo(cms, modelConfig.getResource(), locale);
info.setDefault(modelConfig.isDefault()); // depends on control dependency: [try], data = [none]
result.add(info); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
LOG.debug(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
Collections.sort(result, new Comparator<CmsNewResourceInfo>() {
public int compare(CmsNewResourceInfo a, CmsNewResourceInfo b) {
return ComparisonChain.start().compareTrueFirst(a.isDefault(), b.isDefault()).compare(
a.getNavPos(),
b.getNavPos(),
Ordering.natural().nullsLast()).result();
}
});
return result;
} } |
public class class_name {
public static <E> Distribution<E> getDistributionFromLogValues(Counter<E> counter) {
ClassicCounter<E> c = new ClassicCounter<E>();
// go through once to get the max
// shift all by max so as to minimize the possibility of underflow
double max = Counters.max(counter); // Thang 17Feb12: max should operate on counter instead of c, fixed!
for (E key : counter.keySet()) {
double count = Math.exp(counter.getCount(key) - max);
c.setCount(key, count);
}
return getDistribution(c);
} } | public class class_name {
public static <E> Distribution<E> getDistributionFromLogValues(Counter<E> counter) {
ClassicCounter<E> c = new ClassicCounter<E>();
// go through once to get the max
// shift all by max so as to minimize the possibility of underflow
double max = Counters.max(counter); // Thang 17Feb12: max should operate on counter instead of c, fixed!
for (E key : counter.keySet()) {
double count = Math.exp(counter.getCount(key) - max);
c.setCount(key, count);
// depends on control dependency: [for], data = [key]
}
return getDistribution(c);
} } |
public class class_name {
private String toJSONString() {
JSONStringer js = new JSONStringer();
try {
js.object();
for (Map.Entry<Integer, Integer> entry : m_tokensMap.get().entrySet()) {
js.key(entry.getKey().toString()).value(entry.getValue());
}
js.endObject();
} catch (JSONException e) {
throw new RuntimeException("Failed to serialize Hashinator Configuration to JSON.", e);
}
return js.toString();
} } | public class class_name {
private String toJSONString() {
JSONStringer js = new JSONStringer();
try {
js.object(); // depends on control dependency: [try], data = [none]
for (Map.Entry<Integer, Integer> entry : m_tokensMap.get().entrySet()) {
js.key(entry.getKey().toString()).value(entry.getValue()); // depends on control dependency: [for], data = [entry]
}
js.endObject(); // depends on control dependency: [try], data = [none]
} catch (JSONException e) {
throw new RuntimeException("Failed to serialize Hashinator Configuration to JSON.", e);
} // depends on control dependency: [catch], data = [none]
return js.toString();
} } |
public class class_name {
public ServiceCall<Counterexample> getCounterexample(GetCounterexampleOptions getCounterexampleOptions) {
Validator.notNull(getCounterexampleOptions, "getCounterexampleOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "counterexamples" };
String[] pathParameters = { getCounterexampleOptions.workspaceId(), getCounterexampleOptions.text() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "getCounterexample");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
if (getCounterexampleOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getCounterexampleOptions.includeAudit()));
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Counterexample.class));
} } | public class class_name {
public ServiceCall<Counterexample> getCounterexample(GetCounterexampleOptions getCounterexampleOptions) {
Validator.notNull(getCounterexampleOptions, "getCounterexampleOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "counterexamples" };
String[] pathParameters = { getCounterexampleOptions.workspaceId(), getCounterexampleOptions.text() };
RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v1", "getCounterexample");
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");
if (getCounterexampleOptions.includeAudit() != null) {
builder.query("include_audit", String.valueOf(getCounterexampleOptions.includeAudit())); // depends on control dependency: [if], data = [(getCounterexampleOptions.includeAudit()]
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Counterexample.class));
} } |
public class class_name {
public void _include(IncludeBuilderBase includes) {
if (includes == null) {
return;
}
if (includes.documentsToInclude != null) {
for (String doc : includes.documentsToInclude) {
documentIncludes.add(doc);
}
}
_includeCounters(includes.alias, includes.countersToIncludeBySourcePath);
} } | public class class_name {
public void _include(IncludeBuilderBase includes) {
if (includes == null) {
return; // depends on control dependency: [if], data = [none]
}
if (includes.documentsToInclude != null) {
for (String doc : includes.documentsToInclude) {
documentIncludes.add(doc); // depends on control dependency: [for], data = [doc]
}
}
_includeCounters(includes.alias, includes.countersToIncludeBySourcePath);
} } |
public class class_name {
public void setBaseGain (float gain)
{
if (_baseGain == gain) {
return;
}
_baseGain = gain;
// alert the groups that inherite the gain
for (int ii = 0, nn = _groups.size(); ii < nn; ii++) {
SoundGroup group = _groups.get(ii);
if (group.getBaseGain() < 0f) {
group.baseGainChanged();
}
}
} } | public class class_name {
public void setBaseGain (float gain)
{
if (_baseGain == gain) {
return; // depends on control dependency: [if], data = [none]
}
_baseGain = gain;
// alert the groups that inherite the gain
for (int ii = 0, nn = _groups.size(); ii < nn; ii++) {
SoundGroup group = _groups.get(ii);
if (group.getBaseGain() < 0f) {
group.baseGainChanged(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static base_responses delete(nitro_service client, String wrapkeyname[]) throws Exception {
base_responses result = null;
if (wrapkeyname != null && wrapkeyname.length > 0) {
sslwrapkey deleteresources[] = new sslwrapkey[wrapkeyname.length];
for (int i=0;i<wrapkeyname.length;i++){
deleteresources[i] = new sslwrapkey();
deleteresources[i].wrapkeyname = wrapkeyname[i];
}
result = delete_bulk_request(client, deleteresources);
}
return result;
} } | public class class_name {
public static base_responses delete(nitro_service client, String wrapkeyname[]) throws Exception {
base_responses result = null;
if (wrapkeyname != null && wrapkeyname.length > 0) {
sslwrapkey deleteresources[] = new sslwrapkey[wrapkeyname.length];
for (int i=0;i<wrapkeyname.length;i++){
deleteresources[i] = new sslwrapkey(); // depends on control dependency: [for], data = [i]
deleteresources[i].wrapkeyname = wrapkeyname[i]; // depends on control dependency: [for], data = [i]
}
result = delete_bulk_request(client, deleteresources);
}
return result;
} } |
public class class_name {
public @Nonnull SetType getBlockedThreads() {
Set<ThreadType> blocked = new LinkedHashSet<ThreadType>();
for (ThreadType thread: runtime.getThreads()) {
if (thread == this) continue;
if (getAcquiredLocks().contains(thread.getWaitingToLock())) {
blocked.add(thread);
}
}
return runtime.getThreadSet(blocked);
} } | public class class_name {
public @Nonnull SetType getBlockedThreads() {
Set<ThreadType> blocked = new LinkedHashSet<ThreadType>();
for (ThreadType thread: runtime.getThreads()) {
if (thread == this) continue;
if (getAcquiredLocks().contains(thread.getWaitingToLock())) {
blocked.add(thread); // depends on control dependency: [if], data = [none]
}
}
return runtime.getThreadSet(blocked);
} } |
public class class_name {
public void marshall(ListRuleNamesByTargetRequest listRuleNamesByTargetRequest, ProtocolMarshaller protocolMarshaller) {
if (listRuleNamesByTargetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listRuleNamesByTargetRequest.getTargetArn(), TARGETARN_BINDING);
protocolMarshaller.marshall(listRuleNamesByTargetRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listRuleNamesByTargetRequest.getLimit(), LIMIT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ListRuleNamesByTargetRequest listRuleNamesByTargetRequest, ProtocolMarshaller protocolMarshaller) {
if (listRuleNamesByTargetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listRuleNamesByTargetRequest.getTargetArn(), TARGETARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listRuleNamesByTargetRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listRuleNamesByTargetRequest.getLimit(), LIMIT_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(FaceDetection faceDetection, ProtocolMarshaller protocolMarshaller) {
if (faceDetection == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(faceDetection.getTimestamp(), TIMESTAMP_BINDING);
protocolMarshaller.marshall(faceDetection.getFace(), FACE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(FaceDetection faceDetection, ProtocolMarshaller protocolMarshaller) {
if (faceDetection == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(faceDetection.getTimestamp(), TIMESTAMP_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(faceDetection.getFace(), FACE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private ArrayList<ArrayDBIDs> buildOneDimIndexes(Relation<? extends NumberVector> relation) {
final int dim = RelationUtil.dimensionality(relation);
ArrayList<ArrayDBIDs> subspaceIndex = new ArrayList<>(dim + 1);
SortDBIDsBySingleDimension comp = new VectorUtil.SortDBIDsBySingleDimension(relation);
for(int i = 0; i < dim; i++) {
ArrayModifiableDBIDs amDBIDs = DBIDUtil.newArray(relation.getDBIDs());
comp.setDimension(i);
amDBIDs.sort(comp);
subspaceIndex.add(amDBIDs);
}
return subspaceIndex;
} } | public class class_name {
private ArrayList<ArrayDBIDs> buildOneDimIndexes(Relation<? extends NumberVector> relation) {
final int dim = RelationUtil.dimensionality(relation);
ArrayList<ArrayDBIDs> subspaceIndex = new ArrayList<>(dim + 1);
SortDBIDsBySingleDimension comp = new VectorUtil.SortDBIDsBySingleDimension(relation);
for(int i = 0; i < dim; i++) {
ArrayModifiableDBIDs amDBIDs = DBIDUtil.newArray(relation.getDBIDs());
comp.setDimension(i); // depends on control dependency: [for], data = [i]
amDBIDs.sort(comp); // depends on control dependency: [for], data = [none]
subspaceIndex.add(amDBIDs); // depends on control dependency: [for], data = [none]
}
return subspaceIndex;
} } |
public class class_name {
@Override
public SparseTensor slice(int[] dimensionNumbers, int[] key) {
if (dimensionNumbers.length == 0) {
return this;
}
// Check for an efficient case, where the dimensions are the first
// elements of this.
if (ArrayUtils.subarrayEquals(getDimensionNumbers(), dimensionNumbers, 0)) {
long minKeyInt = 0;
int numDimensions = dimensionNumbers.length;
for (int i = 0; i < numDimensions; i++) {
minKeyInt += indexOffsets[i] * key[i];
}
long maxKeyInt = minKeyInt + indexOffsets[numDimensions - 1];
int startIndex = getNearestIndex(minKeyInt);
int endIndex = getNearestIndex(maxKeyInt);
long[] newKeyInts = ArrayUtils.copyOfRange(keyNums, startIndex, endIndex);
int numKeyInts = newKeyInts.length;
for (int i = 0; i < numKeyInts; i++) {
newKeyInts[i] -= minKeyInt;
}
int[] newDimensionNumbers = ArrayUtils.copyOfRange(getDimensionNumbers(), dimensionNumbers.length, getDimensionNumbers().length);
int[] newDimensionSizes = ArrayUtils.copyOfRange(getDimensionSizes(), dimensionNumbers.length, getDimensionSizes().length);
double[] newValues = ArrayUtils.copyOfRange(values, startIndex, endIndex);
return new SparseTensor(newDimensionNumbers, newDimensionSizes, newKeyInts, newValues);
}
// TODO(jayantk): This is an extremely naive implementation of
// slice.
// Figure out the appropriate sizes for the subset of dimensions.
int[] dimensionSizes = new int[dimensionNumbers.length];
for (int i = 0; i < dimensionNumbers.length; i++) {
int dimIndex = getDimensionIndex(dimensionNumbers[i]);
Preconditions.checkArgument(dimIndex >= 0);
dimensionSizes[i] = getDimensionSizes()[dimIndex];
}
SparseTensorBuilder builder = new SparseTensorBuilder(dimensionNumbers, dimensionSizes);
builder.put(key, 1.0);
return elementwiseProduct(builder.build()).sumOutDimensions(Ints.asList(dimensionNumbers));
} } | public class class_name {
@Override
public SparseTensor slice(int[] dimensionNumbers, int[] key) {
if (dimensionNumbers.length == 0) {
return this; // depends on control dependency: [if], data = [none]
}
// Check for an efficient case, where the dimensions are the first
// elements of this.
if (ArrayUtils.subarrayEquals(getDimensionNumbers(), dimensionNumbers, 0)) {
long minKeyInt = 0;
int numDimensions = dimensionNumbers.length;
for (int i = 0; i < numDimensions; i++) {
minKeyInt += indexOffsets[i] * key[i]; // depends on control dependency: [for], data = [i]
}
long maxKeyInt = minKeyInt + indexOffsets[numDimensions - 1];
int startIndex = getNearestIndex(minKeyInt);
int endIndex = getNearestIndex(maxKeyInt);
long[] newKeyInts = ArrayUtils.copyOfRange(keyNums, startIndex, endIndex);
int numKeyInts = newKeyInts.length;
for (int i = 0; i < numKeyInts; i++) {
newKeyInts[i] -= minKeyInt; // depends on control dependency: [for], data = [i]
}
int[] newDimensionNumbers = ArrayUtils.copyOfRange(getDimensionNumbers(), dimensionNumbers.length, getDimensionNumbers().length);
int[] newDimensionSizes = ArrayUtils.copyOfRange(getDimensionSizes(), dimensionNumbers.length, getDimensionSizes().length);
double[] newValues = ArrayUtils.copyOfRange(values, startIndex, endIndex);
return new SparseTensor(newDimensionNumbers, newDimensionSizes, newKeyInts, newValues); // depends on control dependency: [if], data = [none]
}
// TODO(jayantk): This is an extremely naive implementation of
// slice.
// Figure out the appropriate sizes for the subset of dimensions.
int[] dimensionSizes = new int[dimensionNumbers.length];
for (int i = 0; i < dimensionNumbers.length; i++) {
int dimIndex = getDimensionIndex(dimensionNumbers[i]);
Preconditions.checkArgument(dimIndex >= 0); // depends on control dependency: [for], data = [none]
dimensionSizes[i] = getDimensionSizes()[dimIndex]; // depends on control dependency: [for], data = [i]
}
SparseTensorBuilder builder = new SparseTensorBuilder(dimensionNumbers, dimensionSizes);
builder.put(key, 1.0);
return elementwiseProduct(builder.build()).sumOutDimensions(Ints.asList(dimensionNumbers));
} } |
public class class_name {
public Document loadDocumentQuiet(GraphRewrite event, EvaluationContext context, XmlFileModel model)
{
try
{
return loadDocument(event, context, model);
}
catch(Exception ex)
{
return null;
}
} } | public class class_name {
public Document loadDocumentQuiet(GraphRewrite event, EvaluationContext context, XmlFileModel model)
{
try
{
return loadDocument(event, context, model); // depends on control dependency: [try], data = [none]
}
catch(Exception ex)
{
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <T> Predicate buildQueryConditions(final Filter filter, final IFilterQueryBuilder<T> filterQueryBuilder) {
if (filterQueryBuilder == null) return null;
// Reset the query builder to ensure it hasn't got any conditions set
filterQueryBuilder.reset();
// the categories to be ANDed will be added to this string
final List<Predicate> andQueryBlock = new ArrayList<Predicate>();
// the categories to be ORed will be added to this string
final List<Predicate> orQueryBlock = new ArrayList<Predicate>();
final CriteriaBuilder queryBuilder = filterQueryBuilder.getCriteriaBuilder();
final List<Predicate> whereQuery = new ArrayList<Predicate>();
/* Check if the Query Builder can build using Tags & Categories */
if (filterQueryBuilder instanceof ITagFilterQueryBuilder) {
final ITagFilterQueryBuilder tagFilterQueryBuilder = (ITagFilterQueryBuilder) filterQueryBuilder;
// loop over the projects that the tags in this filter are assigned to
for (final Project project : filter.getFilterTagProjects()) {
// loop over the categories that the tags in this filter are
// assigned to
for (final Category category : filter.getFilterTagCategories()) {
// define the default logic used for the FilterTag categories
String catInternalLogic = CommonFilterConstants.OR_LOGIC;
String catExternalLogic = CommonFilterConstants.AND_LOGIC;
/*
* Now loop over the FilterCategories, looking for any
* categories that specify a particular boolean logic to apply.
* Remember that not all FilterTags will have an associated
* FilterCategory that specifies the logic to use, in which case
* the default logic defined above will be used.
*/
final Set<FilterCategory> filterCategories = filter.getFilterCategories();
for (final FilterCategory filterCategory : filterCategories) {
final boolean categoryMatch = category.equals(filterCategory.getCategory());
/*
* project or filterCatgeory.getProject() might be null.
* CollectionUtilities.isEqual deals with this situation
*/
final boolean projectMatch = CollectionUtilities.isEqual(project, filterCategory.getProject());
if (categoryMatch && projectMatch) {
final int categoryState = filterCategory.getCategoryState();
if (categoryState == CommonFilterConstants.CATEGORY_INTERNAL_AND_STATE)
catInternalLogic = CommonFilterConstants.AND_LOGIC;
else if (categoryState == CommonFilterConstants.CATEGORY_INTERNAL_OR_STATE)
catInternalLogic = CommonFilterConstants.OR_LOGIC;
else if (categoryState == CommonFilterConstants.CATEGORY_EXTERNAL_AND_STATE)
catExternalLogic = CommonFilterConstants.AND_LOGIC;
else if (categoryState == CommonFilterConstants.CATEGORY_EXTERNAL_OR_STATE)
catExternalLogic = CommonFilterConstants.OR_LOGIC;
}
}
/*
* now build up the HQL that checks to see if the FilterTags
* exist (or not) in this category
*/
final List<Predicate> categoryBlocks = new ArrayList<Predicate>();
boolean matchedSomeTags = false;
final Set<FilterTag> filterTags = filter.getFilterTags();
for (final FilterTag filterTag : filterTags) {
final Tag tag = filterTag.getTag();
/*
* first check to make sure that the FilterTag is actually
* associated with the category we are looking at now
*/
if (tag.isInCategory(category) && tag.isInProject(project)) {
/*
* a FilterTag state of 1 "means exists in category",
* and 0 means "does not exist in category"
*/
final boolean matchTag = filterTag.getTagState() == CommonFilterConstants.MATCH_TAG_STATE;
final boolean notMatchTag = filterTag.getTagState() == CommonFilterConstants.NOT_MATCH_TAG_STATE;
if (matchTag || notMatchTag) {
matchedSomeTags = true;
if (matchTag) {
/* match the tag in this category */
categoryBlocks.add(tagFilterQueryBuilder.getMatchTagString(tag.getTagId()));
} else if (notMatchTag) {
/*
* make sure this tag does not exist in this
* category
*/
categoryBlocks.add(tagFilterQueryBuilder.getNotMatchTagString(tag.getTagId()));
}
}
}
}
if (matchedSomeTags) {
final Predicate categoryBlock;
if (categoryBlocks.size() > 1) {
final Predicate[] catBlockArray = categoryBlocks.toArray(new Predicate[categoryBlocks.size()]);
if (catInternalLogic.equalsIgnoreCase(CommonFilterConstants.OR_LOGIC)) {
categoryBlock = queryBuilder.or(catBlockArray);
} else {
categoryBlock = queryBuilder.and(catBlockArray);
}
} else {
categoryBlock = categoryBlocks.get(0);
}
// append this clause to the appropriate block
if (catExternalLogic.equalsIgnoreCase(CommonFilterConstants.AND_LOGIC)) {
andQueryBlock.add(categoryBlock);
} else {
orQueryBlock.add(categoryBlock);
}
}
}
}
}
/* Check if the Query Builder can build using Locales */
if (filterQueryBuilder instanceof ILocaleFilterQueryBuilder) {
final ILocaleFilterQueryBuilder localeFilterQueryBuilder = (ILocaleFilterQueryBuilder) filterQueryBuilder;
/*
* Loop over the locales and add the query
*/
final List<Predicate> localeBlock = new ArrayList<Predicate>();
final List<Predicate> notLocaleBlock = new ArrayList<Predicate>();
for (final FilterLocale filterLocale : filter.getFilterLocales()) {
if (filterLocale.getLocaleState() == CommonFilterConstants.MATCH_TAG_STATE) {
localeBlock.add(localeFilterQueryBuilder.getMatchingLocaleString(filterLocale.getLocaleName()));
} else if (filterLocale.getLocaleState() == CommonFilterConstants.NOT_MATCH_TAG_STATE) {
notLocaleBlock.add(localeFilterQueryBuilder.getNotMatchingLocaleString(filterLocale.getLocaleName()));
}
}
if (!localeBlock.isEmpty() || !notLocaleBlock.isEmpty()) {
Predicate localeBlockPredicate = null;
if (localeBlock.size() > 1) {
final Predicate[] predicateArray = localeBlock.toArray(new Predicate[localeBlock.size()]);
localeBlockPredicate = queryBuilder.or(predicateArray);
} else if (localeBlock.size() == 1) {
localeBlockPredicate = localeBlock.get(0);
}
Predicate notLocaleBlockPredicate = null;
if (notLocaleBlock.size() > 1) {
final Predicate[] predicateArray = notLocaleBlock.toArray(new Predicate[notLocaleBlock.size()]);
notLocaleBlockPredicate = queryBuilder.and(predicateArray);
} else if (notLocaleBlock.size() == 1) {
notLocaleBlockPredicate = notLocaleBlock.get(0);
}
if (localeBlockPredicate != null && notLocaleBlockPredicate != null)
andQueryBlock.add(queryBuilder.and(localeBlockPredicate, notLocaleBlockPredicate));
else if (localeBlockPredicate != null) andQueryBlock.add(localeBlockPredicate);
else andQueryBlock.add(notLocaleBlockPredicate);
}
}
/*
* build up the category query if some conditions were specified if not,
* we will just return an empty string
*/
if (!andQueryBlock.isEmpty() || !orQueryBlock.isEmpty()) {
// add the and categories
Predicate andQueryPredicate = null;
if (andQueryBlock.size() > 1) {
final Predicate[] predicateArray = andQueryBlock.toArray(new Predicate[andQueryBlock.size()]);
andQueryPredicate = queryBuilder.and(predicateArray);
} else if (andQueryBlock.size() == 1) {
andQueryPredicate = andQueryBlock.get(0);
}
// add the or categories
Predicate orQueryPredicate = null;
if (orQueryBlock.size() > 1) {
final Predicate[] predicateArray = orQueryBlock.toArray(new Predicate[orQueryBlock.size()]);
orQueryPredicate = queryBuilder.or(predicateArray);
} else if (orQueryBlock.size() == 1) {
orQueryPredicate = orQueryBlock.get(0);
}
if (andQueryPredicate != null && orQueryPredicate != null) whereQuery.add(queryBuilder.or(andQueryPredicate, orQueryPredicate));
else if (andQueryPredicate != null) whereQuery.add(andQueryPredicate);
else whereQuery.add(orQueryPredicate);
}
/*
* Do an initial loop over the FilterFields, looking for the field logic
* value
*/
for (final FilterField filterField : filter.getFilterFields())
filterQueryBuilder.addFilterField(filterField.getField(), filterField.getValue());
filterQueryBuilder.process();
final Predicate fieldQuery = filterQueryBuilder.getFilterConditions();
if (fieldQuery != null) {
whereQuery.add(fieldQuery);
}
if (whereQuery.size() > 1) {
final Predicate[] queries = whereQuery.toArray(new Predicate[whereQuery.size()]);
return queryBuilder.and(queries);
} else if (whereQuery.size() == 1) {
return whereQuery.get(0);
}
return null;
} } | public class class_name {
public static <T> Predicate buildQueryConditions(final Filter filter, final IFilterQueryBuilder<T> filterQueryBuilder) {
if (filterQueryBuilder == null) return null;
// Reset the query builder to ensure it hasn't got any conditions set
filterQueryBuilder.reset();
// the categories to be ANDed will be added to this string
final List<Predicate> andQueryBlock = new ArrayList<Predicate>();
// the categories to be ORed will be added to this string
final List<Predicate> orQueryBlock = new ArrayList<Predicate>();
final CriteriaBuilder queryBuilder = filterQueryBuilder.getCriteriaBuilder();
final List<Predicate> whereQuery = new ArrayList<Predicate>();
/* Check if the Query Builder can build using Tags & Categories */
if (filterQueryBuilder instanceof ITagFilterQueryBuilder) {
final ITagFilterQueryBuilder tagFilterQueryBuilder = (ITagFilterQueryBuilder) filterQueryBuilder;
// loop over the projects that the tags in this filter are assigned to
for (final Project project : filter.getFilterTagProjects()) {
// loop over the categories that the tags in this filter are
// assigned to
for (final Category category : filter.getFilterTagCategories()) {
// define the default logic used for the FilterTag categories
String catInternalLogic = CommonFilterConstants.OR_LOGIC;
String catExternalLogic = CommonFilterConstants.AND_LOGIC;
/*
* Now loop over the FilterCategories, looking for any
* categories that specify a particular boolean logic to apply.
* Remember that not all FilterTags will have an associated
* FilterCategory that specifies the logic to use, in which case
* the default logic defined above will be used.
*/
final Set<FilterCategory> filterCategories = filter.getFilterCategories();
for (final FilterCategory filterCategory : filterCategories) {
final boolean categoryMatch = category.equals(filterCategory.getCategory());
/*
* project or filterCatgeory.getProject() might be null.
* CollectionUtilities.isEqual deals with this situation
*/
final boolean projectMatch = CollectionUtilities.isEqual(project, filterCategory.getProject());
if (categoryMatch && projectMatch) {
final int categoryState = filterCategory.getCategoryState();
if (categoryState == CommonFilterConstants.CATEGORY_INTERNAL_AND_STATE)
catInternalLogic = CommonFilterConstants.AND_LOGIC;
else if (categoryState == CommonFilterConstants.CATEGORY_INTERNAL_OR_STATE)
catInternalLogic = CommonFilterConstants.OR_LOGIC;
else if (categoryState == CommonFilterConstants.CATEGORY_EXTERNAL_AND_STATE)
catExternalLogic = CommonFilterConstants.AND_LOGIC;
else if (categoryState == CommonFilterConstants.CATEGORY_EXTERNAL_OR_STATE)
catExternalLogic = CommonFilterConstants.OR_LOGIC;
}
}
/*
* now build up the HQL that checks to see if the FilterTags
* exist (or not) in this category
*/
final List<Predicate> categoryBlocks = new ArrayList<Predicate>();
boolean matchedSomeTags = false;
final Set<FilterTag> filterTags = filter.getFilterTags();
for (final FilterTag filterTag : filterTags) {
final Tag tag = filterTag.getTag();
/*
* first check to make sure that the FilterTag is actually
* associated with the category we are looking at now
*/
if (tag.isInCategory(category) && tag.isInProject(project)) {
/*
* a FilterTag state of 1 "means exists in category",
* and 0 means "does not exist in category"
*/
final boolean matchTag = filterTag.getTagState() == CommonFilterConstants.MATCH_TAG_STATE;
final boolean notMatchTag = filterTag.getTagState() == CommonFilterConstants.NOT_MATCH_TAG_STATE;
if (matchTag || notMatchTag) {
matchedSomeTags = true; // depends on control dependency: [if], data = [none]
if (matchTag) {
/* match the tag in this category */
categoryBlocks.add(tagFilterQueryBuilder.getMatchTagString(tag.getTagId())); // depends on control dependency: [if], data = [none]
} else if (notMatchTag) {
/*
* make sure this tag does not exist in this
* category
*/
categoryBlocks.add(tagFilterQueryBuilder.getNotMatchTagString(tag.getTagId())); // depends on control dependency: [if], data = [none]
}
}
}
}
if (matchedSomeTags) {
final Predicate categoryBlock;
if (categoryBlocks.size() > 1) {
final Predicate[] catBlockArray = categoryBlocks.toArray(new Predicate[categoryBlocks.size()]);
if (catInternalLogic.equalsIgnoreCase(CommonFilterConstants.OR_LOGIC)) {
categoryBlock = queryBuilder.or(catBlockArray); // depends on control dependency: [if], data = [none]
} else {
categoryBlock = queryBuilder.and(catBlockArray); // depends on control dependency: [if], data = [none]
}
} else {
categoryBlock = categoryBlocks.get(0); // depends on control dependency: [if], data = [none]
}
// append this clause to the appropriate block
if (catExternalLogic.equalsIgnoreCase(CommonFilterConstants.AND_LOGIC)) {
andQueryBlock.add(categoryBlock); // depends on control dependency: [if], data = [none]
} else {
orQueryBlock.add(categoryBlock); // depends on control dependency: [if], data = [none]
}
}
}
}
}
/* Check if the Query Builder can build using Locales */
if (filterQueryBuilder instanceof ILocaleFilterQueryBuilder) {
final ILocaleFilterQueryBuilder localeFilterQueryBuilder = (ILocaleFilterQueryBuilder) filterQueryBuilder;
/*
* Loop over the locales and add the query
*/
final List<Predicate> localeBlock = new ArrayList<Predicate>();
final List<Predicate> notLocaleBlock = new ArrayList<Predicate>();
for (final FilterLocale filterLocale : filter.getFilterLocales()) {
if (filterLocale.getLocaleState() == CommonFilterConstants.MATCH_TAG_STATE) {
localeBlock.add(localeFilterQueryBuilder.getMatchingLocaleString(filterLocale.getLocaleName())); // depends on control dependency: [if], data = [none]
} else if (filterLocale.getLocaleState() == CommonFilterConstants.NOT_MATCH_TAG_STATE) {
notLocaleBlock.add(localeFilterQueryBuilder.getNotMatchingLocaleString(filterLocale.getLocaleName())); // depends on control dependency: [if], data = [none]
}
}
if (!localeBlock.isEmpty() || !notLocaleBlock.isEmpty()) {
Predicate localeBlockPredicate = null;
if (localeBlock.size() > 1) {
final Predicate[] predicateArray = localeBlock.toArray(new Predicate[localeBlock.size()]);
localeBlockPredicate = queryBuilder.or(predicateArray); // depends on control dependency: [if], data = [none]
} else if (localeBlock.size() == 1) {
localeBlockPredicate = localeBlock.get(0); // depends on control dependency: [if], data = [none]
}
Predicate notLocaleBlockPredicate = null;
if (notLocaleBlock.size() > 1) {
final Predicate[] predicateArray = notLocaleBlock.toArray(new Predicate[notLocaleBlock.size()]);
notLocaleBlockPredicate = queryBuilder.and(predicateArray); // depends on control dependency: [if], data = [none]
} else if (notLocaleBlock.size() == 1) {
notLocaleBlockPredicate = notLocaleBlock.get(0); // depends on control dependency: [if], data = [none]
}
if (localeBlockPredicate != null && notLocaleBlockPredicate != null)
andQueryBlock.add(queryBuilder.and(localeBlockPredicate, notLocaleBlockPredicate));
else if (localeBlockPredicate != null) andQueryBlock.add(localeBlockPredicate);
else andQueryBlock.add(notLocaleBlockPredicate);
}
}
/*
* build up the category query if some conditions were specified if not,
* we will just return an empty string
*/
if (!andQueryBlock.isEmpty() || !orQueryBlock.isEmpty()) {
// add the and categories
Predicate andQueryPredicate = null;
if (andQueryBlock.size() > 1) {
final Predicate[] predicateArray = andQueryBlock.toArray(new Predicate[andQueryBlock.size()]);
andQueryPredicate = queryBuilder.and(predicateArray); // depends on control dependency: [if], data = [none]
} else if (andQueryBlock.size() == 1) {
andQueryPredicate = andQueryBlock.get(0); // depends on control dependency: [if], data = [none]
}
// add the or categories
Predicate orQueryPredicate = null;
if (orQueryBlock.size() > 1) {
final Predicate[] predicateArray = orQueryBlock.toArray(new Predicate[orQueryBlock.size()]);
orQueryPredicate = queryBuilder.or(predicateArray); // depends on control dependency: [if], data = [none]
} else if (orQueryBlock.size() == 1) {
orQueryPredicate = orQueryBlock.get(0); // depends on control dependency: [if], data = [none]
}
if (andQueryPredicate != null && orQueryPredicate != null) whereQuery.add(queryBuilder.or(andQueryPredicate, orQueryPredicate));
else if (andQueryPredicate != null) whereQuery.add(andQueryPredicate);
else whereQuery.add(orQueryPredicate);
}
/*
* Do an initial loop over the FilterFields, looking for the field logic
* value
*/
for (final FilterField filterField : filter.getFilterFields())
filterQueryBuilder.addFilterField(filterField.getField(), filterField.getValue());
filterQueryBuilder.process();
final Predicate fieldQuery = filterQueryBuilder.getFilterConditions();
if (fieldQuery != null) {
whereQuery.add(fieldQuery); // depends on control dependency: [if], data = [(fieldQuery]
}
if (whereQuery.size() > 1) {
final Predicate[] queries = whereQuery.toArray(new Predicate[whereQuery.size()]);
return queryBuilder.and(queries); // depends on control dependency: [if], data = [none]
} else if (whereQuery.size() == 1) {
return whereQuery.get(0); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
private void retireReduceUnprotected(TaskInProgress tip) {
if (runningReduces == null) {
LOG.warn("Running list for reducers missing!! "
+ "Job details are missing.");
return;
}
runningReduces.remove(tip);
} } | public class class_name {
private void retireReduceUnprotected(TaskInProgress tip) {
if (runningReduces == null) {
LOG.warn("Running list for reducers missing!! "
+ "Job details are missing."); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
runningReduces.remove(tip);
} } |
public class class_name {
public static String chop(String str) {
if (str == null) {
return null;
}
int strLen = str.length();
if (strLen < 2) {
return EMPTY;
}
int lastIdx = strLen - 1;
String ret = str.substring(0, lastIdx);
char last = str.charAt(lastIdx);
if (last == LF) {
if (ret.charAt(lastIdx - 1) == CR) {
return ret.substring(0, lastIdx - 1);
}
}
return ret;
} } | public class class_name {
public static String chop(String str) {
if (str == null) {
return null; // depends on control dependency: [if], data = [none]
}
int strLen = str.length();
if (strLen < 2) {
return EMPTY; // depends on control dependency: [if], data = [none]
}
int lastIdx = strLen - 1;
String ret = str.substring(0, lastIdx);
char last = str.charAt(lastIdx);
if (last == LF) {
if (ret.charAt(lastIdx - 1) == CR) {
return ret.substring(0, lastIdx - 1); // depends on control dependency: [if], data = [none]
}
}
return ret;
} } |
public class class_name {
private String clean(final String _endPointName)
{
String localTo = _endPointName.trim();
// strip all white space from within the name as some source
// pass in a formatted phone number (e.g. 03 8320 8100)
int tmp = localTo.indexOf(" "); //$NON-NLS-1$
while (tmp != -1)
{
localTo = localTo.substring(0, tmp) + localTo.substring(tmp + 1, localTo.length());
tmp = localTo.indexOf(" "); //$NON-NLS-1$
}
return localTo.toLowerCase();
} } | public class class_name {
private String clean(final String _endPointName)
{
String localTo = _endPointName.trim();
// strip all white space from within the name as some source
// pass in a formatted phone number (e.g. 03 8320 8100)
int tmp = localTo.indexOf(" "); //$NON-NLS-1$
while (tmp != -1)
{
localTo = localTo.substring(0, tmp) + localTo.substring(tmp + 1, localTo.length()); // depends on control dependency: [while], data = [(tmp]
tmp = localTo.indexOf(" "); //$NON-NLS-1$ // depends on control dependency: [while], data = [none]
}
return localTo.toLowerCase();
} } |
public class class_name {
public static String getEditState(CmsUUID resourceId, boolean plainText, String backLink) {
try {
backLink = URLEncoder.encode(backLink, CmsEncoder.ENCODING_UTF_8);
} catch (UnsupportedEncodingException e) {
LOG.error(e.getLocalizedMessage(), e);
}
String state = "";
state = A_CmsWorkplaceApp.addParamToState(state, CmsEditor.RESOURCE_ID_PREFIX, resourceId.toString());
state = A_CmsWorkplaceApp.addParamToState(state, CmsEditor.PLAIN_TEXT_PREFIX, String.valueOf(plainText));
state = A_CmsWorkplaceApp.addParamToState(state, CmsEditor.BACK_LINK_PREFIX, backLink);
return state;
} } | public class class_name {
public static String getEditState(CmsUUID resourceId, boolean plainText, String backLink) {
try {
backLink = URLEncoder.encode(backLink, CmsEncoder.ENCODING_UTF_8); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
String state = "";
state = A_CmsWorkplaceApp.addParamToState(state, CmsEditor.RESOURCE_ID_PREFIX, resourceId.toString());
state = A_CmsWorkplaceApp.addParamToState(state, CmsEditor.PLAIN_TEXT_PREFIX, String.valueOf(plainText));
state = A_CmsWorkplaceApp.addParamToState(state, CmsEditor.BACK_LINK_PREFIX, backLink);
return state;
} } |
public class class_name {
public static Resource getFileResource(String filePath, TestContext context) {
if (filePath.contains(FILE_PATH_CHARSET_PARAMETER)) {
return new PathMatchingResourcePatternResolver().getResource(
context.replaceDynamicContentInString(filePath.substring(0, filePath.indexOf(FileUtils.FILE_PATH_CHARSET_PARAMETER))));
} else {
return new PathMatchingResourcePatternResolver().getResource(
context.replaceDynamicContentInString(filePath));
}
} } | public class class_name {
public static Resource getFileResource(String filePath, TestContext context) {
if (filePath.contains(FILE_PATH_CHARSET_PARAMETER)) {
return new PathMatchingResourcePatternResolver().getResource(
context.replaceDynamicContentInString(filePath.substring(0, filePath.indexOf(FileUtils.FILE_PATH_CHARSET_PARAMETER)))); // depends on control dependency: [if], data = [none]
} else {
return new PathMatchingResourcePatternResolver().getResource(
context.replaceDynamicContentInString(filePath)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public synchronized void lostNodeFound(Address address) {
Preconditions.checkNotNull(address, "address should not be null");
mLostNodes.remove(address);
for (Runnable function : mChangeListeners) {
function.run();
}
} } | public class class_name {
public synchronized void lostNodeFound(Address address) {
Preconditions.checkNotNull(address, "address should not be null");
mLostNodes.remove(address);
for (Runnable function : mChangeListeners) {
function.run(); // depends on control dependency: [for], data = [function]
}
} } |
public class class_name {
public void setContexts(java.util.Collection<PhaseContext> contexts) {
if (contexts == null) {
this.contexts = null;
return;
}
this.contexts = new java.util.ArrayList<PhaseContext>(contexts);
} } | public class class_name {
public void setContexts(java.util.Collection<PhaseContext> contexts) {
if (contexts == null) {
this.contexts = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.contexts = new java.util.ArrayList<PhaseContext>(contexts);
} } |
public class class_name {
public void refreshNodes(Configuration conf) throws IOException {
LOG.info("Refreshing nodes.");
checkSuperuserPrivilege();
// Reread the config to get dfs.hosts and dfs.hosts.exclude filenames.
// Update the file names and refresh internal includes and excludes list
if (conf == null) {
conf = new Configuration();
}
hostsReader.updateFileNames(conf.get(FSConstants.DFS_HOSTS, ""),
conf.get("dfs.hosts.exclude", ""), true);
Set<String> includes = hostsReader.getNewIncludes();
Set<String> excludes = hostsReader.getNewExcludes();
Set<String> prevIncludes = hostsReader.getHosts();
Set<String> prevExcludes = hostsReader.getExcludedHosts();
// We need to syncrhonize on hostsReader here so that no thread reads from
// hostsReader between the two updates to hostsReader in this function.
synchronized (hostsReader) {
hostsReader.switchFiles(includes, excludes);
try {
replicator.hostsUpdated();
} catch (DefaultRackException e) {
// We want to update the includes and excludes files only if hostsUpdated,
// doesn't throw an exception. This avoids inconsitency between the
// replicator and the fnamesystem especially for
// BlockPlacementPolicyConfigurable.
hostsReader.switchFiles(prevIncludes, prevExcludes);
throw e;
}
}
writeLock();
try {
for (Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator();
it.hasNext();) {
DatanodeDescriptor node = it.next();
// Check if not include.
if (!inHostsList(node, null)) {
node.setDisallowed(true); // case 2.
} else {
if (inExcludedHostsList(node, null)) {
startDecommission(node); // case 3.
} else {
stopDecommission(node); // case 4.
}
}
}
} finally {
writeUnlock();
}
LOG.info("Refreshing nodes - DONE");
} } | public class class_name {
public void refreshNodes(Configuration conf) throws IOException {
LOG.info("Refreshing nodes.");
checkSuperuserPrivilege();
// Reread the config to get dfs.hosts and dfs.hosts.exclude filenames.
// Update the file names and refresh internal includes and excludes list
if (conf == null) {
conf = new Configuration();
}
hostsReader.updateFileNames(conf.get(FSConstants.DFS_HOSTS, ""),
conf.get("dfs.hosts.exclude", ""), true);
Set<String> includes = hostsReader.getNewIncludes();
Set<String> excludes = hostsReader.getNewExcludes();
Set<String> prevIncludes = hostsReader.getHosts();
Set<String> prevExcludes = hostsReader.getExcludedHosts();
// We need to syncrhonize on hostsReader here so that no thread reads from
// hostsReader between the two updates to hostsReader in this function.
synchronized (hostsReader) {
hostsReader.switchFiles(includes, excludes);
try {
replicator.hostsUpdated(); // depends on control dependency: [try], data = [none]
} catch (DefaultRackException e) {
// We want to update the includes and excludes files only if hostsUpdated,
// doesn't throw an exception. This avoids inconsitency between the
// replicator and the fnamesystem especially for
// BlockPlacementPolicyConfigurable.
hostsReader.switchFiles(prevIncludes, prevExcludes);
throw e;
} // depends on control dependency: [catch], data = [none]
}
writeLock();
try {
for (Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator();
it.hasNext();) {
DatanodeDescriptor node = it.next();
// Check if not include.
if (!inHostsList(node, null)) {
node.setDisallowed(true); // case 2. // depends on control dependency: [if], data = [none]
} else {
if (inExcludedHostsList(node, null)) {
startDecommission(node); // case 3. // depends on control dependency: [if], data = [none]
} else {
stopDecommission(node); // case 4. // depends on control dependency: [if], data = [none]
}
}
}
} finally {
writeUnlock();
}
LOG.info("Refreshing nodes - DONE");
} } |
public class class_name {
final void addException(SQLException exception) {
if (!(exception instanceof SQLTimeoutException) && !(exception instanceof SQLTransactionRollbackException)) {
getOrInit().offer(exception); // SQLExceptions from the above two sub-types are not stored
}
} } | public class class_name {
final void addException(SQLException exception) {
if (!(exception instanceof SQLTimeoutException) && !(exception instanceof SQLTransactionRollbackException)) {
getOrInit().offer(exception); // SQLExceptions from the above two sub-types are not stored // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String validate (ActionSequence seq)
{
if (StringUtil.isBlank(seq.name)) {
return "Missing 'name' definition.";
}
if (seq.framesPerSecond == 0) {
return "Missing 'framesPerSecond' definition.";
}
if (seq.orients == null) {
return "Missing 'orients' definition.";
}
return null;
} } | public class class_name {
public static String validate (ActionSequence seq)
{
if (StringUtil.isBlank(seq.name)) {
return "Missing 'name' definition."; // depends on control dependency: [if], data = [none]
}
if (seq.framesPerSecond == 0) {
return "Missing 'framesPerSecond' definition."; // depends on control dependency: [if], data = [none]
}
if (seq.orients == null) {
return "Missing 'orients' definition."; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static <T> IPromise<T> race( IPromise<T>... futures ) {
Promise p = new Promise();
AtomicBoolean fin = new AtomicBoolean(false);
for (int i = 0; i < futures.length; i++) {
futures[i].then( (r,e) -> {
if ( fin.compareAndSet(false,true) ) {
p.complete(r, e);
}
});
}
return p;
} } | public class class_name {
public static <T> IPromise<T> race( IPromise<T>... futures ) {
Promise p = new Promise();
AtomicBoolean fin = new AtomicBoolean(false);
for (int i = 0; i < futures.length; i++) {
futures[i].then( (r,e) -> {
if ( fin.compareAndSet(false,true) ) {
p.complete(r, e); // depends on control dependency: [if], data = [none]
}
});
}
return p;
} } |
public class class_name {
public List<GetterType<BeanType<T>>> getAllGetter()
{
List<GetterType<BeanType<T>>> list = new ArrayList<GetterType<BeanType<T>>>();
List<Node> nodeList = childNode.get("getter");
for(Node node: nodeList)
{
GetterType<BeanType<T>> type = new GetterTypeImpl<BeanType<T>>(this, "getter", childNode, node);
list.add(type);
}
return list;
} } | public class class_name {
public List<GetterType<BeanType<T>>> getAllGetter()
{
List<GetterType<BeanType<T>>> list = new ArrayList<GetterType<BeanType<T>>>();
List<Node> nodeList = childNode.get("getter");
for(Node node: nodeList)
{
GetterType<BeanType<T>> type = new GetterTypeImpl<BeanType<T>>(this, "getter", childNode, node);
list.add(type); // depends on control dependency: [for], data = [none]
}
return list;
} } |
public class class_name {
protected String getToNames() {
List<String> excluded = new ArrayList<String>();
List<String> users = new ArrayList<String>();
Iterator<String> itGroups = getGroups().iterator();
while (itGroups.hasNext()) {
String groupName = itGroups.next();
try {
Iterator<CmsUser> itUsers = getCms().getUsersOfGroup(groupName, true).iterator();
while (itUsers.hasNext()) {
CmsUser user = itUsers.next();
String userName = user.getFullName();
if (!users.contains(userName)) {
String emailAddress = user.getEmail();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(emailAddress)) {
users.add(userName);
} else {
excluded.add(userName);
}
}
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
if (!excluded.isEmpty()) {
StringBuffer text = new StringBuffer(500);
text.append(Messages.get().container(Messages.GUI_EXCLUDED_USERS_WARNING_0).key(getLocale()));
text.append("<br>");
Iterator<String> it = excluded.iterator();
while (it.hasNext()) {
text.append("- ");
text.append(it.next());
text.append("<br>");
}
setExcludedUsers(text.toString());
}
if (users.isEmpty()) {
setCommitErrors(
Collections.singletonList((Throwable)new CmsIllegalStateException(
Messages.get().container(Messages.ERR_NO_SELECTED_USER_WITH_EMAIL_0))));
return "";
}
StringBuffer result = new StringBuffer(256);
Iterator<String> itUsers = users.iterator();
while (itUsers.hasNext()) {
result.append(itUsers.next().toString());
if (itUsers.hasNext()) {
result.append("; ");
}
}
return result.toString();
} } | public class class_name {
protected String getToNames() {
List<String> excluded = new ArrayList<String>();
List<String> users = new ArrayList<String>();
Iterator<String> itGroups = getGroups().iterator();
while (itGroups.hasNext()) {
String groupName = itGroups.next();
try {
Iterator<CmsUser> itUsers = getCms().getUsersOfGroup(groupName, true).iterator();
while (itUsers.hasNext()) {
CmsUser user = itUsers.next();
String userName = user.getFullName();
if (!users.contains(userName)) {
String emailAddress = user.getEmail();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(emailAddress)) {
users.add(userName); // depends on control dependency: [if], data = [none]
} else {
excluded.add(userName); // depends on control dependency: [if], data = [none]
}
}
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
if (!excluded.isEmpty()) {
StringBuffer text = new StringBuffer(500);
text.append(Messages.get().container(Messages.GUI_EXCLUDED_USERS_WARNING_0).key(getLocale())); // depends on control dependency: [if], data = [none]
text.append("<br>"); // depends on control dependency: [if], data = [none]
Iterator<String> it = excluded.iterator();
while (it.hasNext()) {
text.append("- "); // depends on control dependency: [while], data = [none]
text.append(it.next()); // depends on control dependency: [while], data = [none]
text.append("<br>"); // depends on control dependency: [while], data = [none]
}
setExcludedUsers(text.toString()); // depends on control dependency: [if], data = [none]
}
if (users.isEmpty()) {
setCommitErrors(
Collections.singletonList((Throwable)new CmsIllegalStateException(
Messages.get().container(Messages.ERR_NO_SELECTED_USER_WITH_EMAIL_0)))); // depends on control dependency: [if], data = [none]
return ""; // depends on control dependency: [if], data = [none]
}
StringBuffer result = new StringBuffer(256);
Iterator<String> itUsers = users.iterator();
while (itUsers.hasNext()) {
result.append(itUsers.next().toString()); // depends on control dependency: [while], data = [none]
if (itUsers.hasNext()) {
result.append("; "); // depends on control dependency: [if], data = [none]
}
}
return result.toString();
} } |
public class class_name {
@Override
public boolean containsKey(Object key) {
if (key == null) {
return false;
}
Map<String, GroovyRunner> map = getMap();
readLock.lock();
try {
return map.containsKey(key);
} finally {
readLock.unlock();
}
} } | public class class_name {
@Override
public boolean containsKey(Object key) {
if (key == null) {
return false; // depends on control dependency: [if], data = [none]
}
Map<String, GroovyRunner> map = getMap();
readLock.lock();
try {
return map.containsKey(key); // depends on control dependency: [try], data = [none]
} finally {
readLock.unlock();
}
} } |
public class class_name {
public void startTransaction()
{
Long key = Long.valueOf(Thread.currentThread().getId());
TransactionImpl tx = txs.get(key);
if (tx == null)
{
TransactionImpl newTx = new TransactionImpl(key);
tx = txs.putIfAbsent(key, newTx);
if (tx == null)
tx = newTx;
}
tx.active();
} } | public class class_name {
public void startTransaction()
{
Long key = Long.valueOf(Thread.currentThread().getId());
TransactionImpl tx = txs.get(key);
if (tx == null)
{
TransactionImpl newTx = new TransactionImpl(key);
tx = txs.putIfAbsent(key, newTx); // depends on control dependency: [if], data = [none]
if (tx == null)
tx = newTx;
}
tx.active();
} } |
public class class_name {
public Accelerator withIpSets(IpSet... ipSets) {
if (this.ipSets == null) {
setIpSets(new java.util.ArrayList<IpSet>(ipSets.length));
}
for (IpSet ele : ipSets) {
this.ipSets.add(ele);
}
return this;
} } | public class class_name {
public Accelerator withIpSets(IpSet... ipSets) {
if (this.ipSets == null) {
setIpSets(new java.util.ArrayList<IpSet>(ipSets.length)); // depends on control dependency: [if], data = [none]
}
for (IpSet ele : ipSets) {
this.ipSets.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public final CountedCompleter<?> nextComplete() {
CountedCompleter<?> p;
if ((p = completer) != null)
return p.firstComplete();
else {
quietlyComplete();
return null;
}
} } | public class class_name {
public final CountedCompleter<?> nextComplete() {
CountedCompleter<?> p;
if ((p = completer) != null)
return p.firstComplete();
else {
quietlyComplete(); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public FrequencyTableEntry toFrequencyTableEntry()
{
FrequencyTableEntry result = new FrequencyTableEntry();
result.setReferencedNode(nr);
if (annotation != null && "tok".equals(annotation))
{
result.setType(FrequencyTableEntryType.span);
}
else
{
result.setType(FrequencyTableEntryType.annotation);
result.setKey(annotation);
}
return result;
} } | public class class_name {
public FrequencyTableEntry toFrequencyTableEntry()
{
FrequencyTableEntry result = new FrequencyTableEntry();
result.setReferencedNode(nr);
if (annotation != null && "tok".equals(annotation))
{
result.setType(FrequencyTableEntryType.span); // depends on control dependency: [if], data = [none]
}
else
{
result.setType(FrequencyTableEntryType.annotation); // depends on control dependency: [if], data = [none]
result.setKey(annotation); // depends on control dependency: [if], data = [(annotation]
}
return result;
} } |
public class class_name {
public void get1Value(int index, float[] valueDestination) {
try {
SFVec3f sfVec3f = value.get(index);
valueDestination[0] = sfVec3f.x;
valueDestination[1] = sfVec3f.y;
valueDestination[2] = sfVec3f.z;
}
catch (IndexOutOfBoundsException e) {
Log.e(TAG, "X3D MFVec3f get1Value(index) out of bounds." + e);
}
catch (Exception e) {
Log.e(TAG, "X3D MFVec3f get1Value(index) exception " + e);
}
} } | public class class_name {
public void get1Value(int index, float[] valueDestination) {
try {
SFVec3f sfVec3f = value.get(index);
valueDestination[0] = sfVec3f.x; // depends on control dependency: [try], data = [none]
valueDestination[1] = sfVec3f.y; // depends on control dependency: [try], data = [none]
valueDestination[2] = sfVec3f.z; // depends on control dependency: [try], data = [none]
}
catch (IndexOutOfBoundsException e) {
Log.e(TAG, "X3D MFVec3f get1Value(index) out of bounds." + e);
} // depends on control dependency: [catch], data = [none]
catch (Exception e) {
Log.e(TAG, "X3D MFVec3f get1Value(index) exception " + e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity", "checkstyle:nestedifdepth"})
protected List<Issue> validate(ResourceSet resourceSet, Collection<Resource> validResources, IProgressMonitor progress) {
assert progress != null;
progress.subTask(Messages.SarlBatchCompiler_38);
getLogger().info(Messages.SarlBatchCompiler_38);
final List<Resource> resources = new LinkedList<>(resourceSet.getResources());
final List<Issue> issuesToReturn = new ArrayList<>();
for (final Resource resource : resources) {
if (progress.isCanceled()) {
return issuesToReturn;
}
if (isSourceFile(resource)) {
if (getLogger().isDebugEnabled()) {
getLogger().debug(Messages.SarlBatchCompiler_22, resource.getURI().lastSegment());
}
final IResourceServiceProvider resourceServiceProvider = IResourceServiceProvider.Registry.INSTANCE
.getResourceServiceProvider(resource.getURI());
if (resourceServiceProvider != null) {
final IResourceValidator resourceValidator = resourceServiceProvider.getResourceValidator();
final List<Issue> result = resourceValidator.validate(resource, CheckMode.ALL, null);
if (progress.isCanceled()) {
return issuesToReturn;
}
final SortedSet<Issue> issues = new TreeSet<>(getIssueComparator());
boolean hasValidationError = false;
for (final Issue issue : result) {
if (progress.isCanceled()) {
return issuesToReturn;
}
if (issue.isSyntaxError() || issue.getSeverity() == Severity.ERROR) {
hasValidationError = true;
}
issues.add(issue);
}
if (!hasValidationError) {
if (!issues.isEmpty()) {
if (getLogger().isDebugEnabled()) {
getLogger().debug(Messages.SarlBatchCompiler_39, resource.getURI().lastSegment());
}
issuesToReturn.addAll(issues);
}
validResources.add(resource);
} else {
if (getLogger().isDebugEnabled()) {
getLogger().debug(Messages.SarlBatchCompiler_39, resource.getURI().lastSegment());
}
issuesToReturn.addAll(issues);
}
}
}
}
return issuesToReturn;
} } | public class class_name {
@SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity", "checkstyle:nestedifdepth"})
protected List<Issue> validate(ResourceSet resourceSet, Collection<Resource> validResources, IProgressMonitor progress) {
assert progress != null;
progress.subTask(Messages.SarlBatchCompiler_38);
getLogger().info(Messages.SarlBatchCompiler_38);
final List<Resource> resources = new LinkedList<>(resourceSet.getResources());
final List<Issue> issuesToReturn = new ArrayList<>();
for (final Resource resource : resources) {
if (progress.isCanceled()) {
return issuesToReturn; // depends on control dependency: [if], data = [none]
}
if (isSourceFile(resource)) {
if (getLogger().isDebugEnabled()) {
getLogger().debug(Messages.SarlBatchCompiler_22, resource.getURI().lastSegment()); // depends on control dependency: [if], data = [none]
}
final IResourceServiceProvider resourceServiceProvider = IResourceServiceProvider.Registry.INSTANCE
.getResourceServiceProvider(resource.getURI());
if (resourceServiceProvider != null) {
final IResourceValidator resourceValidator = resourceServiceProvider.getResourceValidator();
final List<Issue> result = resourceValidator.validate(resource, CheckMode.ALL, null);
if (progress.isCanceled()) {
return issuesToReturn; // depends on control dependency: [if], data = [none]
}
final SortedSet<Issue> issues = new TreeSet<>(getIssueComparator());
boolean hasValidationError = false;
for (final Issue issue : result) {
if (progress.isCanceled()) {
return issuesToReturn; // depends on control dependency: [if], data = [none]
}
if (issue.isSyntaxError() || issue.getSeverity() == Severity.ERROR) {
hasValidationError = true; // depends on control dependency: [if], data = [none]
}
issues.add(issue); // depends on control dependency: [for], data = [issue]
}
if (!hasValidationError) {
if (!issues.isEmpty()) {
if (getLogger().isDebugEnabled()) {
getLogger().debug(Messages.SarlBatchCompiler_39, resource.getURI().lastSegment()); // depends on control dependency: [if], data = [none]
}
issuesToReturn.addAll(issues); // depends on control dependency: [if], data = [none]
}
validResources.add(resource); // depends on control dependency: [if], data = [none]
} else {
if (getLogger().isDebugEnabled()) {
getLogger().debug(Messages.SarlBatchCompiler_39, resource.getURI().lastSegment()); // depends on control dependency: [if], data = [none]
}
issuesToReturn.addAll(issues); // depends on control dependency: [if], data = [none]
}
}
}
}
return issuesToReturn;
} } |
public class class_name {
public static ByteBuf wrappedBuffer(ByteBuffer buffer) {
if (!buffer.hasRemaining()) {
return EMPTY_BUFFER;
}
if (!buffer.isDirect() && buffer.hasArray()) {
return wrappedBuffer(
buffer.array(),
buffer.arrayOffset() + buffer.position(),
buffer.remaining()).order(buffer.order());
} else if (PlatformDependent.hasUnsafe()) {
if (buffer.isReadOnly()) {
if (buffer.isDirect()) {
return new ReadOnlyUnsafeDirectByteBuf(ALLOC, buffer);
} else {
return new ReadOnlyByteBufferBuf(ALLOC, buffer);
}
} else {
return new UnpooledUnsafeDirectByteBuf(ALLOC, buffer, buffer.remaining());
}
} else {
if (buffer.isReadOnly()) {
return new ReadOnlyByteBufferBuf(ALLOC, buffer);
} else {
return new UnpooledDirectByteBuf(ALLOC, buffer, buffer.remaining());
}
}
} } | public class class_name {
public static ByteBuf wrappedBuffer(ByteBuffer buffer) {
if (!buffer.hasRemaining()) {
return EMPTY_BUFFER; // depends on control dependency: [if], data = [none]
}
if (!buffer.isDirect() && buffer.hasArray()) {
return wrappedBuffer(
buffer.array(),
buffer.arrayOffset() + buffer.position(),
buffer.remaining()).order(buffer.order()); // depends on control dependency: [if], data = [none]
} else if (PlatformDependent.hasUnsafe()) {
if (buffer.isReadOnly()) {
if (buffer.isDirect()) {
return new ReadOnlyUnsafeDirectByteBuf(ALLOC, buffer); // depends on control dependency: [if], data = [none]
} else {
return new ReadOnlyByteBufferBuf(ALLOC, buffer); // depends on control dependency: [if], data = [none]
}
} else {
return new UnpooledUnsafeDirectByteBuf(ALLOC, buffer, buffer.remaining()); // depends on control dependency: [if], data = [none]
}
} else {
if (buffer.isReadOnly()) {
return new ReadOnlyByteBufferBuf(ALLOC, buffer); // depends on control dependency: [if], data = [none]
} else {
return new UnpooledDirectByteBuf(ALLOC, buffer, buffer.remaining()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static void main(String [] args){
//tagging
if (args.length != 2){
System.out.println("WordTrainGenerating [Model Dir] [File/Folder]");
System.out.println("Generating training data for word segmentation with FlexCRFs++ or jvnmaxent (in JVnTextPro)");
System.out.println("Model Dir: directory containing featuretemple file");
System.out.println("Input File/Folder: file/folder name containing data manually tagged for training");
return;
}
WordTrainGenerating trainGen = new WordTrainGenerating(args[0]);
trainGen.generateTrainData(args[1], args[1]);
} } | public class class_name {
public static void main(String [] args){
//tagging
if (args.length != 2){
System.out.println("WordTrainGenerating [Model Dir] [File/Folder]");
// depends on control dependency: [if], data = [none]
System.out.println("Generating training data for word segmentation with FlexCRFs++ or jvnmaxent (in JVnTextPro)");
// depends on control dependency: [if], data = [none]
System.out.println("Model Dir: directory containing featuretemple file");
// depends on control dependency: [if], data = [none]
System.out.println("Input File/Folder: file/folder name containing data manually tagged for training");
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
WordTrainGenerating trainGen = new WordTrainGenerating(args[0]);
trainGen.generateTrainData(args[1], args[1]);
} } |
public class class_name {
public ClassLoader getExternalClassLoader()
{
Map<String,String> opts = _ap.getAnnotationProcessorEnvironment().getOptions();
String classpath = opts.get("-classpath");
if ( classpath != null )
{
String [] cpEntries = classpath.split( File.pathSeparator );
ArrayList a = new ArrayList();
for ( String e : cpEntries )
{
try
{
File f = (new File(e)).getCanonicalFile();
URL u = f.toURL();
a.add(u);
}
catch (Exception ex)
{
System.err.println( "getExternalClassLoader(): bad cp entry=" + e );
System.err.println( "Exception processing e=" + ex );
}
}
URL [] urls = new URL[a.size()];
urls = (URL[]) a.toArray(urls);
return new URLClassLoader( urls, ControlChecker.class.getClassLoader() );
}
return null;
} } | public class class_name {
public ClassLoader getExternalClassLoader()
{
Map<String,String> opts = _ap.getAnnotationProcessorEnvironment().getOptions();
String classpath = opts.get("-classpath");
if ( classpath != null )
{
String [] cpEntries = classpath.split( File.pathSeparator );
ArrayList a = new ArrayList();
for ( String e : cpEntries )
{
try
{
File f = (new File(e)).getCanonicalFile();
URL u = f.toURL();
a.add(u); // depends on control dependency: [try], data = [none]
}
catch (Exception ex)
{
System.err.println( "getExternalClassLoader(): bad cp entry=" + e );
System.err.println( "Exception processing e=" + ex );
} // depends on control dependency: [catch], data = [none]
}
URL [] urls = new URL[a.size()];
urls = (URL[]) a.toArray(urls); // depends on control dependency: [if], data = [none]
return new URLClassLoader( urls, ControlChecker.class.getClassLoader() ); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Pure
public Point1d getPosition1D() {
if (this.bufferPosition1D == null) {
final RoadSegment segment = getRoadSegment();
if (segment != null && !Double.isNaN(this.curvilineDistance)) {
final RoadNetwork network = segment.getRoadNetwork();
assert network != null;
double lateral = segment.getRoadBorderDistance();
if (lateral < 0.) {
lateral -= DISTANCE_BETWEEN_HALT_AND_ROAD_BORDER;
} else {
lateral += DISTANCE_BETWEEN_HALT_AND_ROAD_BORDER;
}
final boolean isSegmentDirection = getRoadSegmentDirection().isSegmentDirection();
if (!isSegmentDirection) {
lateral = -lateral;
}
this.bufferPosition1D = new Point1d(segment, this.curvilineDistance, lateral);
}
}
return this.bufferPosition1D;
} } | public class class_name {
@Pure
public Point1d getPosition1D() {
if (this.bufferPosition1D == null) {
final RoadSegment segment = getRoadSegment();
if (segment != null && !Double.isNaN(this.curvilineDistance)) {
final RoadNetwork network = segment.getRoadNetwork();
assert network != null;
double lateral = segment.getRoadBorderDistance();
if (lateral < 0.) {
lateral -= DISTANCE_BETWEEN_HALT_AND_ROAD_BORDER; // depends on control dependency: [if], data = [none]
} else {
lateral += DISTANCE_BETWEEN_HALT_AND_ROAD_BORDER; // depends on control dependency: [if], data = [none]
}
final boolean isSegmentDirection = getRoadSegmentDirection().isSegmentDirection();
if (!isSegmentDirection) {
lateral = -lateral; // depends on control dependency: [if], data = [none]
}
this.bufferPosition1D = new Point1d(segment, this.curvilineDistance, lateral); // depends on control dependency: [if], data = [(segment]
}
}
return this.bufferPosition1D;
} } |
public class class_name {
@Override public void setID(Integer val)
{
ProjectFile parent = getParentFile();
Integer previous = getID();
if (previous != null)
{
parent.getResources().unmapID(previous);
}
parent.getResources().mapID(val, this);
set(ResourceField.ID, val);
} } | public class class_name {
@Override public void setID(Integer val)
{
ProjectFile parent = getParentFile();
Integer previous = getID();
if (previous != null)
{
parent.getResources().unmapID(previous); // depends on control dependency: [if], data = [(previous]
}
parent.getResources().mapID(val, this);
set(ResourceField.ID, val);
} } |
public class class_name {
boolean isAggregatedQuery()
{
if (kunderaQuery.getSelectStatement() != null)
{
Expression exp = ((SelectClause) kunderaQuery.getSelectStatement().getSelectClause()).getSelectExpression();
return AggregateFunction.class.isAssignableFrom(exp.getClass());
}
else
{
return false;
}
} } | public class class_name {
boolean isAggregatedQuery()
{
if (kunderaQuery.getSelectStatement() != null)
{
Expression exp = ((SelectClause) kunderaQuery.getSelectStatement().getSelectClause()).getSelectExpression();
return AggregateFunction.class.isAssignableFrom(exp.getClass()); // depends on control dependency: [if], data = [none]
}
else
{
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
protected final String getDescription(MBeanOperationInfo info) {
String description = "Unknown operation";
if (info != null) {
String operationName = info.getName();
if (operationName != null) {
if (operationName.equals("generateDDL")) {
description = "Generates DDL for components using the PersistenceService.";
}
}
}
return description;
} } | public class class_name {
@Override
protected final String getDescription(MBeanOperationInfo info) {
String description = "Unknown operation";
if (info != null) {
String operationName = info.getName();
if (operationName != null) {
if (operationName.equals("generateDDL")) {
description = "Generates DDL for components using the PersistenceService."; // depends on control dependency: [if], data = [none]
}
}
}
return description;
} } |
public class class_name {
public int addAll(Iterable<? extends KTypeCursor<? extends KType>> iterable) {
int count = 0;
for (KTypeCursor<? extends KType> cursor : iterable) {
if (add(cursor.value)) {
count++;
}
}
return count;
} } | public class class_name {
public int addAll(Iterable<? extends KTypeCursor<? extends KType>> iterable) {
int count = 0;
for (KTypeCursor<? extends KType> cursor : iterable) {
if (add(cursor.value)) {
count++; // depends on control dependency: [if], data = [none]
}
}
return count;
} } |
public class class_name {
private void createRelationshipForCollectionOfPrimitivesOrMap(AssociationKey associationKey, String collectionRole, String[] columnNames, StringBuilder queryBuilder) {
String relationshipType = collectionRole;
if ( isPartOfEmbedded( collectionRole ) ) {
queryBuilder.append( " MERGE (owner) " );
String[] pathToEmbedded = appendEmbeddedNodes( collectionRole, queryBuilder );
relationshipType = pathToEmbedded[pathToEmbedded.length - 1];
queryBuilder.append( " CREATE (e) -[r:" );
}
else {
queryBuilder.append( " CREATE (owner) -[r:" );
}
escapeIdentifier( queryBuilder, relationshipType );
queryBuilder.append( "]->(new:" );
queryBuilder.append( EMBEDDED );
queryBuilder.append( ":" );
escapeIdentifier( queryBuilder, associationKey.getTable() );
queryBuilder.append( " {" );
// THe name of the property is the same as the relationship type
escapeIdentifier( queryBuilder, relationshipType );
queryBuilder.append( ": {" );
queryBuilder.append( columnNames.length );
queryBuilder.append( "}" );
queryBuilder.append( "}" );
queryBuilder.append( ")" );
queryBuilder.append( " RETURN r" );
} } | public class class_name {
private void createRelationshipForCollectionOfPrimitivesOrMap(AssociationKey associationKey, String collectionRole, String[] columnNames, StringBuilder queryBuilder) {
String relationshipType = collectionRole;
if ( isPartOfEmbedded( collectionRole ) ) {
queryBuilder.append( " MERGE (owner) " ); // depends on control dependency: [if], data = [none]
String[] pathToEmbedded = appendEmbeddedNodes( collectionRole, queryBuilder );
relationshipType = pathToEmbedded[pathToEmbedded.length - 1]; // depends on control dependency: [if], data = [none]
queryBuilder.append( " CREATE (e) -[r:" ); // depends on control dependency: [if], data = [none]
}
else {
queryBuilder.append( " CREATE (owner) -[r:" ); // depends on control dependency: [if], data = [none]
}
escapeIdentifier( queryBuilder, relationshipType );
queryBuilder.append( "]->(new:" );
queryBuilder.append( EMBEDDED );
queryBuilder.append( ":" );
escapeIdentifier( queryBuilder, associationKey.getTable() );
queryBuilder.append( " {" );
// THe name of the property is the same as the relationship type
escapeIdentifier( queryBuilder, relationshipType );
queryBuilder.append( ": {" );
queryBuilder.append( columnNames.length );
queryBuilder.append( "}" );
queryBuilder.append( "}" );
queryBuilder.append( ")" );
queryBuilder.append( " RETURN r" );
} } |
public class class_name {
public boolean matchMetadata(Fingerprint fp) {
for (Tag tag : METADATA_TAGS) {
if (!getTag(tag).equals(fp.getTag(tag))) {
return false;
}
}
return true;
} } | public class class_name {
public boolean matchMetadata(Fingerprint fp) {
for (Tag tag : METADATA_TAGS) {
if (!getTag(tag).equals(fp.getTag(tag))) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
private void addPostParams(final Request request) {
if (ttl != null) {
request.addPostParam("Ttl", ttl.toString());
}
if (collectionTtl != null) {
request.addPostParam("CollectionTtl", collectionTtl.toString());
}
} } | public class class_name {
private void addPostParams(final Request request) {
if (ttl != null) {
request.addPostParam("Ttl", ttl.toString()); // depends on control dependency: [if], data = [none]
}
if (collectionTtl != null) {
request.addPostParam("CollectionTtl", collectionTtl.toString()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String getCssPath() {
StringBuilder path = new StringBuilder();
Node node = this;
while (node != null) {
String nodeName = node.getNodeName();
if (nodeName != null) {
StringBuilder sb = new StringBuilder();
sb.append(' ').append(nodeName);
String id = node.getAttribute("id");
if (id != null) {
sb.append('#').append(id);
}
path.insert(0, sb);
}
node = node.getParentNode();
}
if (path.charAt(0) == ' ') {
return path.substring(1);
}
return path.toString();
} } | public class class_name {
public String getCssPath() {
StringBuilder path = new StringBuilder();
Node node = this;
while (node != null) {
String nodeName = node.getNodeName();
if (nodeName != null) {
StringBuilder sb = new StringBuilder();
sb.append(' ').append(nodeName); // depends on control dependency: [if], data = [(nodeName]
String id = node.getAttribute("id");
if (id != null) {
sb.append('#').append(id); // depends on control dependency: [if], data = [(id]
}
path.insert(0, sb); // depends on control dependency: [if], data = [none]
}
node = node.getParentNode(); // depends on control dependency: [while], data = [none]
}
if (path.charAt(0) == ' ') {
return path.substring(1); // depends on control dependency: [if], data = [none]
}
return path.toString();
} } |
public class class_name {
public FacesConfigSystemEventListenerType<FacesConfigApplicationType<T>> getOrCreateSystemEventListener()
{
List<Node> nodeList = childNode.get("system-event-listener");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigSystemEventListenerTypeImpl<FacesConfigApplicationType<T>>(this, "system-event-listener", childNode, nodeList.get(0));
}
return createSystemEventListener();
} } | public class class_name {
public FacesConfigSystemEventListenerType<FacesConfigApplicationType<T>> getOrCreateSystemEventListener()
{
List<Node> nodeList = childNode.get("system-event-listener");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigSystemEventListenerTypeImpl<FacesConfigApplicationType<T>>(this, "system-event-listener", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createSystemEventListener();
} } |
public class class_name {
public final String getNodeNameX(int nodeHandle)
{
int nodeID = makeNodeIdentity(nodeHandle);
int eType = _exptype2(nodeID);
if (eType == DTM.PROCESSING_INSTRUCTION_NODE)
{
int dataIndex = _dataOrQName(nodeID);
dataIndex = m_data.elementAt(-dataIndex);
return m_valuesOrPrefixes.indexToString(dataIndex);
}
final ExtendedType extType = m_extendedTypes[eType];
if (extType.getNamespace().length() == 0)
{
return extType.getLocalName();
}
else
{
int qnameIndex = m_dataOrQName.elementAt(nodeID);
if (qnameIndex == 0)
return extType.getLocalName();
if (qnameIndex < 0)
{
qnameIndex = -qnameIndex;
qnameIndex = m_data.elementAt(qnameIndex);
}
return m_valuesOrPrefixes.indexToString(qnameIndex);
}
} } | public class class_name {
public final String getNodeNameX(int nodeHandle)
{
int nodeID = makeNodeIdentity(nodeHandle);
int eType = _exptype2(nodeID);
if (eType == DTM.PROCESSING_INSTRUCTION_NODE)
{
int dataIndex = _dataOrQName(nodeID);
dataIndex = m_data.elementAt(-dataIndex); // depends on control dependency: [if], data = [none]
return m_valuesOrPrefixes.indexToString(dataIndex); // depends on control dependency: [if], data = [none]
}
final ExtendedType extType = m_extendedTypes[eType];
if (extType.getNamespace().length() == 0)
{
return extType.getLocalName(); // depends on control dependency: [if], data = [none]
}
else
{
int qnameIndex = m_dataOrQName.elementAt(nodeID);
if (qnameIndex == 0)
return extType.getLocalName();
if (qnameIndex < 0)
{
qnameIndex = -qnameIndex; // depends on control dependency: [if], data = [none]
qnameIndex = m_data.elementAt(qnameIndex); // depends on control dependency: [if], data = [(qnameIndex]
}
return m_valuesOrPrefixes.indexToString(qnameIndex); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public V get(K key) {
getObserver.begin();
try {
statusTransitioner.checkAvailable();
checkNonNull(key);
try {
Store.ValueHolder<V> valueHolder = doGet(key);
// Check for expiry first
if (valueHolder == null) {
getObserver.end(GetOutcome.MISS);
return null;
} else {
getObserver.end(GetOutcome.HIT);
return valueHolder.get();
}
} catch (StoreAccessException e) {
V value = resilienceStrategy.getFailure(key, e);
getObserver.end(GetOutcome.FAILURE);
return value;
}
} catch (Throwable e) {
getObserver.end(GetOutcome.FAILURE);
throw e;
}
} } | public class class_name {
@Override
public V get(K key) {
getObserver.begin();
try {
statusTransitioner.checkAvailable(); // depends on control dependency: [try], data = [none]
checkNonNull(key); // depends on control dependency: [try], data = [none]
try {
Store.ValueHolder<V> valueHolder = doGet(key);
// Check for expiry first
if (valueHolder == null) {
getObserver.end(GetOutcome.MISS); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
} else {
getObserver.end(GetOutcome.HIT); // depends on control dependency: [if], data = [none]
return valueHolder.get(); // depends on control dependency: [if], data = [none]
}
} catch (StoreAccessException e) {
V value = resilienceStrategy.getFailure(key, e);
getObserver.end(GetOutcome.FAILURE);
return value;
} // depends on control dependency: [catch], data = [none]
} catch (Throwable e) {
getObserver.end(GetOutcome.FAILURE);
throw e;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void driftHandled(boolean dropOld)
{
/*
* Iterate through and either drop everything to the left OR the right
* Track statiscits so that we can update allStats
*/
Iterator<OnLineStatistics> testIter = windows.descendingIterator();
OnLineStatistics leftStats = new OnLineStatistics();
while (testIter.hasNext())
{
OnLineStatistics windowItem = testIter.next();
//accumulate left side statistics
if(leftStats.getSumOfWeights() < driftStart)
{
leftStats.add(windowItem);
if(dropOld)
testIter.remove();
}
else
{
if(!dropOld)
testIter.remove();
}
}
if(dropOld)
allStats.remove(leftStats);
else
allStats = leftStats;
time = (int) allStats.getSumOfWeights();
leftMean = leftVariance = rightMean = rightVariance = Double.NaN;
//Calling at the end b/c we need driftStart's value
super.driftHandled();
} } | public class class_name {
public void driftHandled(boolean dropOld)
{
/*
* Iterate through and either drop everything to the left OR the right
* Track statiscits so that we can update allStats
*/
Iterator<OnLineStatistics> testIter = windows.descendingIterator();
OnLineStatistics leftStats = new OnLineStatistics();
while (testIter.hasNext())
{
OnLineStatistics windowItem = testIter.next();
//accumulate left side statistics
if(leftStats.getSumOfWeights() < driftStart)
{
leftStats.add(windowItem); // depends on control dependency: [if], data = [none]
if(dropOld)
testIter.remove();
}
else
{
if(!dropOld)
testIter.remove();
}
}
if(dropOld)
allStats.remove(leftStats);
else
allStats = leftStats;
time = (int) allStats.getSumOfWeights();
leftMean = leftVariance = rightMean = rightVariance = Double.NaN;
//Calling at the end b/c we need driftStart's value
super.driftHandled();
} } |
public class class_name {
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity"})
protected void generateExecutable(String name, XtendExecutable executable, boolean appendSelf, boolean isAbstract,
JvmTypeReference returnType, String comment, PyAppendable it, IExtraLanguageGeneratorContext context) {
it.append("def ").append(name); //$NON-NLS-1$
it.append("("); //$NON-NLS-1$
boolean firstParam = true;
if (appendSelf) {
firstParam = false;
it.append(getExpressionGenerator().getExtraLanguageKeywordProvider().getThisKeywordLambda().apply());
}
for (final XtendParameter parameter : executable.getParameters()) {
if (firstParam) {
firstParam = false;
} else {
it.append(", "); //$NON-NLS-1$
}
if (parameter.isVarArg()) {
it.append("*"); //$NON-NLS-1$
}
final String pname = it.declareUniqueNameVariable(parameter, parameter.getName());
it.append(pname).append(" : ").append(parameter.getParameterType().getType()); //$NON-NLS-1$
}
final LightweightTypeReference actualReturnType = getExpectedType(executable, returnType);
it.append(")"); //$NON-NLS-1$
if (actualReturnType != null) {
it.append(" -> ").append(actualReturnType); //$NON-NLS-1$
}
it.append(":"); //$NON-NLS-1$
it.increaseIndentation().newLine();
generateDocString(comment, it);
if (executable.getExpression() != null) {
it.openScope();
generate(executable.getExpression(), actualReturnType, it, context);
it.closeScope();
} else if (isAbstract) {
it.append("raise Exception(\"Unimplemented function\")"); //$NON-NLS-1$
} else {
it.append("pass"); //$NON-NLS-1$
}
it.decreaseIndentation().newLine();
//
// Generate the additional functions
final IActionPrototypeProvider prototypeProvider = getActionPrototypeProvider();
final QualifiedActionName actionName = prototypeProvider.createQualifiedActionName(
(JvmIdentifiableElement) getJvmModelAssociations().getPrimaryJvmElement(executable.getDeclaringType()),
name);
final InferredPrototype inferredPrototype = getActionPrototypeProvider().createPrototypeFromSarlModel(actionName,
Utils.isVarArg(executable.getParameters()), executable.getParameters());
for (final Entry<ActionParameterTypes, List<InferredStandardParameter>> types : inferredPrototype.getInferredParameterTypes().entrySet()) {
final List<InferredStandardParameter> argumentsToOriginal = types.getValue();
it.append("def ").append(name); //$NON-NLS-1$
it.append("(self"); //$NON-NLS-1$
for (final InferredStandardParameter parameter : argumentsToOriginal) {
if (!(parameter instanceof InferredValuedParameter)) {
it.append(", "); //$NON-NLS-1$
if (((XtendParameter) parameter.getParameter()).isVarArg()) {
it.append("*"); //$NON-NLS-1$
}
it.append(parameter.getName()).append(" : ").append(parameter.getType().getType()); //$NON-NLS-1$
}
}
it.append(")"); //$NON-NLS-1$
if (actualReturnType != null) {
it.append(" -> ").append(actualReturnType); //$NON-NLS-1$
}
it.append(":"); //$NON-NLS-1$
it.increaseIndentation().newLine();
if (actualReturnType != null) {
it.append("return "); //$NON-NLS-1$
}
it.append("self.").append(name).append("("); //$NON-NLS-1$ //$NON-NLS-2$
boolean first = true;
for (final InferredStandardParameter parameter : argumentsToOriginal) {
if (first) {
first = false;
} else {
it.append(", "); //$NON-NLS-1$
}
if (parameter instanceof InferredValuedParameter) {
final InferredValuedParameter valuedParameter = (InferredValuedParameter) parameter;
generate(((SarlFormalParameter) valuedParameter.getParameter()).getDefaultValue(), null, it, context);
} else {
it.append(parameter.getName());
}
}
it.append(")"); //$NON-NLS-1$
it.decreaseIndentation().newLine();
}
} } | public class class_name {
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity"})
protected void generateExecutable(String name, XtendExecutable executable, boolean appendSelf, boolean isAbstract,
JvmTypeReference returnType, String comment, PyAppendable it, IExtraLanguageGeneratorContext context) {
it.append("def ").append(name); //$NON-NLS-1$
it.append("("); //$NON-NLS-1$
boolean firstParam = true;
if (appendSelf) {
firstParam = false; // depends on control dependency: [if], data = [none]
it.append(getExpressionGenerator().getExtraLanguageKeywordProvider().getThisKeywordLambda().apply()); // depends on control dependency: [if], data = [none]
}
for (final XtendParameter parameter : executable.getParameters()) {
if (firstParam) {
firstParam = false; // depends on control dependency: [if], data = [none]
} else {
it.append(", "); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
if (parameter.isVarArg()) {
it.append("*"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
final String pname = it.declareUniqueNameVariable(parameter, parameter.getName());
it.append(pname).append(" : ").append(parameter.getParameterType().getType()); //$NON-NLS-1$ // depends on control dependency: [for], data = [parameter]
}
final LightweightTypeReference actualReturnType = getExpectedType(executable, returnType);
it.append(")"); //$NON-NLS-1$
if (actualReturnType != null) {
it.append(" -> ").append(actualReturnType); //$NON-NLS-1$ // depends on control dependency: [if], data = [(actualReturnType]
}
it.append(":"); //$NON-NLS-1$
it.increaseIndentation().newLine();
generateDocString(comment, it);
if (executable.getExpression() != null) {
it.openScope(); // depends on control dependency: [if], data = [none]
generate(executable.getExpression(), actualReturnType, it, context); // depends on control dependency: [if], data = [(executable.getExpression()]
it.closeScope(); // depends on control dependency: [if], data = [none]
} else if (isAbstract) {
it.append("raise Exception(\"Unimplemented function\")"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
} else {
it.append("pass"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
it.decreaseIndentation().newLine();
//
// Generate the additional functions
final IActionPrototypeProvider prototypeProvider = getActionPrototypeProvider();
final QualifiedActionName actionName = prototypeProvider.createQualifiedActionName(
(JvmIdentifiableElement) getJvmModelAssociations().getPrimaryJvmElement(executable.getDeclaringType()),
name);
final InferredPrototype inferredPrototype = getActionPrototypeProvider().createPrototypeFromSarlModel(actionName,
Utils.isVarArg(executable.getParameters()), executable.getParameters());
for (final Entry<ActionParameterTypes, List<InferredStandardParameter>> types : inferredPrototype.getInferredParameterTypes().entrySet()) {
final List<InferredStandardParameter> argumentsToOriginal = types.getValue();
it.append("def ").append(name); //$NON-NLS-1$ // depends on control dependency: [for], data = [none]
it.append("(self"); //$NON-NLS-1$ // depends on control dependency: [for], data = [none]
for (final InferredStandardParameter parameter : argumentsToOriginal) {
if (!(parameter instanceof InferredValuedParameter)) {
it.append(", "); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
if (((XtendParameter) parameter.getParameter()).isVarArg()) {
it.append("*"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
it.append(parameter.getName()).append(" : ").append(parameter.getType().getType()); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
}
it.append(")"); //$NON-NLS-1$ // depends on control dependency: [for], data = [none]
if (actualReturnType != null) {
it.append(" -> ").append(actualReturnType); //$NON-NLS-1$ // depends on control dependency: [if], data = [(actualReturnType]
}
it.append(":"); //$NON-NLS-1$ // depends on control dependency: [for], data = [none]
it.increaseIndentation().newLine(); // depends on control dependency: [for], data = [none]
if (actualReturnType != null) {
it.append("return "); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
it.append("self.").append(name).append("("); //$NON-NLS-1$ //$NON-NLS-2$ // depends on control dependency: [for], data = [none]
boolean first = true;
for (final InferredStandardParameter parameter : argumentsToOriginal) {
if (first) {
first = false; // depends on control dependency: [if], data = [none]
} else {
it.append(", "); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
if (parameter instanceof InferredValuedParameter) {
final InferredValuedParameter valuedParameter = (InferredValuedParameter) parameter;
generate(((SarlFormalParameter) valuedParameter.getParameter()).getDefaultValue(), null, it, context); // depends on control dependency: [if], data = [none]
} else {
it.append(parameter.getName()); // depends on control dependency: [if], data = [none]
}
}
it.append(")"); //$NON-NLS-1$ // depends on control dependency: [for], data = [none]
it.decreaseIndentation().newLine(); // depends on control dependency: [for], data = [none]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.