code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
|---|---|
public class class_name {
public void addListener (Telegraph listener, int msg) {
Array<Telegraph> listeners = msgListeners.get(msg);
if (listeners == null) {
// Associate an empty unordered array with the message code
listeners = new Array<Telegraph>(false, 16);
msgListeners.put(msg, listeners);
}
listeners.add(listener);
// Dispatch messages from registered providers
Array<TelegramProvider> providers = msgProviders.get(msg);
if (providers != null) {
for (int i = 0, n = providers.size; i < n; i++) {
TelegramProvider provider = providers.get(i);
Object info = provider.provideMessageInfo(msg, listener);
if (info != null) {
Telegraph sender = ClassReflection.isInstance(Telegraph.class, provider) ? (Telegraph)provider : null;
dispatchMessage(0, sender, listener, msg, info, false);
}
}
}
} }
|
public class class_name {
public void addListener (Telegraph listener, int msg) {
Array<Telegraph> listeners = msgListeners.get(msg);
if (listeners == null) {
// Associate an empty unordered array with the message code
listeners = new Array<Telegraph>(false, 16); // depends on control dependency: [if], data = [none]
msgListeners.put(msg, listeners); // depends on control dependency: [if], data = [none]
}
listeners.add(listener);
// Dispatch messages from registered providers
Array<TelegramProvider> providers = msgProviders.get(msg);
if (providers != null) {
for (int i = 0, n = providers.size; i < n; i++) {
TelegramProvider provider = providers.get(i);
Object info = provider.provideMessageInfo(msg, listener);
if (info != null) {
Telegraph sender = ClassReflection.isInstance(Telegraph.class, provider) ? (Telegraph)provider : null;
dispatchMessage(0, sender, listener, msg, info, false); // depends on control dependency: [if], data = [none]
}
}
}
} }
|
public class class_name {
public boolean detectTierIphone()
{
if ((this.initCompleted == true) ||
(this.isTierIphone == true))
return this.isTierIphone;
if (detectIphoneOrIpod()
|| detectAndroidPhone()
|| detectWindowsPhone()
|| detectBlackBerry10Phone()
|| (detectBlackBerryWebKit()
&& detectBlackBerryTouch())
|| detectPalmWebOS()
|| detectBada()
|| detectTizen()
|| detectGamingHandheld()) {
return true;
}
return false;
} }
|
public class class_name {
public boolean detectTierIphone()
{
if ((this.initCompleted == true) ||
(this.isTierIphone == true))
return this.isTierIphone;
if (detectIphoneOrIpod()
|| detectAndroidPhone()
|| detectWindowsPhone()
|| detectBlackBerry10Phone()
|| (detectBlackBerryWebKit()
&& detectBlackBerryTouch())
|| detectPalmWebOS()
|| detectBada()
|| detectTizen()
|| detectGamingHandheld()) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} }
|
public class class_name {
public static final synchronized void terminate()
{
if (started)
{
engine.close();
started = false;
Verbose.info(ENGINE_TERMINATED);
engine.postClose();
engine = null;
}
} }
|
public class class_name {
public static final synchronized void terminate()
{
if (started)
{
engine.close(); // depends on control dependency: [if], data = [none]
started = false; // depends on control dependency: [if], data = [none]
Verbose.info(ENGINE_TERMINATED); // depends on control dependency: [if], data = [none]
engine.postClose(); // depends on control dependency: [if], data = [none]
engine = null; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public int getLengthInBytes() {
long length = polygonOverheadInBytes();
for (List<XYZPoint> loop : m_loops) {
length += loopLengthInBytes(loop.size());
}
return (int)length;
} }
|
public class class_name {
public int getLengthInBytes() {
long length = polygonOverheadInBytes();
for (List<XYZPoint> loop : m_loops) {
length += loopLengthInBytes(loop.size()); // depends on control dependency: [for], data = [loop]
}
return (int)length;
} }
|
public class class_name {
public void scrollVerticallyToPosition(int position) {
LayoutManager lm = getLayoutManager();
if (lm != null && lm instanceof LinearLayoutManager) {
((LinearLayoutManager) lm).scrollToPositionWithOffset(position, 0);
} else {
scrollToPosition(position);
}
} }
|
public class class_name {
public void scrollVerticallyToPosition(int position) {
LayoutManager lm = getLayoutManager();
if (lm != null && lm instanceof LinearLayoutManager) {
((LinearLayoutManager) lm).scrollToPositionWithOffset(position, 0); // depends on control dependency: [if], data = [none]
} else {
scrollToPosition(position); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private T retain0(T instance, final int increment, final int rawIncrement) {
int oldRef = updater().getAndAdd(instance, rawIncrement);
if (oldRef != 2 && oldRef != 4 && (oldRef & 1) != 0) {
throw new IllegalReferenceCountException(0, increment);
}
// don't pass 0!
if ((oldRef <= 0 && oldRef + rawIncrement >= 0)
|| (oldRef >= 0 && oldRef + rawIncrement < oldRef)) {
// overflow case
updater().getAndAdd(instance, -rawIncrement);
throw new IllegalReferenceCountException(realRefCnt(oldRef), increment);
}
return instance;
} }
|
public class class_name {
private T retain0(T instance, final int increment, final int rawIncrement) {
int oldRef = updater().getAndAdd(instance, rawIncrement);
if (oldRef != 2 && oldRef != 4 && (oldRef & 1) != 0) {
throw new IllegalReferenceCountException(0, increment);
}
// don't pass 0!
if ((oldRef <= 0 && oldRef + rawIncrement >= 0)
|| (oldRef >= 0 && oldRef + rawIncrement < oldRef)) {
// overflow case
updater().getAndAdd(instance, -rawIncrement); // depends on control dependency: [if], data = [none]
throw new IllegalReferenceCountException(realRefCnt(oldRef), increment);
}
return instance;
} }
|
public class class_name {
public ElemTemplateElement appendChild(ElemTemplateElement elem)
{
if (null == elem)
{
error(XSLTErrorResources.ER_NULL_CHILD, null); //"Trying to add a null child!");
}
if (null == m_firstChild)
{
m_firstChild = elem;
}
else
{
ElemTemplateElement last = getLastChildElem();
last.m_nextSibling = elem;
}
elem.setParentElem(this);
return elem;
} }
|
public class class_name {
public ElemTemplateElement appendChild(ElemTemplateElement elem)
{
if (null == elem)
{
error(XSLTErrorResources.ER_NULL_CHILD, null); //"Trying to add a null child!"); // depends on control dependency: [if], data = [none]
}
if (null == m_firstChild)
{
m_firstChild = elem; // depends on control dependency: [if], data = [none]
}
else
{
ElemTemplateElement last = getLastChildElem();
last.m_nextSibling = elem; // depends on control dependency: [if], data = [none]
}
elem.setParentElem(this);
return elem;
} }
|
public class class_name {
protected Set common_keySet(boolean includeDiskCache) {
Set cacheIds = cache.getCacheIds();
/*
* If the cache is an instanceof CacheProviderWrapper then we know it's not dynacache so
* we need to check if it supports disk caching. If it doesn't then we don't need incude keys
* from the disk cache.
*/
if (cache instanceof CacheProviderWrapper)
includeDiskCache = ((CacheProviderWrapper) cache).featureSupport.isDiskCacheSupported();
if (includeDiskCache && cache.getIdsSizeDisk() > 0) {
int index = 0;
boolean more = true;
Set cacheIdsDisk = null;
do {
cacheIdsDisk = cache.getIdsByRangeDisk(index, 100);
if (cacheIdsDisk != null) {
cacheIds.addAll(cacheIdsDisk);
if (!cacheIdsDisk.contains(HTODDynacache.DISKCACHE_MORE)) {
more = false;
}
} else {
more = false;
}
index = 1;
} while (more == true);
cacheIds.remove(HTODDynacache.DISKCACHE_MORE);
}
return cacheIds;
} }
|
public class class_name {
protected Set common_keySet(boolean includeDiskCache) {
Set cacheIds = cache.getCacheIds();
/*
* If the cache is an instanceof CacheProviderWrapper then we know it's not dynacache so
* we need to check if it supports disk caching. If it doesn't then we don't need incude keys
* from the disk cache.
*/
if (cache instanceof CacheProviderWrapper)
includeDiskCache = ((CacheProviderWrapper) cache).featureSupport.isDiskCacheSupported();
if (includeDiskCache && cache.getIdsSizeDisk() > 0) {
int index = 0;
boolean more = true;
Set cacheIdsDisk = null;
do {
cacheIdsDisk = cache.getIdsByRangeDisk(index, 100);
if (cacheIdsDisk != null) {
cacheIds.addAll(cacheIdsDisk); // depends on control dependency: [if], data = [(cacheIdsDisk]
if (!cacheIdsDisk.contains(HTODDynacache.DISKCACHE_MORE)) {
more = false; // depends on control dependency: [if], data = [none]
}
} else {
more = false; // depends on control dependency: [if], data = [none]
}
index = 1;
} while (more == true);
cacheIds.remove(HTODDynacache.DISKCACHE_MORE); // depends on control dependency: [if], data = [none]
}
return cacheIds;
} }
|
public class class_name {
public java.util.List<String> getResults() {
if (results == null) {
results = new com.amazonaws.internal.SdkInternalList<String>();
}
return results;
} }
|
public class class_name {
public java.util.List<String> getResults() {
if (results == null) {
results = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return results;
} }
|
public class class_name {
public int getArgmaxConfigId() {
int argmax = -1;
double max = s.minValue();
for (int c = 0; c < this.size(); c++) {
double val = getValue(c);
if (s.gte(val, max)) {
max = val;
argmax = c;
}
}
return argmax;
} }
|
public class class_name {
public int getArgmaxConfigId() {
int argmax = -1;
double max = s.minValue();
for (int c = 0; c < this.size(); c++) {
double val = getValue(c);
if (s.gte(val, max)) {
max = val; // depends on control dependency: [if], data = [none]
argmax = c; // depends on control dependency: [if], data = [none]
}
}
return argmax;
} }
|
public class class_name {
public final synchronized MngDatabaseSqliteEncrypted<ResultSet>
lazyGetMngDatabaseSqliteEncrypted() throws Exception {
String beanName = getMngDatabaseName();
@SuppressWarnings("unchecked")
MngDatabaseSqliteEncrypted<ResultSet> mngDatabaseSqlite =
(MngDatabaseSqliteEncrypted<ResultSet>) getBeansMap().get(beanName);
if (mngDatabaseSqlite == null) {
mngDatabaseSqlite = new MngDatabaseSqliteEncrypted<ResultSet>();
mngDatabaseSqlite.setFactoryAppBeans(this);
mngDatabaseSqlite.setCryptoHelper(lazyGetCryptoHelper());
File webAppDir = new File(getWebAppPath());
mngDatabaseSqlite.setLogDir(webAppDir);
mngDatabaseSqlite.setDatabaseDir(getWebAppPath());
mngDatabaseSqlite.setDatabasePrefix("jdbc:sqlite:"
+ getWebAppPath() + File.separator);
File backupDir = new File(webAppDir.getParent()
+ File.separator + "backup");
if (!backupDir.exists() && !backupDir.mkdir()) {
throw new Exception("Can't create directory: " + backupDir);
}
mngDatabaseSqlite.setBackupDir(backupDir.getPath());
getBeansMap().put(beanName, mngDatabaseSqlite);
lazyGetLogger().info(null, FactoryAccAppBeansSqlite.class, beanName
+ " has been created.");
}
return mngDatabaseSqlite;
} }
|
public class class_name {
public final synchronized MngDatabaseSqliteEncrypted<ResultSet>
lazyGetMngDatabaseSqliteEncrypted() throws Exception {
String beanName = getMngDatabaseName();
@SuppressWarnings("unchecked")
MngDatabaseSqliteEncrypted<ResultSet> mngDatabaseSqlite =
(MngDatabaseSqliteEncrypted<ResultSet>) getBeansMap().get(beanName);
if (mngDatabaseSqlite == null) {
mngDatabaseSqlite = new MngDatabaseSqliteEncrypted<ResultSet>(); // depends on control dependency: [if], data = [none]
mngDatabaseSqlite.setFactoryAppBeans(this); // depends on control dependency: [if], data = [none]
mngDatabaseSqlite.setCryptoHelper(lazyGetCryptoHelper()); // depends on control dependency: [if], data = [none]
File webAppDir = new File(getWebAppPath());
mngDatabaseSqlite.setLogDir(webAppDir); // depends on control dependency: [if], data = [none]
mngDatabaseSqlite.setDatabaseDir(getWebAppPath()); // depends on control dependency: [if], data = [none]
mngDatabaseSqlite.setDatabasePrefix("jdbc:sqlite:"
+ getWebAppPath() + File.separator); // depends on control dependency: [if], data = [none]
File backupDir = new File(webAppDir.getParent()
+ File.separator + "backup");
if (!backupDir.exists() && !backupDir.mkdir()) {
throw new Exception("Can't create directory: " + backupDir);
}
mngDatabaseSqlite.setBackupDir(backupDir.getPath()); // depends on control dependency: [if], data = [none]
getBeansMap().put(beanName, mngDatabaseSqlite); // depends on control dependency: [if], data = [none]
lazyGetLogger().info(null, FactoryAccAppBeansSqlite.class, beanName
+ " has been created."); // depends on control dependency: [if], data = [none]
}
return mngDatabaseSqlite;
} }
|
public class class_name {
public long skip(long n) throws IOException {
int s = cache.size();
if(s > 0){
if(s < n){
n = n - s;
} else {
for(int i = 0; i < n; i ++){
cache.poll();
}
return n;
}
}
return super.skip(n) + s;
} }
|
public class class_name {
public long skip(long n) throws IOException {
int s = cache.size();
if(s > 0){
if(s < n){
n = n - s; // depends on control dependency: [if], data = [none]
} else {
for(int i = 0; i < n; i ++){
cache.poll(); // depends on control dependency: [for], data = [none]
}
return n; // depends on control dependency: [if], data = [none]
}
}
return super.skip(n) + s;
} }
|
public class class_name {
public static LogFactory init() {
try {
LogFactory theLogFactory = (LogFactory) EPackage.Registry.INSTANCE.getEFactory(LogPackage.eNS_URI);
if (theLogFactory != null) {
return theLogFactory;
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new LogFactoryImpl();
} }
|
public class class_name {
public static LogFactory init() {
try {
LogFactory theLogFactory = (LogFactory) EPackage.Registry.INSTANCE.getEFactory(LogPackage.eNS_URI);
if (theLogFactory != null) {
return theLogFactory;
// depends on control dependency: [if], data = [none]
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
// depends on control dependency: [catch], data = [none]
return new LogFactoryImpl();
} }
|
public class class_name {
private Cursor integrityCheck(Cursor cursor) {
if (cursor.moveToNext()) {
String value = cursor.getString(0);
if (value.equals("ok")) {
cursor.close();
cursor = null;
}
}
return cursor;
} }
|
public class class_name {
private Cursor integrityCheck(Cursor cursor) {
if (cursor.moveToNext()) {
String value = cursor.getString(0);
if (value.equals("ok")) {
cursor.close(); // depends on control dependency: [if], data = [none]
cursor = null; // depends on control dependency: [if], data = [none]
}
}
return cursor;
} }
|
public class class_name {
public String getMimeType(String file) {
if (defaultExternalContext != null) {
return defaultExternalContext.getMimeType(file);
}
throw new UnsupportedOperationException();
} }
|
public class class_name {
public String getMimeType(String file) {
if (defaultExternalContext != null) {
return defaultExternalContext.getMimeType(file); // depends on control dependency: [if], data = [none]
}
throw new UnsupportedOperationException();
} }
|
public class class_name {
private static WritableRaster shadow( int i, int j, WritableRaster tmpWR, WritableRaster demWR, double res,
double[] normalSunVector, double[] inverseSunVector ) {
int n = 0;
double zcompare = -Double.MAX_VALUE;
double dx = (inverseSunVector[0] * n);
double dy = (inverseSunVector[1] * n);
int nCols = tmpWR.getWidth();
int nRows = tmpWR.getHeight();
int idx = (int) Math.round(i + dx);
int jdy = (int) Math.round(j + dy);
double vectorToOrigin[] = new double[3];
while( idx >= 0 && idx <= nCols - 1 && jdy >= 0 && jdy <= nRows - 1 ) {
vectorToOrigin[0] = dx * res;
vectorToOrigin[1] = dy * res;
int tmpY = (int) (j + dy);
if (tmpY < 0) {
tmpY = 0;
} else if (tmpY > nRows) {
tmpY = nRows - 1;
}
int tmpX = (int) (i + dx);
if (tmpX < 0) {
tmpX = 0;
} else if (tmpY > nCols) {
tmpX = nCols - 1;
}
vectorToOrigin[2] = demWR.getSampleDouble(idx, jdy, 0);
// vectorToOrigin[2] = (pitRandomIter.getSampleDouble(idx, jdy, 0) +
// pitRandomIter
// .getSampleDouble(tmpX, tmpY, 0)) / 2;
double zprojection = scalarProduct(vectorToOrigin, normalSunVector);
if ((zprojection < zcompare)) {
tmpWR.setSample(idx, jdy, 0, 0);
} else {
zcompare = zprojection;
}
n = n + 1;
dy = (inverseSunVector[1] * n);
dx = (inverseSunVector[0] * n);
idx = (int) Math.round(i + dx);
jdy = (int) Math.round(j + dy);
}
return tmpWR;
} }
|
public class class_name {
private static WritableRaster shadow( int i, int j, WritableRaster tmpWR, WritableRaster demWR, double res,
double[] normalSunVector, double[] inverseSunVector ) {
int n = 0;
double zcompare = -Double.MAX_VALUE;
double dx = (inverseSunVector[0] * n);
double dy = (inverseSunVector[1] * n);
int nCols = tmpWR.getWidth();
int nRows = tmpWR.getHeight();
int idx = (int) Math.round(i + dx);
int jdy = (int) Math.round(j + dy);
double vectorToOrigin[] = new double[3];
while( idx >= 0 && idx <= nCols - 1 && jdy >= 0 && jdy <= nRows - 1 ) {
vectorToOrigin[0] = dx * res; // depends on control dependency: [while], data = [none]
vectorToOrigin[1] = dy * res; // depends on control dependency: [while], data = [none]
int tmpY = (int) (j + dy);
if (tmpY < 0) {
tmpY = 0; // depends on control dependency: [if], data = [none]
} else if (tmpY > nRows) {
tmpY = nRows - 1; // depends on control dependency: [if], data = [none]
}
int tmpX = (int) (i + dx);
if (tmpX < 0) {
tmpX = 0; // depends on control dependency: [if], data = [none]
} else if (tmpY > nCols) {
tmpX = nCols - 1; // depends on control dependency: [if], data = [none]
}
vectorToOrigin[2] = demWR.getSampleDouble(idx, jdy, 0); // depends on control dependency: [while], data = [none]
// vectorToOrigin[2] = (pitRandomIter.getSampleDouble(idx, jdy, 0) +
// pitRandomIter
// .getSampleDouble(tmpX, tmpY, 0)) / 2;
double zprojection = scalarProduct(vectorToOrigin, normalSunVector);
if ((zprojection < zcompare)) {
tmpWR.setSample(idx, jdy, 0, 0); // depends on control dependency: [if], data = [none]
} else {
zcompare = zprojection; // depends on control dependency: [if], data = [none]
}
n = n + 1; // depends on control dependency: [while], data = [none]
dy = (inverseSunVector[1] * n); // depends on control dependency: [while], data = [none]
dx = (inverseSunVector[0] * n); // depends on control dependency: [while], data = [none]
idx = (int) Math.round(i + dx); // depends on control dependency: [while], data = [none]
jdy = (int) Math.round(j + dy); // depends on control dependency: [while], data = [none]
}
return tmpWR;
} }
|
public class class_name {
public void reportFailure(String importerName, String procName, boolean decrementPending) {
StatsInfo statsInfo = getStatsInfo(importerName, procName);
if (decrementPending) {
statsInfo.m_pendingCount.decrementAndGet();
}
statsInfo.m_failureCount.incrementAndGet();
} }
|
public class class_name {
public void reportFailure(String importerName, String procName, boolean decrementPending) {
StatsInfo statsInfo = getStatsInfo(importerName, procName);
if (decrementPending) {
statsInfo.m_pendingCount.decrementAndGet(); // depends on control dependency: [if], data = [none]
}
statsInfo.m_failureCount.incrementAndGet();
} }
|
public class class_name {
protected void start() {
try {
if (!db.isOpen()) {
String msg = String.format(Locale.ENGLISH, "Db: %s is not open, abort replication", db);
parentReplication.setLastError(new Exception(msg));
fireTrigger(ReplicationTrigger.STOP_IMMEDIATE);
return;
}
db.addActiveReplication(parentReplication);
this.authenticating = false;
initSessionId();
// initialize batcher
initBatcher();
// initialize authorizer / authenticator
initAuthorizer();
// initialize request workers
initializeRequestWorkers();
// reset lastSequence
// https://github.com/couchbase/couchbase-lite-java-core/issues/1623
this.lastSequence = null;
// single-shot replication
if (!isContinuous())
goOnline();
// continuous mode
else {
if (isNetworkReachable())
goOnline();
else
triggerGoOffline();
startNetworkReachabilityManager();
}
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "%s: Exception in start()", e, this);
}
} }
|
public class class_name {
protected void start() {
try {
if (!db.isOpen()) {
String msg = String.format(Locale.ENGLISH, "Db: %s is not open, abort replication", db);
parentReplication.setLastError(new Exception(msg)); // depends on control dependency: [if], data = [none]
fireTrigger(ReplicationTrigger.STOP_IMMEDIATE); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
db.addActiveReplication(parentReplication); // depends on control dependency: [try], data = [none]
this.authenticating = false; // depends on control dependency: [try], data = [none]
initSessionId(); // depends on control dependency: [try], data = [none]
// initialize batcher
initBatcher(); // depends on control dependency: [try], data = [none]
// initialize authorizer / authenticator
initAuthorizer(); // depends on control dependency: [try], data = [none]
// initialize request workers
initializeRequestWorkers(); // depends on control dependency: [try], data = [none]
// reset lastSequence
// https://github.com/couchbase/couchbase-lite-java-core/issues/1623
this.lastSequence = null; // depends on control dependency: [try], data = [none]
// single-shot replication
if (!isContinuous())
goOnline();
// continuous mode
else {
if (isNetworkReachable())
goOnline();
else
triggerGoOffline();
startNetworkReachabilityManager(); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "%s: Exception in start()", e, this);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private <T> Provider<T> createProvider(Key<T> key)
{
Class<T> type = (Class<T>) key.rawClass();
if (Provider.class.equals(type)) {
TypeRef subType = TypeRef.of(key.type()).to(Provider.class).param(0);
Key<Object> subkey = Key.of(subType.type(), key.annotationTypes());
return (Provider) new ProviderProvider(key, -10, provider(subkey));
}
else if (Optional.class.equals(type)) {
TypeRef subType = TypeRef.of(key.type()).to(Optional.class).param(0);
Key<Object> subkey = Key.of(subType.type(), key.annotationTypes());
return (Provider) new ProviderOptional(key, -10, provider(subkey));
}
else if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) {
return new ProviderNull(key, -10000, new InjectScopeSingleton());
}
int priority = -10;
// auto-provider is factory
InjectScope<T> scope = findScope(type);
BindingAmp<T> binding = new ProviderConstructor<>(this, key, priority, scope, type);
binding.bind();
return binding.provider();
} }
|
public class class_name {
private <T> Provider<T> createProvider(Key<T> key)
{
Class<T> type = (Class<T>) key.rawClass();
if (Provider.class.equals(type)) {
TypeRef subType = TypeRef.of(key.type()).to(Provider.class).param(0);
Key<Object> subkey = Key.of(subType.type(), key.annotationTypes());
return (Provider) new ProviderProvider(key, -10, provider(subkey)); // depends on control dependency: [if], data = [none]
}
else if (Optional.class.equals(type)) {
TypeRef subType = TypeRef.of(key.type()).to(Optional.class).param(0);
Key<Object> subkey = Key.of(subType.type(), key.annotationTypes());
return (Provider) new ProviderOptional(key, -10, provider(subkey)); // depends on control dependency: [if], data = [none]
}
else if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) {
return new ProviderNull(key, -10000, new InjectScopeSingleton()); // depends on control dependency: [if], data = [none]
}
int priority = -10;
// auto-provider is factory
InjectScope<T> scope = findScope(type);
BindingAmp<T> binding = new ProviderConstructor<>(this, key, priority, scope, type);
binding.bind();
return binding.provider();
} }
|
public class class_name {
public synchronized ValT put(KeyT key, ValT value) {
if (isDiskCacheEnabled) {
cacheToDisk(key, value);
}
return cache.put(key, value);
} }
|
public class class_name {
public synchronized ValT put(KeyT key, ValT value) {
if (isDiskCacheEnabled) {
cacheToDisk(key, value); // depends on control dependency: [if], data = [none]
}
return cache.put(key, value);
} }
|
public class class_name {
public EClass getFNI() {
if (fniEClass == null) {
fniEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(265);
}
return fniEClass;
} }
|
public class class_name {
public EClass getFNI() {
if (fniEClass == null) {
fniEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(265); // depends on control dependency: [if], data = [none]
}
return fniEClass;
} }
|
public class class_name {
protected List<ConsumerHolder> filterConsumersForActiveFlag(boolean active) {
List<ConsumerHolder> consumerHolderSubList = new LinkedList<ConsumerHolder>();
for (ConsumerHolder consumerHolder : consumerHolders) {
if (consumerHolder.isActive() == active) {
consumerHolderSubList.add(consumerHolder);
}
}
return consumerHolderSubList;
} }
|
public class class_name {
protected List<ConsumerHolder> filterConsumersForActiveFlag(boolean active) {
List<ConsumerHolder> consumerHolderSubList = new LinkedList<ConsumerHolder>();
for (ConsumerHolder consumerHolder : consumerHolders) {
if (consumerHolder.isActive() == active) {
consumerHolderSubList.add(consumerHolder);
// depends on control dependency: [if], data = [none]
}
}
return consumerHolderSubList;
} }
|
public class class_name {
protected void view(Map<String, Object> values){
for(String key:values.keySet() ){
view(key, values.get(key));
}
} }
|
public class class_name {
protected void view(Map<String, Object> values){
for(String key:values.keySet() ){
view(key, values.get(key)); // depends on control dependency: [for], data = [key]
}
} }
|
public class class_name {
@Override
public Schema getSchema() {
if (this.workUnit.contains(ConfigurationKeys.SOURCE_SCHEMA)) {
return new Schema.Parser().parse(this.workUnit.getProp(ConfigurationKeys.SOURCE_SCHEMA));
}
AvroFsHelper hfsHelper = (AvroFsHelper) this.fsHelper;
if (this.filesToPull.isEmpty()) {
return null;
}
try {
return hfsHelper.getAvroSchema(this.filesToPull.get(0));
} catch (FileBasedHelperException e) {
Throwables.propagate(e);
return null;
}
} }
|
public class class_name {
@Override
public Schema getSchema() {
if (this.workUnit.contains(ConfigurationKeys.SOURCE_SCHEMA)) {
return new Schema.Parser().parse(this.workUnit.getProp(ConfigurationKeys.SOURCE_SCHEMA)); // depends on control dependency: [if], data = [none]
}
AvroFsHelper hfsHelper = (AvroFsHelper) this.fsHelper;
if (this.filesToPull.isEmpty()) {
return null; // depends on control dependency: [if], data = [none]
}
try {
return hfsHelper.getAvroSchema(this.filesToPull.get(0)); // depends on control dependency: [try], data = [none]
} catch (FileBasedHelperException e) {
Throwables.propagate(e);
return null;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private void softmax() {
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < outputLayer.units; i++) {
if (outputLayer.output[i] > max) {
max = outputLayer.output[i];
}
}
double sum = 0.0;
for (int i = 0; i < outputLayer.units; i++) {
double out = Math.exp(outputLayer.output[i] - max);
outputLayer.output[i] = out;
sum += out;
}
for (int i = 0; i < outputLayer.units; i++) {
outputLayer.output[i] /= sum;
}
} }
|
public class class_name {
private void softmax() {
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < outputLayer.units; i++) {
if (outputLayer.output[i] > max) {
max = outputLayer.output[i]; // depends on control dependency: [if], data = [none]
}
}
double sum = 0.0;
for (int i = 0; i < outputLayer.units; i++) {
double out = Math.exp(outputLayer.output[i] - max);
outputLayer.output[i] = out; // depends on control dependency: [for], data = [i]
sum += out; // depends on control dependency: [for], data = [none]
}
for (int i = 0; i < outputLayer.units; i++) {
outputLayer.output[i] /= sum; // depends on control dependency: [for], data = [i]
}
} }
|
public class class_name {
public String getOperatorFunctionModifier(Expression expr) {
VariableElement var = TreeUtil.getVariableElement(expr);
if (var == null) {
assert TreeUtil.trimParentheses(expr) instanceof ArrayAccess
: "Expression cannot be resolved to a variable or array access.";
return "Array";
}
String modifier = "";
if (ElementUtil.isVolatile(var)) {
modifier += "Volatile";
}
if (!ElementUtil.isWeakReference(var) && (var.getKind().isField() || options.useARC())) {
modifier += "Strong";
}
return modifier;
} }
|
public class class_name {
public String getOperatorFunctionModifier(Expression expr) {
VariableElement var = TreeUtil.getVariableElement(expr);
if (var == null) {
assert TreeUtil.trimParentheses(expr) instanceof ArrayAccess
: "Expression cannot be resolved to a variable or array access.";
return "Array"; // depends on control dependency: [if], data = [none]
}
String modifier = "";
if (ElementUtil.isVolatile(var)) {
modifier += "Volatile"; // depends on control dependency: [if], data = [none]
}
if (!ElementUtil.isWeakReference(var) && (var.getKind().isField() || options.useARC())) {
modifier += "Strong"; // depends on control dependency: [if], data = [none]
}
return modifier;
} }
|
public class class_name {
private Object unwrap(EntityMetadata entityMetadata, Map<byte[], byte[]> results, Object key)
throws InstantiationException, IllegalAccessException
{
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
entityMetadata.getPersistenceUnit());
List<String> relationNames = entityMetadata.getRelationNames();
EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
Map<String, Object> relations = new HashMap<String, Object>();
Object entity = null;
// Set<Attribute> attributes = entityType.getAttributes();
Set<byte[]> columnNames = results.keySet();
for (byte[] nameInByte : columnNames)
{
if (entity == null)
{
entity = KunderaCoreUtils.createNewInstance(entityMetadata.getEntityClazz());
}
String columnName = PropertyAccessorFactory.STRING.fromBytes(String.class, nameInByte);
byte[] value = results.get(nameInByte);
String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
if (columnName != null && !columnName.equals(discriminatorColumn))
{
String fieldName = entityMetadata.getFieldName(columnName);
if (fieldName != null)
{
Attribute attribute = entityType.getAttribute(fieldName);
if (relationNames != null && relationNames.contains(columnName))
{
Field field = (Field) attribute.getJavaMember();
EntityMetadata associationMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
((AbstractAttribute) attribute).getBindableJavaType());
relations.put(columnName, PropertyAccessorHelper.getObject(associationMetadata.getIdAttribute()
.getBindableJavaType(), value));
}
else
{
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), value);
}
}
else
{
// means it might be an embeddable field, if not simply omit
// this field.
if (StringUtils.contains(columnName, ":"))
{
StringTokenizer tokenizer = new StringTokenizer(columnName, ":");
while (tokenizer.hasMoreTokens())
{
String embeddedFieldName = tokenizer.nextToken();
String embeddedColumnName = tokenizer.nextToken();
Map<String, EmbeddableType> embeddables = metaModel.getEmbeddables(entityMetadata
.getEntityClazz());
EmbeddableType embeddableAttribute = embeddables.get(embeddedFieldName);
AbstractAttribute attrib = null;
Iterator itr = embeddableAttribute.getAttributes().iterator();
while (itr.hasNext())
{
attrib = (AbstractAttribute) itr.next();
if (attrib.getJPAColumnName().equals(embeddedColumnName))
{
break;
}
}
Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) entityType
.getAttribute(embeddedFieldName).getJavaMember());
if (embeddedObject == null)
{
embeddedObject = KunderaCoreUtils.createNewInstance(((AbstractAttribute) entityType
.getAttribute(embeddedFieldName)).getBindableJavaType());
PropertyAccessorHelper.set(entity, (Field) entityType.getAttribute(embeddedFieldName)
.getJavaMember(), embeddedObject);
}
PropertyAccessorHelper.set(embeddedObject, (Field) attrib.getJavaMember(), value);
// PropertyAccessorHelper.
}
}
// It might be a case of embeddable attribute.
}
}
}
if (entity != null)
{
Class javaType = entityMetadata.getIdAttribute().getBindableJavaType();
if (!metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())
&& key.getClass().isAssignableFrom(String.class) && !key.getClass().equals(javaType))
{
key = PropertyAccessorFactory.getPropertyAccessor(javaType).fromString(javaType, key.toString());
}
// PropertyAccessorHelper.set(entity, (Field) entityMetadata.getIdAttribute().getJavaMember(), key);
}
if (!relations.isEmpty())
{
return new EnhanceEntity(entity, key, relations);
}
return entity;
} }
|
public class class_name {
private Object unwrap(EntityMetadata entityMetadata, Map<byte[], byte[]> results, Object key)
throws InstantiationException, IllegalAccessException
{
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
entityMetadata.getPersistenceUnit());
List<String> relationNames = entityMetadata.getRelationNames();
EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
Map<String, Object> relations = new HashMap<String, Object>();
Object entity = null;
// Set<Attribute> attributes = entityType.getAttributes();
Set<byte[]> columnNames = results.keySet();
for (byte[] nameInByte : columnNames)
{
if (entity == null)
{
entity = KunderaCoreUtils.createNewInstance(entityMetadata.getEntityClazz()); // depends on control dependency: [if], data = [(entity]
}
String columnName = PropertyAccessorFactory.STRING.fromBytes(String.class, nameInByte);
byte[] value = results.get(nameInByte);
String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
if (columnName != null && !columnName.equals(discriminatorColumn))
{
String fieldName = entityMetadata.getFieldName(columnName);
if (fieldName != null)
{
Attribute attribute = entityType.getAttribute(fieldName);
if (relationNames != null && relationNames.contains(columnName))
{
Field field = (Field) attribute.getJavaMember();
EntityMetadata associationMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
((AbstractAttribute) attribute).getBindableJavaType());
relations.put(columnName, PropertyAccessorHelper.getObject(associationMetadata.getIdAttribute()
.getBindableJavaType(), value)); // depends on control dependency: [if], data = [none]
}
else
{
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), value); // depends on control dependency: [if], data = [none]
}
}
else
{
// means it might be an embeddable field, if not simply omit
// this field.
if (StringUtils.contains(columnName, ":"))
{
StringTokenizer tokenizer = new StringTokenizer(columnName, ":");
while (tokenizer.hasMoreTokens())
{
String embeddedFieldName = tokenizer.nextToken();
String embeddedColumnName = tokenizer.nextToken();
Map<String, EmbeddableType> embeddables = metaModel.getEmbeddables(entityMetadata
.getEntityClazz());
EmbeddableType embeddableAttribute = embeddables.get(embeddedFieldName);
AbstractAttribute attrib = null;
Iterator itr = embeddableAttribute.getAttributes().iterator();
while (itr.hasNext())
{
attrib = (AbstractAttribute) itr.next(); // depends on control dependency: [while], data = [none]
if (attrib.getJPAColumnName().equals(embeddedColumnName))
{
break;
}
}
Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) entityType
.getAttribute(embeddedFieldName).getJavaMember());
if (embeddedObject == null)
{
embeddedObject = KunderaCoreUtils.createNewInstance(((AbstractAttribute) entityType
.getAttribute(embeddedFieldName)).getBindableJavaType()); // depends on control dependency: [if], data = [none]
PropertyAccessorHelper.set(entity, (Field) entityType.getAttribute(embeddedFieldName)
.getJavaMember(), embeddedObject); // depends on control dependency: [if], data = [none]
}
PropertyAccessorHelper.set(embeddedObject, (Field) attrib.getJavaMember(), value); // depends on control dependency: [while], data = [none]
// PropertyAccessorHelper.
}
}
// It might be a case of embeddable attribute.
}
}
}
if (entity != null)
{
Class javaType = entityMetadata.getIdAttribute().getBindableJavaType();
if (!metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())
&& key.getClass().isAssignableFrom(String.class) && !key.getClass().equals(javaType))
{
key = PropertyAccessorFactory.getPropertyAccessor(javaType).fromString(javaType, key.toString());
}
// PropertyAccessorHelper.set(entity, (Field) entityMetadata.getIdAttribute().getJavaMember(), key);
}
if (!relations.isEmpty())
{
return new EnhanceEntity(entity, key, relations);
}
return entity;
} }
|
public class class_name {
private void signalConnected() {
if (alternate != null) {
LOGGER.info("Connected to Node {} ({})",
system(hostname.nameAndAddress()), system(alternate.nameAndAddress()));
} else {
LOGGER.info("Connected to Node {}", system(hostname.nameAndAddress()));
}
if (eventBus != null && eventBus.hasSubscribers()) {
eventBus.publish(new NodeConnectedEvent(hostname));
}
} }
|
public class class_name {
private void signalConnected() {
if (alternate != null) {
LOGGER.info("Connected to Node {} ({})",
system(hostname.nameAndAddress()), system(alternate.nameAndAddress())); // depends on control dependency: [if], data = [none]
} else {
LOGGER.info("Connected to Node {}", system(hostname.nameAndAddress())); // depends on control dependency: [if], data = [none]
}
if (eventBus != null && eventBus.hasSubscribers()) {
eventBus.publish(new NodeConnectedEvent(hostname)); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
@SuppressWarnings("unchecked")
public static <T> Collection<T> flattenCollection(final Collection<? extends Object> source) {
Validate.notNull(source, "Cannot flatten a null collection.");
final Collection<T> result = new LinkedList<>();
for (final Object value : source) {
if (value instanceof Collection) {
final Collection<Object> flatCollection = flattenCollection((Collection<Object>) value);
result.addAll((Collection<T>) flatCollection);
} else {
result.add((T) value);
}
}
return result;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
public static <T> Collection<T> flattenCollection(final Collection<? extends Object> source) {
Validate.notNull(source, "Cannot flatten a null collection.");
final Collection<T> result = new LinkedList<>();
for (final Object value : source) {
if (value instanceof Collection) {
final Collection<Object> flatCollection = flattenCollection((Collection<Object>) value);
result.addAll((Collection<T>) flatCollection); // depends on control dependency: [if], data = [none]
} else {
result.add((T) value); // depends on control dependency: [if], data = [none]
}
}
return result;
} }
|
public class class_name {
public void pause(ServerActivityCallback requestCountListener) {
if (paused) {
throw ServerLogger.ROOT_LOGGER.serverAlreadyPaused();
}
this.paused = true;
listenerUpdater.set(this, requestCountListener);
if (activeRequestCountUpdater.get(this) == 0) {
if (listenerUpdater.compareAndSet(this, requestCountListener, null)) {
requestCountListener.done();
}
}
} }
|
public class class_name {
public void pause(ServerActivityCallback requestCountListener) {
if (paused) {
throw ServerLogger.ROOT_LOGGER.serverAlreadyPaused();
}
this.paused = true;
listenerUpdater.set(this, requestCountListener);
if (activeRequestCountUpdater.get(this) == 0) {
if (listenerUpdater.compareAndSet(this, requestCountListener, null)) {
requestCountListener.done(); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public static <T> List<T> removeTypes(final List<T> list, final List<Class<? extends T>> filter) {
final Iterator it = list.iterator();
while (it.hasNext()) {
final Class type = it.next().getClass();
if (filter.contains(type)) {
it.remove();
}
}
return list;
} }
|
public class class_name {
public static <T> List<T> removeTypes(final List<T> list, final List<Class<? extends T>> filter) {
final Iterator it = list.iterator();
while (it.hasNext()) {
final Class type = it.next().getClass();
if (filter.contains(type)) {
it.remove(); // depends on control dependency: [if], data = [none]
}
}
return list;
} }
|
public class class_name {
public int getListNumber(RtfList list) {
if(lists.contains(list)) {
return lists.indexOf(list);
} else {
lists.add(list);
return lists.size();
}
} }
|
public class class_name {
public int getListNumber(RtfList list) {
if(lists.contains(list)) {
return lists.indexOf(list); // depends on control dependency: [if], data = [none]
} else {
lists.add(list); // depends on control dependency: [if], data = [none]
return lists.size(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public String[] getVideoUrls() {
Video[] video = getVideo();
if (video == null || video.length == 0) {
return null;
}
String[] urls = new String[video.length];
// this variable needs to be set in the portlet environment.
String url = getEnvironment().getWServletPath();
Map<String, String> parameters = getBaseParameterMap();
for (int i = 0; i < urls.length; i++) {
parameters.put(VIDEO_INDEX_REQUEST_PARAM_KEY, String.valueOf(i));
urls[i] = WebUtilities.getPath(url, parameters, true);
}
return urls;
} }
|
public class class_name {
public String[] getVideoUrls() {
Video[] video = getVideo();
if (video == null || video.length == 0) {
return null; // depends on control dependency: [if], data = [none]
}
String[] urls = new String[video.length];
// this variable needs to be set in the portlet environment.
String url = getEnvironment().getWServletPath();
Map<String, String> parameters = getBaseParameterMap();
for (int i = 0; i < urls.length; i++) {
parameters.put(VIDEO_INDEX_REQUEST_PARAM_KEY, String.valueOf(i)); // depends on control dependency: [for], data = [i]
urls[i] = WebUtilities.getPath(url, parameters, true); // depends on control dependency: [for], data = [i]
}
return urls;
} }
|
public class class_name {
@Override
public Certificate[] engineGetCertificateChain(String s) {
CredentialWrapper credential = getKeyEntry(s);
X509Certificate[] chain = new X509Certificate[0];
if (credential != null) {
try {
chain = credential.getCredential().getCertificateChain();
} catch (ResourceStoreException e) {
logger.warn(e.getMessage(), e);
chain = null;
}
}
return chain;
} }
|
public class class_name {
@Override
public Certificate[] engineGetCertificateChain(String s) {
CredentialWrapper credential = getKeyEntry(s);
X509Certificate[] chain = new X509Certificate[0];
if (credential != null) {
try {
chain = credential.getCredential().getCertificateChain(); // depends on control dependency: [try], data = [none]
} catch (ResourceStoreException e) {
logger.warn(e.getMessage(), e);
chain = null;
} // depends on control dependency: [catch], data = [none]
}
return chain;
} }
|
public class class_name {
public static CertifiedPublicKey convertCertificate(CertificateFactory certFactory, X509CertificateHolder cert)
{
if (cert == null) {
return null;
}
if (certFactory instanceof BcX509CertificateFactory) {
return ((BcX509CertificateFactory) certFactory).convert(cert);
} else {
try {
return certFactory.decode(cert.getEncoded());
} catch (IOException e) {
// Very unlikely
throw new IllegalArgumentException("Invalid Certificate, unable to encode", e);
}
}
} }
|
public class class_name {
public static CertifiedPublicKey convertCertificate(CertificateFactory certFactory, X509CertificateHolder cert)
{
if (cert == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (certFactory instanceof BcX509CertificateFactory) {
return ((BcX509CertificateFactory) certFactory).convert(cert); // depends on control dependency: [if], data = [none]
} else {
try {
return certFactory.decode(cert.getEncoded()); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
// Very unlikely
throw new IllegalArgumentException("Invalid Certificate, unable to encode", e);
} // depends on control dependency: [catch], data = [none]
}
} }
|
public class class_name {
void or(LongBitSet other) {
assert other.numWords <= numWords : "numWords=" + numWords + ", other.numWords=" + other.numWords;
int pos = Math.min(numWords, other.numWords);
while (--pos >= 0) {
bits[pos] |= other.bits[pos];
}
} }
|
public class class_name {
void or(LongBitSet other) {
assert other.numWords <= numWords : "numWords=" + numWords + ", other.numWords=" + other.numWords;
int pos = Math.min(numWords, other.numWords);
while (--pos >= 0) {
bits[pos] |= other.bits[pos];
// depends on control dependency: [while], data = [none]
}
} }
|
public class class_name {
public static <K, KK, VV> Map<KK, VV> getAndPutMapIfAbsent(final Map<K, Map<KK, VV>> map, final K key) {
Map<KK, VV> v = map.get(key);
if (v == null) {
v = new HashMap<>();
v = map.put(key, v);
}
return v;
} }
|
public class class_name {
public static <K, KK, VV> Map<KK, VV> getAndPutMapIfAbsent(final Map<K, Map<KK, VV>> map, final K key) {
Map<KK, VV> v = map.get(key);
if (v == null) {
v = new HashMap<>();
// depends on control dependency: [if], data = [none]
v = map.put(key, v);
// depends on control dependency: [if], data = [none]
}
return v;
} }
|
public class class_name {
public <T> QueryCriteria addParameter( String listId, T... param ) {
if( param.length == 0 ) {
return null;
}
if( QueryCriteriaType.REGEXP.equals(this.type) && ! (param[0] instanceof String) ) {
throw new IllegalArgumentException("Only String parameters may be used in regular expressions.");
}
QueryCriteria criteria = new QueryCriteria(listId, this.union, this.type, param.length);
for( T paramElem : param ) {
criteria.addParameter(paramElem);
}
addCriteria(criteria);
return criteria;
} }
|
public class class_name {
public <T> QueryCriteria addParameter( String listId, T... param ) {
if( param.length == 0 ) {
return null; // depends on control dependency: [if], data = [none]
}
if( QueryCriteriaType.REGEXP.equals(this.type) && ! (param[0] instanceof String) ) {
throw new IllegalArgumentException("Only String parameters may be used in regular expressions.");
}
QueryCriteria criteria = new QueryCriteria(listId, this.union, this.type, param.length);
for( T paramElem : param ) {
criteria.addParameter(paramElem); // depends on control dependency: [for], data = [paramElem]
}
addCriteria(criteria);
return criteria;
} }
|
public class class_name {
public FilterMappingType<PortletDescriptor> getOrCreateFilterMapping()
{
List<Node> nodeList = model.get("filter-mapping");
if (nodeList != null && nodeList.size() > 0)
{
return new FilterMappingTypeImpl<PortletDescriptor>(this, "filter-mapping", model, nodeList.get(0));
}
return createFilterMapping();
} }
|
public class class_name {
public FilterMappingType<PortletDescriptor> getOrCreateFilterMapping()
{
List<Node> nodeList = model.get("filter-mapping");
if (nodeList != null && nodeList.size() > 0)
{
return new FilterMappingTypeImpl<PortletDescriptor>(this, "filter-mapping", model, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createFilterMapping();
} }
|
public class class_name {
public String getSelectPath(CmsSitemapEntryBean sitemapEntry) {
String normalizedSiteRoot = CmsStringUtil.joinPaths(CmsCoreProvider.get().getSiteRoot(), "/");
String rootPath = sitemapEntry.getRootPath();
if (rootPath.startsWith(normalizedSiteRoot)) {
return rootPath.substring(normalizedSiteRoot.length() - 1);
}
return sitemapEntry.getRootPath();
} }
|
public class class_name {
public String getSelectPath(CmsSitemapEntryBean sitemapEntry) {
String normalizedSiteRoot = CmsStringUtil.joinPaths(CmsCoreProvider.get().getSiteRoot(), "/");
String rootPath = sitemapEntry.getRootPath();
if (rootPath.startsWith(normalizedSiteRoot)) {
return rootPath.substring(normalizedSiteRoot.length() - 1);
// depends on control dependency: [if], data = [none]
}
return sitemapEntry.getRootPath();
} }
|
public class class_name {
private void initDockerFileFile(Logger log) {
// can't have dockerFile/dockerFileDir and dockerArchive
if ((dockerFile != null || dockerFileDir != null) && dockerArchive != null) {
throw new IllegalArgumentException("Both <dockerFile> (<dockerFileDir>) and <dockerArchive> are set. " +
"Only one of them can be specified.");
}
dockerFileFile = findDockerFileFile(log);
if (dockerArchive != null) {
dockerArchiveFile = new File(dockerArchive);
}
} }
|
public class class_name {
private void initDockerFileFile(Logger log) {
// can't have dockerFile/dockerFileDir and dockerArchive
if ((dockerFile != null || dockerFileDir != null) && dockerArchive != null) {
throw new IllegalArgumentException("Both <dockerFile> (<dockerFileDir>) and <dockerArchive> are set. " +
"Only one of them can be specified.");
}
dockerFileFile = findDockerFileFile(log);
if (dockerArchive != null) {
dockerArchiveFile = new File(dockerArchive); // depends on control dependency: [if], data = [(dockerArchive]
}
} }
|
public class class_name {
public Set<Failure> validateArchive(List<Validate> archiveValidationObjs, Set<Failure> failures)
{
// Archive validation
if (!archiveValidation)
{
return null;
}
for (Validate validate : archiveValidationObjs)
{
if (!(validate instanceof Validate))
return null;
}
org.ironjacamar.validator.Validator validator = new org.ironjacamar.validator.Validator();
List<Failure> partialFailures = validator.validate(archiveValidationObjs);
if (partialFailures != null)
{
if (failures == null)
{
failures = new HashSet<>();
}
failures.addAll(partialFailures);
}
return failures;
} }
|
public class class_name {
public Set<Failure> validateArchive(List<Validate> archiveValidationObjs, Set<Failure> failures)
{
// Archive validation
if (!archiveValidation)
{
return null; // depends on control dependency: [if], data = [none]
}
for (Validate validate : archiveValidationObjs)
{
if (!(validate instanceof Validate))
return null;
}
org.ironjacamar.validator.Validator validator = new org.ironjacamar.validator.Validator();
List<Failure> partialFailures = validator.validate(archiveValidationObjs);
if (partialFailures != null)
{
if (failures == null)
{
failures = new HashSet<>(); // depends on control dependency: [if], data = [none]
}
failures.addAll(partialFailures); // depends on control dependency: [if], data = [(partialFailures]
}
return failures;
} }
|
public class class_name {
private QuorumImpl findQuorum(Operation op) {
if (!isNamedOperation(op) || !isQuorumAware(op)) {
return null;
}
String quorumName = getQuorumName(op);
if (quorumName == null) {
return null;
}
return quorums.get(quorumName);
} }
|
public class class_name {
private QuorumImpl findQuorum(Operation op) {
if (!isNamedOperation(op) || !isQuorumAware(op)) {
return null; // depends on control dependency: [if], data = [none]
}
String quorumName = getQuorumName(op);
if (quorumName == null) {
return null; // depends on control dependency: [if], data = [none]
}
return quorums.get(quorumName);
} }
|
public class class_name {
private void startLauncherActivityIfRoot() {
try {
if (isTaskRoot()) {
PackageManager packageManager = getPackageManager();
Intent intent = packageManager.getLaunchIntentForPackage(getPackageName());
/*
Make this work with Instant Apps. It is possible and even likely to create an Instant App
that doesn't have the Main Activity included in its APK. In such cases, this Intent is null,
and we can't do anything apart from exiting our Activity.
*/
if (intent != null) {
ComponentName componentName = intent.getComponent();
/* Backwards compatible method that will clear all activities in the stack. */
Intent mainIntent = Util.makeRestartActivityTask(componentName);
if (mainIntent != null) {
startActivity(mainIntent);
}
} else {
ApptentiveLog.w("Unable to start app's main activity: launch intent is missing");
}
}
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while starting app's main activity");
logException(e);
}
} }
|
public class class_name {
private void startLauncherActivityIfRoot() {
try {
if (isTaskRoot()) {
PackageManager packageManager = getPackageManager();
Intent intent = packageManager.getLaunchIntentForPackage(getPackageName());
/*
Make this work with Instant Apps. It is possible and even likely to create an Instant App
that doesn't have the Main Activity included in its APK. In such cases, this Intent is null,
and we can't do anything apart from exiting our Activity.
*/
if (intent != null) {
ComponentName componentName = intent.getComponent();
/* Backwards compatible method that will clear all activities in the stack. */
Intent mainIntent = Util.makeRestartActivityTask(componentName);
if (mainIntent != null) {
startActivity(mainIntent); // depends on control dependency: [if], data = [(mainIntent]
}
} else {
ApptentiveLog.w("Unable to start app's main activity: launch intent is missing");
}
}
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while starting app's main activity"); // depends on control dependency: [if], data = [none]
logException(e); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private static Map<String, String> generateMapChangeIds(List<String> newIDs) {
Map<String, String> mapIds = new HashMap<String, String>();
List<String> oldIds = HELM2NotationUtils.helm2notation.getPolymerAndGroupingIDs();
Map<String, String> mapOldIds = new HashMap<String, String>();
for (String oldID : oldIds) {
mapOldIds.put(oldID, "");
}
for (String newId : newIDs) {
if (mapOldIds.containsKey(newId)) {
int i = 1;
String type = newId.split("\\d")[0];
while (mapOldIds.containsKey(type + i)) {
i++;
}
mapIds.put(newId, type + i);
}
}
return mapIds;
} }
|
public class class_name {
private static Map<String, String> generateMapChangeIds(List<String> newIDs) {
Map<String, String> mapIds = new HashMap<String, String>();
List<String> oldIds = HELM2NotationUtils.helm2notation.getPolymerAndGroupingIDs();
Map<String, String> mapOldIds = new HashMap<String, String>();
for (String oldID : oldIds) {
mapOldIds.put(oldID, "");
// depends on control dependency: [for], data = [oldID]
}
for (String newId : newIDs) {
if (mapOldIds.containsKey(newId)) {
int i = 1;
String type = newId.split("\\d")[0];
while (mapOldIds.containsKey(type + i)) {
i++;
// depends on control dependency: [while], data = [none]
}
mapIds.put(newId, type + i);
// depends on control dependency: [if], data = [none]
}
}
return mapIds;
} }
|
public class class_name {
protected void registerPublicPermissions(Class<? extends Permission> clazz) {
Assert.notNull(clazz, "Class required");
Field[] fields = clazz.getFields();
for (Field field : fields) {
try {
Object fieldValue = field.get(null);
if (Permission.class.isAssignableFrom(fieldValue.getClass())) {
// Found a Permission static field
Permission perm = (Permission) fieldValue;
String permissionName = field.getName();
registerPermission(perm, permissionName);
}
}
catch (Exception ignore) {
}
}
} }
|
public class class_name {
protected void registerPublicPermissions(Class<? extends Permission> clazz) {
Assert.notNull(clazz, "Class required");
Field[] fields = clazz.getFields();
for (Field field : fields) {
try {
Object fieldValue = field.get(null);
if (Permission.class.isAssignableFrom(fieldValue.getClass())) {
// Found a Permission static field
Permission perm = (Permission) fieldValue;
String permissionName = field.getName();
registerPermission(perm, permissionName); // depends on control dependency: [if], data = [none]
}
}
catch (Exception ignore) {
} // depends on control dependency: [catch], data = [none]
}
} }
|
public class class_name {
private void printTerms(PrintStream out, TermedDocument termedDocument,
EntityIdValue entityIdValue, String specialLabel) {
String label = specialLabel;
String description = "-";
if (termedDocument != null) {
if (label == null) {
MonolingualTextValue labelValue = termedDocument.getLabels()
.get("en");
if (labelValue != null) {
label = csvStringEscape(labelValue.getText());
}
}
MonolingualTextValue descriptionValue = termedDocument
.getDescriptions().get("en");
if (descriptionValue != null) {
description = csvStringEscape(descriptionValue.getText());
}
}
if (label == null) {
label = entityIdValue.getId();
}
out.print(entityIdValue.getId() + "," + label + "," + description + ","
+ entityIdValue.getIri());
} }
|
public class class_name {
private void printTerms(PrintStream out, TermedDocument termedDocument,
EntityIdValue entityIdValue, String specialLabel) {
String label = specialLabel;
String description = "-";
if (termedDocument != null) {
if (label == null) {
MonolingualTextValue labelValue = termedDocument.getLabels()
.get("en");
if (labelValue != null) {
label = csvStringEscape(labelValue.getText()); // depends on control dependency: [if], data = [(labelValue]
}
}
MonolingualTextValue descriptionValue = termedDocument
.getDescriptions().get("en");
if (descriptionValue != null) {
description = csvStringEscape(descriptionValue.getText()); // depends on control dependency: [if], data = [(descriptionValue]
}
}
if (label == null) {
label = entityIdValue.getId(); // depends on control dependency: [if], data = [none]
}
out.print(entityIdValue.getId() + "," + label + "," + description + ","
+ entityIdValue.getIri());
} }
|
public class class_name {
@Override
public EClass getIfcTextureMap() {
if (ifcTextureMapEClass == null) {
ifcTextureMapEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(719);
}
return ifcTextureMapEClass;
} }
|
public class class_name {
@Override
public EClass getIfcTextureMap() {
if (ifcTextureMapEClass == null) {
ifcTextureMapEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(719);
// depends on control dependency: [if], data = [none]
}
return ifcTextureMapEClass;
} }
|
public class class_name {
public static Expression compile(String exp) {
if (Miscellaneous.isEmpty(exp) || exp.equals(".")) {
exp = "$";
}
Queue<String> queue = new LinkedList<String>();
List<String> tokens = parseTokens(exp);
boolean isInBracket = false;
int numInBracket = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < tokens.size(); i++) {
String token = tokens.get(i);
if (token.equals("[")) {
if (isInBracket) {
throw new IllegalArgumentException("Error parsing expression '" + exp + "': Nested [ found");
}
isInBracket = true;
numInBracket = 0;
sb.append(token);
} else if (token.equals("]")) {
if (!isInBracket) {
throw new IllegalArgumentException("Error parsing expression '" + exp + "': Unbalanced ] found");
}
isInBracket = false;
sb.append(token);
queue.add(sb.toString());
sb = new StringBuilder();
} else {
if (isInBracket) {
if (numInBracket > 0) {
throw new IllegalArgumentException("Error parsing expression '" + exp + "': Multiple tokens found inside a bracket");
}
sb.append(token);
numInBracket++;
} else {
queue.add(token);
}
}
if (i == tokens.size() - 1) {
if (isInBracket) {
throw new IllegalArgumentException("Error parsing expression '" + exp + "': Unbalanced [ found");
}
}
}
return new Expression(queue, exp);
} }
|
public class class_name {
public static Expression compile(String exp) {
if (Miscellaneous.isEmpty(exp) || exp.equals(".")) {
exp = "$"; // depends on control dependency: [if], data = [none]
}
Queue<String> queue = new LinkedList<String>();
List<String> tokens = parseTokens(exp);
boolean isInBracket = false;
int numInBracket = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < tokens.size(); i++) {
String token = tokens.get(i);
if (token.equals("[")) {
if (isInBracket) {
throw new IllegalArgumentException("Error parsing expression '" + exp + "': Nested [ found");
}
isInBracket = true;
numInBracket = 0;
sb.append(token);
} else if (token.equals("]")) {
if (!isInBracket) {
throw new IllegalArgumentException("Error parsing expression '" + exp + "': Unbalanced ] found");
}
isInBracket = false;
sb.append(token);
queue.add(sb.toString());
sb = new StringBuilder();
} else {
if (isInBracket) {
if (numInBracket > 0) {
throw new IllegalArgumentException("Error parsing expression '" + exp + "': Multiple tokens found inside a bracket");
}
sb.append(token);
numInBracket++;
} else {
queue.add(token);
}
}
if (i == tokens.size() - 1) {
if (isInBracket) {
throw new IllegalArgumentException("Error parsing expression '" + exp + "': Unbalanced [ found");
}
}
}
return new Expression(queue, exp);
} }
|
public class class_name {
private void expand(String mediaQueryPath, Section section, List<Section> stack) {
stack = new ArrayList<>(stack);
if (!section.getSelectors().isEmpty()) {
expandSection(mediaQueryPath, section, stack);
} else {
mediaQueryPath = expandMediaQuery(mediaQueryPath, section, stack);
}
if (section.getSelectorString() != null && !section.getSelectorString().startsWith("@")) {
// Unfold subsections
for (Section child : section.getSubSections()) {
expand(mediaQueryPath, child, stack);
}
// Delete subsections - no longer necessary (and not supported by css)
section.getSubSections().clear();
}
} }
|
public class class_name {
private void expand(String mediaQueryPath, Section section, List<Section> stack) {
stack = new ArrayList<>(stack);
if (!section.getSelectors().isEmpty()) {
expandSection(mediaQueryPath, section, stack); // depends on control dependency: [if], data = [none]
} else {
mediaQueryPath = expandMediaQuery(mediaQueryPath, section, stack); // depends on control dependency: [if], data = [none]
}
if (section.getSelectorString() != null && !section.getSelectorString().startsWith("@")) {
// Unfold subsections
for (Section child : section.getSubSections()) {
expand(mediaQueryPath, child, stack); // depends on control dependency: [for], data = [child]
}
// Delete subsections - no longer necessary (and not supported by css)
section.getSubSections().clear(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void remove(List<Value> values) {
Key[] keys = makeSubKeys(values);
List<byte[]> digestList = getDigestList();
// int startIndex = digestList.IndexOf (subKey.digest);
// int count = values.Count;
// foreach (Key key in keys){
//
// client.Delete (this.policy, key);
// }
// client.Operate(this.policy, this.key, ListOperation.Remove(this.binNameString, startIndex, count));
for (Key key : keys) {
client.delete(this.policy, key);
digestList.remove(key.digest);
}
client.put(this.policy, this.key, new Bin(this.binNameString, digestList));
} }
|
public class class_name {
public void remove(List<Value> values) {
Key[] keys = makeSubKeys(values);
List<byte[]> digestList = getDigestList();
// int startIndex = digestList.IndexOf (subKey.digest);
// int count = values.Count;
// foreach (Key key in keys){
//
// client.Delete (this.policy, key);
// }
// client.Operate(this.policy, this.key, ListOperation.Remove(this.binNameString, startIndex, count));
for (Key key : keys) {
client.delete(this.policy, key); // depends on control dependency: [for], data = [key]
digestList.remove(key.digest); // depends on control dependency: [for], data = [key]
}
client.put(this.policy, this.key, new Bin(this.binNameString, digestList));
} }
|
public class class_name {
@Override
public void removeByCommerceOrderId(long commerceOrderId) {
for (CommerceOrderItem commerceOrderItem : findByCommerceOrderId(
commerceOrderId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceOrderItem);
}
} }
|
public class class_name {
@Override
public void removeByCommerceOrderId(long commerceOrderId) {
for (CommerceOrderItem commerceOrderItem : findByCommerceOrderId(
commerceOrderId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceOrderItem); // depends on control dependency: [for], data = [commerceOrderItem]
}
} }
|
public class class_name {
private boolean inHostsList(DatanodeID node, String ipAddr) {
Set<String> hostsList = hostsReader.getHosts();
try {
if (hostsList.isEmpty()
|| (ipAddr != null && hostsList.contains(ipAddr))
|| hostsList.contains(node.getHost())
|| hostsList.contains(node.getName())
|| ((node instanceof DatanodeInfo) && (hostsList.contains(((DatanodeInfo) node)
.getHostName())
|| hostsList.contains(((DatanodeInfo) node).getHostName() + ":"
+ node.getPort())))
// this is for the mixed mode in which the hostnames in the includes file
// are followed with a "." and the datanodes are using IP addresses
// during registration
|| (ipAddr != null &&
hostsList.contains(InetAddress.getByName(ipAddr).getHostName()
+ "."))) {
return true;
}
// for several calls we pass ipAddr = null, but the datanode name
// is an IP address, for this we need to do best effort reverse DNS
// resolution
String host = getHostNameForIp(node.getHost());
if (host != null) {
return hostsList.contains(host + ".") || hostsList.contains(host);
}
// host is not in the list
return false;
} catch (UnknownHostException e) {
LOG.error(e);
}
return false;
} }
|
public class class_name {
private boolean inHostsList(DatanodeID node, String ipAddr) {
Set<String> hostsList = hostsReader.getHosts();
try {
if (hostsList.isEmpty()
|| (ipAddr != null && hostsList.contains(ipAddr))
|| hostsList.contains(node.getHost())
|| hostsList.contains(node.getName())
|| ((node instanceof DatanodeInfo) && (hostsList.contains(((DatanodeInfo) node)
.getHostName())
|| hostsList.contains(((DatanodeInfo) node).getHostName() + ":"
+ node.getPort())))
// this is for the mixed mode in which the hostnames in the includes file
// are followed with a "." and the datanodes are using IP addresses
// during registration
|| (ipAddr != null &&
hostsList.contains(InetAddress.getByName(ipAddr).getHostName()
+ "."))) {
return true; // depends on control dependency: [if], data = [none]
}
// for several calls we pass ipAddr = null, but the datanode name
// is an IP address, for this we need to do best effort reverse DNS
// resolution
String host = getHostNameForIp(node.getHost());
if (host != null) {
return hostsList.contains(host + ".") || hostsList.contains(host); // depends on control dependency: [if], data = [(host]
}
// host is not in the list
return false; // depends on control dependency: [try], data = [none]
} catch (UnknownHostException e) {
LOG.error(e);
} // depends on control dependency: [catch], data = [none]
return false;
} }
|
public class class_name {
public static void repairParentRelationships(Collection<ActivityInstanceImpl> values, String processInstanceId) {
for (ActivityInstanceImpl activityInstance : values) {
// if the determined activity instance id and the parent activity instance are equal,
// just put the activity instance under the process instance
if (valuesEqual(activityInstance.getId(), activityInstance.getParentActivityInstanceId())) {
activityInstance.setParentActivityInstanceId(processInstanceId);
}
}
} }
|
public class class_name {
public static void repairParentRelationships(Collection<ActivityInstanceImpl> values, String processInstanceId) {
for (ActivityInstanceImpl activityInstance : values) {
// if the determined activity instance id and the parent activity instance are equal,
// just put the activity instance under the process instance
if (valuesEqual(activityInstance.getId(), activityInstance.getParentActivityInstanceId())) {
activityInstance.setParentActivityInstanceId(processInstanceId); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
private static boolean isValidStack(VdmThread thread)
{
final IDebugOptions debugOptions = thread.getDbgpSession().getDebugOptions();
if (debugOptions.get(DebugOption.ENGINE_VALIDATE_STACK))
{
thread.updateStack();
if (thread.hasStackFrames())
{
return thread.isValidStack();
}
}
return true;
} }
|
public class class_name {
private static boolean isValidStack(VdmThread thread)
{
final IDebugOptions debugOptions = thread.getDbgpSession().getDebugOptions();
if (debugOptions.get(DebugOption.ENGINE_VALIDATE_STACK))
{
thread.updateStack(); // depends on control dependency: [if], data = [none]
if (thread.hasStackFrames())
{
return thread.isValidStack(); // depends on control dependency: [if], data = [none]
}
}
return true;
} }
|
public class class_name {
public void setReasonCodes(java.util.Collection<String> reasonCodes) {
if (reasonCodes == null) {
this.reasonCodes = null;
return;
}
this.reasonCodes = new com.amazonaws.internal.SdkInternalList<String>(reasonCodes);
} }
|
public class class_name {
public void setReasonCodes(java.util.Collection<String> reasonCodes) {
if (reasonCodes == null) {
this.reasonCodes = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.reasonCodes = new com.amazonaws.internal.SdkInternalList<String>(reasonCodes);
} }
|
public class class_name {
public static List<Domain> getRunningDomains(Connect libvirt) {
try {
List<Domain> domains = new ArrayList<>();
int[] ids = libvirt.listDomains();
for (int id : ids) {
domains.add(libvirt.domainLookupByID(id));
}
return domains;
} catch (LibvirtException e) {
throw new LibvirtRuntimeException("Unable to list defined domains", e);
}
} }
|
public class class_name {
public static List<Domain> getRunningDomains(Connect libvirt) {
try {
List<Domain> domains = new ArrayList<>();
int[] ids = libvirt.listDomains();
for (int id : ids) {
domains.add(libvirt.domainLookupByID(id)); // depends on control dependency: [for], data = [id]
}
return domains; // depends on control dependency: [try], data = [none]
} catch (LibvirtException e) {
throw new LibvirtRuntimeException("Unable to list defined domains", e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private boolean exposesNoInterfaceView(Class<?> beanClass) {
Class<?>[] interfaces = beanClass.getInterfaces();
if (interfaces.length == 0) {
return true;
}
// As per section 4.9.8 (bullet 1.3) of EJB3.1 spec
// java.io.Serializable; java.io.Externalizable; any of the interfaces defined by the javax.ejb
// are excluded from interface check
List<Class<?>> implementedInterfaces = new ArrayList<Class<?>>(Arrays.asList(interfaces));
List<Class<?>> filteredInterfaces = this.filterInterfaces(implementedInterfaces);
// Now that we have removed the interfaces that should be excluded from the check,
// if the filtered interfaces collection is empty then this bean can be considered for no-interface view
return filteredInterfaces.isEmpty();
} }
|
public class class_name {
private boolean exposesNoInterfaceView(Class<?> beanClass) {
Class<?>[] interfaces = beanClass.getInterfaces();
if (interfaces.length == 0) {
return true; // depends on control dependency: [if], data = [none]
}
// As per section 4.9.8 (bullet 1.3) of EJB3.1 spec
// java.io.Serializable; java.io.Externalizable; any of the interfaces defined by the javax.ejb
// are excluded from interface check
List<Class<?>> implementedInterfaces = new ArrayList<Class<?>>(Arrays.asList(interfaces));
List<Class<?>> filteredInterfaces = this.filterInterfaces(implementedInterfaces);
// Now that we have removed the interfaces that should be excluded from the check,
// if the filtered interfaces collection is empty then this bean can be considered for no-interface view
return filteredInterfaces.isEmpty();
} }
|
public class class_name {
public static <T> void quickSelect(T data, Adapter<T> adapter, int start, int end, int rank) {
while(true) {
// Optimization for small arrays
// This also ensures a minimum size below
if(start + SMALL > end) {
insertionSort(data, adapter, start, end);
return;
}
// Best of 5 pivot picking:
// Choose pivots by looking at five candidates.
final int len = end - start;
final int seventh = (len >> 3) + (len >> 6) + 1;
final int m3 = (start + end) >> 1; // middle
final int m2 = m3 - seventh;
final int m1 = m2 - seventh;
final int m4 = m3 + seventh;
final int m5 = m4 + seventh;
// Explicit (and optimal) sorting network for 5 elements
// See Knuth for details.
if(adapter.compare(data, m1, m2) > 0) {
adapter.swap(data, m1, m2);
}
if(adapter.compare(data, m1, m3) > 0) {
adapter.swap(data, m1, m3);
}
if(adapter.compare(data, m2, m3) > 0) {
adapter.swap(data, m2, m3);
}
if(adapter.compare(data, m4, m5) > 0) {
adapter.swap(data, m4, m5);
}
if(adapter.compare(data, m1, m4) > 0) {
adapter.swap(data, m1, m4);
}
if(adapter.compare(data, m3, m4) > 0) {
adapter.swap(data, m3, m4);
}
if(adapter.compare(data, m2, m5) > 0) {
adapter.swap(data, m2, m5);
}
if(adapter.compare(data, m2, m3) > 0) {
adapter.swap(data, m2, m3);
}
if(adapter.compare(data, m4, m5) > 0) {
adapter.swap(data, m4, m5);
}
int best = bestPivot(rank, m1, m2, m3, m4, m5);
// final double pivot = data[best];
// Move middle element out of the way.
adapter.swap(data, best, end - 1);
// Begin partitioning
int i = start, j = end - 2;
// This is classic quicksort stuff
while(true) {
while(i <= j && adapter.compare(data, end - 1, i) >= 0) {
i++;
}
while(j >= i && adapter.compare(data, end - 1, j) <= 0) {
j--;
}
if(i >= j) {
break;
}
adapter.swap(data, i, j);
}
// Move pivot (former middle element) back into the appropriate place
adapter.swap(data, i, end - 1);
// Skip duplicates to narrow down the search interval:
while(rank < i && adapter.compare(data, i, i - 1) == 0) {
--i;
}
while(rank > i && adapter.compare(data, i, i + 1) == 0) {
++i;
}
// In contrast to quicksort, we only need to recurse into the half we are
// interested in. Instead of recursion we now use iteration.
if(rank < i) {
end = i;
}
else if(rank > i) {
start = i + 1;
}
else {
break;
}
} // Loop until rank==i
} }
|
public class class_name {
public static <T> void quickSelect(T data, Adapter<T> adapter, int start, int end, int rank) {
while(true) {
// Optimization for small arrays
// This also ensures a minimum size below
if(start + SMALL > end) {
insertionSort(data, adapter, start, end); // depends on control dependency: [if], data = [end)]
return; // depends on control dependency: [if], data = [none]
}
// Best of 5 pivot picking:
// Choose pivots by looking at five candidates.
final int len = end - start;
final int seventh = (len >> 3) + (len >> 6) + 1;
final int m3 = (start + end) >> 1; // middle
final int m2 = m3 - seventh;
final int m1 = m2 - seventh;
final int m4 = m3 + seventh;
final int m5 = m4 + seventh;
// Explicit (and optimal) sorting network for 5 elements
// See Knuth for details.
if(adapter.compare(data, m1, m2) > 0) {
adapter.swap(data, m1, m2); // depends on control dependency: [if], data = [none]
}
if(adapter.compare(data, m1, m3) > 0) {
adapter.swap(data, m1, m3); // depends on control dependency: [if], data = [none]
}
if(adapter.compare(data, m2, m3) > 0) {
adapter.swap(data, m2, m3); // depends on control dependency: [if], data = [none]
}
if(adapter.compare(data, m4, m5) > 0) {
adapter.swap(data, m4, m5); // depends on control dependency: [if], data = [none]
}
if(adapter.compare(data, m1, m4) > 0) {
adapter.swap(data, m1, m4); // depends on control dependency: [if], data = [none]
}
if(adapter.compare(data, m3, m4) > 0) {
adapter.swap(data, m3, m4); // depends on control dependency: [if], data = [none]
}
if(adapter.compare(data, m2, m5) > 0) {
adapter.swap(data, m2, m5); // depends on control dependency: [if], data = [none]
}
if(adapter.compare(data, m2, m3) > 0) {
adapter.swap(data, m2, m3); // depends on control dependency: [if], data = [none]
}
if(adapter.compare(data, m4, m5) > 0) {
adapter.swap(data, m4, m5); // depends on control dependency: [if], data = [none]
}
int best = bestPivot(rank, m1, m2, m3, m4, m5);
// final double pivot = data[best];
// Move middle element out of the way.
adapter.swap(data, best, end - 1); // depends on control dependency: [while], data = [none]
// Begin partitioning
int i = start, j = end - 2;
// This is classic quicksort stuff
while(true) {
while(i <= j && adapter.compare(data, end - 1, i) >= 0) {
i++; // depends on control dependency: [while], data = [none]
}
while(j >= i && adapter.compare(data, end - 1, j) <= 0) {
j--; // depends on control dependency: [while], data = [none]
}
if(i >= j) {
break;
}
adapter.swap(data, i, j); // depends on control dependency: [while], data = [none]
}
// Move pivot (former middle element) back into the appropriate place
adapter.swap(data, i, end - 1); // depends on control dependency: [while], data = [none]
// Skip duplicates to narrow down the search interval:
while(rank < i && adapter.compare(data, i, i - 1) == 0) {
--i; // depends on control dependency: [while], data = [none]
}
while(rank > i && adapter.compare(data, i, i + 1) == 0) {
++i; // depends on control dependency: [while], data = [none]
}
// In contrast to quicksort, we only need to recurse into the half we are
// interested in. Instead of recursion we now use iteration.
if(rank < i) {
end = i; // depends on control dependency: [if], data = [none]
}
else if(rank > i) {
start = i + 1; // depends on control dependency: [if], data = [none]
}
else {
break;
}
} // Loop until rank==i
} }
|
public class class_name {
@Override
public void visitAfter(JavaClass obj) {
isListenerMethod = true;
for (Code l : listenerCode.keySet()) {
try {
super.visitCode(l);
} catch (StopOpcodeParsingException e) {
// method already reported
}
}
super.visitAfter(obj);
} }
|
public class class_name {
@Override
public void visitAfter(JavaClass obj) {
isListenerMethod = true;
for (Code l : listenerCode.keySet()) {
try {
super.visitCode(l); // depends on control dependency: [try], data = [none]
} catch (StopOpcodeParsingException e) {
// method already reported
} // depends on control dependency: [catch], data = [none]
}
super.visitAfter(obj);
} }
|
public class class_name {
public void onGeometryEditStart(GeometryEditStartEvent event) {
if (container != null) {
mapPresenter.getContainerManager().removeVectorContainer(container);
}
container = mapPresenter.getContainerManager().addScreenContainer();
redraw();
} }
|
public class class_name {
public void onGeometryEditStart(GeometryEditStartEvent event) {
if (container != null) {
mapPresenter.getContainerManager().removeVectorContainer(container); // depends on control dependency: [if], data = [(container]
}
container = mapPresenter.getContainerManager().addScreenContainer();
redraw();
} }
|
public class class_name {
public void startElement (String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException {
if (abandonHope) {
return;
}
if (saxParser == null) {
String saxParserClass = getCatalogParser(namespaceURI,
localName);
if (saxParserClass == null) {
abandonHope = true;
if (namespaceURI == null) {
debug.message(2, "No Catalog parser for " + localName);
} else {
debug.message(2, "No Catalog parser for "
+ "{" + namespaceURI + "}"
+ localName);
}
return;
}
try {
saxParser = (SAXCatalogParser)
Class.forName(saxParserClass).newInstance();
saxParser.setCatalog(catalog);
saxParser.startDocument();
saxParser.startElement(namespaceURI, localName, qName, atts);
} catch (ClassNotFoundException cnfe) {
saxParser = null;
abandonHope = true;
debug.message(2, cnfe.toString());
} catch (InstantiationException ie) {
saxParser = null;
abandonHope = true;
debug.message(2, ie.toString());
} catch (IllegalAccessException iae) {
saxParser = null;
abandonHope = true;
debug.message(2, iae.toString());
} catch (ClassCastException cce ) {
saxParser = null;
abandonHope = true;
debug.message(2, cce.toString());
}
} else {
saxParser.startElement(namespaceURI, localName, qName, atts);
}
} }
|
public class class_name {
public void startElement (String namespaceURI,
String localName,
String qName,
Attributes atts)
throws SAXException {
if (abandonHope) {
return;
}
if (saxParser == null) {
String saxParserClass = getCatalogParser(namespaceURI,
localName);
if (saxParserClass == null) {
abandonHope = true;
if (namespaceURI == null) {
debug.message(2, "No Catalog parser for " + localName); // depends on control dependency: [if], data = [none]
} else {
debug.message(2, "No Catalog parser for "
+ "{" + namespaceURI + "}"
+ localName); // depends on control dependency: [if], data = [none]
}
return;
}
try {
saxParser = (SAXCatalogParser)
Class.forName(saxParserClass).newInstance();
saxParser.setCatalog(catalog);
saxParser.startDocument();
saxParser.startElement(namespaceURI, localName, qName, atts);
} catch (ClassNotFoundException cnfe) {
saxParser = null;
abandonHope = true;
debug.message(2, cnfe.toString());
} catch (InstantiationException ie) {
saxParser = null;
abandonHope = true;
debug.message(2, ie.toString());
} catch (IllegalAccessException iae) {
saxParser = null;
abandonHope = true;
debug.message(2, iae.toString());
} catch (ClassCastException cce ) {
saxParser = null;
abandonHope = true;
debug.message(2, cce.toString());
}
} else {
saxParser.startElement(namespaceURI, localName, qName, atts);
}
} }
|
public class class_name {
private void setLimit(int from, int size) {
request.setFrom(from);
if (size > -1) {
request.setSize(size);
}
} }
|
public class class_name {
private void setLimit(int from, int size) {
request.setFrom(from);
if (size > -1) {
request.setSize(size); // depends on control dependency: [if], data = [(size]
}
} }
|
public class class_name {
public void setSchemas(java.util.Collection<String> schemas) {
if (schemas == null) {
this.schemas = null;
return;
}
this.schemas = new java.util.ArrayList<String>(schemas);
} }
|
public class class_name {
public void setSchemas(java.util.Collection<String> schemas) {
if (schemas == null) {
this.schemas = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.schemas = new java.util.ArrayList<String>(schemas);
} }
|
public class class_name {
public void replace(Card oldOne, Card newOne) {
VirtualLayoutManager layoutManager = getLayoutManager();
if (oldOne != null && newOne != null && mGroupBasicAdapter != null && layoutManager != null) {
List<LayoutHelper> layoutHelpers = layoutManager.getLayoutHelpers();
int cardIdx = mGroupBasicAdapter.findCardIdxForCard(oldOne);
if (layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers.size()) {
final List<LayoutHelper> newLayoutHelpers = new LinkedList<>();
for (int i = 0, size = layoutHelpers.size(); i < size; i++) {
LayoutHelper layoutHelper = layoutHelpers.get(i);
if (i == cardIdx) {
layoutHelper = newOne.getLayoutHelper();
}
newLayoutHelpers.add(layoutHelper);
}
layoutManager.setLayoutHelpers(newLayoutHelpers);
mGroupBasicAdapter.replaceComponent(oldOne, newOne);
}
}
} }
|
public class class_name {
public void replace(Card oldOne, Card newOne) {
VirtualLayoutManager layoutManager = getLayoutManager();
if (oldOne != null && newOne != null && mGroupBasicAdapter != null && layoutManager != null) {
List<LayoutHelper> layoutHelpers = layoutManager.getLayoutHelpers();
int cardIdx = mGroupBasicAdapter.findCardIdxForCard(oldOne);
if (layoutHelpers != null && cardIdx >= 0 && cardIdx < layoutHelpers.size()) {
final List<LayoutHelper> newLayoutHelpers = new LinkedList<>();
for (int i = 0, size = layoutHelpers.size(); i < size; i++) {
LayoutHelper layoutHelper = layoutHelpers.get(i);
if (i == cardIdx) {
layoutHelper = newOne.getLayoutHelper(); // depends on control dependency: [if], data = [none]
}
newLayoutHelpers.add(layoutHelper); // depends on control dependency: [for], data = [none]
}
layoutManager.setLayoutHelpers(newLayoutHelpers); // depends on control dependency: [if], data = [none]
mGroupBasicAdapter.replaceComponent(oldOne, newOne); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public void handleStateEvent(String callbackKey) {
if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {
((StateEventHandler) handlers.get(callbackKey)).handle();
} else {
System.err.println("Error in handle: " + callbackKey + " for state handler ");
}
} }
|
public class class_name {
public void handleStateEvent(String callbackKey) {
if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {
((StateEventHandler) handlers.get(callbackKey)).handle(); // depends on control dependency: [if], data = [none]
} else {
System.err.println("Error in handle: " + callbackKey + " for state handler "); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
@Override
public long getLong(TemporalField field) {
if (field instanceof ChronoField) {
if (field == OFFSET_SECONDS) {
return getOffset().getTotalSeconds();
}
return time.getLong(field);
}
return field.getFrom(this);
} }
|
public class class_name {
@Override
public long getLong(TemporalField field) {
if (field instanceof ChronoField) {
if (field == OFFSET_SECONDS) {
return getOffset().getTotalSeconds(); // depends on control dependency: [if], data = [none]
}
return time.getLong(field); // depends on control dependency: [if], data = [none]
}
return field.getFrom(this);
} }
|
public class class_name {
@SuppressWarnings({"checkstyle:cyclomaticcomplexity"})
protected int checkSuperTypes(
XtendTypeDeclaration element,
EReference feature,
List<? extends JvmTypeReference> superTypes,
Class<?> expectedType,
boolean onlySubTypes) {
int nbSuperTypes = 0;
final JvmDeclaredType inferredType = this.associations.getInferredType(element);
if (inferredType instanceof JvmGenericType) {
final LinkedList<JvmTypeReference> inferredSuperTypes = CollectionLiterals.newLinkedList();
inferredSuperTypes.addAll(inferredType.getSuperTypes());
final boolean isExpectingInterface = expectedType.isInterface();
int superTypeIndex = 0;
for (final JvmTypeReference superType : superTypes) {
boolean success = true;
final JvmType jvmSuperType = (superType == null) ? null : superType.getType();
if (jvmSuperType != null) {
final JvmTypeReference inferredSuperType =
(inferredSuperTypes.isEmpty()) ? null : inferredSuperTypes.removeFirst();
final LightweightTypeReference lighweightSuperType = toLightweightTypeReference(superType);
if (!(jvmSuperType instanceof JvmGenericType)
|| (isExpectingInterface != ((JvmGenericType) jvmSuperType).isInterface())) {
if (isExpectingInterface) {
error(
MessageFormat.format(Messages.SARLValidator_63, Messages.SARLValidator_64),
feature,
superTypeIndex,
INTERFACE_EXPECTED,
jvmSuperType.getIdentifier());
} else {
error(
MessageFormat.format(Messages.SARLValidator_63, Messages.SARLValidator_66),
feature,
superTypeIndex,
CLASS_EXPECTED,
jvmSuperType.getIdentifier());
}
success = false;
} else if (isFinal(lighweightSuperType)) {
error(Messages.SARLValidator_67,
feature,
superTypeIndex,
OVERRIDDEN_FINAL,
inferredType.getIdentifier(),
jvmSuperType.getIdentifier());
success = false;
} else if (!lighweightSuperType.isSubtypeOf(expectedType)
|| (onlySubTypes && lighweightSuperType.isType(expectedType))) {
if (onlySubTypes) {
error(MessageFormat.format(Messages.SARLValidator_68, expectedType.getName()),
feature,
superTypeIndex,
INVALID_EXTENDED_TYPE,
jvmSuperType.getIdentifier());
} else {
error(MessageFormat.format(Messages.SARLValidator_69, expectedType.getName()),
feature,
superTypeIndex,
INVALID_EXTENDED_TYPE,
jvmSuperType.getIdentifier());
}
success = false;
} else if (inferredSuperType == null
|| !Objects.equal(inferredSuperType.getIdentifier(), jvmSuperType.getIdentifier())
|| Objects.equal(inferredType.getIdentifier(), jvmSuperType.getIdentifier())
|| hasCycleInHierarchy((JvmGenericType) inferredType, Sets.<JvmGenericType>newHashSet())) {
error(MessageFormat.format(Messages.SARLValidator_70,
inferredType.getQualifiedName()),
feature,
superTypeIndex,
CYCLIC_INHERITANCE,
jvmSuperType.getIdentifier());
success = false;
}
} else if (superType != null) {
error(MessageFormat.format(Messages.SARLValidator_70,
inferredType.getQualifiedName()),
feature,
superTypeIndex,
CYCLIC_INHERITANCE,
superType.getIdentifier());
success = false;
}
checkWildcardSupertype(element, superType, feature, superTypeIndex);
++superTypeIndex;
if (success) {
++nbSuperTypes;
}
}
}
return nbSuperTypes;
} }
|
public class class_name {
@SuppressWarnings({"checkstyle:cyclomaticcomplexity"})
protected int checkSuperTypes(
XtendTypeDeclaration element,
EReference feature,
List<? extends JvmTypeReference> superTypes,
Class<?> expectedType,
boolean onlySubTypes) {
int nbSuperTypes = 0;
final JvmDeclaredType inferredType = this.associations.getInferredType(element);
if (inferredType instanceof JvmGenericType) {
final LinkedList<JvmTypeReference> inferredSuperTypes = CollectionLiterals.newLinkedList();
inferredSuperTypes.addAll(inferredType.getSuperTypes()); // depends on control dependency: [if], data = [none]
final boolean isExpectingInterface = expectedType.isInterface();
int superTypeIndex = 0;
for (final JvmTypeReference superType : superTypes) {
boolean success = true;
final JvmType jvmSuperType = (superType == null) ? null : superType.getType();
if (jvmSuperType != null) {
final JvmTypeReference inferredSuperType =
(inferredSuperTypes.isEmpty()) ? null : inferredSuperTypes.removeFirst();
final LightweightTypeReference lighweightSuperType = toLightweightTypeReference(superType);
if (!(jvmSuperType instanceof JvmGenericType)
|| (isExpectingInterface != ((JvmGenericType) jvmSuperType).isInterface())) {
if (isExpectingInterface) {
error(
MessageFormat.format(Messages.SARLValidator_63, Messages.SARLValidator_64),
feature,
superTypeIndex,
INTERFACE_EXPECTED,
jvmSuperType.getIdentifier()); // depends on control dependency: [if], data = [none]
} else {
error(
MessageFormat.format(Messages.SARLValidator_63, Messages.SARLValidator_66),
feature,
superTypeIndex,
CLASS_EXPECTED,
jvmSuperType.getIdentifier()); // depends on control dependency: [if], data = [none]
}
success = false; // depends on control dependency: [if], data = [none]
} else if (isFinal(lighweightSuperType)) {
error(Messages.SARLValidator_67,
feature,
superTypeIndex,
OVERRIDDEN_FINAL,
inferredType.getIdentifier(),
jvmSuperType.getIdentifier()); // depends on control dependency: [if], data = [none]
success = false; // depends on control dependency: [if], data = [none]
} else if (!lighweightSuperType.isSubtypeOf(expectedType)
|| (onlySubTypes && lighweightSuperType.isType(expectedType))) {
if (onlySubTypes) {
error(MessageFormat.format(Messages.SARLValidator_68, expectedType.getName()),
feature,
superTypeIndex,
INVALID_EXTENDED_TYPE,
jvmSuperType.getIdentifier()); // depends on control dependency: [if], data = [none]
} else {
error(MessageFormat.format(Messages.SARLValidator_69, expectedType.getName()),
feature,
superTypeIndex,
INVALID_EXTENDED_TYPE,
jvmSuperType.getIdentifier()); // depends on control dependency: [if], data = [none]
}
success = false; // depends on control dependency: [if], data = [none]
} else if (inferredSuperType == null
|| !Objects.equal(inferredSuperType.getIdentifier(), jvmSuperType.getIdentifier())
|| Objects.equal(inferredType.getIdentifier(), jvmSuperType.getIdentifier())
|| hasCycleInHierarchy((JvmGenericType) inferredType, Sets.<JvmGenericType>newHashSet())) {
error(MessageFormat.format(Messages.SARLValidator_70,
inferredType.getQualifiedName()),
feature,
superTypeIndex,
CYCLIC_INHERITANCE,
jvmSuperType.getIdentifier()); // depends on control dependency: [if], data = [none]
success = false; // depends on control dependency: [if], data = [none]
}
} else if (superType != null) {
error(MessageFormat.format(Messages.SARLValidator_70,
inferredType.getQualifiedName()),
feature,
superTypeIndex,
CYCLIC_INHERITANCE,
superType.getIdentifier()); // depends on control dependency: [if], data = [none]
success = false; // depends on control dependency: [if], data = [none]
}
checkWildcardSupertype(element, superType, feature, superTypeIndex); // depends on control dependency: [for], data = [superType]
++superTypeIndex; // depends on control dependency: [for], data = [superType]
if (success) {
++nbSuperTypes; // depends on control dependency: [if], data = [none]
}
}
}
return nbSuperTypes;
} }
|
public class class_name {
public DescribeStackResourceDriftsRequest withStackResourceDriftStatusFilters(StackResourceDriftStatus... stackResourceDriftStatusFilters) {
com.amazonaws.internal.SdkInternalList<String> stackResourceDriftStatusFiltersCopy = new com.amazonaws.internal.SdkInternalList<String>(
stackResourceDriftStatusFilters.length);
for (StackResourceDriftStatus value : stackResourceDriftStatusFilters) {
stackResourceDriftStatusFiltersCopy.add(value.toString());
}
if (getStackResourceDriftStatusFilters() == null) {
setStackResourceDriftStatusFilters(stackResourceDriftStatusFiltersCopy);
} else {
getStackResourceDriftStatusFilters().addAll(stackResourceDriftStatusFiltersCopy);
}
return this;
} }
|
public class class_name {
public DescribeStackResourceDriftsRequest withStackResourceDriftStatusFilters(StackResourceDriftStatus... stackResourceDriftStatusFilters) {
com.amazonaws.internal.SdkInternalList<String> stackResourceDriftStatusFiltersCopy = new com.amazonaws.internal.SdkInternalList<String>(
stackResourceDriftStatusFilters.length);
for (StackResourceDriftStatus value : stackResourceDriftStatusFilters) {
stackResourceDriftStatusFiltersCopy.add(value.toString()); // depends on control dependency: [for], data = [value]
}
if (getStackResourceDriftStatusFilters() == null) {
setStackResourceDriftStatusFilters(stackResourceDriftStatusFiltersCopy); // depends on control dependency: [if], data = [none]
} else {
getStackResourceDriftStatusFilters().addAll(stackResourceDriftStatusFiltersCopy); // depends on control dependency: [if], data = [none]
}
return this;
} }
|
public class class_name {
void rightShift(int n) {
if (intLen == 0)
return;
int nInts = n >>> 5;
int nBits = n & 0x1F;
this.intLen -= nInts;
if (nBits == 0)
return;
int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
if (nBits >= bitsInHighWord) {
this.primitiveLeftShift(32 - nBits);
this.intLen--;
} else {
primitiveRightShift(nBits);
}
} }
|
public class class_name {
void rightShift(int n) {
if (intLen == 0)
return;
int nInts = n >>> 5;
int nBits = n & 0x1F;
this.intLen -= nInts;
if (nBits == 0)
return;
int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
if (nBits >= bitsInHighWord) {
this.primitiveLeftShift(32 - nBits); // depends on control dependency: [if], data = [none]
this.intLen--; // depends on control dependency: [if], data = [none]
} else {
primitiveRightShift(nBits); // depends on control dependency: [if], data = [(nBits]
}
} }
|
public class class_name {
private Collection<ComputationState> computeNextStates(
final SharedBufferAccessor<T> sharedBufferAccessor,
final ComputationState computationState,
final EventWrapper event,
final TimerService timerService) throws Exception {
final ConditionContext context = new ConditionContext(
sharedBufferAccessor,
computationState,
timerService,
event.getTimestamp());
final OutgoingEdges<T> outgoingEdges = createDecisionGraph(context, computationState, event.getEvent());
// Create the computing version based on the previously computed edges
// We need to defer the creation of computation states until we know how many edges start
// at this computation state so that we can assign proper version
final List<StateTransition<T>> edges = outgoingEdges.getEdges();
int takeBranchesToVisit = Math.max(0, outgoingEdges.getTotalTakeBranches() - 1);
int ignoreBranchesToVisit = outgoingEdges.getTotalIgnoreBranches();
int totalTakeToSkip = Math.max(0, outgoingEdges.getTotalTakeBranches() - 1);
final List<ComputationState> resultingComputationStates = new ArrayList<>();
for (StateTransition<T> edge : edges) {
switch (edge.getAction()) {
case IGNORE: {
if (!isStartState(computationState)) {
final DeweyNumber version;
if (isEquivalentState(edge.getTargetState(), getState(computationState))) {
//Stay in the same state (it can be either looping one or singleton)
final int toIncrease = calculateIncreasingSelfState(
outgoingEdges.getTotalIgnoreBranches(),
outgoingEdges.getTotalTakeBranches());
version = computationState.getVersion().increase(toIncrease);
} else {
//IGNORE after PROCEED
version = computationState.getVersion()
.increase(totalTakeToSkip + ignoreBranchesToVisit)
.addStage();
ignoreBranchesToVisit--;
}
addComputationState(
sharedBufferAccessor,
resultingComputationStates,
edge.getTargetState(),
computationState.getPreviousBufferEntry(),
version,
computationState.getStartTimestamp(),
computationState.getStartEventID()
);
}
}
break;
case TAKE:
final State<T> nextState = edge.getTargetState();
final State<T> currentState = edge.getSourceState();
final NodeId previousEntry = computationState.getPreviousBufferEntry();
final DeweyNumber currentVersion = computationState.getVersion().increase(takeBranchesToVisit);
final DeweyNumber nextVersion = new DeweyNumber(currentVersion).addStage();
takeBranchesToVisit--;
final NodeId newEntry = sharedBufferAccessor.put(
currentState.getName(),
event.getEventId(),
previousEntry,
currentVersion);
final long startTimestamp;
final EventId startEventId;
if (isStartState(computationState)) {
startTimestamp = event.getTimestamp();
startEventId = event.getEventId();
} else {
startTimestamp = computationState.getStartTimestamp();
startEventId = computationState.getStartEventID();
}
addComputationState(
sharedBufferAccessor,
resultingComputationStates,
nextState,
newEntry,
nextVersion,
startTimestamp,
startEventId);
//check if newly created state is optional (have a PROCEED path to Final state)
final State<T> finalState = findFinalStateAfterProceed(context, nextState, event.getEvent());
if (finalState != null) {
addComputationState(
sharedBufferAccessor,
resultingComputationStates,
finalState,
newEntry,
nextVersion,
startTimestamp,
startEventId);
}
break;
}
}
if (isStartState(computationState)) {
int totalBranches = calculateIncreasingSelfState(
outgoingEdges.getTotalIgnoreBranches(),
outgoingEdges.getTotalTakeBranches());
DeweyNumber startVersion = computationState.getVersion().increase(totalBranches);
ComputationState startState = ComputationState.createStartState(computationState.getCurrentStateName(), startVersion);
resultingComputationStates.add(startState);
}
if (computationState.getPreviousBufferEntry() != null) {
// release the shared entry referenced by the current computation state.
sharedBufferAccessor.releaseNode(computationState.getPreviousBufferEntry());
}
return resultingComputationStates;
} }
|
public class class_name {
private Collection<ComputationState> computeNextStates(
final SharedBufferAccessor<T> sharedBufferAccessor,
final ComputationState computationState,
final EventWrapper event,
final TimerService timerService) throws Exception {
final ConditionContext context = new ConditionContext(
sharedBufferAccessor,
computationState,
timerService,
event.getTimestamp());
final OutgoingEdges<T> outgoingEdges = createDecisionGraph(context, computationState, event.getEvent());
// Create the computing version based on the previously computed edges
// We need to defer the creation of computation states until we know how many edges start
// at this computation state so that we can assign proper version
final List<StateTransition<T>> edges = outgoingEdges.getEdges();
int takeBranchesToVisit = Math.max(0, outgoingEdges.getTotalTakeBranches() - 1);
int ignoreBranchesToVisit = outgoingEdges.getTotalIgnoreBranches();
int totalTakeToSkip = Math.max(0, outgoingEdges.getTotalTakeBranches() - 1);
final List<ComputationState> resultingComputationStates = new ArrayList<>();
for (StateTransition<T> edge : edges) {
switch (edge.getAction()) {
case IGNORE: {
if (!isStartState(computationState)) {
final DeweyNumber version;
if (isEquivalentState(edge.getTargetState(), getState(computationState))) {
//Stay in the same state (it can be either looping one or singleton)
final int toIncrease = calculateIncreasingSelfState(
outgoingEdges.getTotalIgnoreBranches(),
outgoingEdges.getTotalTakeBranches());
version = computationState.getVersion().increase(toIncrease); // depends on control dependency: [if], data = [none]
} else {
//IGNORE after PROCEED
version = computationState.getVersion()
.increase(totalTakeToSkip + ignoreBranchesToVisit)
.addStage(); // depends on control dependency: [if], data = [none]
ignoreBranchesToVisit--; // depends on control dependency: [if], data = [none]
}
addComputationState(
sharedBufferAccessor,
resultingComputationStates,
edge.getTargetState(),
computationState.getPreviousBufferEntry(),
version,
computationState.getStartTimestamp(),
computationState.getStartEventID()
); // depends on control dependency: [if], data = [none]
}
}
break;
case TAKE:
final State<T> nextState = edge.getTargetState();
final State<T> currentState = edge.getSourceState();
final NodeId previousEntry = computationState.getPreviousBufferEntry();
final DeweyNumber currentVersion = computationState.getVersion().increase(takeBranchesToVisit);
final DeweyNumber nextVersion = new DeweyNumber(currentVersion).addStage();
takeBranchesToVisit--;
final NodeId newEntry = sharedBufferAccessor.put(
currentState.getName(),
event.getEventId(),
previousEntry,
currentVersion);
final long startTimestamp;
final EventId startEventId;
if (isStartState(computationState)) {
startTimestamp = event.getTimestamp(); // depends on control dependency: [if], data = [none]
startEventId = event.getEventId(); // depends on control dependency: [if], data = [none]
} else {
startTimestamp = computationState.getStartTimestamp(); // depends on control dependency: [if], data = [none]
startEventId = computationState.getStartEventID(); // depends on control dependency: [if], data = [none]
}
addComputationState(
sharedBufferAccessor,
resultingComputationStates,
nextState,
newEntry,
nextVersion,
startTimestamp,
startEventId);
//check if newly created state is optional (have a PROCEED path to Final state)
final State<T> finalState = findFinalStateAfterProceed(context, nextState, event.getEvent());
if (finalState != null) {
addComputationState(
sharedBufferAccessor,
resultingComputationStates,
finalState,
newEntry,
nextVersion,
startTimestamp,
startEventId); // depends on control dependency: [if], data = [none]
}
break;
}
}
if (isStartState(computationState)) {
int totalBranches = calculateIncreasingSelfState(
outgoingEdges.getTotalIgnoreBranches(),
outgoingEdges.getTotalTakeBranches());
DeweyNumber startVersion = computationState.getVersion().increase(totalBranches);
ComputationState startState = ComputationState.createStartState(computationState.getCurrentStateName(), startVersion);
resultingComputationStates.add(startState);
}
if (computationState.getPreviousBufferEntry() != null) {
// release the shared entry referenced by the current computation state.
sharedBufferAccessor.releaseNode(computationState.getPreviousBufferEntry());
}
return resultingComputationStates;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
@Deprecated
public static <T> TemplateExpression<T> template(Class<? extends T> cl, Template template, ImmutableList<?> args) {
if (cl.equals(Boolean.class)) {
return (TemplateExpression<T>) new PredicateTemplate(template, args);
} else {
return new TemplateExpressionImpl<T>(cl, template, args);
}
} }
|
public class class_name {
@SuppressWarnings("unchecked")
@Deprecated
public static <T> TemplateExpression<T> template(Class<? extends T> cl, Template template, ImmutableList<?> args) {
if (cl.equals(Boolean.class)) {
return (TemplateExpression<T>) new PredicateTemplate(template, args); // depends on control dependency: [if], data = [none]
} else {
return new TemplateExpressionImpl<T>(cl, template, args); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void releaseResponse(HttpResponseMessageImpl response) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "releaseResponse: " + response);
}
this.respPool.put(response);
} }
|
public class class_name {
public void releaseResponse(HttpResponseMessageImpl response) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "releaseResponse: " + response); // depends on control dependency: [if], data = [none]
}
this.respPool.put(response);
} }
|
public class class_name {
public void stop() {
synchronized (lock) {
Log.i(DOMAIN, "%s: Replicator is stopping ...", this);
if (c4repl != null) {
c4repl.stop(); // this is async; status will change when repl actually stops
}
else { Log.i(DOMAIN, "%s: Replicator has been stopped or offlined ...", this); }
if (c4ReplStatus.getActivityLevel() == C4ReplicatorStatus.ActivityLevel.OFFLINE) {
Log.i(DOMAIN, "%s: Replicator has been offlined; " +
"make the replicator into the stopped state now.", this);
final C4ReplicatorStatus c4replStatus = new C4ReplicatorStatus();
c4replStatus.setActivityLevel(C4ReplicatorStatus.ActivityLevel.STOPPED);
this.c4StatusChanged(c4replStatus);
}
if (reachabilityManager != null) { reachabilityManager.removeNetworkReachabilityListener(this); }
}
} }
|
public class class_name {
public void stop() {
synchronized (lock) {
Log.i(DOMAIN, "%s: Replicator is stopping ...", this);
if (c4repl != null) {
c4repl.stop(); // this is async; status will change when repl actually stops // depends on control dependency: [if], data = [none]
}
else { Log.i(DOMAIN, "%s: Replicator has been stopped or offlined ...", this); } // depends on control dependency: [if], data = [none]
if (c4ReplStatus.getActivityLevel() == C4ReplicatorStatus.ActivityLevel.OFFLINE) {
Log.i(DOMAIN, "%s: Replicator has been offlined; " +
"make the replicator into the stopped state now.", this); // depends on control dependency: [if], data = [none]
final C4ReplicatorStatus c4replStatus = new C4ReplicatorStatus();
c4replStatus.setActivityLevel(C4ReplicatorStatus.ActivityLevel.STOPPED); // depends on control dependency: [if], data = [none]
this.c4StatusChanged(c4replStatus); // depends on control dependency: [if], data = [none]
}
if (reachabilityManager != null) { reachabilityManager.removeNetworkReachabilityListener(this); } // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private String canonPodName(String name)
{
name = name.replace('-', '_');
if (name.indexOf('.') < 0) {
name = name + '.' + _serverSelf.getClusterId();
}
return name;
} }
|
public class class_name {
private String canonPodName(String name)
{
name = name.replace('-', '_');
if (name.indexOf('.') < 0) {
name = name + '.' + _serverSelf.getClusterId(); // depends on control dependency: [if], data = [none]
}
return name;
} }
|
public class class_name {
public int logPrecision(int recall) {
int totaltaken = 0;
int rightIndex = numSamples() - 1; //next right candidate
int leftIndex = 0; //next left candidate
int totalcorrect = 0;
while (totaltaken < recall) {
double confr = Math.abs(scores[rightIndex] - .5);
double confl = Math.abs(scores[leftIndex] - .5);
int chosen = leftIndex;
if (confr > confl) {
chosen = rightIndex;
rightIndex--;
} else {
leftIndex++;
}
//System.err.println("chose "+chosen+" score "+scores[chosen]+" class "+classes[chosen]+" correct "+correct(scores[chosen],classes[chosen]));
if ((scores[chosen] >= .5) && (classes[chosen] == 1)) {
totalcorrect++;
}
if ((scores[chosen] < .5) && (classes[chosen] == 0)) {
totalcorrect++;
}
totaltaken++;
}
return totalcorrect;
} }
|
public class class_name {
public int logPrecision(int recall) {
int totaltaken = 0;
int rightIndex = numSamples() - 1; //next right candidate
int leftIndex = 0; //next left candidate
int totalcorrect = 0;
while (totaltaken < recall) {
double confr = Math.abs(scores[rightIndex] - .5);
double confl = Math.abs(scores[leftIndex] - .5);
int chosen = leftIndex;
if (confr > confl) {
chosen = rightIndex;
// depends on control dependency: [if], data = [none]
rightIndex--;
// depends on control dependency: [if], data = [none]
} else {
leftIndex++;
// depends on control dependency: [if], data = [none]
}
//System.err.println("chose "+chosen+" score "+scores[chosen]+" class "+classes[chosen]+" correct "+correct(scores[chosen],classes[chosen]));
if ((scores[chosen] >= .5) && (classes[chosen] == 1)) {
totalcorrect++;
// depends on control dependency: [if], data = [none]
}
if ((scores[chosen] < .5) && (classes[chosen] == 0)) {
totalcorrect++;
// depends on control dependency: [if], data = [none]
}
totaltaken++;
// depends on control dependency: [while], data = [none]
}
return totalcorrect;
} }
|
public class class_name {
public void setCurrentPasswordHashPassword(String newPassword) {
this.passwordSalt = UUID.randomUUID().toString();
try {
this.currentPasswordHash = pwm.makePassword(new SecureUTF8String(newPassword),
masterPwdHashAccount, getPasswordSalt());
} catch (Exception ignored) {}
setStorePasswordHash(true);
} }
|
public class class_name {
public void setCurrentPasswordHashPassword(String newPassword) {
this.passwordSalt = UUID.randomUUID().toString();
try {
this.currentPasswordHash = pwm.makePassword(new SecureUTF8String(newPassword),
masterPwdHashAccount, getPasswordSalt()); // depends on control dependency: [try], data = [none]
} catch (Exception ignored) {} // depends on control dependency: [catch], data = [none]
setStorePasswordHash(true);
} }
|
public class class_name {
public Observable<ServiceResponse<List<AvailablePrebuiltEntityModel>>> listPrebuiltEntitiesWithServiceResponseAsync(UUID appId, String versionId) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
return service.listPrebuiltEntities(appId, versionId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<AvailablePrebuiltEntityModel>>>>() {
@Override
public Observable<ServiceResponse<List<AvailablePrebuiltEntityModel>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<AvailablePrebuiltEntityModel>> clientResponse = listPrebuiltEntitiesDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} }
|
public class class_name {
public Observable<ServiceResponse<List<AvailablePrebuiltEntityModel>>> listPrebuiltEntitiesWithServiceResponseAsync(UUID appId, String versionId) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (appId == null) {
throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
}
if (versionId == null) {
throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
}
String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
return service.listPrebuiltEntities(appId, versionId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<AvailablePrebuiltEntityModel>>>>() {
@Override
public Observable<ServiceResponse<List<AvailablePrebuiltEntityModel>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<AvailablePrebuiltEntityModel>> clientResponse = listPrebuiltEntitiesDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} }
|
public class class_name {
public QueryStringBuilder addParameterArrays(final Map<String, String[]> params)
{
if (params != null)
{
for (Entry<String, String[]> entry : params.entrySet())
{
List<String> values = null;
if (entry.getValue() != null)
{
List<String> temp = new ArrayList<String>();
if (entry.getValue() != null)
{
for (String value : entry.getValue()) {
temp.add(value);
}
}
values = temp;
}
parameters.put(entry.getKey(), values);
}
}
return this;
} }
|
public class class_name {
public QueryStringBuilder addParameterArrays(final Map<String, String[]> params)
{
if (params != null)
{
for (Entry<String, String[]> entry : params.entrySet())
{
List<String> values = null;
if (entry.getValue() != null)
{
List<String> temp = new ArrayList<String>();
if (entry.getValue() != null)
{
for (String value : entry.getValue()) {
temp.add(value); // depends on control dependency: [for], data = [value]
}
}
values = temp; // depends on control dependency: [if], data = [none]
}
parameters.put(entry.getKey(), values); // depends on control dependency: [for], data = [entry]
}
}
return this;
} }
|
public class class_name {
public Object create(String name, Object... args)
throws ClassNotFoundException,
NoSuchMethodException,
IllegalAccessException,
InstantiationException,
InvocationTargetException
{
try {
return super.create(name, args);
} catch (NoSuchMethodException x) {
Class<?> type = Class.forName(name);
Object singleton = _singleton.get(name);
if (singleton != null) {
return singleton;
} else {
Object[] burnedin = _arguments.get(type);
if (burnedin != null) {
Object[] nargs = new Object[burnedin.length + args.length];
System.arraycopy(burnedin, 0, nargs, 0, burnedin.length);
System.arraycopy(args, 0, nargs, burnedin.length, args.length);
return Beans.create(type, nargs);
} else {
throw x;
}
}
}
} }
|
public class class_name {
public Object create(String name, Object... args)
throws ClassNotFoundException,
NoSuchMethodException,
IllegalAccessException,
InstantiationException,
InvocationTargetException
{
try {
return super.create(name, args);
// depends on control dependency: [try], data = [none]
} catch (NoSuchMethodException x) {
Class<?> type = Class.forName(name);
Object singleton = _singleton.get(name);
if (singleton != null) {
return singleton;
// depends on control dependency: [if], data = [none]
} else {
Object[] burnedin = _arguments.get(type);
if (burnedin != null) {
Object[] nargs = new Object[burnedin.length + args.length];
System.arraycopy(burnedin, 0, nargs, 0, burnedin.length);
// depends on control dependency: [if], data = [(burnedin]
System.arraycopy(args, 0, nargs, burnedin.length, args.length);
// depends on control dependency: [if], data = [none]
return Beans.create(type, nargs);
// depends on control dependency: [if], data = [none]
} else {
throw x;
}
}
}
// depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
void postAdapterUpdate(UpdateOp op) {
mPendingUpdates.add(op);
if (mPendingUpdates.size() == 1) {
if (mPostUpdatesOnAnimation && mHasFixedSize && mIsAttached) {
ViewCompat.postOnAnimation(this, mUpdateChildViewsRunnable);
} else {
mAdapterUpdateDuringMeasure = true;
requestLayout();
}
}
} }
|
public class class_name {
void postAdapterUpdate(UpdateOp op) {
mPendingUpdates.add(op);
if (mPendingUpdates.size() == 1) {
if (mPostUpdatesOnAnimation && mHasFixedSize && mIsAttached) {
ViewCompat.postOnAnimation(this, mUpdateChildViewsRunnable); // depends on control dependency: [if], data = [none]
} else {
mAdapterUpdateDuringMeasure = true; // depends on control dependency: [if], data = [none]
requestLayout(); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public static TimeUnit extractTimeUnitFromString(String timeString){
timeString=timeString.toLowerCase();
if(timeString.contains("minute")){
return TimeUnit.MINUTES;
}
else if(timeString.contains("microsecond")){
return TimeUnit.MICROSECONDS;
}
else if(timeString.contains("millisecond")){
return TimeUnit.MILLISECONDS;
}
else if(timeString.contains("second")){
return TimeUnit.SECONDS;
}
else if(timeString.contains("hour")){
return TimeUnit.HOURS;
}
else if(timeString.toLowerCase().contains("day")){
return TimeUnit.DAYS;
}
else
return null;
} }
|
public class class_name {
public static TimeUnit extractTimeUnitFromString(String timeString){
timeString=timeString.toLowerCase();
if(timeString.contains("minute")){
return TimeUnit.MINUTES; // depends on control dependency: [if], data = [none]
}
else if(timeString.contains("microsecond")){
return TimeUnit.MICROSECONDS; // depends on control dependency: [if], data = [none]
}
else if(timeString.contains("millisecond")){
return TimeUnit.MILLISECONDS; // depends on control dependency: [if], data = [none]
}
else if(timeString.contains("second")){
return TimeUnit.SECONDS; // depends on control dependency: [if], data = [none]
}
else if(timeString.contains("hour")){
return TimeUnit.HOURS; // depends on control dependency: [if], data = [none]
}
else if(timeString.toLowerCase().contains("day")){
return TimeUnit.DAYS; // depends on control dependency: [if], data = [none]
}
else
return null;
} }
|
public class class_name {
public void marshall(CreateRepositoryRequest createRepositoryRequest, ProtocolMarshaller protocolMarshaller) {
if (createRepositoryRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createRepositoryRequest.getRepositoryName(), REPOSITORYNAME_BINDING);
protocolMarshaller.marshall(createRepositoryRequest.getTags(), TAGS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(CreateRepositoryRequest createRepositoryRequest, ProtocolMarshaller protocolMarshaller) {
if (createRepositoryRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createRepositoryRequest.getRepositoryName(), REPOSITORYNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createRepositoryRequest.getTags(), TAGS_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 updateTimer(boolean cancel1xxTimer, MobicentsSipApplicationSession mobicentsSipApplicationSession) {
if(logger.isDebugEnabled()) {
logger.debug("updateTimer - cancel1xxTimer=" + cancel1xxTimer + ", mobicentsSipApplicationSession=" + mobicentsSipApplicationSession);
if (mobicentsSipApplicationSession != null){
logger.debug("updateTimer - cancel1xxTimer=" + cancel1xxTimer + ", mobicentsSipApplicationSession.getApplicationName()=" + mobicentsSipApplicationSession.getApplicationName());
logger.debug("updateTimer - cancel1xxTimer=" + cancel1xxTimer + ", mobicentsSipApplicationSession.getSipContext()=" + mobicentsSipApplicationSession.getSipContext());
}
}
if(cancel1xxTimer) {
cancel1xxTimer();
}
cancelTimer();
if(proxyBranchTimeout > 0) {
synchronized (cTimerLock) {
if(!proxyBranchTimerStarted) {
try {
final ProxyBranchTimerTask timerCTask = new ProxyBranchTimerTask(this, ResponseType.FINAL, mobicentsSipApplicationSession);
if(logger.isDebugEnabled()) {
logger.debug("Proxy Branch Timeout set to " + proxyBranchTimeout);
logger.debug("updateTimer - proxy=" + proxy);
if (proxy != null){
logger.debug("updateTimer - proxy.getProxyTimerService()=" + proxy.getProxyTimerService());
}
}
proxy.getProxyTimerService().schedule(timerCTask, proxyBranchTimeout * 1000L);
proxyTimeoutTask = timerCTask;
proxyBranchTimerStarted = true;
} catch (IllegalStateException e) {
logger.error("Unexpected exception while scheduling Timer C" ,e);
}
}
}
}
} }
|
public class class_name {
public void updateTimer(boolean cancel1xxTimer, MobicentsSipApplicationSession mobicentsSipApplicationSession) {
if(logger.isDebugEnabled()) {
logger.debug("updateTimer - cancel1xxTimer=" + cancel1xxTimer + ", mobicentsSipApplicationSession=" + mobicentsSipApplicationSession); // depends on control dependency: [if], data = [none]
if (mobicentsSipApplicationSession != null){
logger.debug("updateTimer - cancel1xxTimer=" + cancel1xxTimer + ", mobicentsSipApplicationSession.getApplicationName()=" + mobicentsSipApplicationSession.getApplicationName()); // depends on control dependency: [if], data = [none]
logger.debug("updateTimer - cancel1xxTimer=" + cancel1xxTimer + ", mobicentsSipApplicationSession.getSipContext()=" + mobicentsSipApplicationSession.getSipContext()); // depends on control dependency: [if], data = [none]
}
}
if(cancel1xxTimer) {
cancel1xxTimer(); // depends on control dependency: [if], data = [none]
}
cancelTimer();
if(proxyBranchTimeout > 0) {
synchronized (cTimerLock) { // depends on control dependency: [if], data = [none]
if(!proxyBranchTimerStarted) {
try {
final ProxyBranchTimerTask timerCTask = new ProxyBranchTimerTask(this, ResponseType.FINAL, mobicentsSipApplicationSession);
if(logger.isDebugEnabled()) {
logger.debug("Proxy Branch Timeout set to " + proxyBranchTimeout); // depends on control dependency: [if], data = [none]
logger.debug("updateTimer - proxy=" + proxy); // depends on control dependency: [if], data = [none]
if (proxy != null){
logger.debug("updateTimer - proxy.getProxyTimerService()=" + proxy.getProxyTimerService()); // depends on control dependency: [if], data = [none]
}
}
proxy.getProxyTimerService().schedule(timerCTask, proxyBranchTimeout * 1000L); // depends on control dependency: [try], data = [none]
proxyTimeoutTask = timerCTask; // depends on control dependency: [try], data = [none]
proxyBranchTimerStarted = true; // depends on control dependency: [try], data = [none]
} catch (IllegalStateException e) {
logger.error("Unexpected exception while scheduling Timer C" ,e);
} // depends on control dependency: [catch], data = [none]
}
}
}
} }
|
public class class_name {
private void showNextSuperToast() {
// Do nothing if the queue is empty
if (superToastPriorityQueue.isEmpty()) return;
// Get next SuperToast in the queue
final SuperToast superToast = superToastPriorityQueue.peek();
if (!superToast.isShowing()) {
final Message message = obtainMessage(Messages.DISPLAY_SUPERTOAST);
message.obj = superToast;
sendMessage(message);
}
} }
|
public class class_name {
private void showNextSuperToast() {
// Do nothing if the queue is empty
if (superToastPriorityQueue.isEmpty()) return;
// Get next SuperToast in the queue
final SuperToast superToast = superToastPriorityQueue.peek();
if (!superToast.isShowing()) {
final Message message = obtainMessage(Messages.DISPLAY_SUPERTOAST);
message.obj = superToast;
// depends on control dependency: [if], data = [none]
sendMessage(message);
// depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void checkDataBase(boolean autoRepair)
{
SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);
Connection jdbcConn = null;
try
{
jdbcConn = jdbcDataContainer.getConnectionFactory().getJdbcConnection();
for (InspectionQuery query : itemsInspectionQuery)
{
PreparedStatement st = null;
ResultSet resultSet = null;
try
{
st = jdbcConn.prepareStatement(query.getStatement());
resultSet = st.executeQuery();
if (resultSet.next())
{
logDescription(query.getDescription());
do
{
logBrokenObjectAndSetInconsistency(getBrokenObject(resultSet, query.getFieldNames()));
if (autoRepair)
{
try
{
query.getRepair().doRepair(resultSet);
logComment("Inconsistency has been fixed");
}
catch (SQLException e)
{
logExceptionAndSetInconsistency("Inconsistency can not been fixed", e);
}
}
}
while (resultSet.next());
}
}
finally
{
JDBCUtils.freeResources(resultSet, st, null);
}
}
}
catch (SQLException e)
{
logExceptionAndSetInconsistency("Unexpected exception during DB checking.", e);
}
catch (RepositoryException e)
{
logExceptionAndSetInconsistency("Unexpected exception during DB checking.", e);
}
finally
{
JDBCUtils.freeResources(null, null, jdbcConn);
}
} }
|
public class class_name {
public void checkDataBase(boolean autoRepair)
{
SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);
Connection jdbcConn = null;
try
{
jdbcConn = jdbcDataContainer.getConnectionFactory().getJdbcConnection();
// depends on control dependency: [try], data = [none]
for (InspectionQuery query : itemsInspectionQuery)
{
PreparedStatement st = null;
ResultSet resultSet = null;
try
{
st = jdbcConn.prepareStatement(query.getStatement());
// depends on control dependency: [try], data = [none]
resultSet = st.executeQuery();
// depends on control dependency: [try], data = [none]
if (resultSet.next())
{
logDescription(query.getDescription());
// depends on control dependency: [if], data = [none]
do
{
logBrokenObjectAndSetInconsistency(getBrokenObject(resultSet, query.getFieldNames()));
if (autoRepair)
{
try
{
query.getRepair().doRepair(resultSet);
// depends on control dependency: [try], data = [none]
logComment("Inconsistency has been fixed");
// depends on control dependency: [try], data = [none]
}
catch (SQLException e)
{
logExceptionAndSetInconsistency("Inconsistency can not been fixed", e);
}
// depends on control dependency: [catch], data = [none]
}
}
while (resultSet.next());
}
}
finally
{
JDBCUtils.freeResources(resultSet, st, null);
}
}
}
catch (SQLException e)
{
logExceptionAndSetInconsistency("Unexpected exception during DB checking.", e);
}
// depends on control dependency: [catch], data = [none]
catch (RepositoryException e)
{
logExceptionAndSetInconsistency("Unexpected exception during DB checking.", e);
}
// depends on control dependency: [catch], data = [none]
finally
{
JDBCUtils.freeResources(null, null, jdbcConn);
}
} }
|
public class class_name {
public EnvironmentConfig setCipherKey(final String cipherKey) {
if (cipherKey == null) {
return (EnvironmentConfig) removeSetting(CIPHER_KEY);
}
return setSetting(CIPHER_KEY, KryptKt.toBinaryKey(cipherKey));
} }
|
public class class_name {
public EnvironmentConfig setCipherKey(final String cipherKey) {
if (cipherKey == null) {
return (EnvironmentConfig) removeSetting(CIPHER_KEY); // depends on control dependency: [if], data = [none]
}
return setSetting(CIPHER_KEY, KryptKt.toBinaryKey(cipherKey));
} }
|
public class class_name {
@Override
protected Object createPoolOrConnection()
{
if (log.isInfoEnabled())
log.info("Initializing Neo4J database connection...");
PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(
getPersistenceUnit());
Properties props = puMetadata.getProperties();
String datastoreFilePath = null;
if (externalProperties != null)
{
datastoreFilePath = (String) externalProperties.get(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);
}
if (StringUtils.isBlank(datastoreFilePath))
{
datastoreFilePath = (String) props.get(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);
}
if (StringUtils.isBlank(datastoreFilePath))
{
throw new PersistenceUnitConfigurationException(
"For Neo4J, it's mandatory to specify kundera.datastore.file.path property in persistence.xml");
}
Neo4JSchemaMetadata nsmd = Neo4JPropertyReader.nsmd;
ClientProperties cp = nsmd != null ? nsmd.getClientProperties() : null;
GraphDatabaseService graphDb = (GraphDatabaseService) getConnectionPoolOrConnection();
if (cp != null && graphDb == null)
{
DataStore dataStore = nsmd != null ? nsmd.getDataStore() : null;
Properties properties = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection()
.getProperties() : null;
if (properties != null)
{
Map<String, String> config = new HashMap<String, String>((Map) properties);
GraphDatabaseBuilder builder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(datastoreFilePath);
builder.setConfig(config);
graphDb = builder.newGraphDatabase();
// registerShutdownHook(graphDb);
}
}
if (graphDb == null)
{
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(datastoreFilePath);
// registerShutdownHook(graphDb);
}
return graphDb;
} }
|
public class class_name {
@Override
protected Object createPoolOrConnection()
{
if (log.isInfoEnabled())
log.info("Initializing Neo4J database connection...");
PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(
getPersistenceUnit());
Properties props = puMetadata.getProperties();
String datastoreFilePath = null;
if (externalProperties != null)
{
datastoreFilePath = (String) externalProperties.get(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH); // depends on control dependency: [if], data = [none]
}
if (StringUtils.isBlank(datastoreFilePath))
{
datastoreFilePath = (String) props.get(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH); // depends on control dependency: [if], data = [none]
}
if (StringUtils.isBlank(datastoreFilePath))
{
throw new PersistenceUnitConfigurationException(
"For Neo4J, it's mandatory to specify kundera.datastore.file.path property in persistence.xml");
}
Neo4JSchemaMetadata nsmd = Neo4JPropertyReader.nsmd;
ClientProperties cp = nsmd != null ? nsmd.getClientProperties() : null;
GraphDatabaseService graphDb = (GraphDatabaseService) getConnectionPoolOrConnection();
if (cp != null && graphDb == null)
{
DataStore dataStore = nsmd != null ? nsmd.getDataStore() : null;
Properties properties = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection()
.getProperties() : null;
if (properties != null)
{
Map<String, String> config = new HashMap<String, String>((Map) properties);
GraphDatabaseBuilder builder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(datastoreFilePath);
builder.setConfig(config); // depends on control dependency: [if], data = [none]
graphDb = builder.newGraphDatabase(); // depends on control dependency: [if], data = [none]
// registerShutdownHook(graphDb);
}
}
if (graphDb == null)
{
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(datastoreFilePath); // depends on control dependency: [if], data = [none]
// registerShutdownHook(graphDb);
}
return graphDb;
} }
|
public class class_name {
private void call(UDF udf, Object[] arguments) {
try {
udf.call(pc, arguments, false);
}
catch (PageException pe) {
error(pe);
}
} }
|
public class class_name {
private void call(UDF udf, Object[] arguments) {
try {
udf.call(pc, arguments, false); // depends on control dependency: [try], data = [none]
}
catch (PageException pe) {
error(pe);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public FilterReply getTurboFilterChainDecision(final Marker marker,
final Logger logger, final Level level, final String format,
final Object[] params, final Throwable t) {
final int size = size();
// if (size == 0) {
// return FilterReply.NEUTRAL;
// }
if (size == 1) {
try {
TurboFilter tf = get(0);
return tf.decide(marker, logger, level, format, params, t);
} catch (IndexOutOfBoundsException iobe) {
return FilterReply.NEUTRAL;
}
}
Object[] tfa = toArray();
final int len = tfa.length;
for (int i = 0; i < len; i++) {
//for (TurboFilter tf : this) {
final TurboFilter tf = (TurboFilter) tfa[i];
final FilterReply r = tf.decide(marker, logger, level, format, params, t);
if (r == FilterReply.DENY || r == FilterReply.ACCEPT) {
return r;
}
}
return FilterReply.NEUTRAL;
} }
|
public class class_name {
public FilterReply getTurboFilterChainDecision(final Marker marker,
final Logger logger, final Level level, final String format,
final Object[] params, final Throwable t) {
final int size = size();
// if (size == 0) {
// return FilterReply.NEUTRAL;
// }
if (size == 1) {
try {
TurboFilter tf = get(0);
return tf.decide(marker, logger, level, format, params, t); // depends on control dependency: [try], data = [none]
} catch (IndexOutOfBoundsException iobe) {
return FilterReply.NEUTRAL;
} // depends on control dependency: [catch], data = [none]
}
Object[] tfa = toArray();
final int len = tfa.length;
for (int i = 0; i < len; i++) {
//for (TurboFilter tf : this) {
final TurboFilter tf = (TurboFilter) tfa[i];
final FilterReply r = tf.decide(marker, logger, level, format, params, t);
if (r == FilterReply.DENY || r == FilterReply.ACCEPT) {
return r; // depends on control dependency: [if], data = [none]
}
}
return FilterReply.NEUTRAL;
} }
|
public class class_name {
public static Expression clockStr(String format) {
if (format == null || format.isEmpty()) {
return x("CLOCK_STR()");
}
return x("CLOCK_STR(\"" + format + "\")");
} }
|
public class class_name {
public static Expression clockStr(String format) {
if (format == null || format.isEmpty()) {
return x("CLOCK_STR()"); // depends on control dependency: [if], data = [none]
}
return x("CLOCK_STR(\"" + format + "\")");
} }
|
public class class_name {
@Override
public int compare(GregorianCalendar c1, GregorianCalendar c2) {
if (c2.getGregorianChange() == null) {
return (int) (c1.getTime().getTime() - c2.getTime().getTime());
} else {
return 0;
}
} }
|
public class class_name {
@Override
public int compare(GregorianCalendar c1, GregorianCalendar c2) {
if (c2.getGregorianChange() == null) {
return (int) (c1.getTime().getTime() - c2.getTime().getTime()); // depends on control dependency: [if], data = [none]
} else {
return 0; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private Config parseConfiguration(String function) {
// Looks like this function_name(,$,)
int first = function.indexOf('(');
int last = function.indexOf(')');
int colon = function.indexOf(EXCLUSION_PREFIX);
// TODO(johnlenz): Make parsing precondition checks JSErrors reports.
checkState(first != -1 && last != -1);
String name = function.substring(0, first);
String params = function.substring(first + 1, last);
int paramCount = 0;
List<Integer> replacementParameters = new ArrayList<>();
String[] parts = params.split(",");
for (String param : parts) {
paramCount++;
if (param.equals(REPLACE_ALL_MARKER)) {
checkState(paramCount == 1 && parts.length == 1);
replacementParameters.add(Config.REPLACE_ALL_VALUE);
} else if (param.equals(REPLACE_ONE_MARKER)) {
// TODO(johnlenz): Support multiple.
checkState(!replacementParameters.contains(Config.REPLACE_ALL_VALUE));
replacementParameters.add(paramCount);
} else {
// TODO(johnlenz): report an error.
Preconditions.checkState(param.isEmpty(), "Unknown marker", param);
}
}
checkState(!replacementParameters.isEmpty());
return new Config(
name,
replacementParameters,
colon == -1
? ImmutableSet.of()
: ImmutableSet.copyOf(
function.substring(colon + EXCLUSION_PREFIX.length()).split(",")));
} }
|
public class class_name {
private Config parseConfiguration(String function) {
// Looks like this function_name(,$,)
int first = function.indexOf('(');
int last = function.indexOf(')');
int colon = function.indexOf(EXCLUSION_PREFIX);
// TODO(johnlenz): Make parsing precondition checks JSErrors reports.
checkState(first != -1 && last != -1);
String name = function.substring(0, first);
String params = function.substring(first + 1, last);
int paramCount = 0;
List<Integer> replacementParameters = new ArrayList<>();
String[] parts = params.split(",");
for (String param : parts) {
paramCount++; // depends on control dependency: [for], data = [param]
if (param.equals(REPLACE_ALL_MARKER)) {
checkState(paramCount == 1 && parts.length == 1); // depends on control dependency: [if], data = [none]
replacementParameters.add(Config.REPLACE_ALL_VALUE); // depends on control dependency: [if], data = [none]
} else if (param.equals(REPLACE_ONE_MARKER)) {
// TODO(johnlenz): Support multiple.
checkState(!replacementParameters.contains(Config.REPLACE_ALL_VALUE)); // depends on control dependency: [if], data = [none]
replacementParameters.add(paramCount); // depends on control dependency: [if], data = [none]
} else {
// TODO(johnlenz): report an error.
Preconditions.checkState(param.isEmpty(), "Unknown marker", param); // depends on control dependency: [if], data = [none]
}
}
checkState(!replacementParameters.isEmpty());
return new Config(
name,
replacementParameters,
colon == -1
? ImmutableSet.of()
: ImmutableSet.copyOf(
function.substring(colon + EXCLUSION_PREFIX.length()).split(",")));
} }
|
public class class_name {
protected static String normaliseTag(String tag) {
StringBuffer nt = new StringBuffer();
for(char c : tag.toLowerCase(Locale.ROOT).toCharArray()) {
if((int)c >= 0x20 && (int)c <= 0x7d &&
(int)c != 0x3d) {
nt.append(c);
}
}
return nt.toString();
} }
|
public class class_name {
protected static String normaliseTag(String tag) {
StringBuffer nt = new StringBuffer();
for(char c : tag.toLowerCase(Locale.ROOT).toCharArray()) {
if((int)c >= 0x20 && (int)c <= 0x7d &&
(int)c != 0x3d) {
nt.append(c); // depends on control dependency: [if], data = [none]
}
}
return nt.toString();
} }
|
public class class_name {
public void marshall(DeleteRealtimeEndpointRequest deleteRealtimeEndpointRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteRealtimeEndpointRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteRealtimeEndpointRequest.getMLModelId(), MLMODELID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(DeleteRealtimeEndpointRequest deleteRealtimeEndpointRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteRealtimeEndpointRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteRealtimeEndpointRequest.getMLModelId(), MLMODELID_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 GetCelebrityRecognitionResult withCelebrities(CelebrityRecognition... celebrities) {
if (this.celebrities == null) {
setCelebrities(new java.util.ArrayList<CelebrityRecognition>(celebrities.length));
}
for (CelebrityRecognition ele : celebrities) {
this.celebrities.add(ele);
}
return this;
} }
|
public class class_name {
public GetCelebrityRecognitionResult withCelebrities(CelebrityRecognition... celebrities) {
if (this.celebrities == null) {
setCelebrities(new java.util.ArrayList<CelebrityRecognition>(celebrities.length)); // depends on control dependency: [if], data = [none]
}
for (CelebrityRecognition ele : celebrities) {
this.celebrities.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} }
|
public class class_name {
@Deprecated
public List<GraphQLObjectType> findImplementations(GraphQLSchema schema, GraphQLInterfaceType interfaceType) {
List<GraphQLObjectType> result = new ArrayList<>();
for (GraphQLType type : schema.getAllTypesAsList()) {
if (!(type instanceof GraphQLObjectType)) {
continue;
}
GraphQLObjectType objectType = (GraphQLObjectType) type;
if ((objectType).getInterfaces().contains(interfaceType)) {
result.add(objectType);
}
}
return result;
} }
|
public class class_name {
@Deprecated
public List<GraphQLObjectType> findImplementations(GraphQLSchema schema, GraphQLInterfaceType interfaceType) {
List<GraphQLObjectType> result = new ArrayList<>();
for (GraphQLType type : schema.getAllTypesAsList()) {
if (!(type instanceof GraphQLObjectType)) {
continue;
}
GraphQLObjectType objectType = (GraphQLObjectType) type;
if ((objectType).getInterfaces().contains(interfaceType)) {
result.add(objectType); // depends on control dependency: [if], data = [none]
}
}
return result;
} }
|
public class class_name {
public static void logout() {
CmsObject cms = A_CmsUI.getCmsObject();
if (UI.getCurrent() instanceof CmsAppWorkplaceUi) {
((CmsAppWorkplaceUi)UI.getCurrent()).onWindowClose();
}
String loggedInUser = cms.getRequestContext().getCurrentUser().getName();
UI.getCurrent().getSession().close();
String loginLink = OpenCms.getLinkManager().substituteLinkForUnknownTarget(
cms,
CmsWorkplaceLoginHandler.LOGIN_HANDLER,
false);
VaadinService.getCurrentRequest().getWrappedSession().invalidate();
Page.getCurrent().setLocation(loginLink);
// logout was successful
if (LOG.isInfoEnabled()) {
LOG.info(
org.opencms.jsp.Messages.get().getBundle().key(
org.opencms.jsp.Messages.LOG_LOGOUT_SUCCESFUL_3,
loggedInUser,
"{workplace logout option}",
cms.getRequestContext().getRemoteAddress()));
}
} }
|
public class class_name {
public static void logout() {
CmsObject cms = A_CmsUI.getCmsObject();
if (UI.getCurrent() instanceof CmsAppWorkplaceUi) {
((CmsAppWorkplaceUi)UI.getCurrent()).onWindowClose(); // depends on control dependency: [if], data = [none]
}
String loggedInUser = cms.getRequestContext().getCurrentUser().getName();
UI.getCurrent().getSession().close();
String loginLink = OpenCms.getLinkManager().substituteLinkForUnknownTarget(
cms,
CmsWorkplaceLoginHandler.LOGIN_HANDLER,
false);
VaadinService.getCurrentRequest().getWrappedSession().invalidate();
Page.getCurrent().setLocation(loginLink);
// logout was successful
if (LOG.isInfoEnabled()) {
LOG.info(
org.opencms.jsp.Messages.get().getBundle().key(
org.opencms.jsp.Messages.LOG_LOGOUT_SUCCESFUL_3,
loggedInUser,
"{workplace logout option}",
cms.getRequestContext().getRemoteAddress())); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static void main(String[] args) {
//============================================================================================//
//=============================== Submitting a Request =======================================//
//============================================================================================//
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (~/.aws/credentials), and is in valid format.",
e);
}
// Create the AmazonEC2Client object so we can call various APIs.
AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-west-2")
.build();
// Initializes a Spot Instance Request
RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
//*************************** Required Parameters Settings ************************//
// Request 1 x t1.micro instance with a bid price of $0.03.
requestRequest.setSpotPrice("0.03");
requestRequest.setInstanceCount(Integer.valueOf(1));
// Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
// and the latest Amazon Linux AMI id available. Note, you should always use the latest
// Amazon Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
launchSpecification.setInstanceType("t1.micro");
// Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
launchSpecification.setSecurityGroups(securityGroups);
//*************************** Bid Type Settings ************************//
// Set the type of the bid to persistent.
requestRequest.setType("persistent");
//*************************** Valid From/To Settings ************************//
// Set the valid start time to be two minutes from now.
Calendar from = Calendar.getInstance();
from.add(Calendar.MINUTE, 2);
requestRequest.setValidFrom(from.getTime());
// Set the valid end time to be two minutes and two hours from now.
Calendar until = (Calendar) from.clone();
until.add(Calendar.HOUR, 2);
requestRequest.setValidUntil(until.getTime());
//*************************** Launch Group Settings ************************//
// Set the launch group.
requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP");
//*************************** Availability Zone Group Settings ************************//
// Set the availability zone group.
requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP");
//*************************** Add the block device mapping ************************//
// Goal: Setup block device mappings to ensure that we will not delete
// the root partition on termination.
// Create the block device mapping to describe the root partition.
BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
blockDeviceMapping.setDeviceName("/dev/sda1");
// Set the delete on termination flag to false.
EbsBlockDevice ebs = new EbsBlockDevice();
ebs.setDeleteOnTermination(Boolean.FALSE);
blockDeviceMapping.setEbs(ebs);
// Add the block device mapping to the block list.
ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>();
blockList.add(blockDeviceMapping);
// Set the block device mapping configuration in the launch specifications.
launchSpecification.setBlockDeviceMappings(blockList);
//*************************** Add the availability zone ************************//
// Setup the availability zone to use. Note we could retrieve the availability
// zones using the ec2.describeAvailabilityZones() API. For this demo we will just use
// us-east-1b.
SpotPlacement placement = new SpotPlacement("us-east-1b");
launchSpecification.setPlacement(placement);
//*************************** Add the placement group ************************//
// Setup the placement group to use with whatever name you desire.
// For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP".
// Note: We have commented this out, because we are not leveraging cc1.4xlarge or
// cg1.4xlarge in this example.
/*
SpotPlacement pg = new SpotPlacement();
pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP");
launchSpecification.setPlacement(pg);
*/
//*************************** Add the launch specification ************************//
// Add the launch specification.
requestRequest.setLaunchSpecification(launchSpecification);
//============================================================================================//
//=========================== Getting the Request ID from the Request ========================//
//============================================================================================//
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();
// Setup an arraylist to collect all of the request ids we want to watch hit the running
// state.
ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();
// Add all of the request ids to the hashset, so we can determine when they hit the
// active state.
for (SpotInstanceRequest requestResponse : requestResponses) {
System.out.println("Created Spot Request: "+requestResponse.getSpotInstanceRequestId());
spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
}
//============================================================================================//
//=========================== Determining the State of the Spot Request ======================//
//============================================================================================//
// Create a variable that will track whether there are any requests still in the open state.
boolean anyOpen;
// Initialize variables.
ArrayList<String> instanceIds = new ArrayList<String>();
do {
// Create the describeRequest with tall of the request id to monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
// Initialize the anyOpen variable to false, which assumes there are no requests open unless
// we find one that is still open.
anyOpen=false;
try {
// Retrieve all of the requests we want to monitor.
DescribeSpotInstanceRequestsResult describeResult = ec2.describeSpotInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();
// Look through each request and determine if they are all in the active state.
for (SpotInstanceRequest describeResponse : describeResponses) {
// If the state is open, it hasn't changed since we attempted to request it.
// There is the potential for it to transition almost immediately to closed or
// cancelled so we compare against open instead of active.
if (describeResponse.getState().equals("open")) {
anyOpen = true;
break;
}
// Add the instance id to the list we will eventually terminate.
instanceIds.add(describeResponse.getInstanceId());
}
} catch (AmazonServiceException e) {
// If we have an exception, ensure we don't break out of the loop.
// This prevents the scenario where there was blip on the wire.
anyOpen = true;
}
try {
// Sleep for 60 seconds.
Thread.sleep(60*1000);
} catch (Exception e) {
// Do nothing because it woke up early.
}
} while (anyOpen);
//============================================================================================//
//====================================== Canceling the Request ==============================//
//============================================================================================//
try {
// Cancel requests.
CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(spotInstanceRequestIds);
ec2.cancelSpotInstanceRequests(cancelRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error cancelling instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
//============================================================================================//
//=================================== Terminating any Instances ==============================//
//============================================================================================//
try {
// Terminate instances.
TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
ec2.terminateInstances(terminateRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
} }
|
public class class_name {
public static void main(String[] args) {
//============================================================================================//
//=============================== Submitting a Request =======================================//
//============================================================================================//
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().getCredentials();
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (~/.aws/credentials), and is in valid format.",
e);
}
// depends on control dependency: [catch], data = [none]
// Create the AmazonEC2Client object so we can call various APIs.
AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-west-2")
.build();
// Initializes a Spot Instance Request
RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
//*************************** Required Parameters Settings ************************//
// Request 1 x t1.micro instance with a bid price of $0.03.
requestRequest.setSpotPrice("0.03");
requestRequest.setInstanceCount(Integer.valueOf(1));
// Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
// and the latest Amazon Linux AMI id available. Note, you should always use the latest
// Amazon Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
launchSpecification.setInstanceType("t1.micro");
// Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
launchSpecification.setSecurityGroups(securityGroups);
//*************************** Bid Type Settings ************************//
// Set the type of the bid to persistent.
requestRequest.setType("persistent");
//*************************** Valid From/To Settings ************************//
// Set the valid start time to be two minutes from now.
Calendar from = Calendar.getInstance();
from.add(Calendar.MINUTE, 2);
requestRequest.setValidFrom(from.getTime());
// Set the valid end time to be two minutes and two hours from now.
Calendar until = (Calendar) from.clone();
until.add(Calendar.HOUR, 2);
requestRequest.setValidUntil(until.getTime());
//*************************** Launch Group Settings ************************//
// Set the launch group.
requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP");
//*************************** Availability Zone Group Settings ************************//
// Set the availability zone group.
requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP");
//*************************** Add the block device mapping ************************//
// Goal: Setup block device mappings to ensure that we will not delete
// the root partition on termination.
// Create the block device mapping to describe the root partition.
BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
blockDeviceMapping.setDeviceName("/dev/sda1");
// Set the delete on termination flag to false.
EbsBlockDevice ebs = new EbsBlockDevice();
ebs.setDeleteOnTermination(Boolean.FALSE);
blockDeviceMapping.setEbs(ebs);
// Add the block device mapping to the block list.
ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>();
blockList.add(blockDeviceMapping);
// Set the block device mapping configuration in the launch specifications.
launchSpecification.setBlockDeviceMappings(blockList);
//*************************** Add the availability zone ************************//
// Setup the availability zone to use. Note we could retrieve the availability
// zones using the ec2.describeAvailabilityZones() API. For this demo we will just use
// us-east-1b.
SpotPlacement placement = new SpotPlacement("us-east-1b");
launchSpecification.setPlacement(placement);
//*************************** Add the placement group ************************//
// Setup the placement group to use with whatever name you desire.
// For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP".
// Note: We have commented this out, because we are not leveraging cc1.4xlarge or
// cg1.4xlarge in this example.
/*
SpotPlacement pg = new SpotPlacement();
pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP");
launchSpecification.setPlacement(pg);
*/
//*************************** Add the launch specification ************************//
// Add the launch specification.
requestRequest.setLaunchSpecification(launchSpecification);
//============================================================================================//
//=========================== Getting the Request ID from the Request ========================//
//============================================================================================//
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();
// Setup an arraylist to collect all of the request ids we want to watch hit the running
// state.
ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();
// Add all of the request ids to the hashset, so we can determine when they hit the
// active state.
for (SpotInstanceRequest requestResponse : requestResponses) {
System.out.println("Created Spot Request: "+requestResponse.getSpotInstanceRequestId());
// depends on control dependency: [for], data = [requestResponse]
spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
// depends on control dependency: [for], data = [requestResponse]
}
//============================================================================================//
//=========================== Determining the State of the Spot Request ======================//
//============================================================================================//
// Create a variable that will track whether there are any requests still in the open state.
boolean anyOpen;
// Initialize variables.
ArrayList<String> instanceIds = new ArrayList<String>();
do {
// Create the describeRequest with tall of the request id to monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
// Initialize the anyOpen variable to false, which assumes there are no requests open unless
// we find one that is still open.
anyOpen=false;
try {
// Retrieve all of the requests we want to monitor.
DescribeSpotInstanceRequestsResult describeResult = ec2.describeSpotInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();
// Look through each request and determine if they are all in the active state.
for (SpotInstanceRequest describeResponse : describeResponses) {
// If the state is open, it hasn't changed since we attempted to request it.
// There is the potential for it to transition almost immediately to closed or
// cancelled so we compare against open instead of active.
if (describeResponse.getState().equals("open")) {
anyOpen = true;
// depends on control dependency: [if], data = [none]
break;
}
// Add the instance id to the list we will eventually terminate.
instanceIds.add(describeResponse.getInstanceId());
// depends on control dependency: [for], data = [describeResponse]
}
} catch (AmazonServiceException e) {
// If we have an exception, ensure we don't break out of the loop.
// This prevents the scenario where there was blip on the wire.
anyOpen = true;
}
// depends on control dependency: [catch], data = [none]
try {
// Sleep for 60 seconds.
Thread.sleep(60*1000);
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
// Do nothing because it woke up early.
}
// depends on control dependency: [catch], data = [none]
} while (anyOpen);
//============================================================================================//
//====================================== Canceling the Request ==============================//
//============================================================================================//
try {
// Cancel requests.
CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(spotInstanceRequestIds);
ec2.cancelSpotInstanceRequests(cancelRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error cancelling instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
//============================================================================================//
//=================================== Terminating any Instances ==============================//
//============================================================================================//
try {
// Terminate instances.
TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
ec2.terminateInstances(terminateRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
} }
|
public class class_name {
public boolean findAndReportCycles(DependencyGraph graph) {
this.graph = graph;
cycleDetected = false;
visitedEdge = new LinkedHashMap<Key<?>, Dependency>(graph.size());
for (Key<?> key : graph.getAllKeys()) {
visit(key, null);
}
return cycleDetected;
} }
|
public class class_name {
public boolean findAndReportCycles(DependencyGraph graph) {
this.graph = graph;
cycleDetected = false;
visitedEdge = new LinkedHashMap<Key<?>, Dependency>(graph.size());
for (Key<?> key : graph.getAllKeys()) {
visit(key, null); // depends on control dependency: [for], data = [key]
}
return cycleDetected;
} }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.