code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private static <T> List<T> lcs(List<T> arg0, List<T> arg1, Comparator<T> comparator, int i,
int j) {
if (arg0.size() == i || arg1.size() == j) {
return new ArrayList<>(Math.min(arg0.size(), arg1.size()));
}
if (comparator.compare(arg0.get(i), arg1.get(j)) == 0) {
T t = arg0.get(i);
List<T> list = lcs(arg0, arg1, comparator, i + 1, j + 1);
list.add(t);
return list;
} else {
List<T> l1 = lcs(arg0, arg1, comparator, i + 1, j);
List<T> l2 = lcs(arg0, arg1, comparator, i, j + 1);
return l1.size() > l2.size() ? l1 : l2;
}
} } | public class class_name {
private static <T> List<T> lcs(List<T> arg0, List<T> arg1, Comparator<T> comparator, int i,
int j) {
if (arg0.size() == i || arg1.size() == j) {
return new ArrayList<>(Math.min(arg0.size(), arg1.size())); // depends on control dependency: [if], data = [(arg0.size()]
}
if (comparator.compare(arg0.get(i), arg1.get(j)) == 0) {
T t = arg0.get(i);
List<T> list = lcs(arg0, arg1, comparator, i + 1, j + 1);
list.add(t); // depends on control dependency: [if], data = [none]
return list; // depends on control dependency: [if], data = [none]
} else {
List<T> l1 = lcs(arg0, arg1, comparator, i + 1, j);
List<T> l2 = lcs(arg0, arg1, comparator, i, j + 1);
return l1.size() > l2.size() ? l1 : l2; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
protected void defineWidgets() {
super.defineWidgets();
// widgets to display
if (m_fieldconfiguration.getName() == null) {
addWidget(new CmsWidgetDialogParameter(m_fieldconfiguration, "name", PAGES[0], new CmsInputWidget()));
} else {
addWidget(new CmsWidgetDialogParameter(m_fieldconfiguration, "name", PAGES[0], new CmsDisplayWidget()));
}
addWidget(
new CmsWidgetDialogParameter(
m_fieldconfiguration,
"description",
"",
PAGES[0],
new CmsInputWidget(),
0,
1));
} } | public class class_name {
@Override
protected void defineWidgets() {
super.defineWidgets();
// widgets to display
if (m_fieldconfiguration.getName() == null) {
addWidget(new CmsWidgetDialogParameter(m_fieldconfiguration, "name", PAGES[0], new CmsInputWidget())); // depends on control dependency: [if], data = [none]
} else {
addWidget(new CmsWidgetDialogParameter(m_fieldconfiguration, "name", PAGES[0], new CmsDisplayWidget())); // depends on control dependency: [if], data = [none]
}
addWidget(
new CmsWidgetDialogParameter(
m_fieldconfiguration,
"description",
"",
PAGES[0],
new CmsInputWidget(),
0,
1));
} } |
public class class_name {
protected int refill() throws IOException
{
UnifiedDataPageX curr = _buffer.getCurrentPage();
SavePoint sp = _save_points.savePointActiveTop();
if (!can_fill_new_page()) {
// aka: there can be only one!
// (and it's used up)
return refill_is_eof();
}
if (sp != null && sp.getEndIdx() == _buffer.getCurrentPageIdx()) {
// also EOF but the case is odd enough to call it out
return refill_is_eof();
}
long file_position;
int start_pos = UNREAD_LIMIT;
if (curr == null) {
file_position = 0;
start_pos = 0;
}
else {
file_position = curr.getFilePosition(_pos);
if (file_position == 0) {
// unread before the beginning of file is not allowed,
// so we don't have to leave room for it
start_pos = 0;
}
}
// see if we are re-reading saved buffers
int new_idx = _buffer.getNextFilledPageIdx();
if (new_idx < 0) {
// there is no pre-filled page waiting for us, so we need to
// read new data on a new page or over our current page
curr = _buffer.getCurrentPage();
boolean needs_new_page = (curr == null);
new_idx = _buffer.getCurrentPageIdx();
if (_save_points.isSavePointOpen()) {
new_idx++;
needs_new_page = true;
}
if (needs_new_page) {
curr = _buffer.getEmptyPageIdx();
}
//
// here we actually read data into our buffers -----
//
int read = load(curr, start_pos, file_position);
if (read < 1) {
return refill_is_eof();
}
assert(curr != null && curr.getOffsetOfFilePosition(file_position) == start_pos);
set_current_page(new_idx, curr, start_pos);
}
else {
assert(!isEOF());
if (sp != null) {
int endidx = sp.getEndIdx();
if (endidx != -1 && endidx < new_idx/*_buffer.getCurrentPageIdx()*/) {
return refill_is_eof();
}
}
curr = _buffer.getPage(new_idx);
assert(curr.getStartingFileOffset() == file_position);
set_current_page(new_idx, curr, curr.getStartingOffset());
if (sp != null && sp.getEndIdx() == new_idx /*_buffer.getCurrentPageIdx()*/ ) {
// the last page in the marked range will probably
// require a different limit
_limit = sp.getEndPos();
}
}
assert(isEOF() ^ (_limit > 0)); // xor: either we're at eof or we have data to read
return _limit;
} } | public class class_name {
protected int refill() throws IOException
{
UnifiedDataPageX curr = _buffer.getCurrentPage();
SavePoint sp = _save_points.savePointActiveTop();
if (!can_fill_new_page()) {
// aka: there can be only one!
// (and it's used up)
return refill_is_eof();
}
if (sp != null && sp.getEndIdx() == _buffer.getCurrentPageIdx()) {
// also EOF but the case is odd enough to call it out
return refill_is_eof();
}
long file_position;
int start_pos = UNREAD_LIMIT;
if (curr == null) {
file_position = 0;
start_pos = 0;
}
else {
file_position = curr.getFilePosition(_pos);
if (file_position == 0) {
// unread before the beginning of file is not allowed,
// so we don't have to leave room for it
start_pos = 0; // depends on control dependency: [if], data = [none]
}
}
// see if we are re-reading saved buffers
int new_idx = _buffer.getNextFilledPageIdx();
if (new_idx < 0) {
// there is no pre-filled page waiting for us, so we need to
// read new data on a new page or over our current page
curr = _buffer.getCurrentPage();
boolean needs_new_page = (curr == null);
new_idx = _buffer.getCurrentPageIdx();
if (_save_points.isSavePointOpen()) {
new_idx++;
needs_new_page = true;
}
if (needs_new_page) {
curr = _buffer.getEmptyPageIdx();
}
//
// here we actually read data into our buffers -----
//
int read = load(curr, start_pos, file_position);
if (read < 1) {
return refill_is_eof();
}
assert(curr != null && curr.getOffsetOfFilePosition(file_position) == start_pos);
set_current_page(new_idx, curr, start_pos);
}
else {
assert(!isEOF());
if (sp != null) {
int endidx = sp.getEndIdx();
if (endidx != -1 && endidx < new_idx/*_buffer.getCurrentPageIdx()*/) {
return refill_is_eof();
}
}
curr = _buffer.getPage(new_idx);
assert(curr.getStartingFileOffset() == file_position);
set_current_page(new_idx, curr, curr.getStartingOffset());
if (sp != null && sp.getEndIdx() == new_idx /*_buffer.getCurrentPageIdx()*/ ) {
// the last page in the marked range will probably
// require a different limit
_limit = sp.getEndPos();
}
}
assert(isEOF() ^ (_limit > 0)); // xor: either we're at eof or we have data to read
return _limit;
} } |
public class class_name {
public final Throwable getFirstThrowableOfType(
Class<? extends Throwable> throwableType, Throwable[] chain) {
if (chain != null) {
for (Throwable t : chain) {
if ((t != null) && throwableType.isInstance(t)) {
return t;
}
}
}
return null;
} } | public class class_name {
public final Throwable getFirstThrowableOfType(
Class<? extends Throwable> throwableType, Throwable[] chain) {
if (chain != null) {
for (Throwable t : chain) {
if ((t != null) && throwableType.isInstance(t)) {
return t; // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
@Override
public void write(String resourceId, byte[] data) {
try {
File file = this.cachedResources.get(resourceId);
if (Objects.isNull(file)) {
file = new File(localDir, resourceId + SUFFIX);
Files.write(file.toPath(), data);
this.cachedResources.put(resourceId, file);
} else {
Files.write(file.toPath(), data);
}
} catch (Exception e) {
LOG.log(Level.WARNING, "Caching of resource failed: " + resourceId, e);
}
} } | public class class_name {
@Override
public void write(String resourceId, byte[] data) {
try {
File file = this.cachedResources.get(resourceId);
if (Objects.isNull(file)) {
file = new File(localDir, resourceId + SUFFIX); // depends on control dependency: [if], data = [none]
Files.write(file.toPath(), data); // depends on control dependency: [if], data = [none]
this.cachedResources.put(resourceId, file); // depends on control dependency: [if], data = [none]
} else {
Files.write(file.toPath(), data); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
LOG.log(Level.WARNING, "Caching of resource failed: " + resourceId, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public Configuration getConfiguration() {
try {
globalLock.readLock().lock();
return configuration;
} finally {
globalLock.readLock().unlock();
}
} } | public class class_name {
@Override
public Configuration getConfiguration() {
try {
globalLock.readLock().lock(); // depends on control dependency: [try], data = [none]
return configuration; // depends on control dependency: [try], data = [none]
} finally {
globalLock.readLock().unlock();
}
} } |
public class class_name {
private CmsADEConfigData wrap(CmsADEConfigDataInternal data) {
String path = data.getBasePath();
List<CmsADEConfigDataInternal> configList = Lists.newArrayList();
configList.add(m_moduleConfiguration);
if (path != null) {
List<String> siteConfigPaths = getSiteConfigPaths(path);
for (String siteConfigPath : siteConfigPaths) {
CmsADEConfigDataInternal currentConfig = m_siteConfigurationsByPath.get(siteConfigPath);
CmsResource masterConfigResource = currentConfig.getMasterConfig();
if (currentConfig.getMasterConfig() != null) {
CmsADEConfigDataInternal masterConfig = m_siteConfigurations.get(
masterConfigResource.getStructureId());
if (masterConfig != null) {
configList.add(masterConfig);
} else {
LOG.warn(
"Master configuration "
+ masterConfigResource.getRootPath()
+ " not found for sitemap configuration in "
+ currentConfig.getBasePath());
}
}
configList.add(currentConfig);
}
}
return new CmsADEConfigData(data, this, new CmsADEConfigurationSequence(configList));
} } | public class class_name {
private CmsADEConfigData wrap(CmsADEConfigDataInternal data) {
String path = data.getBasePath();
List<CmsADEConfigDataInternal> configList = Lists.newArrayList();
configList.add(m_moduleConfiguration);
if (path != null) {
List<String> siteConfigPaths = getSiteConfigPaths(path);
for (String siteConfigPath : siteConfigPaths) {
CmsADEConfigDataInternal currentConfig = m_siteConfigurationsByPath.get(siteConfigPath);
CmsResource masterConfigResource = currentConfig.getMasterConfig();
if (currentConfig.getMasterConfig() != null) {
CmsADEConfigDataInternal masterConfig = m_siteConfigurations.get(
masterConfigResource.getStructureId());
if (masterConfig != null) {
configList.add(masterConfig); // depends on control dependency: [if], data = [(masterConfig]
} else {
LOG.warn(
"Master configuration "
+ masterConfigResource.getRootPath()
+ " not found for sitemap configuration in "
+ currentConfig.getBasePath()); // depends on control dependency: [if], data = [none]
}
}
configList.add(currentConfig); // depends on control dependency: [for], data = [none]
}
}
return new CmsADEConfigData(data, this, new CmsADEConfigurationSequence(configList));
} } |
public class class_name {
public static void shutdownAndAwaitTermination(ExecutorService pool, long timeoutMs) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(timeoutMs / 2, TimeUnit.MILLISECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(timeoutMs / 2, TimeUnit.MILLISECONDS)) {
LOG.warn("Pool did not terminate");
}
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
}
} } | public class class_name {
public static void shutdownAndAwaitTermination(ExecutorService pool, long timeoutMs) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(timeoutMs / 2, TimeUnit.MILLISECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks // depends on control dependency: [if], data = [none]
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(timeoutMs / 2, TimeUnit.MILLISECONDS)) {
LOG.warn("Pool did not terminate"); // depends on control dependency: [if], data = [none]
}
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static boolean hasDefaultConstructor(TypeRef item) {
DefinitionRepository repository = DefinitionRepository.getRepository();
TypeDef def = repository.getDefinition(item);
if (def == null && item instanceof ClassRef) {
def = ((ClassRef)item).getDefinition();
}
return hasDefaultConstructor(def);
} } | public class class_name {
public static boolean hasDefaultConstructor(TypeRef item) {
DefinitionRepository repository = DefinitionRepository.getRepository();
TypeDef def = repository.getDefinition(item);
if (def == null && item instanceof ClassRef) {
def = ((ClassRef)item).getDefinition(); // depends on control dependency: [if], data = [none]
}
return hasDefaultConstructor(def);
} } |
public class class_name {
private static LocalTime create(int hour, int minute, int second, int nanoOfSecond) {
if ((minute | second | nanoOfSecond) == 0) {
return HOURS[hour];
}
return new LocalTime(hour, minute, second, nanoOfSecond);
} } | public class class_name {
private static LocalTime create(int hour, int minute, int second, int nanoOfSecond) {
if ((minute | second | nanoOfSecond) == 0) {
return HOURS[hour]; // depends on control dependency: [if], data = [none]
}
return new LocalTime(hour, minute, second, nanoOfSecond);
} } |
public class class_name {
private static String fetchHttpResponse(URL url) throws IOException {
HttpURLConnection conn = null;
try {
logger.info("fetching from url = " + url);
conn = (HttpURLConnection) url.openConnection();
int response = conn.getResponseCode();
if (response != HttpURLConnection.HTTP_ACCEPTED) {
String responseContent = IOUtils.toString(conn.getInputStream());
logger.info("responseContent = " + responseContent);
return responseContent;
}
throw new IOException("response from service not valid");
} catch (IOException e) {
logger.severe("unable to do proper http request url = " + url.toString());
throw e;
} finally {
conn.disconnect();
}
} } | public class class_name {
private static String fetchHttpResponse(URL url) throws IOException {
HttpURLConnection conn = null;
try {
logger.info("fetching from url = " + url);
conn = (HttpURLConnection) url.openConnection();
int response = conn.getResponseCode();
if (response != HttpURLConnection.HTTP_ACCEPTED) {
String responseContent = IOUtils.toString(conn.getInputStream());
logger.info("responseContent = " + responseContent); // depends on control dependency: [if], data = [none]
return responseContent; // depends on control dependency: [if], data = [none]
}
throw new IOException("response from service not valid");
} catch (IOException e) {
logger.severe("unable to do proper http request url = " + url.toString());
throw e;
} finally {
conn.disconnect();
}
} } |
public class class_name {
private long sendEntireMessage(SIBusMessage msg, List<DataSlice> messageSlices)
throws OperationFailedException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "sendEntireMessage", new Object[] { msg, messageSlices });
ConversationState convState = (ConversationState) getConversation().getAttachment();
long retValue = 0;
// Now build the header for this message.
CommsServerByteBuffer buffer = poolManager.allocate();
try {
buffer.putShort(convState.getConnectionObjectId());
buffer.putShort(mainConsumer.getClientSessionId());
buffer.putShort(msgBatch);
int msgLen = 0;
if (messageSlices == null) {
msgLen = buffer.putMessage((JsMessage) msg,
convState.getCommsConnection(),
getConversation());
} else {
msgLen = buffer.putMessgeWithoutEncode(messageSlices);
}
// Perform the send (and take care of any exceptions)
try {
retValue = getConversation().send(buffer,
JFapChannelConstants.SEG_BROWSE_MESSAGE,
0,
JFapChannelConstants.PRIORITY_LOWEST,
false,
ThrottlingPolicy.BLOCK_THREAD,
null);
} catch (SIException e) {
FFDCFilter.processException(e, CLASS_NAME + ".sendEntireMessage",
CommsConstants.CATBROWSECONSUMER_SENDMESSAGE_02,
this);
SibTr.error(tc, "COMMUNICATION_ERROR_SICO2012", e);
// No point trying to transmit this to the client, as it has already gone away.
throw new OperationFailedException();
}
} catch (Exception e) {
//No FFDC code needed
//Only FFDC if we haven't received a meTerminated event OR if this Exception is a SIException.
if (!(e instanceof SIException) || !convState.hasMETerminated()) {
FFDCFilter.processException(e, CLASS_NAME + ".sendEntireMessage",
CommsConstants.CATBROWSECONSUMER_SENDMESSAGE_01,
this);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
SibTr.exception(this, tc, e);
// If the connection drops during the encode, don't try and send an exception to the client
if (e instanceof SIConnectionDroppedException) {
SibTr.error(tc, "COMMUNICATION_ERROR_SICO2012", e);
// No point trying to transmit this to the client, as it has already gone away.
throw new OperationFailedException();
}
SIResourceException coreException = new SIResourceException();
coreException.initCause(e);
StaticCATHelper.sendAsyncExceptionToClient(coreException,
CommsConstants.CATBROWSECONSUMER_SENDMESSAGE_01,
getClientSessionId(), getConversation(), 0);
throw new OperationFailedException();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "sendEntireMessage", retValue);
return retValue;
} } | public class class_name {
private long sendEntireMessage(SIBusMessage msg, List<DataSlice> messageSlices)
throws OperationFailedException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "sendEntireMessage", new Object[] { msg, messageSlices });
ConversationState convState = (ConversationState) getConversation().getAttachment();
long retValue = 0;
// Now build the header for this message.
CommsServerByteBuffer buffer = poolManager.allocate();
try {
buffer.putShort(convState.getConnectionObjectId());
buffer.putShort(mainConsumer.getClientSessionId());
buffer.putShort(msgBatch);
int msgLen = 0;
if (messageSlices == null) {
msgLen = buffer.putMessage((JsMessage) msg,
convState.getCommsConnection(),
getConversation()); // depends on control dependency: [if], data = [none]
} else {
msgLen = buffer.putMessgeWithoutEncode(messageSlices); // depends on control dependency: [if], data = [(messageSlices]
}
// Perform the send (and take care of any exceptions)
try {
retValue = getConversation().send(buffer,
JFapChannelConstants.SEG_BROWSE_MESSAGE,
0,
JFapChannelConstants.PRIORITY_LOWEST,
false,
ThrottlingPolicy.BLOCK_THREAD,
null); // depends on control dependency: [try], data = [none]
} catch (SIException e) {
FFDCFilter.processException(e, CLASS_NAME + ".sendEntireMessage",
CommsConstants.CATBROWSECONSUMER_SENDMESSAGE_02,
this);
SibTr.error(tc, "COMMUNICATION_ERROR_SICO2012", e);
// No point trying to transmit this to the client, as it has already gone away.
throw new OperationFailedException();
} // depends on control dependency: [catch], data = [none]
} catch (Exception e) {
//No FFDC code needed
//Only FFDC if we haven't received a meTerminated event OR if this Exception is a SIException.
if (!(e instanceof SIException) || !convState.hasMETerminated()) {
FFDCFilter.processException(e, CLASS_NAME + ".sendEntireMessage",
CommsConstants.CATBROWSECONSUMER_SENDMESSAGE_01,
this); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
SibTr.exception(this, tc, e);
// If the connection drops during the encode, don't try and send an exception to the client
if (e instanceof SIConnectionDroppedException) {
SibTr.error(tc, "COMMUNICATION_ERROR_SICO2012", e); // depends on control dependency: [if], data = [none]
// No point trying to transmit this to the client, as it has already gone away.
throw new OperationFailedException();
}
SIResourceException coreException = new SIResourceException();
coreException.initCause(e);
StaticCATHelper.sendAsyncExceptionToClient(coreException,
CommsConstants.CATBROWSECONSUMER_SENDMESSAGE_01,
getClientSessionId(), getConversation(), 0);
throw new OperationFailedException();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "sendEntireMessage", retValue);
return retValue;
} } |
public class class_name {
public Governator addOverrideModules(List<Module> modules) {
if (modules != null) {
this.overrideModules.addAll(modules);
}
return this;
} } | public class class_name {
public Governator addOverrideModules(List<Module> modules) {
if (modules != null) {
this.overrideModules.addAll(modules); // depends on control dependency: [if], data = [(modules]
}
return this;
} } |
public class class_name {
@Override
public EEnum getIfcCoveringTypeEnum() {
if (ifcCoveringTypeEnumEEnum == null) {
ifcCoveringTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(951);
}
return ifcCoveringTypeEnumEEnum;
} } | public class class_name {
@Override
public EEnum getIfcCoveringTypeEnum() {
if (ifcCoveringTypeEnumEEnum == null) {
ifcCoveringTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(951);
// depends on control dependency: [if], data = [none]
}
return ifcCoveringTypeEnumEEnum;
} } |
public class class_name {
protected void doFinalApply(IPolicyContext context, TransferQuotaConfig config, long downloadedBytes) {
if (config.getDirection() == TransferDirectionType.download || config.getDirection() == TransferDirectionType.both) {
final String bucketId = context.getAttribute(BUCKET_ID_ATTR, (String) null);
final RateBucketPeriod period = context.getAttribute(PERIOD_ATTR, (RateBucketPeriod) null);
IRateLimiterComponent rateLimiter = context.getComponent(IRateLimiterComponent.class);
rateLimiter.accept(bucketId, period, config.getLimit(), downloadedBytes, new IAsyncResultHandler<RateLimitResponse>() {
@Override
public void handle(IAsyncResult<RateLimitResponse> result) {
// No need to handle the response - it's too late to do anything meaningful with the result.
// TODO log any error that might have ocurred
}
});
}
} } | public class class_name {
protected void doFinalApply(IPolicyContext context, TransferQuotaConfig config, long downloadedBytes) {
if (config.getDirection() == TransferDirectionType.download || config.getDirection() == TransferDirectionType.both) {
final String bucketId = context.getAttribute(BUCKET_ID_ATTR, (String) null);
final RateBucketPeriod period = context.getAttribute(PERIOD_ATTR, (RateBucketPeriod) null);
IRateLimiterComponent rateLimiter = context.getComponent(IRateLimiterComponent.class);
rateLimiter.accept(bucketId, period, config.getLimit(), downloadedBytes, new IAsyncResultHandler<RateLimitResponse>() {
@Override
public void handle(IAsyncResult<RateLimitResponse> result) {
// No need to handle the response - it's too late to do anything meaningful with the result.
// TODO log any error that might have ocurred
}
}); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@NullSafe
public static boolean containsAny(Collection<?> collection, Object... elements) {
for (Object element : nullSafeArray(elements)) {
if (nullSafeCollection(collection).contains(element)) {
return true;
}
}
return false;
} } | public class class_name {
@NullSafe
public static boolean containsAny(Collection<?> collection, Object... elements) {
for (Object element : nullSafeArray(elements)) {
if (nullSafeCollection(collection).contains(element)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
@Override
public void removeByCommercePriceListId(long commercePriceListId) {
for (CommercePriceListUserSegmentEntryRel commercePriceListUserSegmentEntryRel : findByCommercePriceListId(
commercePriceListId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commercePriceListUserSegmentEntryRel);
}
} } | public class class_name {
@Override
public void removeByCommercePriceListId(long commercePriceListId) {
for (CommercePriceListUserSegmentEntryRel commercePriceListUserSegmentEntryRel : findByCommercePriceListId(
commercePriceListId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commercePriceListUserSegmentEntryRel); // depends on control dependency: [for], data = [commercePriceListUserSegmentEntryRel]
}
} } |
public class class_name {
protected static String getPayload(SAXSymbol symbol) {
if (symbol.isGuard()) {
return "guard of the rule " + ((SAXGuard) symbol).r.ruleIndex;
}
else if (symbol.isNonTerminal()) {
return "nonterminal " + ((SAXNonTerminal) symbol).value;
}
return "symbol " + symbol.value;
} } | public class class_name {
protected static String getPayload(SAXSymbol symbol) {
if (symbol.isGuard()) {
return "guard of the rule " + ((SAXGuard) symbol).r.ruleIndex;
// depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
}
else if (symbol.isNonTerminal()) {
return "nonterminal " + ((SAXNonTerminal) symbol).value;
// depends on control dependency: [if], data = [none]
}
return "symbol " + symbol.value;
} } |
public class class_name {
@SuppressWarnings("unchecked")
protected Collection<Object> newArrayInstance(final Class targetType) {
if (targetType == null ||
targetType == List.class ||
targetType == Collection.class ||
targetType.isArray()) {
return listSupplier.get();
}
if (targetType == Set.class) {
return new HashSet<>();
}
try {
return (Collection<Object>) targetType.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new JsonException(e);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
protected Collection<Object> newArrayInstance(final Class targetType) {
if (targetType == null ||
targetType == List.class ||
targetType == Collection.class ||
targetType.isArray()) {
return listSupplier.get(); // depends on control dependency: [if], data = [none]
}
if (targetType == Set.class) {
return new HashSet<>(); // depends on control dependency: [if], data = [none]
}
try {
return (Collection<Object>) targetType.getDeclaredConstructor().newInstance(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new JsonException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void afterCompletion(int status) {
TransactionContextThreadLocal.setTransactionContext(null);
switch (status) {
case Status.STATUS_COMMITTED:
if (logger.isDebugEnabled()) {
logger.debug("Completed commit of tx " + tx);
}
txContext.executeAfterCommitPriorityActions();
txContext.executeAfterCommitActions();
break;
case Status.STATUS_ROLLEDBACK:
if (logger.isDebugEnabled()) {
logger.debug("Completed rollback of tx " + tx);
}
txContext.executeAfterRollbackActions();
break;
default:
throw new IllegalStateException("Unexpected transaction state "
+ status);
}
txContext.cleanup();
} } | public class class_name {
public void afterCompletion(int status) {
TransactionContextThreadLocal.setTransactionContext(null);
switch (status) {
case Status.STATUS_COMMITTED:
if (logger.isDebugEnabled()) {
logger.debug("Completed commit of tx " + tx);
// depends on control dependency: [if], data = [none]
}
txContext.executeAfterCommitPriorityActions();
txContext.executeAfterCommitActions();
break;
case Status.STATUS_ROLLEDBACK:
if (logger.isDebugEnabled()) {
logger.debug("Completed rollback of tx " + tx);
// depends on control dependency: [if], data = [none]
}
txContext.executeAfterRollbackActions();
break;
default:
throw new IllegalStateException("Unexpected transaction state "
+ status);
}
txContext.cleanup();
} } |
public class class_name {
protected Map<String, String> mergeXMLProperties(Map<String, String> oldProperties,
Set<String> oldXMLProperties,
List<Property> properties) throws InjectionConfigurationException {
if (!properties.isEmpty()) {
if (oldProperties == null) {
oldProperties = new HashMap<String, String>();
}
for (Property property : properties) {
String name = property.getName();
String newValue = property.getValue();
Object oldValue = oldProperties.put(name, newValue);
if (oldValue != null && !newValue.equals(oldValue)) {
mergeError(oldValue, newValue, true, name + " property", true, name);
continue;
}
oldXMLProperties.add(name);
}
}
return oldProperties;
} } | public class class_name {
protected Map<String, String> mergeXMLProperties(Map<String, String> oldProperties,
Set<String> oldXMLProperties,
List<Property> properties) throws InjectionConfigurationException {
if (!properties.isEmpty()) {
if (oldProperties == null) {
oldProperties = new HashMap<String, String>(); // depends on control dependency: [if], data = [none]
}
for (Property property : properties) {
String name = property.getName();
String newValue = property.getValue();
Object oldValue = oldProperties.put(name, newValue);
if (oldValue != null && !newValue.equals(oldValue)) {
mergeError(oldValue, newValue, true, name + " property", true, name); // depends on control dependency: [if], data = [(oldValue]
continue;
}
oldXMLProperties.add(name); // depends on control dependency: [for], data = [none]
}
}
return oldProperties;
} } |
public class class_name {
@Override
protected void preparePaintComponent(final Request request) {
if (!isInitialised()) {
MyData data = new MyData("Homer");
basic.setData(data);
List<MyData> dataList = new ArrayList<>();
dataList.add(new MyData("Homer"));
dataList.add(new MyData("Marge"));
dataList.add(new MyData("Bart"));
repeated.setBeanList(dataList);
dataList = new ArrayList<>();
dataList.add(new MyData("Greg"));
dataList.add(new MyData("Jeff"));
dataList.add(new MyData("Anthony"));
dataList.add(new MyData("Murray"));
repeatedLink.setData(dataList);
List<List<MyData>> rootList = new ArrayList<>();
List<MyData> subList = new ArrayList<>();
subList.add(new MyData("Ernie"));
subList.add(new MyData("Bert"));
rootList.add(subList);
subList = new ArrayList<>();
subList.add(new MyData("Starsky"));
subList.add(new MyData("Hutch"));
rootList.add(subList);
nestedRepeaterTab.setData(rootList);
setInitialised(true);
}
} } | public class class_name {
@Override
protected void preparePaintComponent(final Request request) {
if (!isInitialised()) {
MyData data = new MyData("Homer");
basic.setData(data); // depends on control dependency: [if], data = [none]
List<MyData> dataList = new ArrayList<>();
dataList.add(new MyData("Homer")); // depends on control dependency: [if], data = [none]
dataList.add(new MyData("Marge")); // depends on control dependency: [if], data = [none]
dataList.add(new MyData("Bart")); // depends on control dependency: [if], data = [none]
repeated.setBeanList(dataList); // depends on control dependency: [if], data = [none]
dataList = new ArrayList<>(); // depends on control dependency: [if], data = [none]
dataList.add(new MyData("Greg")); // depends on control dependency: [if], data = [none]
dataList.add(new MyData("Jeff")); // depends on control dependency: [if], data = [none]
dataList.add(new MyData("Anthony")); // depends on control dependency: [if], data = [none]
dataList.add(new MyData("Murray")); // depends on control dependency: [if], data = [none]
repeatedLink.setData(dataList); // depends on control dependency: [if], data = [none]
List<List<MyData>> rootList = new ArrayList<>();
List<MyData> subList = new ArrayList<>();
subList.add(new MyData("Ernie")); // depends on control dependency: [if], data = [none]
subList.add(new MyData("Bert")); // depends on control dependency: [if], data = [none]
rootList.add(subList); // depends on control dependency: [if], data = [none]
subList = new ArrayList<>(); // depends on control dependency: [if], data = [none]
subList.add(new MyData("Starsky")); // depends on control dependency: [if], data = [none]
subList.add(new MyData("Hutch")); // depends on control dependency: [if], data = [none]
rootList.add(subList); // depends on control dependency: [if], data = [none]
nestedRepeaterTab.setData(rootList); // depends on control dependency: [if], data = [none]
setInitialised(true); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
private void decreaseKey(Node<K, V> n, K newKey) {
int c;
if (comparator == null) {
c = ((Comparable<? super K>) newKey).compareTo(n.key);
} else {
c = comparator.compare(newKey, n.key);
}
if (c > 0) {
throw new IllegalArgumentException("Keys can only be decreased!");
}
n.key = newKey;
if (c == 0 || root == n) {
return;
}
if (n.o_s == null) {
throw new IllegalArgumentException("Invalid handle!");
}
// unlink from parent
if (n.y_s != null) {
n.y_s.o_s = n.o_s;
}
if (n.o_s.o_c == n) { // I am the oldest :(
n.o_s.o_c = n.y_s;
} else { // I have an older sibling!
n.o_s.y_s = n.y_s;
}
n.y_s = null;
n.o_s = null;
// merge with root
if (comparator == null) {
root = link(root, n);
} else {
root = linkWithComparator(root, n);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
private void decreaseKey(Node<K, V> n, K newKey) {
int c;
if (comparator == null) {
c = ((Comparable<? super K>) newKey).compareTo(n.key); // depends on control dependency: [if], data = [none]
} else {
c = comparator.compare(newKey, n.key); // depends on control dependency: [if], data = [none]
}
if (c > 0) {
throw new IllegalArgumentException("Keys can only be decreased!");
}
n.key = newKey;
if (c == 0 || root == n) {
return; // depends on control dependency: [if], data = [none]
}
if (n.o_s == null) {
throw new IllegalArgumentException("Invalid handle!");
}
// unlink from parent
if (n.y_s != null) {
n.y_s.o_s = n.o_s; // depends on control dependency: [if], data = [none]
}
if (n.o_s.o_c == n) { // I am the oldest :(
n.o_s.o_c = n.y_s; // depends on control dependency: [if], data = [none]
} else { // I have an older sibling!
n.o_s.y_s = n.y_s; // depends on control dependency: [if], data = [none]
}
n.y_s = null;
n.o_s = null;
// merge with root
if (comparator == null) {
root = link(root, n); // depends on control dependency: [if], data = [none]
} else {
root = linkWithComparator(root, n); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public final AItemSpecifics<T, ID> process(final Map<String, Object> pReqVars,
final AItemSpecifics<T, ID> pEntity,
final IRequestData pRequestData) throws Exception {
AItemSpecifics<T, ID> entity = this.prcEntityRetrieve
.process(pReqVars, pEntity, pRequestData);
if (entity.getSpecifics().getItsType() != null
&& entity.getSpecifics().getItsType()
.equals(ESpecificsItemType.BIGDECIMAL)) {
if (entity.getNumericValue1() == null) {
entity.setNumericValue1(BigDecimal.ZERO);
}
if (entity.getLongValue1() == null) {
entity.setLongValue2(2L);
}
pReqVars.put("RSisUsePrecision" + entity.getLongValue2(), true);
}
return entity;
} } | public class class_name {
@Override
public final AItemSpecifics<T, ID> process(final Map<String, Object> pReqVars,
final AItemSpecifics<T, ID> pEntity,
final IRequestData pRequestData) throws Exception {
AItemSpecifics<T, ID> entity = this.prcEntityRetrieve
.process(pReqVars, pEntity, pRequestData);
if (entity.getSpecifics().getItsType() != null
&& entity.getSpecifics().getItsType()
.equals(ESpecificsItemType.BIGDECIMAL)) {
if (entity.getNumericValue1() == null) {
entity.setNumericValue1(BigDecimal.ZERO); // depends on control dependency: [if], data = [none]
}
if (entity.getLongValue1() == null) {
entity.setLongValue2(2L); // depends on control dependency: [if], data = [none]
}
pReqVars.put("RSisUsePrecision" + entity.getLongValue2(), true);
}
return entity;
} } |
public class class_name {
public Row executeOne(Statement stm, ConsistencyLevel consistencyLevel) {
if (consistencyLevel != null) {
if (consistencyLevel == ConsistencyLevel.SERIAL
|| consistencyLevel == ConsistencyLevel.LOCAL_SERIAL) {
stm.setSerialConsistencyLevel(consistencyLevel);
} else {
stm.setConsistencyLevel(consistencyLevel);
}
}
return getSession().execute(stm).one();
} } | public class class_name {
public Row executeOne(Statement stm, ConsistencyLevel consistencyLevel) {
if (consistencyLevel != null) {
if (consistencyLevel == ConsistencyLevel.SERIAL
|| consistencyLevel == ConsistencyLevel.LOCAL_SERIAL) {
stm.setSerialConsistencyLevel(consistencyLevel); // depends on control dependency: [if], data = [(consistencyLevel]
} else {
stm.setConsistencyLevel(consistencyLevel); // depends on control dependency: [if], data = [(consistencyLevel]
}
}
return getSession().execute(stm).one();
} } |
public class class_name {
private void buildErrorStatus(BatchResult result, Throwable ex) {
result.setStatus(BatchResult.Status.ERROR);
result.setErrorMessage(ex.getLocalizedMessage());
if (ex instanceof IllegalArgumentException) {
m_logger.debug("Batch update error: {}", ex.toString());
} else {
result.setStackTrace(Utils.getStackTrace(ex));
m_logger.debug("Batch update error: {} stacktrace: {}",
ex.toString(), Utils.getStackTrace(ex));
}
} } | public class class_name {
private void buildErrorStatus(BatchResult result, Throwable ex) {
result.setStatus(BatchResult.Status.ERROR);
result.setErrorMessage(ex.getLocalizedMessage());
if (ex instanceof IllegalArgumentException) {
m_logger.debug("Batch update error: {}", ex.toString());
// depends on control dependency: [if], data = [none]
} else {
result.setStackTrace(Utils.getStackTrace(ex));
// depends on control dependency: [if], data = [none]
m_logger.debug("Batch update error: {} stacktrace: {}",
ex.toString(), Utils.getStackTrace(ex));
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setCenterColor(Color color) {
if (centerColor == null) {
centerColor = new RGBColor(0.0, 0.0, 0.0);
}
setGradation(true);
this.centerColor = color;
} } | public class class_name {
public void setCenterColor(Color color) {
if (centerColor == null) {
centerColor = new RGBColor(0.0, 0.0, 0.0); // depends on control dependency: [if], data = [none]
}
setGradation(true);
this.centerColor = color;
} } |
public class class_name {
private static void addAction(@Nonnull Computer c, @Nonnull Action a) {
try {
c.addAction(a);
} catch (UnsupportedOperationException x) {
try {
Field actionsF = Actionable.class.getDeclaredField("actions");
actionsF.setAccessible(true);
@SuppressWarnings("unchecked")
List<Action> actions = (List) actionsF.get(c);
actions.add(a);
} catch (Exception x2) {
LOGGER.log(Level.WARNING, null, x2);
}
}
} } | public class class_name {
private static void addAction(@Nonnull Computer c, @Nonnull Action a) {
try {
c.addAction(a); // depends on control dependency: [try], data = [none]
} catch (UnsupportedOperationException x) {
try {
Field actionsF = Actionable.class.getDeclaredField("actions");
actionsF.setAccessible(true); // depends on control dependency: [try], data = [none]
@SuppressWarnings("unchecked")
List<Action> actions = (List) actionsF.get(c);
actions.add(a); // depends on control dependency: [try], data = [none]
} catch (Exception x2) {
LOGGER.log(Level.WARNING, null, x2);
} // depends on control dependency: [catch], data = [none]
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <TERM> Iterable<Map<TERM, Double>> tfs(Iterable<Collection<TERM>> documents, TfType type)
{
List<Map<TERM, Double>> tfs = new ArrayList<Map<TERM, Double>>();
for (Collection<TERM> document : documents)
{
tfs.add(tf(document, type));
}
return tfs;
} } | public class class_name {
public static <TERM> Iterable<Map<TERM, Double>> tfs(Iterable<Collection<TERM>> documents, TfType type)
{
List<Map<TERM, Double>> tfs = new ArrayList<Map<TERM, Double>>();
for (Collection<TERM> document : documents)
{
tfs.add(tf(document, type)); // depends on control dependency: [for], data = [document]
}
return tfs;
} } |
public class class_name {
@Override
public void validate(ValidationHelper helper, Context context, String key, Discriminator t) {
if (t != null) {
ValidatorUtils.validateRequiredField(t.getPropertyName(), context, "propertyName").ifPresent(helper::addValidationEvent);
}
} } | public class class_name {
@Override
public void validate(ValidationHelper helper, Context context, String key, Discriminator t) {
if (t != null) {
ValidatorUtils.validateRequiredField(t.getPropertyName(), context, "propertyName").ifPresent(helper::addValidationEvent); // depends on control dependency: [if], data = [(t]
}
} } |
public class class_name {
protected void masonryRemove(Widget target) {
this.target = target;
if (target != sizerDiv) {
super.remove(target);
reload();
}
} } | public class class_name {
protected void masonryRemove(Widget target) {
this.target = target;
if (target != sizerDiv) {
super.remove(target); // depends on control dependency: [if], data = [(target]
reload(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public List<BeanId> getReference(final String propertyName) {
List<BeanId> values = references.get(propertyName);
if (values == null) {
return null;
}
return values;
} } | public class class_name {
public List<BeanId> getReference(final String propertyName) {
List<BeanId> values = references.get(propertyName);
if (values == null) {
return null; // depends on control dependency: [if], data = [none]
}
return values;
} } |
public class class_name {
public String getObjectType(int groupID, int objectID) {
if (groupID >= 0 && groupID < objectGroups.size()) {
ObjectGroup grp = (ObjectGroup) objectGroups.get(groupID);
if (objectID >= 0 && objectID < grp.objects.size()) {
GroupObject object = (GroupObject) grp.objects.get(objectID);
return object.type;
}
}
return null;
} } | public class class_name {
public String getObjectType(int groupID, int objectID) {
if (groupID >= 0 && groupID < objectGroups.size()) {
ObjectGroup grp = (ObjectGroup) objectGroups.get(groupID);
if (objectID >= 0 && objectID < grp.objects.size()) {
GroupObject object = (GroupObject) grp.objects.get(objectID);
return object.type;
// depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public <T> void contextSet(Class<T> key, T value)
{
synchronized (TypeCheckInfo.class)
{
Stack<T> contextStack = lookupListForType(key);
if (contextStack == null)
{
contextStack = new Stack<T>();
context.put(key, contextStack);
}
contextStack.push(value);
}
} } | public class class_name {
public <T> void contextSet(Class<T> key, T value)
{
synchronized (TypeCheckInfo.class)
{
Stack<T> contextStack = lookupListForType(key);
if (contextStack == null)
{
contextStack = new Stack<T>(); // depends on control dependency: [if], data = [none]
context.put(key, contextStack); // depends on control dependency: [if], data = [none]
}
contextStack.push(value);
}
} } |
public class class_name {
private boolean isEligibleCallSite(Node access, Node definitionSite) {
Node invocation = access.getParent();
if (!NodeUtil.isInvocationTarget(access) || !invocation.isCall()) {
// TODO(nickreid): Use the same definition of "a call" as
// `OptimizeCalls::ReferenceMap::isCallTarget`.
//
// Accessing the property in any way besides CALL has issues:
// - tear-off: invocations can't be tracked
// - as constructor: unsupported rewrite
// - as tagged template string: unspported rewrite
return false;
}
// We can't rewrite functions called in modules that do not depend on the defining module.
// This is due to a subtle execution order change introduced by rewriting. Example:
//
// `x.foo().bar()` => `JSCompiler_StaticMethods_bar(x.foo())`
//
// Note how `JSCompiler_StaticMethods_bar` will be resolved before `x.foo()` is executed. In
// the case that `x.foo()` defines `JSCompiler_StaticMethods_bar` (e.g. by dynamically loading
// the defining module) this change in ordering will cause a `ReferenceError`. No error would
// be thrown by the original code because `bar` would be resolved later.
//
// We choose to use module ordering to avoid this issue because:
// - The other eligibility checks for devirtualization prevent any other dangerous cases
// that JSCompiler supports.
// - Rewriting all call-sites in a way that preserves exact ordering (e.g. using
// `ExpressionDecomposer`) has a significant code-size impact (circa 2018-11-19).
JSModuleGraph moduleGraph = compiler.getModuleGraph();
@Nullable JSModule definitionModule = moduleForNode(definitionSite);
@Nullable JSModule callModule = moduleForNode(access);
if (definitionModule == callModule) {
// Do nothing.
} else if (callModule == null) {
return false;
} else if (!moduleGraph.dependsOn(callModule, definitionModule)) {
return false;
}
return true;
} } | public class class_name {
private boolean isEligibleCallSite(Node access, Node definitionSite) {
Node invocation = access.getParent();
if (!NodeUtil.isInvocationTarget(access) || !invocation.isCall()) {
// TODO(nickreid): Use the same definition of "a call" as
// `OptimizeCalls::ReferenceMap::isCallTarget`.
//
// Accessing the property in any way besides CALL has issues:
// - tear-off: invocations can't be tracked
// - as constructor: unsupported rewrite
// - as tagged template string: unspported rewrite
return false; // depends on control dependency: [if], data = [none]
}
// We can't rewrite functions called in modules that do not depend on the defining module.
// This is due to a subtle execution order change introduced by rewriting. Example:
//
// `x.foo().bar()` => `JSCompiler_StaticMethods_bar(x.foo())`
//
// Note how `JSCompiler_StaticMethods_bar` will be resolved before `x.foo()` is executed. In
// the case that `x.foo()` defines `JSCompiler_StaticMethods_bar` (e.g. by dynamically loading
// the defining module) this change in ordering will cause a `ReferenceError`. No error would
// be thrown by the original code because `bar` would be resolved later.
//
// We choose to use module ordering to avoid this issue because:
// - The other eligibility checks for devirtualization prevent any other dangerous cases
// that JSCompiler supports.
// - Rewriting all call-sites in a way that preserves exact ordering (e.g. using
// `ExpressionDecomposer`) has a significant code-size impact (circa 2018-11-19).
JSModuleGraph moduleGraph = compiler.getModuleGraph();
@Nullable JSModule definitionModule = moduleForNode(definitionSite);
@Nullable JSModule callModule = moduleForNode(access);
if (definitionModule == callModule) {
// Do nothing.
} else if (callModule == null) {
return false; // depends on control dependency: [if], data = [none]
} else if (!moduleGraph.dependsOn(callModule, definitionModule)) {
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
private static <T extends TableEntity, R> TableResult parseJsonEntity(final JsonParser parser,
final Class<T> clazzType, HashMap<String, PropertyPair> classProperties, final EntityResolver<R> resolver,
final TableRequestOptions options, final OperationContext opContext) throws JsonParseException,
IOException, StorageException, InstantiationException, IllegalAccessException {
final TableResult res = new TableResult();
final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();
if (!parser.hasCurrentToken()) {
parser.nextToken();
}
JsonUtilities.assertIsStartObjectJsonToken(parser);
parser.nextToken();
// get all metadata, if present
while (parser.getCurrentName().startsWith(ODataConstants.ODATA_PREFIX)) {
final String name = parser.getCurrentName().substring(ODataConstants.ODATA_PREFIX.length());
// get the value token
parser.nextToken();
if (name.equals(ODataConstants.ETAG)) {
String etag = parser.getValueAsString();
res.setEtag(etag);
}
// get the key token
parser.nextToken();
}
if (resolver == null && clazzType == null) {
return res;
}
// get object properties
while (parser.getCurrentToken() != JsonToken.END_OBJECT) {
String key = Constants.EMPTY_STRING;
String val = Constants.EMPTY_STRING;
EdmType edmType = null;
// checks if this property is preceded by an OData property type annotation
if (options.getTablePayloadFormat() != TablePayloadFormat.JsonNoMetadata
&& parser.getCurrentName().endsWith(ODataConstants.ODATA_TYPE_SUFFIX)) {
parser.nextToken();
edmType = EdmType.parse(parser.getValueAsString());
parser.nextValue();
key = parser.getCurrentName();
val = parser.getValueAsString();
}
else {
key = parser.getCurrentName();
parser.nextToken();
val = parser.getValueAsString();
edmType = evaluateEdmType(parser.getCurrentToken(), parser.getValueAsString());
}
final EntityProperty newProp = new EntityProperty(val, edmType);
newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility());
properties.put(key, newProp);
parser.nextToken();
}
String partitionKey = null;
String rowKey = null;
Date timestamp = null;
String etag = null;
// Remove core properties from map and set individually
EntityProperty tempProp = properties.remove(TableConstants.PARTITION_KEY);
if (tempProp != null) {
partitionKey = tempProp.getValueAsString();
}
tempProp = properties.remove(TableConstants.ROW_KEY);
if (tempProp != null) {
rowKey = tempProp.getValueAsString();
}
tempProp = properties.remove(TableConstants.TIMESTAMP);
if (tempProp != null) {
tempProp.setDateBackwardCompatibility(false);
timestamp = tempProp.getValueAsDate();
if (res.getEtag() == null) {
etag = getETagFromTimestamp(tempProp.getValueAsString());
res.setEtag(etag);
}
}
// do further processing for type if JsonNoMetdata by inferring type information via resolver or clazzType
if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata
&& (options.getPropertyResolver() != null || clazzType != null)) {
if (options.getPropertyResolver() != null) {
for (final Entry<String, EntityProperty> p : properties.entrySet()) {
final String key = p.getKey();
final String value = p.getValue().getValueAsString();
EdmType edmType;
// try to use the property resolver to get the type
try {
edmType = options.getPropertyResolver().propertyResolver(partitionKey, rowKey, key, value);
}
catch (Exception e) {
throw new StorageException(StorageErrorCodeStrings.INTERNAL_ERROR, SR.CUSTOM_RESOLVER_THREW,
Constants.HeaderConstants.HTTP_UNUSED_306, null, e);
}
// try to create a new entity property using the returned type
try {
final EntityProperty newProp = new EntityProperty(value, edmType);
newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility());
properties.put(p.getKey(), newProp);
}
catch (IllegalArgumentException e) {
throw new StorageException(StorageErrorCodeStrings.INVALID_TYPE, String.format(
SR.FAILED_TO_PARSE_PROPERTY, key, value, edmType),
Constants.HeaderConstants.HTTP_UNUSED_306, null, e);
}
}
}
else if (clazzType != null) {
if (classProperties == null) {
classProperties = PropertyPair.generatePropertyPairs(clazzType);
}
for (final Entry<String, EntityProperty> p : properties.entrySet()) {
PropertyPair propPair = classProperties.get(p.getKey());
if (propPair != null) {
final EntityProperty newProp = new EntityProperty(p.getValue().getValueAsString(),
propPair.type);
newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility());
properties.put(p.getKey(), newProp);
}
}
}
}
// set the result properties, now that they are appropriately parsed
res.setProperties(properties);
// use resolver if provided, else create entity based on clazz type
if (resolver != null) {
res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag()));
}
else if (clazzType != null) {
// Generate new entity and return
final T entity = clazzType.newInstance();
entity.setEtag(res.getEtag());
entity.setPartitionKey(partitionKey);
entity.setRowKey(rowKey);
entity.setTimestamp(timestamp);
entity.readEntity(res.getProperties(), opContext);
res.setResult(entity);
}
return res;
} } | public class class_name {
private static <T extends TableEntity, R> TableResult parseJsonEntity(final JsonParser parser,
final Class<T> clazzType, HashMap<String, PropertyPair> classProperties, final EntityResolver<R> resolver,
final TableRequestOptions options, final OperationContext opContext) throws JsonParseException,
IOException, StorageException, InstantiationException, IllegalAccessException {
final TableResult res = new TableResult();
final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();
if (!parser.hasCurrentToken()) {
parser.nextToken();
}
JsonUtilities.assertIsStartObjectJsonToken(parser);
parser.nextToken();
// get all metadata, if present
while (parser.getCurrentName().startsWith(ODataConstants.ODATA_PREFIX)) {
final String name = parser.getCurrentName().substring(ODataConstants.ODATA_PREFIX.length());
// get the value token
parser.nextToken();
if (name.equals(ODataConstants.ETAG)) {
String etag = parser.getValueAsString();
res.setEtag(etag); // depends on control dependency: [if], data = [none]
}
// get the key token
parser.nextToken();
}
if (resolver == null && clazzType == null) {
return res;
}
// get object properties
while (parser.getCurrentToken() != JsonToken.END_OBJECT) {
String key = Constants.EMPTY_STRING;
String val = Constants.EMPTY_STRING;
EdmType edmType = null;
// checks if this property is preceded by an OData property type annotation
if (options.getTablePayloadFormat() != TablePayloadFormat.JsonNoMetadata
&& parser.getCurrentName().endsWith(ODataConstants.ODATA_TYPE_SUFFIX)) {
parser.nextToken(); // depends on control dependency: [if], data = [none]
edmType = EdmType.parse(parser.getValueAsString()); // depends on control dependency: [if], data = [none]
parser.nextValue(); // depends on control dependency: [if], data = [none]
key = parser.getCurrentName(); // depends on control dependency: [if], data = [none]
val = parser.getValueAsString(); // depends on control dependency: [if], data = [none]
}
else {
key = parser.getCurrentName(); // depends on control dependency: [if], data = [none]
parser.nextToken(); // depends on control dependency: [if], data = [none]
val = parser.getValueAsString(); // depends on control dependency: [if], data = [none]
edmType = evaluateEdmType(parser.getCurrentToken(), parser.getValueAsString()); // depends on control dependency: [if], data = [none]
}
final EntityProperty newProp = new EntityProperty(val, edmType);
newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility());
properties.put(key, newProp);
parser.nextToken();
}
String partitionKey = null;
String rowKey = null;
Date timestamp = null;
String etag = null;
// Remove core properties from map and set individually
EntityProperty tempProp = properties.remove(TableConstants.PARTITION_KEY);
if (tempProp != null) {
partitionKey = tempProp.getValueAsString();
}
tempProp = properties.remove(TableConstants.ROW_KEY);
if (tempProp != null) {
rowKey = tempProp.getValueAsString();
}
tempProp = properties.remove(TableConstants.TIMESTAMP);
if (tempProp != null) {
tempProp.setDateBackwardCompatibility(false);
timestamp = tempProp.getValueAsDate();
if (res.getEtag() == null) {
etag = getETagFromTimestamp(tempProp.getValueAsString());
res.setEtag(etag);
}
}
// do further processing for type if JsonNoMetdata by inferring type information via resolver or clazzType
if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata
&& (options.getPropertyResolver() != null || clazzType != null)) {
if (options.getPropertyResolver() != null) {
for (final Entry<String, EntityProperty> p : properties.entrySet()) {
final String key = p.getKey();
final String value = p.getValue().getValueAsString();
EdmType edmType;
// try to use the property resolver to get the type
try {
edmType = options.getPropertyResolver().propertyResolver(partitionKey, rowKey, key, value);
}
catch (Exception e) {
throw new StorageException(StorageErrorCodeStrings.INTERNAL_ERROR, SR.CUSTOM_RESOLVER_THREW,
Constants.HeaderConstants.HTTP_UNUSED_306, null, e);
}
// try to create a new entity property using the returned type
try {
final EntityProperty newProp = new EntityProperty(value, edmType);
newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility());
properties.put(p.getKey(), newProp);
}
catch (IllegalArgumentException e) {
throw new StorageException(StorageErrorCodeStrings.INVALID_TYPE, String.format(
SR.FAILED_TO_PARSE_PROPERTY, key, value, edmType),
Constants.HeaderConstants.HTTP_UNUSED_306, null, e);
}
}
}
else if (clazzType != null) {
if (classProperties == null) {
classProperties = PropertyPair.generatePropertyPairs(clazzType);
}
for (final Entry<String, EntityProperty> p : properties.entrySet()) {
PropertyPair propPair = classProperties.get(p.getKey());
if (propPair != null) {
final EntityProperty newProp = new EntityProperty(p.getValue().getValueAsString(),
propPair.type);
newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility());
properties.put(p.getKey(), newProp);
}
}
}
}
// set the result properties, now that they are appropriately parsed
res.setProperties(properties);
// use resolver if provided, else create entity based on clazz type
if (resolver != null) {
res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag()));
}
else if (clazzType != null) {
// Generate new entity and return
final T entity = clazzType.newInstance();
entity.setEtag(res.getEtag());
entity.setPartitionKey(partitionKey);
entity.setRowKey(rowKey);
entity.setTimestamp(timestamp);
entity.readEntity(res.getProperties(), opContext);
res.setResult(entity);
}
return res;
} } |
public class class_name {
@Override
public boolean isSubgraph(boolean shouldMatchBonds) {
CDKRMapHandler rmap = new CDKRMapHandler();
try {
if ((source.getAtomCount() == target.getAtomCount()) && source.getBondCount() == target.getBondCount()) {
rOnPFlag = true;
rmap.calculateIsomorphs(source, target, shouldMatchBonds);
} else if (source.getAtomCount() > target.getAtomCount() && source.getBondCount() != target.getBondCount()) {
rOnPFlag = true;
rmap.calculateSubGraphs(source, target, shouldMatchBonds);
} else {
rOnPFlag = false;
rmap.calculateSubGraphs(target, source, shouldMatchBonds);
}
setAllMapping();
setAllAtomMapping();
setFirstMapping();
setFirstAtomMapping();
} catch (CDKException e) {
rmap = null;
// System.err.println("WARNING: graphContainer: most probably time out error ");
}
return !getFirstMapping().isEmpty();
} } | public class class_name {
@Override
public boolean isSubgraph(boolean shouldMatchBonds) {
CDKRMapHandler rmap = new CDKRMapHandler();
try {
if ((source.getAtomCount() == target.getAtomCount()) && source.getBondCount() == target.getBondCount()) {
rOnPFlag = true; // depends on control dependency: [if], data = [none]
rmap.calculateIsomorphs(source, target, shouldMatchBonds); // depends on control dependency: [if], data = [none]
} else if (source.getAtomCount() > target.getAtomCount() && source.getBondCount() != target.getBondCount()) {
rOnPFlag = true; // depends on control dependency: [if], data = [none]
rmap.calculateSubGraphs(source, target, shouldMatchBonds); // depends on control dependency: [if], data = [none]
} else {
rOnPFlag = false; // depends on control dependency: [if], data = [none]
rmap.calculateSubGraphs(target, source, shouldMatchBonds); // depends on control dependency: [if], data = [none]
}
setAllMapping(); // depends on control dependency: [try], data = [none]
setAllAtomMapping(); // depends on control dependency: [try], data = [none]
setFirstMapping(); // depends on control dependency: [try], data = [none]
setFirstAtomMapping(); // depends on control dependency: [try], data = [none]
} catch (CDKException e) {
rmap = null;
// System.err.println("WARNING: graphContainer: most probably time out error ");
} // depends on control dependency: [catch], data = [none]
return !getFirstMapping().isEmpty();
} } |
public class class_name {
private void updateMinPunctuatedWatermark(Watermark nextWatermark) {
if (nextWatermark.getTimestamp() > maxWatermarkSoFar) {
long newMin = Long.MAX_VALUE;
for (KafkaTopicPartitionState<?> state : subscribedPartitionStates) {
@SuppressWarnings("unchecked")
final KafkaTopicPartitionStateWithPunctuatedWatermarks<T, KPH> withWatermarksState =
(KafkaTopicPartitionStateWithPunctuatedWatermarks<T, KPH>) state;
newMin = Math.min(newMin, withWatermarksState.getCurrentPartitionWatermark());
}
// double-check locking pattern
if (newMin > maxWatermarkSoFar) {
synchronized (checkpointLock) {
if (newMin > maxWatermarkSoFar) {
maxWatermarkSoFar = newMin;
sourceContext.emitWatermark(new Watermark(newMin));
}
}
}
}
} } | public class class_name {
private void updateMinPunctuatedWatermark(Watermark nextWatermark) {
if (nextWatermark.getTimestamp() > maxWatermarkSoFar) {
long newMin = Long.MAX_VALUE;
for (KafkaTopicPartitionState<?> state : subscribedPartitionStates) {
@SuppressWarnings("unchecked")
final KafkaTopicPartitionStateWithPunctuatedWatermarks<T, KPH> withWatermarksState =
(KafkaTopicPartitionStateWithPunctuatedWatermarks<T, KPH>) state;
newMin = Math.min(newMin, withWatermarksState.getCurrentPartitionWatermark()); // depends on control dependency: [for], data = [none]
}
// double-check locking pattern
if (newMin > maxWatermarkSoFar) {
synchronized (checkpointLock) { // depends on control dependency: [if], data = [none]
if (newMin > maxWatermarkSoFar) {
maxWatermarkSoFar = newMin; // depends on control dependency: [if], data = [none]
sourceContext.emitWatermark(new Watermark(newMin)); // depends on control dependency: [if], data = [(newMin]
}
}
}
}
} } |
public class class_name {
public static String getUTCTimeOrEmpty(final Date value) {
if (value == null) {
return Constants.EMPTY_STRING;
}
final DateFormat iso8601Format = new SimpleDateFormat(ISO8601_PATTERN, LOCALE_US);
iso8601Format.setTimeZone(UTC_ZONE);
return iso8601Format.format(value);
} } | public class class_name {
public static String getUTCTimeOrEmpty(final Date value) {
if (value == null) {
return Constants.EMPTY_STRING; // depends on control dependency: [if], data = [none]
}
final DateFormat iso8601Format = new SimpleDateFormat(ISO8601_PATTERN, LOCALE_US);
iso8601Format.setTimeZone(UTC_ZONE);
return iso8601Format.format(value);
} } |
public class class_name {
static Matcher combineCharSeqAfterStartsWith(Matcher matcher) {
if (matcher instanceof SeqMatcher) {
List<Matcher> matchers = matcher.<SeqMatcher>as().matchers();
if (matchers.size() >= 2
&& matchers.get(0) instanceof StartsWithMatcher
&& matchers.get(1) instanceof CharSeqMatcher) {
List<Matcher> ms = new ArrayList<>();
String prefix = matchers.get(0).<StartsWithMatcher>as().pattern()
+ matchers.get(1).<CharSeqMatcher>as().pattern();
ms.add(new StartsWithMatcher(prefix));
ms.addAll(matchers.subList(2, matchers.size()));
return SeqMatcher.create(ms);
} else {
return matcher;
}
}
return matcher;
} } | public class class_name {
static Matcher combineCharSeqAfterStartsWith(Matcher matcher) {
if (matcher instanceof SeqMatcher) {
List<Matcher> matchers = matcher.<SeqMatcher>as().matchers();
if (matchers.size() >= 2
&& matchers.get(0) instanceof StartsWithMatcher
&& matchers.get(1) instanceof CharSeqMatcher) {
List<Matcher> ms = new ArrayList<>();
String prefix = matchers.get(0).<StartsWithMatcher>as().pattern()
+ matchers.get(1).<CharSeqMatcher>as().pattern();
ms.add(new StartsWithMatcher(prefix)); // depends on control dependency: [if], data = [none]
ms.addAll(matchers.subList(2, matchers.size())); // depends on control dependency: [if], data = [none]
return SeqMatcher.create(ms); // depends on control dependency: [if], data = [none]
} else {
return matcher; // depends on control dependency: [if], data = [none]
}
}
return matcher;
} } |
public class class_name {
public int getScrollableViewScrollPosition(View scrollableView, boolean isSlidingUp) {
if (scrollableView == null) return 0;
if (scrollableView instanceof ScrollView) {
if (isSlidingUp) {
return scrollableView.getScrollY();
} else {
ScrollView sv = ((ScrollView) scrollableView);
View child = sv.getChildAt(0);
return (child.getBottom() - (sv.getHeight() + sv.getScrollY()));
}
} else if (scrollableView instanceof ListView && ((ListView) scrollableView).getChildCount() > 0) {
ListView lv = ((ListView) scrollableView);
if (lv.getAdapter() == null) return 0;
if (isSlidingUp) {
View firstChild = lv.getChildAt(0);
// Approximate the scroll position based on the top child and the first visible item
return lv.getFirstVisiblePosition() * firstChild.getHeight() - firstChild.getTop();
} else {
View lastChild = lv.getChildAt(lv.getChildCount() - 1);
// Approximate the scroll position based on the bottom child and the last visible item
return (lv.getAdapter().getCount() - lv.getLastVisiblePosition() - 1) * lastChild.getHeight() + lastChild.getBottom() - lv.getBottom();
}
} else if (scrollableView instanceof RecyclerView && ((RecyclerView) scrollableView).getChildCount() > 0) {
RecyclerView rv = ((RecyclerView) scrollableView);
RecyclerView.LayoutManager lm = rv.getLayoutManager();
if (rv.getAdapter() == null) return 0;
if (isSlidingUp) {
View firstChild = rv.getChildAt(0);
// Approximate the scroll position based on the top child and the first visible item
return rv.getChildLayoutPosition(firstChild) * lm.getDecoratedMeasuredHeight(firstChild) - lm.getDecoratedTop(firstChild);
} else {
View lastChild = rv.getChildAt(rv.getChildCount() - 1);
// Approximate the scroll position based on the bottom child and the last visible item
return (rv.getAdapter().getItemCount() - 1) * lm.getDecoratedMeasuredHeight(lastChild) + lm.getDecoratedBottom(lastChild) - rv.getBottom();
}
} else {
return 0;
}
} } | public class class_name {
public int getScrollableViewScrollPosition(View scrollableView, boolean isSlidingUp) {
if (scrollableView == null) return 0;
if (scrollableView instanceof ScrollView) {
if (isSlidingUp) {
return scrollableView.getScrollY(); // depends on control dependency: [if], data = [none]
} else {
ScrollView sv = ((ScrollView) scrollableView);
View child = sv.getChildAt(0);
return (child.getBottom() - (sv.getHeight() + sv.getScrollY())); // depends on control dependency: [if], data = [none]
}
} else if (scrollableView instanceof ListView && ((ListView) scrollableView).getChildCount() > 0) {
ListView lv = ((ListView) scrollableView);
if (lv.getAdapter() == null) return 0;
if (isSlidingUp) {
View firstChild = lv.getChildAt(0);
// Approximate the scroll position based on the top child and the first visible item
return lv.getFirstVisiblePosition() * firstChild.getHeight() - firstChild.getTop(); // depends on control dependency: [if], data = [none]
} else {
View lastChild = lv.getChildAt(lv.getChildCount() - 1);
// Approximate the scroll position based on the bottom child and the last visible item
return (lv.getAdapter().getCount() - lv.getLastVisiblePosition() - 1) * lastChild.getHeight() + lastChild.getBottom() - lv.getBottom(); // depends on control dependency: [if], data = [none]
}
} else if (scrollableView instanceof RecyclerView && ((RecyclerView) scrollableView).getChildCount() > 0) {
RecyclerView rv = ((RecyclerView) scrollableView);
RecyclerView.LayoutManager lm = rv.getLayoutManager();
if (rv.getAdapter() == null) return 0;
if (isSlidingUp) {
View firstChild = rv.getChildAt(0);
// Approximate the scroll position based on the top child and the first visible item
return rv.getChildLayoutPosition(firstChild) * lm.getDecoratedMeasuredHeight(firstChild) - lm.getDecoratedTop(firstChild); // depends on control dependency: [if], data = [none]
} else {
View lastChild = rv.getChildAt(rv.getChildCount() - 1);
// Approximate the scroll position based on the bottom child and the last visible item
return (rv.getAdapter().getItemCount() - 1) * lm.getDecoratedMeasuredHeight(lastChild) + lm.getDecoratedBottom(lastChild) - rv.getBottom(); // depends on control dependency: [if], data = [none]
}
} else {
return 0; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected static JSONObject propertyPut(JSONObject jsonObject, Object key, Object value) {
String keyStr = Convert.toStr(key);
String[] path = StrUtil.split(keyStr, StrUtil.DOT);
int last = path.length - 1;
JSONObject target = jsonObject;
for (int i = 0; i < last; i += 1) {
String segment = path[i];
JSONObject nextTarget = target.getJSONObject(segment);
if (nextTarget == null) {
nextTarget = new JSONObject();
target.put(segment, nextTarget);
}
target = nextTarget;
}
target.put(path[last], value);
return jsonObject;
} } | public class class_name {
protected static JSONObject propertyPut(JSONObject jsonObject, Object key, Object value) {
String keyStr = Convert.toStr(key);
String[] path = StrUtil.split(keyStr, StrUtil.DOT);
int last = path.length - 1;
JSONObject target = jsonObject;
for (int i = 0; i < last; i += 1) {
String segment = path[i];
JSONObject nextTarget = target.getJSONObject(segment);
if (nextTarget == null) {
nextTarget = new JSONObject();
// depends on control dependency: [if], data = [none]
target.put(segment, nextTarget);
// depends on control dependency: [if], data = [none]
}
target = nextTarget;
// depends on control dependency: [for], data = [none]
}
target.put(path[last], value);
return jsonObject;
} } |
public class class_name {
public static String[] encodeString(String[] values) {
if (values == null) {
return null;
}
String[] encodedValues = new String[values.length];
for (int i = 0; i < values.length; i++) {
encodedValues[i] = encodeString(values[i]);
}
return encodedValues;
} } | public class class_name {
public static String[] encodeString(String[] values) {
if (values == null) {
return null; // depends on control dependency: [if], data = [none]
}
String[] encodedValues = new String[values.length];
for (int i = 0; i < values.length; i++) {
encodedValues[i] = encodeString(values[i]); // depends on control dependency: [for], data = [i]
}
return encodedValues;
} } |
public class class_name {
public @Nullable InputStream getInputStream() {
if (mInputStreamSupplier != null) {
return mInputStreamSupplier.get();
}
CloseableReference<PooledByteBuffer> pooledByteBufferRef =
CloseableReference.cloneOrNull(mPooledByteBufferRef);
if (pooledByteBufferRef != null) {
try {
return new PooledByteBufferInputStream(pooledByteBufferRef.get());
} finally {
CloseableReference.closeSafely(pooledByteBufferRef);
}
}
return null;
} } | public class class_name {
public @Nullable InputStream getInputStream() {
if (mInputStreamSupplier != null) {
return mInputStreamSupplier.get(); // depends on control dependency: [if], data = [none]
}
CloseableReference<PooledByteBuffer> pooledByteBufferRef =
CloseableReference.cloneOrNull(mPooledByteBufferRef);
if (pooledByteBufferRef != null) {
try {
return new PooledByteBufferInputStream(pooledByteBufferRef.get()); // depends on control dependency: [try], data = [none]
} finally {
CloseableReference.closeSafely(pooledByteBufferRef);
}
}
return null;
} } |
public class class_name {
@EventHandler("action")
private void onAction(PluginEvent event) {
PluginException exception = null;
PluginAction action = event.getAction();
boolean debug = log.isDebugEnabled();
if (pluginEventListeners1 != null) {
for (IPluginEvent listener : new ArrayList<>(pluginEventListeners1)) {
try {
if (debug) {
log.debug("Invoking IPluginEvent.on" + WordUtils.capitalizeFully(action.name()) + " for listener "
+ listener);
}
switch (action) {
case LOAD:
listener.onLoad(this);
continue;
case UNLOAD:
listener.onUnload();
continue;
case ACTIVATE:
listener.onActivate();
continue;
case INACTIVATE:
listener.onInactivate();
continue;
}
} catch (Throwable e) {
exception = createChainedException(action.name(), e, exception);
}
}
}
if (pluginEventListeners2 != null) {
for (IPluginEventListener listener : new ArrayList<>(pluginEventListeners2)) {
try {
if (debug) {
log.debug("Delivering " + action.name() + " event to IPluginEventListener listener " + listener);
}
listener.onPluginEvent(event);
} catch (Throwable e) {
exception = createChainedException(action.name(), e, exception);
}
}
}
if (action == PluginAction.LOAD) {
doAfterLoad();
}
if (exception != null) {
throw exception;
}
} } | public class class_name {
@EventHandler("action")
private void onAction(PluginEvent event) {
PluginException exception = null;
PluginAction action = event.getAction();
boolean debug = log.isDebugEnabled();
if (pluginEventListeners1 != null) {
for (IPluginEvent listener : new ArrayList<>(pluginEventListeners1)) {
try {
if (debug) {
log.debug("Invoking IPluginEvent.on" + WordUtils.capitalizeFully(action.name()) + " for listener "
+ listener); // depends on control dependency: [if], data = [none]
}
switch (action) {
case LOAD:
listener.onLoad(this);
continue;
case UNLOAD:
listener.onUnload();
continue;
case ACTIVATE:
listener.onActivate();
continue;
case INACTIVATE:
listener.onInactivate();
continue;
}
} catch (Throwable e) {
exception = createChainedException(action.name(), e, exception);
} // depends on control dependency: [catch], data = [none]
}
}
if (pluginEventListeners2 != null) {
for (IPluginEventListener listener : new ArrayList<>(pluginEventListeners2)) {
try {
if (debug) {
log.debug("Delivering " + action.name() + " event to IPluginEventListener listener " + listener); // depends on control dependency: [if], data = [none]
}
listener.onPluginEvent(event); // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
exception = createChainedException(action.name(), e, exception);
} // depends on control dependency: [catch], data = [none]
}
}
if (action == PluginAction.LOAD) {
doAfterLoad(); // depends on control dependency: [if], data = [none]
}
if (exception != null) {
throw exception;
}
} } |
public class class_name {
@Override
public Integer parameterAsInteger(String name) {
String parameter = parameter(name);
try {
return Integer.parseInt(parameter);
} catch (Exception e) { //NOSONAR
return null;
}
} } | public class class_name {
@Override
public Integer parameterAsInteger(String name) {
String parameter = parameter(name);
try {
return Integer.parseInt(parameter); // depends on control dependency: [try], data = [none]
} catch (Exception e) { //NOSONAR
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void drawLine(int x1, int y1, int x2, int y2) {
if (this.line == null) {
this.line = new Line2D.Double(x1, y1, x2, y2);
} else {
this.line.setLine(x1, y1, x2, y2);
}
draw(this.line);
} } | public class class_name {
@Override
public void drawLine(int x1, int y1, int x2, int y2) {
if (this.line == null) {
this.line = new Line2D.Double(x1, y1, x2, y2); // depends on control dependency: [if], data = [none]
} else {
this.line.setLine(x1, y1, x2, y2); // depends on control dependency: [if], data = [none]
}
draw(this.line);
} } |
public class class_name {
private String replaceMacros(String msg, String contentLocale) {
CmsMacroResolver resolver = CmsMacroResolver.newInstance();
resolver.addMacro(MACRO_DECORATION, m_decoration);
resolver.addMacro(MACRO_DECORATIONKEY, m_decorationKey);
if (m_locale != null) {
resolver.addMacro(MACRO_LOCALE, m_locale.toString());
if (!contentLocale.equals(m_locale.toString())) {
resolver.addMacro(MACRO_LANGUAGE, "lang=\"" + m_locale.toString() + "\"");
}
}
return resolver.resolveMacros(msg);
} } | public class class_name {
private String replaceMacros(String msg, String contentLocale) {
CmsMacroResolver resolver = CmsMacroResolver.newInstance();
resolver.addMacro(MACRO_DECORATION, m_decoration);
resolver.addMacro(MACRO_DECORATIONKEY, m_decorationKey);
if (m_locale != null) {
resolver.addMacro(MACRO_LOCALE, m_locale.toString()); // depends on control dependency: [if], data = [none]
if (!contentLocale.equals(m_locale.toString())) {
resolver.addMacro(MACRO_LANGUAGE, "lang=\"" + m_locale.toString() + "\""); // depends on control dependency: [if], data = [none]
}
}
return resolver.resolveMacros(msg);
} } |
public class class_name {
private void addCapabilities(CollectionReaderDescription crd) {
for (Capability capability : crd.getCollectionReaderMetaData()
.getCapabilities()) {
for (TypeOrFeature output : capability.getOutputs()) {
// LOG.info("add @TypeCapability: " + output.getName());
outputTypes.add(output.getName());
}
}
} } | public class class_name {
private void addCapabilities(CollectionReaderDescription crd) {
for (Capability capability : crd.getCollectionReaderMetaData()
.getCapabilities()) {
for (TypeOrFeature output : capability.getOutputs()) {
// LOG.info("add @TypeCapability: " + output.getName());
outputTypes.add(output.getName()); // depends on control dependency: [for], data = [output]
}
}
} } |
public class class_name {
public static Long getSeqIncrementBy(Properties prop)
{
String result = prop.getProperty(PROP_SEQ_INCREMENT_BY, null);
if(result != null)
{
return new Long(Long.parseLong(result));
}
else
{
return null;
}
} } | public class class_name {
public static Long getSeqIncrementBy(Properties prop)
{
String result = prop.getProperty(PROP_SEQ_INCREMENT_BY, null);
if(result != null)
{
return new Long(Long.parseLong(result));
// depends on control dependency: [if], data = [(result]
}
else
{
return null;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void trace( Marker marker, String msg )
{
if( m_delegate.isTraceEnabled() )
{
setMDCMarker( marker );
m_delegate.trace( msg, null );
resetMDCMarker();
}
} } | public class class_name {
public void trace( Marker marker, String msg )
{
if( m_delegate.isTraceEnabled() )
{
setMDCMarker( marker ); // depends on control dependency: [if], data = [none]
m_delegate.trace( msg, null ); // depends on control dependency: [if], data = [none]
resetMDCMarker(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void activate(ComponentContext compcontext, Map<String, Object> properties) {
String methodName = "activate";
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Activating the WebContainer bundle");
}
WebContainer.instance.set(this);
this.context = compcontext;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName, "Default Port [ " + DEFAULT_PORT + " ]");
Tr.debug(tc, methodName, "Default Virtual Host [ " + DEFAULT_VHOST_NAME + " ]");
}
WebContainerConfiguration webconfig = new WebContainerConfiguration(DEFAULT_PORT);
webconfig.setDefaultVirtualHostName(DEFAULT_VHOST_NAME);
this.initialize(webconfig, properties);
this.classLoadingSRRef.activate(context);
this.sessionHelperSRRef.activate(context);
this.cacheManagerSRRef.activate(context);
this.injectionEngineSRRef.activate(context);
this.managedObjectServiceSRRef.activate(context);
this.servletContainerInitializers.activate(context);
this.transferContextServiceRef.activate(context);
this.webMBeanRuntimeServiceRef.activate(context);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Object mbeanService = context.locateService(REFERENCE_WEB_MBEAN_RUNTIME);
Tr.debug(tc, methodName, "Web MBean Runtime [ " + mbeanService + " ]");
Tr.debug(tc, methodName, "Web MBean Runtime Reference [ " + webMBeanRuntimeServiceRef.getReference() + " ]");
Tr.debug(tc, methodName, "Web MBean Runtime Service [ " + webMBeanRuntimeServiceRef.getService() + " ]");
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName, "Posting STARTED_EVENT");
}
Event event = this.eventService.createEvent(WebContainerConstants.STARTED_EVENT);
this.eventService.postEvent(event);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName, "Posted STARTED_EVENT");
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName, "Activating the WebContainer bundle: Complete");
}
} } | public class class_name {
public void activate(ComponentContext compcontext, Map<String, Object> properties) {
String methodName = "activate";
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Activating the WebContainer bundle"); // depends on control dependency: [if], data = [none]
}
WebContainer.instance.set(this);
this.context = compcontext;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName, "Default Port [ " + DEFAULT_PORT + " ]"); // depends on control dependency: [if], data = [none]
Tr.debug(tc, methodName, "Default Virtual Host [ " + DEFAULT_VHOST_NAME + " ]"); // depends on control dependency: [if], data = [none]
}
WebContainerConfiguration webconfig = new WebContainerConfiguration(DEFAULT_PORT);
webconfig.setDefaultVirtualHostName(DEFAULT_VHOST_NAME);
this.initialize(webconfig, properties);
this.classLoadingSRRef.activate(context);
this.sessionHelperSRRef.activate(context);
this.cacheManagerSRRef.activate(context);
this.injectionEngineSRRef.activate(context);
this.managedObjectServiceSRRef.activate(context);
this.servletContainerInitializers.activate(context);
this.transferContextServiceRef.activate(context);
this.webMBeanRuntimeServiceRef.activate(context);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Object mbeanService = context.locateService(REFERENCE_WEB_MBEAN_RUNTIME);
Tr.debug(tc, methodName, "Web MBean Runtime [ " + mbeanService + " ]"); // depends on control dependency: [if], data = [none]
Tr.debug(tc, methodName, "Web MBean Runtime Reference [ " + webMBeanRuntimeServiceRef.getReference() + " ]"); // depends on control dependency: [if], data = [none]
Tr.debug(tc, methodName, "Web MBean Runtime Service [ " + webMBeanRuntimeServiceRef.getService() + " ]"); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName, "Posting STARTED_EVENT"); // depends on control dependency: [if], data = [none]
}
Event event = this.eventService.createEvent(WebContainerConstants.STARTED_EVENT);
this.eventService.postEvent(event);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName, "Posted STARTED_EVENT"); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName, "Activating the WebContainer bundle: Complete"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected final void setUp(DataSet dataSet, Set<Integer> categoricalToRemove, Set<Integer> numericalToRemove)
{
for(int i : categoricalToRemove)
if (i >= dataSet.getNumCategoricalVars())
throw new RuntimeException("The data set does not have a categorical value " + i + " to remove");
for(int i : numericalToRemove)
if (i >= dataSet.getNumNumericalVars())
throw new RuntimeException("The data set does not have a numercal value " + i + " to remove");
catIndexMap = new int[dataSet.getNumCategoricalVars()-categoricalToRemove.size()];
newCatHeader = new CategoricalData[catIndexMap.length];
numIndexMap = new int[dataSet.getNumNumericalVars()-numericalToRemove.size()];
int k = 0;
for(int i = 0; i < dataSet.getNumCategoricalVars(); i++)
{
if(categoricalToRemove.contains(i))
continue;
newCatHeader[k] = dataSet.getCategories()[i].clone();
catIndexMap[k++] = i;
}
k = 0;
for(int i = 0; i < dataSet.getNumNumericalVars(); i++)
{
if(numericalToRemove.contains(i))
continue;
numIndexMap[k++] = i;
}
} } | public class class_name {
protected final void setUp(DataSet dataSet, Set<Integer> categoricalToRemove, Set<Integer> numericalToRemove)
{
for(int i : categoricalToRemove)
if (i >= dataSet.getNumCategoricalVars())
throw new RuntimeException("The data set does not have a categorical value " + i + " to remove");
for(int i : numericalToRemove)
if (i >= dataSet.getNumNumericalVars())
throw new RuntimeException("The data set does not have a numercal value " + i + " to remove");
catIndexMap = new int[dataSet.getNumCategoricalVars()-categoricalToRemove.size()];
newCatHeader = new CategoricalData[catIndexMap.length];
numIndexMap = new int[dataSet.getNumNumericalVars()-numericalToRemove.size()];
int k = 0;
for(int i = 0; i < dataSet.getNumCategoricalVars(); i++)
{
if(categoricalToRemove.contains(i))
continue;
newCatHeader[k] = dataSet.getCategories()[i].clone(); // depends on control dependency: [for], data = [i]
catIndexMap[k++] = i; // depends on control dependency: [for], data = [i]
}
k = 0;
for(int i = 0; i < dataSet.getNumNumericalVars(); i++)
{
if(numericalToRemove.contains(i))
continue;
numIndexMap[k++] = i; // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
@Override
public void write(Iterable<QueryResult> results) {
logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results);
HttpURLConnection urlConnection = null;
try {
if (proxy == null) {
urlConnection = (HttpURLConnection) url.openConnection();
} else {
urlConnection = (HttpURLConnection) url.openConnection(proxy);
}
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setReadTimeout(stackdriverApiTimeoutInMillis);
urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey);
serialize(results, urlConnection.getOutputStream());
int responseCode = urlConnection.getResponseCode();
if (responseCode != 200 && responseCode != 201) {
exceptionCounter.incrementAndGet();
logger.warn("Failure {}:'{}' to send result to Stackdriver server '{}' with proxy {}", responseCode,
urlConnection.getResponseMessage(), url, proxy);
}
if (logger.isTraceEnabled()) {
IoUtils2.copy(urlConnection.getInputStream(), System.out);
}
} catch (Exception e) {
exceptionCounter.incrementAndGet();
logger.warn("Failure to send result to Stackdriver server '{}' with proxy {}", url, proxy, e);
} finally {
if (urlConnection != null) {
try {
InputStream in = urlConnection.getInputStream();
IoUtils2.copy(in, IoUtils2.nullOutputStream());
IoUtils2.closeQuietly(in);
InputStream err = urlConnection.getErrorStream();
if (err != null) {
IoUtils2.copy(err, IoUtils2.nullOutputStream());
IoUtils2.closeQuietly(err);
}
urlConnection.disconnect();
} catch (IOException e) {
logger.warn("Error flushing http connection for one result, continuing");
logger.debug("Stack trace for the http connection, usually a network timeout", e);
}
}
}
} } | public class class_name {
@Override
public void write(Iterable<QueryResult> results) {
logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results);
HttpURLConnection urlConnection = null;
try {
if (proxy == null) {
urlConnection = (HttpURLConnection) url.openConnection(); // depends on control dependency: [if], data = [none]
} else {
urlConnection = (HttpURLConnection) url.openConnection(proxy); // depends on control dependency: [if], data = [(proxy]
}
urlConnection.setRequestMethod("POST"); // depends on control dependency: [try], data = [none]
urlConnection.setDoInput(true); // depends on control dependency: [try], data = [none]
urlConnection.setDoOutput(true); // depends on control dependency: [try], data = [none]
urlConnection.setReadTimeout(stackdriverApiTimeoutInMillis); // depends on control dependency: [try], data = [none]
urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); // depends on control dependency: [try], data = [none]
urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey); // depends on control dependency: [try], data = [none]
serialize(results, urlConnection.getOutputStream()); // depends on control dependency: [try], data = [none]
int responseCode = urlConnection.getResponseCode();
if (responseCode != 200 && responseCode != 201) {
exceptionCounter.incrementAndGet(); // depends on control dependency: [if], data = [none]
logger.warn("Failure {}:'{}' to send result to Stackdriver server '{}' with proxy {}", responseCode,
urlConnection.getResponseMessage(), url, proxy); // depends on control dependency: [if], data = [none]
}
if (logger.isTraceEnabled()) {
IoUtils2.copy(urlConnection.getInputStream(), System.out); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
exceptionCounter.incrementAndGet();
logger.warn("Failure to send result to Stackdriver server '{}' with proxy {}", url, proxy, e);
} finally { // depends on control dependency: [catch], data = [none]
if (urlConnection != null) {
try {
InputStream in = urlConnection.getInputStream();
IoUtils2.copy(in, IoUtils2.nullOutputStream()); // depends on control dependency: [try], data = [none]
IoUtils2.closeQuietly(in); // depends on control dependency: [try], data = [none]
InputStream err = urlConnection.getErrorStream();
if (err != null) {
IoUtils2.copy(err, IoUtils2.nullOutputStream()); // depends on control dependency: [if], data = [(err]
IoUtils2.closeQuietly(err); // depends on control dependency: [if], data = [(err]
}
urlConnection.disconnect(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
logger.warn("Error flushing http connection for one result, continuing");
logger.debug("Stack trace for the http connection, usually a network timeout", e);
} // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
protected void parentStateChanged(PropertyChangeEvent evt) {
super.parentStateChanged(evt);
if (ValidatingFormModel.VALIDATING_PROPERTY.equals(evt.getPropertyName())) {
validatingUpdated();
}
} } | public class class_name {
protected void parentStateChanged(PropertyChangeEvent evt) {
super.parentStateChanged(evt);
if (ValidatingFormModel.VALIDATING_PROPERTY.equals(evt.getPropertyName())) {
validatingUpdated(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
protected void doExecute(ProfileRequestContext profileRequestContext, AuthenticationContext authenticationContext) {
final ProxyIdpAuthenticationContext proxyContext = this.proxyIdpAuthenticationContextLookupStrategy.apply(authenticationContext);
if (proxyContext == null) {
return;
}
if (proxyContext.getAssertion() == null) {
log.info("No Assertion saved in ProxyIdpAuthenticationContext - cannot process");
return;
}
final Assertion assertion = assertionLookupStrategy.apply(profileRequestContext);
if (assertion == null) {
log.error("Unable to obtain Assertion to modify");
ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_MSG_CTX);
return;
}
this.setAuthenticatingAuthority(assertion, proxyContext.getAssertion());
} } | public class class_name {
@Override
protected void doExecute(ProfileRequestContext profileRequestContext, AuthenticationContext authenticationContext) {
final ProxyIdpAuthenticationContext proxyContext = this.proxyIdpAuthenticationContextLookupStrategy.apply(authenticationContext);
if (proxyContext == null) {
return; // depends on control dependency: [if], data = [none]
}
if (proxyContext.getAssertion() == null) {
log.info("No Assertion saved in ProxyIdpAuthenticationContext - cannot process"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
final Assertion assertion = assertionLookupStrategy.apply(profileRequestContext);
if (assertion == null) {
log.error("Unable to obtain Assertion to modify"); // depends on control dependency: [if], data = [none]
ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_MSG_CTX); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.setAuthenticatingAuthority(assertion, proxyContext.getAssertion());
} } |
public class class_name {
public static String toUnicodeLocaleKey(String keyword) {
String bcpKey = KeyTypeData.toBcpKey(keyword);
if (bcpKey == null && UnicodeLocaleExtension.isKey(keyword)) {
// unknown keyword, but syntax is fine..
bcpKey = AsciiUtil.toLowerString(keyword);
}
return bcpKey;
} } | public class class_name {
public static String toUnicodeLocaleKey(String keyword) {
String bcpKey = KeyTypeData.toBcpKey(keyword);
if (bcpKey == null && UnicodeLocaleExtension.isKey(keyword)) {
// unknown keyword, but syntax is fine..
bcpKey = AsciiUtil.toLowerString(keyword); // depends on control dependency: [if], data = [none]
}
return bcpKey;
} } |
public class class_name {
public List<ResourceEnvRefType<ApplicationDescriptor>> getAllResourceEnvRef()
{
List<ResourceEnvRefType<ApplicationDescriptor>> list = new ArrayList<ResourceEnvRefType<ApplicationDescriptor>>();
List<Node> nodeList = model.get("resource-env-ref");
for(Node node: nodeList)
{
ResourceEnvRefType<ApplicationDescriptor> type = new ResourceEnvRefTypeImpl<ApplicationDescriptor>(this, "resource-env-ref", model, node);
list.add(type);
}
return list;
} } | public class class_name {
public List<ResourceEnvRefType<ApplicationDescriptor>> getAllResourceEnvRef()
{
List<ResourceEnvRefType<ApplicationDescriptor>> list = new ArrayList<ResourceEnvRefType<ApplicationDescriptor>>();
List<Node> nodeList = model.get("resource-env-ref");
for(Node node: nodeList)
{
ResourceEnvRefType<ApplicationDescriptor> type = new ResourceEnvRefTypeImpl<ApplicationDescriptor>(this, "resource-env-ref", model, node);
list.add(type); // depends on control dependency: [for], data = [none]
}
return list;
} } |
public class class_name {
public void updateTrafficControl(T session) {
try {
setInterestedInRead(session, !session.isReadSuspended());
} catch (Exception e) {
IoFilterChain filterChain = session.getFilterChain();
filterChain.fireExceptionCaught(e);
}
try {
setInterestedInWrite(session,
!session.getWriteRequestQueue().isEmpty(session) &&
!session.isWriteSuspended());
} catch (Exception e) {
IoFilterChain filterChain = session.getFilterChain();
filterChain.fireExceptionCaught(e);
}
} } | public class class_name {
public void updateTrafficControl(T session) {
try {
setInterestedInRead(session, !session.isReadSuspended()); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
IoFilterChain filterChain = session.getFilterChain();
filterChain.fireExceptionCaught(e);
} // depends on control dependency: [catch], data = [none]
try {
setInterestedInWrite(session,
!session.getWriteRequestQueue().isEmpty(session) &&
!session.isWriteSuspended()); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
IoFilterChain filterChain = session.getFilterChain();
filterChain.fireExceptionCaught(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(PutSubscriptionFilterRequest putSubscriptionFilterRequest, ProtocolMarshaller protocolMarshaller) {
if (putSubscriptionFilterRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(putSubscriptionFilterRequest.getLogGroupName(), LOGGROUPNAME_BINDING);
protocolMarshaller.marshall(putSubscriptionFilterRequest.getFilterName(), FILTERNAME_BINDING);
protocolMarshaller.marshall(putSubscriptionFilterRequest.getFilterPattern(), FILTERPATTERN_BINDING);
protocolMarshaller.marshall(putSubscriptionFilterRequest.getDestinationArn(), DESTINATIONARN_BINDING);
protocolMarshaller.marshall(putSubscriptionFilterRequest.getRoleArn(), ROLEARN_BINDING);
protocolMarshaller.marshall(putSubscriptionFilterRequest.getDistribution(), DISTRIBUTION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(PutSubscriptionFilterRequest putSubscriptionFilterRequest, ProtocolMarshaller protocolMarshaller) {
if (putSubscriptionFilterRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(putSubscriptionFilterRequest.getLogGroupName(), LOGGROUPNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(putSubscriptionFilterRequest.getFilterName(), FILTERNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(putSubscriptionFilterRequest.getFilterPattern(), FILTERPATTERN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(putSubscriptionFilterRequest.getDestinationArn(), DESTINATIONARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(putSubscriptionFilterRequest.getRoleArn(), ROLEARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(putSubscriptionFilterRequest.getDistribution(), DISTRIBUTION_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static int bkdrHash(String str) {
int seed = 131; // 31 131 1313 13131 131313 etc..
int hash = 0;
for (int i = 0; i < str.length(); i++) {
hash = (hash * seed) + str.charAt(i);
}
return hash & 0x7FFFFFFF;
} } | public class class_name {
public static int bkdrHash(String str) {
int seed = 131; // 31 131 1313 13131 131313 etc..
int hash = 0;
for (int i = 0; i < str.length(); i++) {
hash = (hash * seed) + str.charAt(i);
// depends on control dependency: [for], data = [i]
}
return hash & 0x7FFFFFFF;
} } |
public class class_name {
public void add(final Formula formula) {
final Formula cnf = formula.cnf();
switch (cnf.type()) {
case TRUE:
break;
case FALSE:
case LITERAL:
case OR:
this.addClause(generateClauseVector(cnf), null);
break;
case AND:
for (final Formula op : cnf) {
this.addClause(generateClauseVector(op), null);
}
break;
default:
throw new IllegalStateException("Unexpected formula type in CNF: " + cnf.type());
}
} } | public class class_name {
public void add(final Formula formula) {
final Formula cnf = formula.cnf();
switch (cnf.type()) {
case TRUE:
break;
case FALSE:
case LITERAL:
case OR:
this.addClause(generateClauseVector(cnf), null);
break;
case AND:
for (final Formula op : cnf) {
this.addClause(generateClauseVector(op), null); // depends on control dependency: [for], data = [op]
}
break;
default:
throw new IllegalStateException("Unexpected formula type in CNF: " + cnf.type());
}
} } |
public class class_name {
public <W> W getValue(Class<W> clazz, String key) {
if (values.get(key) == null) {
return null;
} else {
try {
return (W) values.get(key);
} catch (ClassCastException e) {
if (Number.class.isAssignableFrom(clazz)) {
try {
return (W) Utils.castNumberType(values.get(key), clazz);
} catch (ClassCastException e1) {
return null;
}
} else {
throw e;
}
}
}
} } | public class class_name {
public <W> W getValue(Class<W> clazz, String key) {
if (values.get(key) == null) {
return null; // depends on control dependency: [if], data = [none]
} else {
try {
return (W) values.get(key); // depends on control dependency: [try], data = [none]
} catch (ClassCastException e) {
if (Number.class.isAssignableFrom(clazz)) {
try {
return (W) Utils.castNumberType(values.get(key), clazz); // depends on control dependency: [try], data = [none]
} catch (ClassCastException e1) {
return null;
} // depends on control dependency: [catch], data = [none]
} else {
throw e;
}
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public void checkSpecialization() {
if (isSpecializing()) {
boolean isNameDefined = getAnnotated().isAnnotationPresent(Named.class);
String previousSpecializedBeanName = null;
for (AbstractBean<?, ?> specializedBean : getSpecializedBeans()) {
String name = specializedBean.getName();
if (previousSpecializedBeanName != null && name != null && !previousSpecializedBeanName.equals(specializedBean.getName())) {
// there may be multiple beans specialized by this bean - make sure they all share the same name
throw BeanLogger.LOG.beansWithDifferentBeanNamesCannotBeSpecialized(previousSpecializedBeanName, specializedBean.getName(), this);
}
previousSpecializedBeanName = name;
if (isNameDefined && name != null) {
throw BeanLogger.LOG.nameNotAllowedOnSpecialization(getAnnotated(), specializedBean.getAnnotated());
}
// When a specializing bean extends the raw type of a generic superclass, types of the generic superclass are
// added into types of the specializing bean because of assignability rules. However, ParameterizedTypes among
// these types are NOT types of the specializing bean (that's the way java works)
boolean rawInsteadOfGeneric = (this instanceof AbstractClassBean<?>
&& specializedBean.getBeanClass().getTypeParameters().length > 0
&& !(((AbstractClassBean<?>) this).getBeanClass().getGenericSuperclass() instanceof ParameterizedType));
for (Type specializedType : specializedBean.getTypes()) {
if (rawInsteadOfGeneric && specializedType instanceof ParameterizedType) {
throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);
}
boolean contains = getTypes().contains(specializedType);
if (!contains) {
for (Type specializingType : getTypes()) {
// In case 'type' is a ParameterizedType, two bean types equivalent in the CDI sense may not be
// equal in the java sense. Therefore we have to use our own equality util.
if (TypeEqualitySpecializationUtils.areTheSame(specializingType, specializedType)) {
contains = true;
break;
}
}
}
if (!contains) {
throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);
}
}
}
}
} } | public class class_name {
public void checkSpecialization() {
if (isSpecializing()) {
boolean isNameDefined = getAnnotated().isAnnotationPresent(Named.class);
String previousSpecializedBeanName = null;
for (AbstractBean<?, ?> specializedBean : getSpecializedBeans()) {
String name = specializedBean.getName();
if (previousSpecializedBeanName != null && name != null && !previousSpecializedBeanName.equals(specializedBean.getName())) {
// there may be multiple beans specialized by this bean - make sure they all share the same name
throw BeanLogger.LOG.beansWithDifferentBeanNamesCannotBeSpecialized(previousSpecializedBeanName, specializedBean.getName(), this);
}
previousSpecializedBeanName = name; // depends on control dependency: [if], data = [none]
if (isNameDefined && name != null) {
throw BeanLogger.LOG.nameNotAllowedOnSpecialization(getAnnotated(), specializedBean.getAnnotated());
}
// When a specializing bean extends the raw type of a generic superclass, types of the generic superclass are
// added into types of the specializing bean because of assignability rules. However, ParameterizedTypes among
// these types are NOT types of the specializing bean (that's the way java works)
boolean rawInsteadOfGeneric = (this instanceof AbstractClassBean<?>
&& specializedBean.getBeanClass().getTypeParameters().length > 0
&& !(((AbstractClassBean<?>) this).getBeanClass().getGenericSuperclass() instanceof ParameterizedType));
for (Type specializedType : specializedBean.getTypes()) {
if (rawInsteadOfGeneric && specializedType instanceof ParameterizedType) {
throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);
}
boolean contains = getTypes().contains(specializedType);
if (!contains) {
for (Type specializingType : getTypes()) {
// In case 'type' is a ParameterizedType, two bean types equivalent in the CDI sense may not be
// equal in the java sense. Therefore we have to use our own equality util.
if (TypeEqualitySpecializationUtils.areTheSame(specializingType, specializedType)) {
contains = true; // depends on control dependency: [if], data = [none]
break;
}
}
}
if (!contains) {
throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean);
}
}
}
}
} } |
public class class_name {
public Observable<ServiceResponse<WorkerPoolResourceInner>> updateMultiRolePoolWithServiceResponseAsync(String resourceGroupName, String name, WorkerPoolResourceInner multiRolePoolEnvelope) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (name == null) {
throw new IllegalArgumentException("Parameter name is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (multiRolePoolEnvelope == null) {
throw new IllegalArgumentException("Parameter multiRolePoolEnvelope is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
Validator.validate(multiRolePoolEnvelope);
return service.updateMultiRolePool(resourceGroupName, name, this.client.subscriptionId(), multiRolePoolEnvelope, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<WorkerPoolResourceInner>>>() {
@Override
public Observable<ServiceResponse<WorkerPoolResourceInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<WorkerPoolResourceInner> clientResponse = updateMultiRolePoolDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<WorkerPoolResourceInner>> updateMultiRolePoolWithServiceResponseAsync(String resourceGroupName, String name, WorkerPoolResourceInner multiRolePoolEnvelope) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (name == null) {
throw new IllegalArgumentException("Parameter name is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (multiRolePoolEnvelope == null) {
throw new IllegalArgumentException("Parameter multiRolePoolEnvelope is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
Validator.validate(multiRolePoolEnvelope);
return service.updateMultiRolePool(resourceGroupName, name, this.client.subscriptionId(), multiRolePoolEnvelope, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<WorkerPoolResourceInner>>>() {
@Override
public Observable<ServiceResponse<WorkerPoolResourceInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<WorkerPoolResourceInner> clientResponse = updateMultiRolePoolDelegate(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 {
private static Iterable<String> toIterable(final String[] strings) {
if (strings == null) {
return null;
}
return Arrays.asList(strings);
} } | public class class_name {
private static Iterable<String> toIterable(final String[] strings) {
if (strings == null) {
return null; // depends on control dependency: [if], data = [none]
}
return Arrays.asList(strings);
} } |
public class class_name {
private static boolean isAssignableFrom(Class<?> src, Class<?> target) {
// src will always be an object
// Short-cut. null is always assignable to an object and in EL null
// can always be coerced to a valid value for a primitive
if (src == null) {
return true;
}
Class<?> targetClass;
if (target.isPrimitive()) {
if (target == Boolean.TYPE) {
targetClass = Boolean.class;
} else if (target == Character.TYPE) {
targetClass = Character.class;
} else if (target == Byte.TYPE) {
targetClass = Byte.class;
} else if (target == Short.TYPE) {
targetClass = Short.class;
} else if (target == Integer.TYPE) {
targetClass = Integer.class;
} else if (target == Long.TYPE) {
targetClass = Long.class;
} else if (target == Float.TYPE) {
targetClass = Float.class;
} else {
targetClass = Double.class;
}
} else {
targetClass = target;
}
return targetClass.isAssignableFrom(src);
} } | public class class_name {
private static boolean isAssignableFrom(Class<?> src, Class<?> target) {
// src will always be an object
// Short-cut. null is always assignable to an object and in EL null
// can always be coerced to a valid value for a primitive
if (src == null) {
return true; // depends on control dependency: [if], data = [none]
}
Class<?> targetClass;
if (target.isPrimitive()) {
if (target == Boolean.TYPE) {
targetClass = Boolean.class; // depends on control dependency: [if], data = [none]
} else if (target == Character.TYPE) {
targetClass = Character.class; // depends on control dependency: [if], data = [none]
} else if (target == Byte.TYPE) {
targetClass = Byte.class; // depends on control dependency: [if], data = [none]
} else if (target == Short.TYPE) {
targetClass = Short.class; // depends on control dependency: [if], data = [none]
} else if (target == Integer.TYPE) {
targetClass = Integer.class; // depends on control dependency: [if], data = [none]
} else if (target == Long.TYPE) {
targetClass = Long.class; // depends on control dependency: [if], data = [none]
} else if (target == Float.TYPE) {
targetClass = Float.class; // depends on control dependency: [if], data = [none]
} else {
targetClass = Double.class; // depends on control dependency: [if], data = [none]
}
} else {
targetClass = target; // depends on control dependency: [if], data = [none]
}
return targetClass.isAssignableFrom(src);
} } |
public class class_name {
public PrivilegeImpl forName(String name) {
if (name.contains("}")) {
String localName = name.substring(name.indexOf('}') + 1);
return privileges.get(localName);
}
if (name.contains(":")) {
String localName = name.substring(name.indexOf(':') + 1);
PrivilegeImpl p = privileges.get(localName);
return p.getName().equals(name) ? p : null;
}
return null;
} } | public class class_name {
public PrivilegeImpl forName(String name) {
if (name.contains("}")) {
String localName = name.substring(name.indexOf('}') + 1);
return privileges.get(localName); // depends on control dependency: [if], data = [none]
}
if (name.contains(":")) {
String localName = name.substring(name.indexOf(':') + 1);
PrivilegeImpl p = privileges.get(localName);
return p.getName().equals(name) ? p : null; // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public boolean hasRoleForResource(CmsObject cms, CmsRole role, String resourceName) {
CmsResource resource;
try {
resource = cms.readResource(resourceName, CmsResourceFilter.ALL);
} catch (CmsException e) {
// ignore
return false;
}
return m_securityManager.hasRoleForResource(
cms.getRequestContext(),
cms.getRequestContext().getCurrentUser(),
role,
resource);
} } | public class class_name {
public boolean hasRoleForResource(CmsObject cms, CmsRole role, String resourceName) {
CmsResource resource;
try {
resource = cms.readResource(resourceName, CmsResourceFilter.ALL); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
// ignore
return false;
} // depends on control dependency: [catch], data = [none]
return m_securityManager.hasRoleForResource(
cms.getRequestContext(),
cms.getRequestContext().getCurrentUser(),
role,
resource);
} } |
public class class_name {
@Override
public ListenableFuture<List<FlatRow>> readFlatRowsAsync(ReadRowsRequest request) {
if (shouldOverrideAppProfile(request.getAppProfileId())) {
request = request.toBuilder().setAppProfileId(clientDefaultAppProfileId).build();
}
return Futures.transform(
createStreamingListener(request, readRowsAsync, request.getTableName()).getAsyncResult(),
FLAT_ROW_LIST_TRANSFORMER, MoreExecutors.directExecutor());
} } | public class class_name {
@Override
public ListenableFuture<List<FlatRow>> readFlatRowsAsync(ReadRowsRequest request) {
if (shouldOverrideAppProfile(request.getAppProfileId())) {
request = request.toBuilder().setAppProfileId(clientDefaultAppProfileId).build(); // depends on control dependency: [if], data = [none]
}
return Futures.transform(
createStreamingListener(request, readRowsAsync, request.getTableName()).getAsyncResult(),
FLAT_ROW_LIST_TRANSFORMER, MoreExecutors.directExecutor());
} } |
public class class_name {
public static ObjectTypeAttributeDefinition.Builder getAttributeBuilder(String name, String xmlName, boolean allowNull,
CapabilityReferenceRecorder capabilityStoreReferenceRecorder) {
if (capabilityStoreReferenceRecorder == null) {
return getAttributeBuilder(name, xmlName, allowNull, false);
}
assert CREDENTIAL_STORE_CAPABILITY.equals(capabilityStoreReferenceRecorder.getBaseRequirementName());
AttributeDefinition csAttr = new SimpleAttributeDefinitionBuilder(credentialStoreAttribute)
.setCapabilityReference(capabilityStoreReferenceRecorder)
.build();
return getAttributeBuilder(name, xmlName, allowNull, csAttr);
} } | public class class_name {
public static ObjectTypeAttributeDefinition.Builder getAttributeBuilder(String name, String xmlName, boolean allowNull,
CapabilityReferenceRecorder capabilityStoreReferenceRecorder) {
if (capabilityStoreReferenceRecorder == null) {
return getAttributeBuilder(name, xmlName, allowNull, false); // depends on control dependency: [if], data = [none]
}
assert CREDENTIAL_STORE_CAPABILITY.equals(capabilityStoreReferenceRecorder.getBaseRequirementName());
AttributeDefinition csAttr = new SimpleAttributeDefinitionBuilder(credentialStoreAttribute)
.setCapabilityReference(capabilityStoreReferenceRecorder)
.build();
return getAttributeBuilder(name, xmlName, allowNull, csAttr);
} } |
public class class_name {
private String getUnavailableServices() {
StringBuilder missingServices = new StringBuilder();
if (tokenService.getReference() == null) {
missingServices.append("tokenService, ");
}
if (tokenManager.getReference() == null) {
missingServices.append("tokenManager, ");
}
if (authenticationService.getReference() == null) {
missingServices.append("authenticationService, ");
}
if (authorizationService.getReference() == null) {
missingServices.append("authorizationService, ");
}
if (userRegistry.getReference() == null) {
missingServices.append("userRegistry, ");
}
if (userRegistryService.getReference() == null) {
missingServices.append("userRegistryService, ");
}
if (missingServices.length() == 0) {
return null;
} else {
// Return everything but the last ", "
return missingServices.substring(0, missingServices.length() - 2);
}
} } | public class class_name {
private String getUnavailableServices() {
StringBuilder missingServices = new StringBuilder();
if (tokenService.getReference() == null) {
missingServices.append("tokenService, "); // depends on control dependency: [if], data = [none]
}
if (tokenManager.getReference() == null) {
missingServices.append("tokenManager, "); // depends on control dependency: [if], data = [none]
}
if (authenticationService.getReference() == null) {
missingServices.append("authenticationService, "); // depends on control dependency: [if], data = [none]
}
if (authorizationService.getReference() == null) {
missingServices.append("authorizationService, "); // depends on control dependency: [if], data = [none]
}
if (userRegistry.getReference() == null) {
missingServices.append("userRegistry, "); // depends on control dependency: [if], data = [none]
}
if (userRegistryService.getReference() == null) {
missingServices.append("userRegistryService, "); // depends on control dependency: [if], data = [none]
}
if (missingServices.length() == 0) {
return null; // depends on control dependency: [if], data = [none]
} else {
// Return everything but the last ", "
return missingServices.substring(0, missingServices.length() - 2); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static <T> void sortEvaluatedPopulation(List<EvaluatedCandidate<T>> evaluatedPopulation,
boolean naturalFitness)
{
// Sort candidates in descending order according to fitness.
if (naturalFitness) // Descending values for natural fitness.
{
Collections.sort(evaluatedPopulation, Collections.reverseOrder());
}
else // Ascending values for non-natural fitness.
{
Collections.sort(evaluatedPopulation);
}
} } | public class class_name {
public static <T> void sortEvaluatedPopulation(List<EvaluatedCandidate<T>> evaluatedPopulation,
boolean naturalFitness)
{
// Sort candidates in descending order according to fitness.
if (naturalFitness) // Descending values for natural fitness.
{
Collections.sort(evaluatedPopulation, Collections.reverseOrder()); // depends on control dependency: [if], data = [none]
}
else // Ascending values for non-natural fitness.
{
Collections.sort(evaluatedPopulation); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@DoesServiceRequest
public boolean deleteIfExists(TableRequestOptions options, OperationContext opContext) throws StorageException {
options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient);
if (this.exists(true, options, opContext)) {
try {
this.delete(options, opContext);
}
catch (StorageException ex) {
if (ex.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND
&& StorageErrorCodeStrings.RESOURCE_NOT_FOUND.equals(ex.getErrorCode())) {
return false;
}
else {
throw ex;
}
}
return true;
}
else {
return false;
}
} } | public class class_name {
@DoesServiceRequest
public boolean deleteIfExists(TableRequestOptions options, OperationContext opContext) throws StorageException {
options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient);
if (this.exists(true, options, opContext)) {
try {
this.delete(options, opContext); // depends on control dependency: [try], data = [none]
}
catch (StorageException ex) {
if (ex.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND
&& StorageErrorCodeStrings.RESOURCE_NOT_FOUND.equals(ex.getErrorCode())) {
return false; // depends on control dependency: [if], data = [none]
}
else {
throw ex;
}
} // depends on control dependency: [catch], data = [none]
return true;
}
else {
return false;
}
} } |
public class class_name {
public static String encodeBase16(byte[] bytesParam)
{
if(bytesParam == null)
{
return null;
}
if(bytesParam.length == 0)
{
return UtilGlobal.EMPTY;
}
return DatatypeConverter.printHexBinary(bytesParam).toUpperCase();
} } | public class class_name {
public static String encodeBase16(byte[] bytesParam)
{
if(bytesParam == null)
{
return null; // depends on control dependency: [if], data = [none]
}
if(bytesParam.length == 0)
{
return UtilGlobal.EMPTY; // depends on control dependency: [if], data = [none]
}
return DatatypeConverter.printHexBinary(bytesParam).toUpperCase();
} } |
public class class_name {
public void stopAllPlugins() {
synchronized (pluginMap) {
// remove the listener for this repository
loggerRepository.removeLoggerRepositoryEventListener(listener);
Iterator iter = pluginMap.values().iterator();
while (iter.hasNext()) {
Plugin plugin = (Plugin) iter.next();
plugin.shutdown();
firePluginStopped(plugin);
}
}
} } | public class class_name {
public void stopAllPlugins() {
synchronized (pluginMap) {
// remove the listener for this repository
loggerRepository.removeLoggerRepositoryEventListener(listener);
Iterator iter = pluginMap.values().iterator();
while (iter.hasNext()) {
Plugin plugin = (Plugin) iter.next();
plugin.shutdown(); // depends on control dependency: [while], data = [none]
firePluginStopped(plugin); // depends on control dependency: [while], data = [none]
}
}
} } |
public class class_name {
public QueryAtomGroupImpl pop() {
QueryAtomGroupImpl group = new QueryAtomGroupImpl();
boolean first = true;
for (QueryAtom atom : atoms) {
if (first) {
first = false;
}
else {
group.addAtom(atom);
}
}
return group;
} } | public class class_name {
public QueryAtomGroupImpl pop() {
QueryAtomGroupImpl group = new QueryAtomGroupImpl();
boolean first = true;
for (QueryAtom atom : atoms) {
if (first) {
first = false; // depends on control dependency: [if], data = [none]
}
else {
group.addAtom(atom); // depends on control dependency: [if], data = [none]
}
}
return group;
} } |
public class class_name {
protected static String buildListString(List<? extends Object> list, Map<Object, String> alreadyAppearedSet) {
final String appeared = handleAlreadyAppeared(list, alreadyAppearedSet);
if (appeared != null) {
return appeared;
}
final StringBuilder listSb = new StringBuilder();
listSb.append("[");
int index = 0;
for (Object element : list) {
listSb.append(index > 0 ? ", " : "");
listSb.append(resolveObjectString(element, alreadyAppearedSet));
++index;
}
listSb.append("]");
final String exp = listSb.toString();
alreadyAppearedSet.put(list, exp); // real expression
return exp;
} } | public class class_name {
protected static String buildListString(List<? extends Object> list, Map<Object, String> alreadyAppearedSet) {
final String appeared = handleAlreadyAppeared(list, alreadyAppearedSet);
if (appeared != null) {
return appeared; // depends on control dependency: [if], data = [none]
}
final StringBuilder listSb = new StringBuilder();
listSb.append("[");
int index = 0;
for (Object element : list) {
listSb.append(index > 0 ? ", " : ""); // depends on control dependency: [for], data = [none]
listSb.append(resolveObjectString(element, alreadyAppearedSet)); // depends on control dependency: [for], data = [element]
++index; // depends on control dependency: [for], data = [none]
}
listSb.append("]");
final String exp = listSb.toString();
alreadyAppearedSet.put(list, exp); // real expression
return exp;
} } |
public class class_name {
public ContentProviderController<T> create(ProviderInfo providerInfo) {
Context baseContext = RuntimeEnvironment.application.getBaseContext();
// make sure the component is enabled
ComponentName componentName =
createRelative(baseContext.getPackageName(), contentProvider.getClass().getName());
baseContext
.getPackageManager()
.setComponentEnabledSetting(
componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
contentProvider.attachInfo(baseContext, providerInfo);
if (providerInfo != null) {
ShadowContentResolver.registerProviderInternal(providerInfo.authority, contentProvider);
}
return this;
} } | public class class_name {
public ContentProviderController<T> create(ProviderInfo providerInfo) {
Context baseContext = RuntimeEnvironment.application.getBaseContext();
// make sure the component is enabled
ComponentName componentName =
createRelative(baseContext.getPackageName(), contentProvider.getClass().getName());
baseContext
.getPackageManager()
.setComponentEnabledSetting(
componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
contentProvider.attachInfo(baseContext, providerInfo);
if (providerInfo != null) {
ShadowContentResolver.registerProviderInternal(providerInfo.authority, contentProvider); // depends on control dependency: [if], data = [(providerInfo]
}
return this;
} } |
public class class_name {
private Map<String, String> getBundleMap() {
Map<String, String> bundles = new HashMap<String, String>();
if (m_bundleComponentKeyMap != null) {
Set<TextField> fields = m_bundleComponentKeyMap.keySet();
for (TextField field : fields) {
bundles.put(m_bundleComponentKeyMap.get(field), field.getValue());
}
}
return bundles;
} } | public class class_name {
private Map<String, String> getBundleMap() {
Map<String, String> bundles = new HashMap<String, String>();
if (m_bundleComponentKeyMap != null) {
Set<TextField> fields = m_bundleComponentKeyMap.keySet();
for (TextField field : fields) {
bundles.put(m_bundleComponentKeyMap.get(field), field.getValue()); // depends on control dependency: [for], data = [field]
}
}
return bundles;
} } |
public class class_name {
public static Class<?> getSubclassInScope(final Class<?> scopeClass) {
final String callerClass = Thread.currentThread().getStackTrace()[3].getClassName();
try {
final Class<?> candidateClass = Class.forName(callerClass, false, Thread.currentThread().getContextClassLoader());
if(!scopeClass.isAssignableFrom(candidateClass)) {
return null;
}
return candidateClass;
} catch (final ClassNotFoundException e) {
throw new IllegalStateException("The class should always exist",e);
}
} } | public class class_name {
public static Class<?> getSubclassInScope(final Class<?> scopeClass) {
final String callerClass = Thread.currentThread().getStackTrace()[3].getClassName();
try {
final Class<?> candidateClass = Class.forName(callerClass, false, Thread.currentThread().getContextClassLoader());
if(!scopeClass.isAssignableFrom(candidateClass)) {
return null; // depends on control dependency: [if], data = [none]
}
return candidateClass;
} catch (final ClassNotFoundException e) {
throw new IllegalStateException("The class should always exist",e);
}
} } |
public class class_name {
public ReloadableType getSuperRtype() {
if (superRtype != null) {
return superRtype;
}
if (superclazz == null) {
// Not filled in yet? Why is this code different to the interface case?
String name = this.getSlashedSupertypeName();
if (name == null) {
return null;
}
else {
ReloadableType rtype = typeRegistry.getReloadableSuperType(name);
superRtype = rtype;
return superRtype;
}
}
else {
ClassLoader superClassLoader = superclazz.getClassLoader();
TypeRegistry superTypeRegistry = TypeRegistry.getTypeRegistryFor(superClassLoader);
superRtype = superTypeRegistry.getReloadableType(superclazz);
return superRtype;
}
} } | public class class_name {
public ReloadableType getSuperRtype() {
if (superRtype != null) {
return superRtype; // depends on control dependency: [if], data = [none]
}
if (superclazz == null) {
// Not filled in yet? Why is this code different to the interface case?
String name = this.getSlashedSupertypeName();
if (name == null) {
return null; // depends on control dependency: [if], data = [none]
}
else {
ReloadableType rtype = typeRegistry.getReloadableSuperType(name);
superRtype = rtype; // depends on control dependency: [if], data = [none]
return superRtype; // depends on control dependency: [if], data = [none]
}
}
else {
ClassLoader superClassLoader = superclazz.getClassLoader();
TypeRegistry superTypeRegistry = TypeRegistry.getTypeRegistryFor(superClassLoader);
superRtype = superTypeRegistry.getReloadableType(superclazz); // depends on control dependency: [if], data = [(superclazz]
return superRtype; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public final void addArgument(@NotNull final Argument argument) {
if (arguments == null) {
arguments = new ArrayList<Argument>();
}
arguments.add(argument);
} } | public class class_name {
public final void addArgument(@NotNull final Argument argument) {
if (arguments == null) {
arguments = new ArrayList<Argument>();
// depends on control dependency: [if], data = [none]
}
arguments.add(argument);
} } |
public class class_name {
@Override
public boolean visit(final PackageNode node) {
if (!node.getName().isEmpty()) {
this.graphStr
.append(" ")
.append(node.getName())
.append(" [label=\"")
.append(node.getFullName())
.append("\", shape=folder];\n");
}
return true;
} } | public class class_name {
@Override
public boolean visit(final PackageNode node) {
if (!node.getName().isEmpty()) {
this.graphStr
.append(" ")
.append(node.getName())
.append(" [label=\"")
.append(node.getFullName())
.append("\", shape=folder];\n"); // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
@Override
public void setSchemeIdentifier(String schemeIdentifier) {
XSURI uri = null;
if (schemeIdentifier != null) {
uri = (new XSURIBuilder()).buildObject(this.getElementQName().getNamespaceURI(), SCHEME_IDENTIFIER_LOCAL_NAME,
this.getElementQName().getPrefix());
uri.setValue(schemeIdentifier);
}
this.setSchemeIdentifier(uri);
} } | public class class_name {
@Override
public void setSchemeIdentifier(String schemeIdentifier) {
XSURI uri = null;
if (schemeIdentifier != null) {
uri = (new XSURIBuilder()).buildObject(this.getElementQName().getNamespaceURI(), SCHEME_IDENTIFIER_LOCAL_NAME,
this.getElementQName().getPrefix()); // depends on control dependency: [if], data = [none]
uri.setValue(schemeIdentifier); // depends on control dependency: [if], data = [(schemeIdentifier]
}
this.setSchemeIdentifier(uri);
} } |
public class class_name {
public static HyphenatorBuilder getInstance() {
if (instance == null) {
synchronized (HyphenatorBuilderImpl.class) {
if (instance == null) {
HyphenatorBuilderImpl impl = new HyphenatorBuilderImpl();
impl.initialize();
instance = impl;
}
}
}
return instance;
} } | public class class_name {
public static HyphenatorBuilder getInstance() {
if (instance == null) {
synchronized (HyphenatorBuilderImpl.class) { // depends on control dependency: [if], data = [none]
if (instance == null) {
HyphenatorBuilderImpl impl = new HyphenatorBuilderImpl();
impl.initialize(); // depends on control dependency: [if], data = [none]
instance = impl; // depends on control dependency: [if], data = [none]
}
}
}
return instance;
} } |
public class class_name {
public static long getEffectivePermission(Channel channel, Member member)
{
Checks.notNull(channel, "Channel");
Checks.notNull(member, "Member");
Checks.check(channel.getGuild().equals(member.getGuild()), "Provided channel and provided member are not of the same guild!");
if (member.isOwner())
{
// Owner effectively has all permissions
return Permission.ALL_PERMISSIONS;
}
long permission = getEffectivePermission(member);
final long admin = Permission.ADMINISTRATOR.getRawValue();
if (isApplied(permission, admin))
return Permission.ALL_PERMISSIONS;
AtomicLong allow = new AtomicLong(0);
AtomicLong deny = new AtomicLong(0);
getExplicitOverrides(channel, member, allow, deny);
permission = apply(permission, allow.get(), deny.get());
final long viewChannel = Permission.VIEW_CHANNEL.getRawValue();
//When the permission to view the channel is not applied it is not granted
// This means that we have no access to this channel at all
return isApplied(permission, viewChannel) ? permission : 0;
/*
// currently discord doesn't implicitly grant permissions that the user can grant others
// so instead the user has to explicitly make an override to grant them the permission in order to be granted that permission
// yes this makes no sense but what can i do, the devs don't like changing things apparently...
// I've been told half a year ago this would be changed but nothing happens
// so instead I'll just bend over for them so people get "correct" permission checks...
//
// only time will tell if something happens and I can finally re-implement this section wew
final long managePerms = Permission.MANAGE_PERMISSIONS.getRawValue();
final long manageChannel = Permission.MANAGE_CHANNEL.getRawValue();
if ((permission & (managePerms | manageChannel)) != 0)
{
// In channels, MANAGE_CHANNEL and MANAGE_PERMISSIONS grant full text/voice permissions
permission |= Permission.ALL_TEXT_PERMISSIONS | Permission.ALL_VOICE_PERMISSIONS;
}
*/
} } | public class class_name {
public static long getEffectivePermission(Channel channel, Member member)
{
Checks.notNull(channel, "Channel");
Checks.notNull(member, "Member");
Checks.check(channel.getGuild().equals(member.getGuild()), "Provided channel and provided member are not of the same guild!");
if (member.isOwner())
{
// Owner effectively has all permissions
return Permission.ALL_PERMISSIONS; // depends on control dependency: [if], data = [none]
}
long permission = getEffectivePermission(member);
final long admin = Permission.ADMINISTRATOR.getRawValue();
if (isApplied(permission, admin))
return Permission.ALL_PERMISSIONS;
AtomicLong allow = new AtomicLong(0);
AtomicLong deny = new AtomicLong(0);
getExplicitOverrides(channel, member, allow, deny);
permission = apply(permission, allow.get(), deny.get());
final long viewChannel = Permission.VIEW_CHANNEL.getRawValue();
//When the permission to view the channel is not applied it is not granted
// This means that we have no access to this channel at all
return isApplied(permission, viewChannel) ? permission : 0;
/*
// currently discord doesn't implicitly grant permissions that the user can grant others
// so instead the user has to explicitly make an override to grant them the permission in order to be granted that permission
// yes this makes no sense but what can i do, the devs don't like changing things apparently...
// I've been told half a year ago this would be changed but nothing happens
// so instead I'll just bend over for them so people get "correct" permission checks...
//
// only time will tell if something happens and I can finally re-implement this section wew
final long managePerms = Permission.MANAGE_PERMISSIONS.getRawValue();
final long manageChannel = Permission.MANAGE_CHANNEL.getRawValue();
if ((permission & (managePerms | manageChannel)) != 0)
{
// In channels, MANAGE_CHANNEL and MANAGE_PERMISSIONS grant full text/voice permissions
permission |= Permission.ALL_TEXT_PERMISSIONS | Permission.ALL_VOICE_PERMISSIONS;
}
*/
} } |
public class class_name {
public void startBackgroundIconColorFadeAnimation(final int cycleCount) {
if (backgroundIcon == null) {
LOGGER.warn("Background animation skipped because background icon not set!");
return;
}
backgroundIconColorFadeAnimation = Animations.createFadeTransition(backgroundIcon, JFXConstants.TRANSPARENCY_FULLY, JFXConstants.TRANSPARENCY_NONE, cycleCount, JFXConstants.ANIMATION_DURATION_FADE_SLOW);
backgroundIconColorFadeAnimation.setOnFinished(event -> backgroundIcon.setOpacity(JFXConstants.TRANSPARENCY_FULLY));
backgroundIconColorFadeAnimation.play();
} } | public class class_name {
public void startBackgroundIconColorFadeAnimation(final int cycleCount) {
if (backgroundIcon == null) {
LOGGER.warn("Background animation skipped because background icon not set!"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
backgroundIconColorFadeAnimation = Animations.createFadeTransition(backgroundIcon, JFXConstants.TRANSPARENCY_FULLY, JFXConstants.TRANSPARENCY_NONE, cycleCount, JFXConstants.ANIMATION_DURATION_FADE_SLOW);
backgroundIconColorFadeAnimation.setOnFinished(event -> backgroundIcon.setOpacity(JFXConstants.TRANSPARENCY_FULLY));
backgroundIconColorFadeAnimation.play();
} } |
public class class_name {
public void setShadowsEnabled(final boolean ENABLED) {
if (null == shadowsEnabled) {
_shadowsEnabled = ENABLED;
fireTileEvent(REDRAW_EVENT);
} else {
shadowsEnabled.set(ENABLED);
}
} } | public class class_name {
public void setShadowsEnabled(final boolean ENABLED) {
if (null == shadowsEnabled) {
_shadowsEnabled = ENABLED; // depends on control dependency: [if], data = [none]
fireTileEvent(REDRAW_EVENT); // depends on control dependency: [if], data = [none]
} else {
shadowsEnabled.set(ENABLED); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected String beginModules(HttpServletRequest request, Object arg) {
StringBuffer sb = new StringBuffer();
if (RequestUtil.isServerExpandedLayers(request) &&
request.getParameter(REQUESTEDMODULESCOUNT_REQPARAM) != null) { // it's a loader generated request
@SuppressWarnings("unchecked")
Set<String> modules = (Set<String>)arg;
sb.append("require.combo.defineModules(["); //$NON-NLS-1$
int i = 0;
for (String module : modules) {
sb.append(i++ > 0 ? "," : "").append("'").append(module).append("'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
sb.append("], function(){\r\n"); //$NON-NLS-1$
}
return sb.toString();
} } | public class class_name {
protected String beginModules(HttpServletRequest request, Object arg) {
StringBuffer sb = new StringBuffer();
if (RequestUtil.isServerExpandedLayers(request) &&
request.getParameter(REQUESTEDMODULESCOUNT_REQPARAM) != null) { // it's a loader generated request
@SuppressWarnings("unchecked")
Set<String> modules = (Set<String>)arg;
sb.append("require.combo.defineModules(["); //$NON-NLS-1$
int i = 0;
for (String module : modules) {
sb.append(i++ > 0 ? "," : "").append("'").append(module).append("'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
sb.append("], function(){\r\n"); //$NON-NLS-1$
// depends on control dependency: [if], data = [none]
}
return sb.toString();
} } |
public class class_name {
protected final void setControllerPath(String path) {
requireNonNull(path, "Global path cannot be change to 'null'");
if (!"".equals(path) && !"/".equals(path)) {
this.controllerPath = pathCorrector.apply(path);
}
} } | public class class_name {
protected final void setControllerPath(String path) {
requireNonNull(path, "Global path cannot be change to 'null'");
if (!"".equals(path) && !"/".equals(path)) {
this.controllerPath = pathCorrector.apply(path); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static boolean containNumber(String str) {
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
return true;
}
}
return false;
} } | public class class_name {
public static boolean containNumber(String str) {
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
return true;
// depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public void init(int iCheckCount, boolean bCheckedIsOn)
{
m_bCheckedIsOn = bCheckedIsOn;
this.setBorder(null);
this.setOpaque(false);
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
for (int i = 0; i < iCheckCount; i++)
{
JCheckBox checkBox = new JCheckBox();
this.add(checkBox);
checkBox.setName(Integer.toString(i));
checkBox.setOpaque(false);
}
} } | public class class_name {
public void init(int iCheckCount, boolean bCheckedIsOn)
{
m_bCheckedIsOn = bCheckedIsOn;
this.setBorder(null);
this.setOpaque(false);
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
for (int i = 0; i < iCheckCount; i++)
{
JCheckBox checkBox = new JCheckBox();
this.add(checkBox); // depends on control dependency: [for], data = [none]
checkBox.setName(Integer.toString(i)); // depends on control dependency: [for], data = [i]
checkBox.setOpaque(false); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
private void setRemoteControlClientPlaybackState(int state) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mRemoteControlClientCompat.setPlaybackState(state);
}
} } | public class class_name {
private void setRemoteControlClientPlaybackState(int state) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mRemoteControlClientCompat.setPlaybackState(state); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
void connectTo(final Node<T> o) {
if (!this.graph.equals(o.graph))
throw new IllegalArgumentException("Cannot connect to nodes of two different graphs.");
if (this.equals(o)) {
return;
}
neighbours.add(o);
} } | public class class_name {
void connectTo(final Node<T> o) {
if (!this.graph.equals(o.graph))
throw new IllegalArgumentException("Cannot connect to nodes of two different graphs.");
if (this.equals(o)) {
return; // depends on control dependency: [if], data = [none]
}
neighbours.add(o);
} } |
public class class_name {
private Statement compileAlterTableDropLimit(Table t) {
HsqlName readName = null;
HsqlName writeName = null;
boolean cascade = false;
if (token.tokenType == Tokens.RESTRICT) {
read();
} else if (token.tokenType == Tokens.CASCADE) {
read();
cascade = true;
}
SchemaObject object = t.getLimitConstraint();
if (object == null) {
throw Error.error(ErrorCode.X_42501);
}
if (cascade) {
writeName = database.getCatalogName();
} else {
writeName = t.getName();
}
Object[] args = new Object[] {
object.getName(), Integer.valueOf(SchemaObject.CONSTRAINT),
Boolean.valueOf(cascade), Boolean.valueOf(false)
};
String sql = getLastPart();
return new StatementSchema(sql, StatementTypes.DROP_CONSTRAINT, args,
readName, writeName);
} } | public class class_name {
private Statement compileAlterTableDropLimit(Table t) {
HsqlName readName = null;
HsqlName writeName = null;
boolean cascade = false;
if (token.tokenType == Tokens.RESTRICT) {
read(); // depends on control dependency: [if], data = [none]
} else if (token.tokenType == Tokens.CASCADE) {
read(); // depends on control dependency: [if], data = [none]
cascade = true; // depends on control dependency: [if], data = [none]
}
SchemaObject object = t.getLimitConstraint();
if (object == null) {
throw Error.error(ErrorCode.X_42501);
}
if (cascade) {
writeName = database.getCatalogName(); // depends on control dependency: [if], data = [none]
} else {
writeName = t.getName(); // depends on control dependency: [if], data = [none]
}
Object[] args = new Object[] {
object.getName(), Integer.valueOf(SchemaObject.CONSTRAINT),
Boolean.valueOf(cascade), Boolean.valueOf(false)
};
String sql = getLastPart();
return new StatementSchema(sql, StatementTypes.DROP_CONSTRAINT, args,
readName, writeName);
} } |
public class class_name {
private BaseLocalTransaction createLocalTransaction(String transId) {
BaseLocalTransaction baseLocalTransaction;
try {
baseLocalTransaction = localTransactionConstructor.newInstance(transId, this);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
BaseLocalTransaction.addLocalTransaction(baseLocalTransaction);
return baseLocalTransaction;
} } | public class class_name {
private BaseLocalTransaction createLocalTransaction(String transId) {
BaseLocalTransaction baseLocalTransaction;
try {
baseLocalTransaction = localTransactionConstructor.newInstance(transId, this); // depends on control dependency: [try], data = [none]
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
BaseLocalTransaction.addLocalTransaction(baseLocalTransaction);
return baseLocalTransaction;
} } |
public class class_name {
@SuppressWarnings("unused")
public boolean onTouchEvent(MotionEvent event) {
try {
int pointerCount = multiTouchSupported ? (Integer) m_getPointerCount.invoke(event) : 1;
if (DEBUG)
Log.i("MultiTouch", "Got here 1 - " + multiTouchSupported + " " + mMode + " " + handleSingleTouchEvents + " " + pointerCount);
if (mMode == MODE_NOTHING && !handleSingleTouchEvents && pointerCount == 1)
// Not handling initial single touch events, just pass them on
return false;
if (DEBUG)
Log.i("MultiTouch", "Got here 2");
// Handle history first (we sometimes get history with ACTION_MOVE events)
int action = event.getAction();
int histLen = event.getHistorySize() / pointerCount;
for (int histIdx = 0; histIdx <= histLen; histIdx++) {
// Read from history entries until histIdx == histLen, then read from current event
boolean processingHist = histIdx < histLen;
if (!multiTouchSupported || pointerCount == 1) {
// Use single-pointer methods -- these are needed as a special case (for some weird reason) even if
// multitouch is supported but there's only one touch point down currently -- event.getX(0) etc. throw
// an exception if there's only one point down.
if (DEBUG)
Log.i("MultiTouch", "Got here 3");
xVals[0] = processingHist ? event.getHistoricalX(histIdx) : event.getX();
yVals[0] = processingHist ? event.getHistoricalY(histIdx) : event.getY();
pressureVals[0] = processingHist ? event.getHistoricalPressure(histIdx) : event.getPressure();
} else {
// Read x, y and pressure of each pointer
if (DEBUG)
Log.i("MultiTouch", "Got here 4");
int numPointers = Math.min(pointerCount, MAX_TOUCH_POINTS);
if (DEBUG && pointerCount > MAX_TOUCH_POINTS)
Log.i("MultiTouch", "Got more pointers than MAX_TOUCH_POINTS");
for (int ptrIdx = 0; ptrIdx < numPointers; ptrIdx++) {
int ptrId = (Integer) m_getPointerId.invoke(event, ptrIdx);
pointerIds[ptrIdx] = ptrId;
// N.B. if pointerCount == 1, then the following methods throw an array index out of range exception,
// and the code above is therefore required not just for Android 1.5/1.6 but also for when there is
// only one touch point on the screen -- pointlessly inconsistent :(
xVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalX.invoke(event, ptrIdx, histIdx) : m_getX.invoke(event, ptrIdx));
yVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalY.invoke(event, ptrIdx, histIdx) : m_getY.invoke(event, ptrIdx));
pressureVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalPressure.invoke(event, ptrIdx, histIdx) : m_getPressure
.invoke(event, ptrIdx));
}
}
// Decode event
decodeTouchEvent(pointerCount, xVals, yVals, pressureVals, pointerIds, //
/* action = */processingHist ? MotionEvent.ACTION_MOVE : action, //
/* down = */processingHist ? true : action != MotionEvent.ACTION_UP //
&& (action & ((1 << ACTION_POINTER_INDEX_SHIFT) - 1)) != ACTION_POINTER_UP //
&& action != MotionEvent.ACTION_CANCEL, //
processingHist ? event.getHistoricalEventTime(histIdx) : event.getEventTime());
}
return true;
} catch (Exception e) {
// In case any of the introspection stuff fails (it shouldn't)
Log.e("MultiTouchController", "onTouchEvent() failed", e);
return false;
}
} } | public class class_name {
@SuppressWarnings("unused")
public boolean onTouchEvent(MotionEvent event) {
try {
int pointerCount = multiTouchSupported ? (Integer) m_getPointerCount.invoke(event) : 1;
if (DEBUG)
Log.i("MultiTouch", "Got here 1 - " + multiTouchSupported + " " + mMode + " " + handleSingleTouchEvents + " " + pointerCount);
if (mMode == MODE_NOTHING && !handleSingleTouchEvents && pointerCount == 1)
// Not handling initial single touch events, just pass them on
return false;
if (DEBUG)
Log.i("MultiTouch", "Got here 2");
// Handle history first (we sometimes get history with ACTION_MOVE events)
int action = event.getAction();
int histLen = event.getHistorySize() / pointerCount;
for (int histIdx = 0; histIdx <= histLen; histIdx++) {
// Read from history entries until histIdx == histLen, then read from current event
boolean processingHist = histIdx < histLen;
if (!multiTouchSupported || pointerCount == 1) {
// Use single-pointer methods -- these are needed as a special case (for some weird reason) even if
// multitouch is supported but there's only one touch point down currently -- event.getX(0) etc. throw
// an exception if there's only one point down.
if (DEBUG)
Log.i("MultiTouch", "Got here 3");
xVals[0] = processingHist ? event.getHistoricalX(histIdx) : event.getX(); // depends on control dependency: [if], data = [none]
yVals[0] = processingHist ? event.getHistoricalY(histIdx) : event.getY(); // depends on control dependency: [if], data = [none]
pressureVals[0] = processingHist ? event.getHistoricalPressure(histIdx) : event.getPressure(); // depends on control dependency: [if], data = [none]
} else {
// Read x, y and pressure of each pointer
if (DEBUG)
Log.i("MultiTouch", "Got here 4");
int numPointers = Math.min(pointerCount, MAX_TOUCH_POINTS);
if (DEBUG && pointerCount > MAX_TOUCH_POINTS)
Log.i("MultiTouch", "Got more pointers than MAX_TOUCH_POINTS");
for (int ptrIdx = 0; ptrIdx < numPointers; ptrIdx++) {
int ptrId = (Integer) m_getPointerId.invoke(event, ptrIdx);
pointerIds[ptrIdx] = ptrId; // depends on control dependency: [for], data = [ptrIdx]
// N.B. if pointerCount == 1, then the following methods throw an array index out of range exception,
// and the code above is therefore required not just for Android 1.5/1.6 but also for when there is
// only one touch point on the screen -- pointlessly inconsistent :(
xVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalX.invoke(event, ptrIdx, histIdx) : m_getX.invoke(event, ptrIdx)); // depends on control dependency: [for], data = [ptrIdx]
yVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalY.invoke(event, ptrIdx, histIdx) : m_getY.invoke(event, ptrIdx)); // depends on control dependency: [for], data = [ptrIdx]
pressureVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalPressure.invoke(event, ptrIdx, histIdx) : m_getPressure
.invoke(event, ptrIdx)); // depends on control dependency: [for], data = [ptrIdx]
}
}
// Decode event
decodeTouchEvent(pointerCount, xVals, yVals, pressureVals, pointerIds, //
/* action = */processingHist ? MotionEvent.ACTION_MOVE : action, //
/* down = */processingHist ? true : action != MotionEvent.ACTION_UP //
&& (action & ((1 << ACTION_POINTER_INDEX_SHIFT) - 1)) != ACTION_POINTER_UP //
&& action != MotionEvent.ACTION_CANCEL, //
processingHist ? event.getHistoricalEventTime(histIdx) : event.getEventTime()); // depends on control dependency: [for], data = [none]
}
return true; // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// In case any of the introspection stuff fails (it shouldn't)
Log.e("MultiTouchController", "onTouchEvent() failed", e);
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static GeometryCriterion buildGeometryCriterion(final Geometry geometry, final MapWidget mapWidget,
VectorLayer layer) {
List<String> layers;
if (null == layer) {
layers = getVisibleServerLayerIds(mapWidget.getMapModel());
} else {
layers = new ArrayList<String>();
layers.add(layer.getServerLayerId());
}
return new GeometryCriterion(layers, GeometryConverter.toDto(geometry));
} } | public class class_name {
public static GeometryCriterion buildGeometryCriterion(final Geometry geometry, final MapWidget mapWidget,
VectorLayer layer) {
List<String> layers;
if (null == layer) {
layers = getVisibleServerLayerIds(mapWidget.getMapModel()); // depends on control dependency: [if], data = [none]
} else {
layers = new ArrayList<String>(); // depends on control dependency: [if], data = [none]
layers.add(layer.getServerLayerId()); // depends on control dependency: [if], data = [none]
}
return new GeometryCriterion(layers, GeometryConverter.toDto(geometry));
} } |
public class class_name {
protected void putCached(String keySpace, String columnFamily, String key, Map<String, Object> encodedProperties,
boolean probablyNew) throws StorageClientException {
String cacheKey = null;
if (sharedCache != null) {
cacheKey = getCacheKey(keySpace, columnFamily, key);
}
if (sharedCache != null && !probablyNew) {
CacheHolder ch = getFromCacheInternal(cacheKey);
if (ch != null && ch.isLocked(this.managerId)) {
LOGGER.debug("Is Locked {} ", ch);
return; // catch the case where another method creates while
// something is in the cache.
// this is a big assumption since if the item is not in the
// cache it will get updated
// there is no difference in sparsemap between create and
// update, they are all insert operations
// what we are really saying here is that inorder to update the
// item you have to have just got it
// and if you failed to get it, your update must have been a
// create operation. As long as the dwell time
// in the cache is longer than the lifetime of an active session
// then this will be true.
// if the lifetime of an active session is longer (like with a
// long running background operation)
// then you should expect to see race conditions at this point
// since the marker in the cache will have
// gone, and the marker in the database has gone, so the put
// operation, must be a create operation.
// To change this behavior we would need to differentiate more
// strongly between new and update and change
// probablyNew into certainlyNew, but that would probably break
// the BASIC assumption of the whole system.
// Update 2011-12-06 related to issue 136
// I am not certain this code is correct. What happens if the
// session wants to remove and then add items.
// the session will never get past this point, since sitting in
// the cache is a null CacheHolder preventing the session
// removing then adding.
// also, how long should the null cache holder be placed in
// there for ?
// I think the solution is to bind the null Cache holder to the
// instance of the caching manager that created it,
// let the null Cache holder last for 10s, and during that time
// only the CachingManagerImpl that created it can remove it.
}
}
LOGGER.debug("Saving {} {} {} {} ", new Object[] { keySpace, columnFamily, key, encodedProperties });
client.insert(keySpace, columnFamily, key, encodedProperties, probablyNew);
if (sharedCache != null) {
// if we just added a value in, remove the key so that any stale
// state (including a previously deleted object is removed)
sharedCache.remove(cacheKey);
}
} } | public class class_name {
protected void putCached(String keySpace, String columnFamily, String key, Map<String, Object> encodedProperties,
boolean probablyNew) throws StorageClientException {
String cacheKey = null;
if (sharedCache != null) {
cacheKey = getCacheKey(keySpace, columnFamily, key);
}
if (sharedCache != null && !probablyNew) {
CacheHolder ch = getFromCacheInternal(cacheKey);
if (ch != null && ch.isLocked(this.managerId)) {
LOGGER.debug("Is Locked {} ", ch); // depends on control dependency: [if], data = [none]
return; // catch the case where another method creates while // depends on control dependency: [if], data = [none]
// something is in the cache.
// this is a big assumption since if the item is not in the
// cache it will get updated
// there is no difference in sparsemap between create and
// update, they are all insert operations
// what we are really saying here is that inorder to update the
// item you have to have just got it
// and if you failed to get it, your update must have been a
// create operation. As long as the dwell time
// in the cache is longer than the lifetime of an active session
// then this will be true.
// if the lifetime of an active session is longer (like with a
// long running background operation)
// then you should expect to see race conditions at this point
// since the marker in the cache will have
// gone, and the marker in the database has gone, so the put
// operation, must be a create operation.
// To change this behavior we would need to differentiate more
// strongly between new and update and change
// probablyNew into certainlyNew, but that would probably break
// the BASIC assumption of the whole system.
// Update 2011-12-06 related to issue 136
// I am not certain this code is correct. What happens if the
// session wants to remove and then add items.
// the session will never get past this point, since sitting in
// the cache is a null CacheHolder preventing the session
// removing then adding.
// also, how long should the null cache holder be placed in
// there for ?
// I think the solution is to bind the null Cache holder to the
// instance of the caching manager that created it,
// let the null Cache holder last for 10s, and during that time
// only the CachingManagerImpl that created it can remove it.
}
}
LOGGER.debug("Saving {} {} {} {} ", new Object[] { keySpace, columnFamily, key, encodedProperties });
client.insert(keySpace, columnFamily, key, encodedProperties, probablyNew);
if (sharedCache != null) {
// if we just added a value in, remove the key so that any stale
// state (including a previously deleted object is removed)
sharedCache.remove(cacheKey);
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.