code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public ISynchronizationPoint<IOException> write(char[] chars, int offset, int length) {
ISynchronizationPoint<IOException> last = lastWrite;
if (length == 0) return last;
if (last.isUnblocked()) {
lastWrite = stream.writeAsync(chars, offset, length);
return lastWrite;
}
SynchronizationPoint<IOException> ours = new SynchronizationPoint<>();
lastWrite = ours;
last.listenInline(() -> { stream.writeAsync(chars, offset, length).listenInline(ours); }, ours);
return ours;
} } | public class class_name {
public ISynchronizationPoint<IOException> write(char[] chars, int offset, int length) {
ISynchronizationPoint<IOException> last = lastWrite;
if (length == 0) return last;
if (last.isUnblocked()) {
lastWrite = stream.writeAsync(chars, offset, length);
// depends on control dependency: [if], data = [none]
return lastWrite;
// depends on control dependency: [if], data = [none]
}
SynchronizationPoint<IOException> ours = new SynchronizationPoint<>();
lastWrite = ours;
last.listenInline(() -> { stream.writeAsync(chars, offset, length).listenInline(ours); }, ours);
return ours;
} } |
public class class_name {
public boolean createDictionaryEntry(String key, long count, SuggestionStage staging) {
if (count <= 0) {
if (this.countThreshold > 0) {
return false; // no point doing anything if count is zero, as it can't change anything
}
count = 0;
}
long countPrevious;
// look first in below threshold words, update count, and allow promotion to correct spelling word if count reaches threshold
// threshold must be >1 for there to be the possibility of low threshold words
if (countThreshold > 1 && belowThresholdWords.containsKey(key)) {
countPrevious = belowThresholdWords.get(key);
// calculate new count for below threshold word
count = (Long.MAX_VALUE - countPrevious > count) ? countPrevious + count : Long.MAX_VALUE;
// has reached threshold - remove from below threshold collection (it will be added to correct words below)
if (count >= countThreshold) {
belowThresholdWords.remove(key);
} else {
belowThresholdWords.put(key, count); // = count;
return false;
}
} else if (words.containsKey(key)) {
countPrevious = words.get(key);
// just update count if it's an already added above threshold word
count = (Long.MAX_VALUE - countPrevious > count) ? countPrevious + count : Long.MAX_VALUE;
words.put(key, count);
return false;
} else if (count < countThreshold) {
// new or existing below threshold word
belowThresholdWords.put(key, count);
return false;
}
// what we have at this point is a new, above threshold word
words.put(key, count);
if (key.equals("can't")) {
System.out.println("Added to words..!");
}
//edits/suggestions are created only once, no matter how often word occurs
//edits/suggestions are created only as soon as the word occurs in the corpus,
//even if the same term existed before in the dictionary as an edit from another word
if (key.length() > maxLength) {
maxLength = key.length();
}
//create deletes
HashSet<String> edits = editsPrefix(key);
// if not staging suggestions, put directly into main data structure
if (staging != null) {
edits.forEach(delete -> staging.add(getStringHash(delete), key));
} else {
if (deletes == null) {
this.deletes = new HashMap<>(initialCapacity); //initialisierung
}
edits.forEach(delete -> {
int deleteHash = getStringHash(delete);
String[] suggestions;
if (deletes.containsKey(deleteHash)) {
suggestions = deletes.get(deleteHash);
String[] newSuggestions = Arrays.copyOf(suggestions, suggestions.length + 1);
deletes.put(deleteHash, newSuggestions);
suggestions = newSuggestions;
} else {
suggestions = new String[1];
deletes.put(deleteHash, suggestions);
}
suggestions[suggestions.length - 1] = key;
});
}
return true;
} } | public class class_name {
public boolean createDictionaryEntry(String key, long count, SuggestionStage staging) {
if (count <= 0) {
if (this.countThreshold > 0) {
return false; // no point doing anything if count is zero, as it can't change anything // depends on control dependency: [if], data = [none]
}
count = 0; // depends on control dependency: [if], data = [none]
}
long countPrevious;
// look first in below threshold words, update count, and allow promotion to correct spelling word if count reaches threshold
// threshold must be >1 for there to be the possibility of low threshold words
if (countThreshold > 1 && belowThresholdWords.containsKey(key)) {
countPrevious = belowThresholdWords.get(key); // depends on control dependency: [if], data = [none]
// calculate new count for below threshold word
count = (Long.MAX_VALUE - countPrevious > count) ? countPrevious + count : Long.MAX_VALUE; // depends on control dependency: [if], data = [none]
// has reached threshold - remove from below threshold collection (it will be added to correct words below)
if (count >= countThreshold) {
belowThresholdWords.remove(key); // depends on control dependency: [if], data = [none]
} else {
belowThresholdWords.put(key, count); // = count; // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
} else if (words.containsKey(key)) {
countPrevious = words.get(key); // depends on control dependency: [if], data = [none]
// just update count if it's an already added above threshold word
count = (Long.MAX_VALUE - countPrevious > count) ? countPrevious + count : Long.MAX_VALUE; // depends on control dependency: [if], data = [none]
words.put(key, count); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
} else if (count < countThreshold) {
// new or existing below threshold word
belowThresholdWords.put(key, count); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
// what we have at this point is a new, above threshold word
words.put(key, count);
if (key.equals("can't")) {
System.out.println("Added to words..!"); // depends on control dependency: [if], data = [none]
}
//edits/suggestions are created only once, no matter how often word occurs
//edits/suggestions are created only as soon as the word occurs in the corpus,
//even if the same term existed before in the dictionary as an edit from another word
if (key.length() > maxLength) {
maxLength = key.length(); // depends on control dependency: [if], data = [none]
}
//create deletes
HashSet<String> edits = editsPrefix(key);
// if not staging suggestions, put directly into main data structure
if (staging != null) {
edits.forEach(delete -> staging.add(getStringHash(delete), key)); // depends on control dependency: [if], data = [none]
} else {
if (deletes == null) {
this.deletes = new HashMap<>(initialCapacity); //initialisierung // depends on control dependency: [if], data = [none]
}
edits.forEach(delete -> {
int deleteHash = getStringHash(delete);
String[] suggestions;
if (deletes.containsKey(deleteHash)) {
suggestions = deletes.get(deleteHash);
String[] newSuggestions = Arrays.copyOf(suggestions, suggestions.length + 1);
deletes.put(deleteHash, newSuggestions);
suggestions = newSuggestions;
} else {
suggestions = new String[1];
deletes.put(deleteHash, suggestions);
}
suggestions[suggestions.length - 1] = key;
}); // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
@Override
protected List<Runner> getChildren() {
// one runner for each parameter
List<Runner> runners = super.getChildren();
List<Runner> proxyRunners = new ArrayList<>(runners.size());
for (Runner runner : runners) {
// if the next line fails then the internal of Parameterized.class has been updated since this works with JUnit 4.11
BlockJUnit4ClassRunner blockJUnit4ClassRunner = (BlockJUnit4ClassRunner) runner;
Description description = blockJUnit4ClassRunner.getDescription();
String name = description.getDisplayName();
try {
proxyRunners
.add(new ProxyTestClassRunnerForParameters(mTestClass, mContainerUrl, name));
} catch (InitializationError e) {
throw new RuntimeException("Could not create runner for paramamter " + name, e);
}
}
return proxyRunners;
} } | public class class_name {
@Override
protected List<Runner> getChildren() {
// one runner for each parameter
List<Runner> runners = super.getChildren();
List<Runner> proxyRunners = new ArrayList<>(runners.size());
for (Runner runner : runners) {
// if the next line fails then the internal of Parameterized.class has been updated since this works with JUnit 4.11
BlockJUnit4ClassRunner blockJUnit4ClassRunner = (BlockJUnit4ClassRunner) runner;
Description description = blockJUnit4ClassRunner.getDescription();
String name = description.getDisplayName();
try {
proxyRunners
.add(new ProxyTestClassRunnerForParameters(mTestClass, mContainerUrl, name)); // depends on control dependency: [try], data = [none]
} catch (InitializationError e) {
throw new RuntimeException("Could not create runner for paramamter " + name, e);
} // depends on control dependency: [catch], data = [none]
}
return proxyRunners;
} } |
public class class_name {
public boolean canAcceptChild() {
if (maxChildren == 0) {
rejectReason = getDisplayName() + " does not accept any children.";
} else if (getChildCount() >= maxChildren) {
rejectReason = "Maximum child count exceeded for " + getDisplayName() + ".";
} else {
rejectReason = null;
}
return rejectReason == null;
} } | public class class_name {
public boolean canAcceptChild() {
if (maxChildren == 0) {
rejectReason = getDisplayName() + " does not accept any children."; // depends on control dependency: [if], data = [none]
} else if (getChildCount() >= maxChildren) {
rejectReason = "Maximum child count exceeded for " + getDisplayName() + "."; // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
} else {
rejectReason = null; // depends on control dependency: [if], data = [none]
}
return rejectReason == null;
} } |
public class class_name {
@Override
public ClassLoader getClassLoader() {
ClassLoader classLoader = this.initialClass.getClassLoader();
if (classLoader == null) {
classLoader = application.getClassLoader();
}
return classLoader;
} } | public class class_name {
@Override
public ClassLoader getClassLoader() {
ClassLoader classLoader = this.initialClass.getClassLoader();
if (classLoader == null) {
classLoader = application.getClassLoader(); // depends on control dependency: [if], data = [none]
}
return classLoader;
} } |
public class class_name {
@Override
public void stopped() {
// Clear endpoints
writeLock.lock();
try {
listeners.clear();
} finally {
// Clear caches
emitterCache.clear();
broadcasterCache.clear();
localBroadcasterCache.clear();
writeLock.unlock();
}
} } | public class class_name {
@Override
public void stopped() {
// Clear endpoints
writeLock.lock();
try {
listeners.clear(); // depends on control dependency: [try], data = [none]
} finally {
// Clear caches
emitterCache.clear();
broadcasterCache.clear();
localBroadcasterCache.clear();
writeLock.unlock();
}
} } |
public class class_name {
public void sync(List<Dml> dmls) {
List<Dml> dmlList = new ArrayList<>();
for (Dml dml : dmls) {
String destination = StringUtils.trimToEmpty(dml.getDestination());
String database = dml.getDatabase();
MirrorDbConfig mirrorDbConfig = mirrorDbConfigCache.get(destination + "." + database);
if (mirrorDbConfig == null) {
continue;
}
if (mirrorDbConfig.getMappingConfig() == null) {
continue;
}
if (dml.getGroupId() != null && StringUtils.isNotEmpty(mirrorDbConfig.getMappingConfig().getGroupId())) {
if (!mirrorDbConfig.getMappingConfig().getGroupId().equals(dml.getGroupId())) {
continue; // 如果groupId不匹配则过滤
}
}
if (dml.getIsDdl() != null && dml.getIsDdl() && StringUtils.isNotEmpty(dml.getSql())) {
// DDL
if (logger.isDebugEnabled()) {
logger.debug("DDL: {}", JSON.toJSONString(dml, SerializerFeature.WriteMapNullValue));
}
executeDdl(mirrorDbConfig, dml);
rdbSyncService.getColumnsTypeCache().remove(destination + "." + database + "." + dml.getTable());
mirrorDbConfig.getTableConfig().remove(dml.getTable()); // 删除对应库表配置
} else {
// DML
initMappingConfig(dml.getTable(), mirrorDbConfig.getMappingConfig(), mirrorDbConfig, dml);
dmlList.add(dml);
}
}
if (!dmlList.isEmpty()) {
rdbSyncService.sync(dmlList, dml -> {
MirrorDbConfig mirrorDbConfig = mirrorDbConfigCache.get(dml.getDestination() + "." + dml.getDatabase());
if (mirrorDbConfig == null) {
return false;
}
String table = dml.getTable();
MappingConfig config = mirrorDbConfig.getTableConfig().get(table);
if (config == null) {
return false;
}
if (config.getConcurrent()) {
List<SingleDml> singleDmls = SingleDml.dml2SingleDmls(dml);
singleDmls.forEach(singleDml -> {
int hash = rdbSyncService.pkHash(config.getDbMapping(), singleDml.getData());
RdbSyncService.SyncItem syncItem = new RdbSyncService.SyncItem(config, singleDml);
rdbSyncService.getDmlsPartition()[hash].add(syncItem);
});
} else {
int hash = 0;
List<SingleDml> singleDmls = SingleDml.dml2SingleDmls(dml);
singleDmls.forEach(singleDml -> {
RdbSyncService.SyncItem syncItem = new RdbSyncService.SyncItem(config, singleDml);
rdbSyncService.getDmlsPartition()[hash].add(syncItem);
});
}
return true;
});
}
} } | public class class_name {
public void sync(List<Dml> dmls) {
List<Dml> dmlList = new ArrayList<>();
for (Dml dml : dmls) {
String destination = StringUtils.trimToEmpty(dml.getDestination());
String database = dml.getDatabase();
MirrorDbConfig mirrorDbConfig = mirrorDbConfigCache.get(destination + "." + database);
if (mirrorDbConfig == null) {
continue;
}
if (mirrorDbConfig.getMappingConfig() == null) {
continue;
}
if (dml.getGroupId() != null && StringUtils.isNotEmpty(mirrorDbConfig.getMappingConfig().getGroupId())) {
if (!mirrorDbConfig.getMappingConfig().getGroupId().equals(dml.getGroupId())) {
continue; // 如果groupId不匹配则过滤
}
}
if (dml.getIsDdl() != null && dml.getIsDdl() && StringUtils.isNotEmpty(dml.getSql())) {
// DDL
if (logger.isDebugEnabled()) {
logger.debug("DDL: {}", JSON.toJSONString(dml, SerializerFeature.WriteMapNullValue)); // depends on control dependency: [if], data = [none]
}
executeDdl(mirrorDbConfig, dml); // depends on control dependency: [if], data = [none]
rdbSyncService.getColumnsTypeCache().remove(destination + "." + database + "." + dml.getTable()); // depends on control dependency: [if], data = [none]
mirrorDbConfig.getTableConfig().remove(dml.getTable()); // 删除对应库表配置 // depends on control dependency: [if], data = [none]
} else {
// DML
initMappingConfig(dml.getTable(), mirrorDbConfig.getMappingConfig(), mirrorDbConfig, dml); // depends on control dependency: [if], data = [none]
dmlList.add(dml); // depends on control dependency: [if], data = [none]
}
}
if (!dmlList.isEmpty()) {
rdbSyncService.sync(dmlList, dml -> {
MirrorDbConfig mirrorDbConfig = mirrorDbConfigCache.get(dml.getDestination() + "." + dml.getDatabase()); // depends on control dependency: [if], data = [none]
if (mirrorDbConfig == null) {
return false; // depends on control dependency: [if], data = [none]
}
String table = dml.getTable();
MappingConfig config = mirrorDbConfig.getTableConfig().get(table);
if (config == null) {
return false; // depends on control dependency: [if], data = [none]
}
if (config.getConcurrent()) {
List<SingleDml> singleDmls = SingleDml.dml2SingleDmls(dml);
singleDmls.forEach(singleDml -> {
int hash = rdbSyncService.pkHash(config.getDbMapping(), singleDml.getData()); // depends on control dependency: [if], data = [none]
RdbSyncService.SyncItem syncItem = new RdbSyncService.SyncItem(config, singleDml);
rdbSyncService.getDmlsPartition()[hash].add(syncItem); // depends on control dependency: [if], data = [none]
});
} else {
int hash = 0;
List<SingleDml> singleDmls = SingleDml.dml2SingleDmls(dml);
singleDmls.forEach(singleDml -> {
RdbSyncService.SyncItem syncItem = new RdbSyncService.SyncItem(config, singleDml); // depends on control dependency: [if], data = [none]
rdbSyncService.getDmlsPartition()[hash].add(syncItem); // depends on control dependency: [if], data = [none]
});
}
return true;
});
}
} } |
public class class_name {
protected void setError(int newPosition, String error,
boolean currentExisting) {
if (!currentExisting) {
newBasicValueSumList[newPosition] = operations.getZero1();
newBasicValueNList[newPosition] = 0;
}
newErrorNumber[newPosition]++;
if (newErrorList[newPosition].containsKey(error)) {
newErrorList[newPosition].put(error,
newErrorList[newPosition].get(error) + 1);
} else {
newErrorList[newPosition].put(error, 1);
}
} } | public class class_name {
protected void setError(int newPosition, String error,
boolean currentExisting) {
if (!currentExisting) {
newBasicValueSumList[newPosition] = operations.getZero1(); // depends on control dependency: [if], data = [none]
newBasicValueNList[newPosition] = 0; // depends on control dependency: [if], data = [none]
}
newErrorNumber[newPosition]++;
if (newErrorList[newPosition].containsKey(error)) {
newErrorList[newPosition].put(error,
newErrorList[newPosition].get(error) + 1); // depends on control dependency: [if], data = [none]
} else {
newErrorList[newPosition].put(error, 1); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void deleteTemplate(File templateFile) {
ThymeLeafTemplateImplementation template = getTemplateByFile(templateFile);
if (template != null) {
deleteTemplate(template);
}
} } | public class class_name {
public void deleteTemplate(File templateFile) {
ThymeLeafTemplateImplementation template = getTemplateByFile(templateFile);
if (template != null) {
deleteTemplate(template); // depends on control dependency: [if], data = [(template]
}
} } |
public class class_name {
private void writeRequestJoinResponse(
int hostId,
JoinAcceptor.PleaDecision decision,
SocketChannel socket,
MessagingChannel messagingChannel) throws Exception {
JSONObject jsObj = new JSONObject();
jsObj.put(SocketJoiner.ACCEPTED, decision.accepted);
if (decision.accepted) {
/*
* Tell the new node what its host id is
*/
jsObj.put(SocketJoiner.NEW_HOST_ID, hostId);
/*
* Echo back the address that the node connected from
*/
jsObj.put(SocketJoiner.REPORTED_ADDRESS,
((InetSocketAddress) socket.socket().getRemoteSocketAddress()).getAddress().getHostAddress());
/*
* Create an array containing an id for every node including this one
* even though the connection has already been made
*/
JSONArray jsArray = new JSONArray();
JSONObject hostObj = new JSONObject();
hostObj.put(SocketJoiner.HOST_ID, getHostId());
hostObj.put(SocketJoiner.ADDRESS,
m_config.internalInterface.isEmpty() ?
socket.socket().getLocalAddress().getHostAddress() :
m_config.internalInterface);
hostObj.put(SocketJoiner.PORT, m_config.internalPort);
jsArray.put(hostObj);
for (Entry<Integer, Collection<ForeignHost>> entry : m_foreignHosts.asMap().entrySet()) {
if (entry.getValue().isEmpty()) {
continue;
}
int hsId = entry.getKey();
Iterator<ForeignHost> it = entry.getValue().iterator();
// all fhs to same host have the same address and port
ForeignHost fh = it.next();
hostObj = new JSONObject();
hostObj.put(SocketJoiner.HOST_ID, hsId);
hostObj.put(SocketJoiner.ADDRESS,
fh.m_listeningAddress.getAddress().getHostAddress());
hostObj.put(SocketJoiner.PORT, fh.m_listeningAddress.getPort());
jsArray.put(hostObj);
}
jsObj.put(SocketJoiner.HOSTS, jsArray);
}
else {
jsObj.put(SocketJoiner.REASON, decision.errMsg);
jsObj.put(SocketJoiner.MAY_RETRY, decision.mayRetry);
}
byte messageBytes[] = jsObj.toString(4).getBytes("UTF-8");
ByteBuffer message = ByteBuffer.allocate(4 + messageBytes.length);
message.putInt(messageBytes.length);
message.put(messageBytes).flip();
messagingChannel.writeMessage(message);
} } | public class class_name {
private void writeRequestJoinResponse(
int hostId,
JoinAcceptor.PleaDecision decision,
SocketChannel socket,
MessagingChannel messagingChannel) throws Exception {
JSONObject jsObj = new JSONObject();
jsObj.put(SocketJoiner.ACCEPTED, decision.accepted);
if (decision.accepted) {
/*
* Tell the new node what its host id is
*/
jsObj.put(SocketJoiner.NEW_HOST_ID, hostId);
/*
* Echo back the address that the node connected from
*/
jsObj.put(SocketJoiner.REPORTED_ADDRESS,
((InetSocketAddress) socket.socket().getRemoteSocketAddress()).getAddress().getHostAddress());
/*
* Create an array containing an id for every node including this one
* even though the connection has already been made
*/
JSONArray jsArray = new JSONArray();
JSONObject hostObj = new JSONObject();
hostObj.put(SocketJoiner.HOST_ID, getHostId());
hostObj.put(SocketJoiner.ADDRESS,
m_config.internalInterface.isEmpty() ?
socket.socket().getLocalAddress().getHostAddress() :
m_config.internalInterface);
hostObj.put(SocketJoiner.PORT, m_config.internalPort);
jsArray.put(hostObj);
for (Entry<Integer, Collection<ForeignHost>> entry : m_foreignHosts.asMap().entrySet()) {
if (entry.getValue().isEmpty()) {
continue;
}
int hsId = entry.getKey();
Iterator<ForeignHost> it = entry.getValue().iterator();
// all fhs to same host have the same address and port
ForeignHost fh = it.next();
hostObj = new JSONObject(); // depends on control dependency: [for], data = [none]
hostObj.put(SocketJoiner.HOST_ID, hsId); // depends on control dependency: [for], data = [none]
hostObj.put(SocketJoiner.ADDRESS,
fh.m_listeningAddress.getAddress().getHostAddress()); // depends on control dependency: [for], data = [none]
hostObj.put(SocketJoiner.PORT, fh.m_listeningAddress.getPort()); // depends on control dependency: [for], data = [none]
jsArray.put(hostObj); // depends on control dependency: [for], data = [none]
}
jsObj.put(SocketJoiner.HOSTS, jsArray);
}
else {
jsObj.put(SocketJoiner.REASON, decision.errMsg);
jsObj.put(SocketJoiner.MAY_RETRY, decision.mayRetry);
}
byte messageBytes[] = jsObj.toString(4).getBytes("UTF-8");
ByteBuffer message = ByteBuffer.allocate(4 + messageBytes.length);
message.putInt(messageBytes.length);
message.put(messageBytes).flip();
messagingChannel.writeMessage(message);
} } |
public class class_name {
@Nullable
@WorkerThread
private LottieComposition fetchFromCache() {
Pair<FileExtension, InputStream> cacheResult = networkCache.fetch();
if (cacheResult == null) {
return null;
}
FileExtension extension = cacheResult.first;
InputStream inputStream = cacheResult.second;
LottieResult<LottieComposition> result;
if (extension == FileExtension.ZIP) {
result = LottieCompositionFactory.fromZipStreamSync(new ZipInputStream(inputStream), url);
} else {
result = LottieCompositionFactory.fromJsonInputStreamSync(inputStream, url);
}
if (result.getValue() != null) {
return result.getValue();
}
return null;
} } | public class class_name {
@Nullable
@WorkerThread
private LottieComposition fetchFromCache() {
Pair<FileExtension, InputStream> cacheResult = networkCache.fetch();
if (cacheResult == null) {
return null; // depends on control dependency: [if], data = [none]
}
FileExtension extension = cacheResult.first;
InputStream inputStream = cacheResult.second;
LottieResult<LottieComposition> result;
if (extension == FileExtension.ZIP) {
result = LottieCompositionFactory.fromZipStreamSync(new ZipInputStream(inputStream), url); // depends on control dependency: [if], data = [none]
} else {
result = LottieCompositionFactory.fromJsonInputStreamSync(inputStream, url); // depends on control dependency: [if], data = [none]
}
if (result.getValue() != null) {
return result.getValue(); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
@Override
public void finalizeFirstPassE() {
double s = 1. / wsum;
for(int i = 0; i < mean.length; i++) {
mean[i] *= s;
}
} } | public class class_name {
@Override
public void finalizeFirstPassE() {
double s = 1. / wsum;
for(int i = 0; i < mean.length; i++) {
mean[i] *= s; // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
protected Collection<Asset> getFilteredAssets(Collection<ResourceType> types, Collection<String> productIds, Visibility visibility, Collection<String> productVersions,
boolean unboundedMaxVersion) throws IOException, RequestFailureException {
Map<FilterableAttribute, Collection<String>> filters = new HashMap<FilterableAttribute, Collection<String>>();
if (types != null && !types.isEmpty()) {
Collection<String> typeValues = new HashSet<String>();
for (ResourceType type : types) {
typeValues.add(type.getValue());
}
filters.put(FilterableAttribute.TYPE, typeValues);
}
filters.put(FilterableAttribute.PRODUCT_ID, productIds);
if (visibility != null) {
filters.put(FilterableAttribute.VISIBILITY, Collections.singleton(visibility.toString()));
}
filters.put(FilterableAttribute.PRODUCT_MIN_VERSION, productVersions);
if (unboundedMaxVersion) {
filters.put(FilterableAttribute.PRODUCT_HAS_MAX_VERSION, Collections.singleton(Boolean.FALSE.toString()));
}
return getFilteredAssets(filters);
} } | public class class_name {
protected Collection<Asset> getFilteredAssets(Collection<ResourceType> types, Collection<String> productIds, Visibility visibility, Collection<String> productVersions,
boolean unboundedMaxVersion) throws IOException, RequestFailureException {
Map<FilterableAttribute, Collection<String>> filters = new HashMap<FilterableAttribute, Collection<String>>();
if (types != null && !types.isEmpty()) {
Collection<String> typeValues = new HashSet<String>();
for (ResourceType type : types) {
typeValues.add(type.getValue()); // depends on control dependency: [for], data = [type]
}
filters.put(FilterableAttribute.TYPE, typeValues);
}
filters.put(FilterableAttribute.PRODUCT_ID, productIds);
if (visibility != null) {
filters.put(FilterableAttribute.VISIBILITY, Collections.singleton(visibility.toString()));
}
filters.put(FilterableAttribute.PRODUCT_MIN_VERSION, productVersions);
if (unboundedMaxVersion) {
filters.put(FilterableAttribute.PRODUCT_HAS_MAX_VERSION, Collections.singleton(Boolean.FALSE.toString()));
}
return getFilteredAssets(filters);
} } |
public class class_name {
public void marshall(HostKeyAttributes hostKeyAttributes, ProtocolMarshaller protocolMarshaller) {
if (hostKeyAttributes == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(hostKeyAttributes.getAlgorithm(), ALGORITHM_BINDING);
protocolMarshaller.marshall(hostKeyAttributes.getPublicKey(), PUBLICKEY_BINDING);
protocolMarshaller.marshall(hostKeyAttributes.getWitnessedAt(), WITNESSEDAT_BINDING);
protocolMarshaller.marshall(hostKeyAttributes.getFingerprintSHA1(), FINGERPRINTSHA1_BINDING);
protocolMarshaller.marshall(hostKeyAttributes.getFingerprintSHA256(), FINGERPRINTSHA256_BINDING);
protocolMarshaller.marshall(hostKeyAttributes.getNotValidBefore(), NOTVALIDBEFORE_BINDING);
protocolMarshaller.marshall(hostKeyAttributes.getNotValidAfter(), NOTVALIDAFTER_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(HostKeyAttributes hostKeyAttributes, ProtocolMarshaller protocolMarshaller) {
if (hostKeyAttributes == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(hostKeyAttributes.getAlgorithm(), ALGORITHM_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(hostKeyAttributes.getPublicKey(), PUBLICKEY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(hostKeyAttributes.getWitnessedAt(), WITNESSEDAT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(hostKeyAttributes.getFingerprintSHA1(), FINGERPRINTSHA1_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(hostKeyAttributes.getFingerprintSHA256(), FINGERPRINTSHA256_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(hostKeyAttributes.getNotValidBefore(), NOTVALIDBEFORE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(hostKeyAttributes.getNotValidAfter(), NOTVALIDAFTER_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 Date getDataAttrAsDate(String dPath, String dateTimeFormat) {
Lock lock = lockForRead();
try {
return DPathUtils.getDate(dataJson, dPath, dateTimeFormat);
} finally {
lock.unlock();
}
} } | public class class_name {
public Date getDataAttrAsDate(String dPath, String dateTimeFormat) {
Lock lock = lockForRead();
try {
return DPathUtils.getDate(dataJson, dPath, dateTimeFormat); // depends on control dependency: [try], data = [none]
} finally {
lock.unlock();
}
} } |
public class class_name {
protected void processUnit (Object unit)
{
long start = System.nanoTime();
// keep track of the largest queue size we've seen
int queueSize = _evqueue.size();
if (queueSize > _current.maxQueueSize) {
_current.maxQueueSize = queueSize;
}
try {
if (unit instanceof Runnable) {
// if this is a runnable, it's just an executable unit that should be invoked
((Runnable)unit).run();
} else {
DEvent event = (DEvent)unit;
// if this event is on a proxied object, forward it to the owning manager
ProxyReference proxy = _proxies.get(event.getTargetOid());
if (proxy != null) {
// rewrite the oid into the originating manager's id space
event.setTargetOid(proxy.origObjectId);
// then pass it on to the originating manager to handle
proxy.origManager.postEvent(event);
} else if (event instanceof CompoundEvent) {
processCompoundEvent((CompoundEvent)event);
} else {
processEvent(event);
}
}
} catch (VirtualMachineError e) {
handleFatalError(unit, e);
} catch (Throwable t) {
log.warning("Execution unit failed", "unit", unit, t);
}
// compute the elapsed time in microseconds
long elapsed = (System.nanoTime() - start)/1000;
// report excessively long units
if (elapsed > 500000 && !(unit instanceof LongRunnable)) {
log.warning("Long dobj unit " + StringUtil.shortClassName(unit), "unit", unit,
"time", (elapsed/1000) + "ms");
}
// periodically sample and record the time spent processing a unit
if (UNIT_PROF_ENABLED && _eventCount % _unitProfInterval == 0) {
String cname;
// do some jiggery pokery to get more fine grained profiling details on certain
// "popular" unit types
if (unit instanceof Interval.RunBuddy) {
cname = StringUtil.shortClassName(
((Interval.RunBuddy)unit).getIntervalClassName());
} else if (unit instanceof InvocationRequestEvent) {
InvocationRequestEvent ire = (InvocationRequestEvent)unit;
Class<?> c = _invmgr.getDispatcherClass(ire.getInvCode());
cname = (c == null) ? "dobj.InvocationRequestEvent:(no longer registered)" :
StringUtil.shortClassName(c) + ":" + ire.getMethodId();
} else {
cname = StringUtil.shortClassName(unit);
}
UnitProfile uprof = _profiles.get(cname);
if (uprof == null) {
_profiles.put(cname, uprof = new UnitProfile());
}
uprof.record(elapsed);
}
} } | public class class_name {
protected void processUnit (Object unit)
{
long start = System.nanoTime();
// keep track of the largest queue size we've seen
int queueSize = _evqueue.size();
if (queueSize > _current.maxQueueSize) {
_current.maxQueueSize = queueSize; // depends on control dependency: [if], data = [none]
}
try {
if (unit instanceof Runnable) {
// if this is a runnable, it's just an executable unit that should be invoked
((Runnable)unit).run(); // depends on control dependency: [if], data = [none]
} else {
DEvent event = (DEvent)unit;
// if this event is on a proxied object, forward it to the owning manager
ProxyReference proxy = _proxies.get(event.getTargetOid());
if (proxy != null) {
// rewrite the oid into the originating manager's id space
event.setTargetOid(proxy.origObjectId); // depends on control dependency: [if], data = [(proxy]
// then pass it on to the originating manager to handle
proxy.origManager.postEvent(event); // depends on control dependency: [if], data = [none]
} else if (event instanceof CompoundEvent) {
processCompoundEvent((CompoundEvent)event); // depends on control dependency: [if], data = [none]
} else {
processEvent(event); // depends on control dependency: [if], data = [none]
}
}
} catch (VirtualMachineError e) {
handleFatalError(unit, e);
} catch (Throwable t) { // depends on control dependency: [catch], data = [none]
log.warning("Execution unit failed", "unit", unit, t);
} // depends on control dependency: [catch], data = [none]
// compute the elapsed time in microseconds
long elapsed = (System.nanoTime() - start)/1000;
// report excessively long units
if (elapsed > 500000 && !(unit instanceof LongRunnable)) {
log.warning("Long dobj unit " + StringUtil.shortClassName(unit), "unit", unit,
"time", (elapsed/1000) + "ms"); // depends on control dependency: [if], data = [none]
}
// periodically sample and record the time spent processing a unit
if (UNIT_PROF_ENABLED && _eventCount % _unitProfInterval == 0) {
String cname;
// do some jiggery pokery to get more fine grained profiling details on certain
// "popular" unit types
if (unit instanceof Interval.RunBuddy) {
cname = StringUtil.shortClassName(
((Interval.RunBuddy)unit).getIntervalClassName()); // depends on control dependency: [if], data = [none]
} else if (unit instanceof InvocationRequestEvent) {
InvocationRequestEvent ire = (InvocationRequestEvent)unit;
Class<?> c = _invmgr.getDispatcherClass(ire.getInvCode());
cname = (c == null) ? "dobj.InvocationRequestEvent:(no longer registered)" :
StringUtil.shortClassName(c) + ":" + ire.getMethodId();
} else {
cname = StringUtil.shortClassName(unit);
}
UnitProfile uprof = _profiles.get(cname);
if (uprof == null) {
_profiles.put(cname, uprof = new UnitProfile()); // depends on control dependency: [if], data = [none]
}
uprof.record(elapsed); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public DescribeClustersRequest withClusters(String... clusters) {
if (this.clusters == null) {
setClusters(new com.amazonaws.internal.SdkInternalList<String>(clusters.length));
}
for (String ele : clusters) {
this.clusters.add(ele);
}
return this;
} } | public class class_name {
public DescribeClustersRequest withClusters(String... clusters) {
if (this.clusters == null) {
setClusters(new com.amazonaws.internal.SdkInternalList<String>(clusters.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : clusters) {
this.clusters.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static <T> Map<? extends String, T> toMap(List<Tag<T>> tags) {
ImmutableMap.Builder<String, T> tagsMapBuilder = ImmutableMap.builder();
for (Tag<T> tag : tags) {
tagsMapBuilder.put(tag.getKey(), tag.getValue());
}
return tagsMapBuilder.build();
} } | public class class_name {
public static <T> Map<? extends String, T> toMap(List<Tag<T>> tags) {
ImmutableMap.Builder<String, T> tagsMapBuilder = ImmutableMap.builder();
for (Tag<T> tag : tags) {
tagsMapBuilder.put(tag.getKey(), tag.getValue()); // depends on control dependency: [for], data = [tag]
}
return tagsMapBuilder.build();
} } |
public class class_name {
public List<PathValidator> getValidatorsForPathParam(final PathParameter param)
{
List<PathValidator> result = new ArrayList<PathValidator>();
for (PathValidator pv : pathValidators)
{
if (pv.getIndex() == param.getPosition())
{
result.add(pv);
}
}
return result;
} } | public class class_name {
public List<PathValidator> getValidatorsForPathParam(final PathParameter param)
{
List<PathValidator> result = new ArrayList<PathValidator>();
for (PathValidator pv : pathValidators)
{
if (pv.getIndex() == param.getPosition())
{
result.add(pv); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public static void addFileToZipOutputStream(File file, ZipOutputStream zipOs) throws IOException {
String fileName = file.getName();
try (FileInputStream fos = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(fileName);
zipEntry.setSize(file.length());
zipEntry.setTime(System.currentTimeMillis());
zipOs.putNextEntry(zipEntry);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = fos.read(buf)) > 0) {
zipOs.write(buf, 0, bytesRead);
}
zipOs.closeEntry();
fos.close();
}
} } | public class class_name {
public static void addFileToZipOutputStream(File file, ZipOutputStream zipOs) throws IOException {
String fileName = file.getName();
try (FileInputStream fos = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(fileName);
zipEntry.setSize(file.length());
zipEntry.setTime(System.currentTimeMillis());
zipOs.putNextEntry(zipEntry);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = fos.read(buf)) > 0) {
zipOs.write(buf, 0, bytesRead); // depends on control dependency: [while], data = [none]
}
zipOs.closeEntry();
fos.close();
}
} } |
public class class_name {
public OIndex<?> createIndex(ODatabaseDocumentInternal database, final String iName, String type,
final OIndexDefinition indexDefinition, final int[] clusterIdsToIndex, OProgressListener progressListener, ODocument metadata,
String algorithm) {
if (database.getTransaction().isActive())
throw new IllegalStateException("Cannot create a new index inside a transaction");
final Character c = OSchemaShared.checkFieldNameIfValid(iName);
if (c != null)
throw new IllegalArgumentException("Invalid index name '" + iName + "'. Character '" + c + "' is invalid");
if (indexDefinition == null) {
throw new IllegalArgumentException("Index definition cannot be null");
}
final Locale locale = getServerLocale();
type = type.toUpperCase(locale);
if (algorithm == null) {
algorithm = OIndexes.chooseDefaultIndexAlgorithm(type);
}
final String valueContainerAlgorithm = chooseContainerAlgorithm(type);
final OIndexInternal<?> index;
acquireExclusiveLock();
try {
if (indexes.containsKey(iName))
throw new OIndexException("Index with name " + iName + " already exists.");
// manual indexes are always durable
if (clusterIdsToIndex == null || clusterIdsToIndex.length == 0) {
if (metadata == null)
metadata = new ODocument().setTrackingChanges(false);
final Object durable = metadata.field("durableInNonTxMode");
if (!(durable instanceof Boolean))
metadata.field("durableInNonTxMode", true);
if (metadata.field("trackMode") == null)
metadata.field("trackMode", "FULL");
}
index = OIndexes.createIndex(getStorage(), iName, type, algorithm, valueContainerAlgorithm, metadata, -1);
if (progressListener == null)
// ASSIGN DEFAULT PROGRESS LISTENER
progressListener = new OIndexRebuildOutputListener(index);
final Set<String> clustersToIndex = findClustersByIds(clusterIdsToIndex, database);
Object ignoreNullValues = metadata == null ? null : metadata.field("ignoreNullValues");
if (Boolean.TRUE.equals(ignoreNullValues)) {
indexDefinition.setNullValuesIgnored(true);
} else if (Boolean.FALSE.equals(ignoreNullValues)) {
indexDefinition.setNullValuesIgnored(false);
} else {
indexDefinition.setNullValuesIgnored(
database.getConfiguration().getValueAsBoolean(OGlobalConfiguration.INDEX_IGNORE_NULL_VALUES_DEFAULT));
}
// decide which cluster to use ("index" - for automatic and "manindex" for manual)
final String clusterName = indexDefinition.getClassName() != null ? defaultClusterName : manualClusterName;
index.create(iName, indexDefinition, clusterName, clustersToIndex, true, progressListener);
addIndexInternal(index);
if (metadata != null) {
final ODocument config = index.getConfiguration();
config.field("metadata", metadata, OType.EMBEDDED);
}
setDirty();
save();
} finally {
releaseExclusiveLock();
}
notifyInvolvedClasses(database, clusterIdsToIndex);
return preProcessBeforeReturn(database, index);
} } | public class class_name {
public OIndex<?> createIndex(ODatabaseDocumentInternal database, final String iName, String type,
final OIndexDefinition indexDefinition, final int[] clusterIdsToIndex, OProgressListener progressListener, ODocument metadata,
String algorithm) {
if (database.getTransaction().isActive())
throw new IllegalStateException("Cannot create a new index inside a transaction");
final Character c = OSchemaShared.checkFieldNameIfValid(iName);
if (c != null)
throw new IllegalArgumentException("Invalid index name '" + iName + "'. Character '" + c + "' is invalid");
if (indexDefinition == null) {
throw new IllegalArgumentException("Index definition cannot be null");
}
final Locale locale = getServerLocale();
type = type.toUpperCase(locale);
if (algorithm == null) {
algorithm = OIndexes.chooseDefaultIndexAlgorithm(type); // depends on control dependency: [if], data = [none]
}
final String valueContainerAlgorithm = chooseContainerAlgorithm(type);
final OIndexInternal<?> index;
acquireExclusiveLock();
try {
if (indexes.containsKey(iName))
throw new OIndexException("Index with name " + iName + " already exists.");
// manual indexes are always durable
if (clusterIdsToIndex == null || clusterIdsToIndex.length == 0) {
if (metadata == null)
metadata = new ODocument().setTrackingChanges(false);
final Object durable = metadata.field("durableInNonTxMode");
if (!(durable instanceof Boolean))
metadata.field("durableInNonTxMode", true);
if (metadata.field("trackMode") == null)
metadata.field("trackMode", "FULL");
}
index = OIndexes.createIndex(getStorage(), iName, type, algorithm, valueContainerAlgorithm, metadata, -1); // depends on control dependency: [try], data = [none]
if (progressListener == null)
// ASSIGN DEFAULT PROGRESS LISTENER
progressListener = new OIndexRebuildOutputListener(index);
final Set<String> clustersToIndex = findClustersByIds(clusterIdsToIndex, database);
Object ignoreNullValues = metadata == null ? null : metadata.field("ignoreNullValues");
if (Boolean.TRUE.equals(ignoreNullValues)) {
indexDefinition.setNullValuesIgnored(true); // depends on control dependency: [if], data = [none]
} else if (Boolean.FALSE.equals(ignoreNullValues)) {
indexDefinition.setNullValuesIgnored(false); // depends on control dependency: [if], data = [none]
} else {
indexDefinition.setNullValuesIgnored(
database.getConfiguration().getValueAsBoolean(OGlobalConfiguration.INDEX_IGNORE_NULL_VALUES_DEFAULT)); // depends on control dependency: [if], data = [none]
}
// decide which cluster to use ("index" - for automatic and "manindex" for manual)
final String clusterName = indexDefinition.getClassName() != null ? defaultClusterName : manualClusterName;
index.create(iName, indexDefinition, clusterName, clustersToIndex, true, progressListener); // depends on control dependency: [try], data = [none]
addIndexInternal(index); // depends on control dependency: [try], data = [none]
if (metadata != null) {
final ODocument config = index.getConfiguration();
config.field("metadata", metadata, OType.EMBEDDED); // depends on control dependency: [if], data = [none]
}
setDirty(); // depends on control dependency: [try], data = [none]
save(); // depends on control dependency: [try], data = [none]
} finally {
releaseExclusiveLock();
}
notifyInvolvedClasses(database, clusterIdsToIndex);
return preProcessBeforeReturn(database, index);
} } |
public class class_name {
public final int read(byte[] dst, int offset, int length) throws IOException
{
if (!is_byte_data()) {
throw new IOException("byte read is not support over character sources");
}
int remaining = length;
while (remaining > 0 && !isEOF()) {
int ready = _limit - _pos;
if (ready > remaining) {
ready = remaining;
}
System.arraycopy(_bytes, _pos, dst, offset, ready);
_pos += ready;
offset += ready;
remaining -= ready;
if (remaining == 0 || _pos < _limit || refill_helper()) {
break;
}
}
return length - remaining;
} } | public class class_name {
public final int read(byte[] dst, int offset, int length) throws IOException
{
if (!is_byte_data()) {
throw new IOException("byte read is not support over character sources");
}
int remaining = length;
while (remaining > 0 && !isEOF()) {
int ready = _limit - _pos;
if (ready > remaining) {
ready = remaining; // depends on control dependency: [if], data = [none]
}
System.arraycopy(_bytes, _pos, dst, offset, ready);
_pos += ready;
offset += ready;
remaining -= ready;
if (remaining == 0 || _pos < _limit || refill_helper()) {
break;
}
}
return length - remaining;
} } |
public class class_name {
public ChannelSpecification withSupportedInputModes(String... supportedInputModes) {
if (this.supportedInputModes == null) {
setSupportedInputModes(new java.util.ArrayList<String>(supportedInputModes.length));
}
for (String ele : supportedInputModes) {
this.supportedInputModes.add(ele);
}
return this;
} } | public class class_name {
public ChannelSpecification withSupportedInputModes(String... supportedInputModes) {
if (this.supportedInputModes == null) {
setSupportedInputModes(new java.util.ArrayList<String>(supportedInputModes.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : supportedInputModes) {
this.supportedInputModes.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private final void readKerning(FontFileReader in) throws IOException {
// Read kerning
kerningTab = new java.util.HashMap();
ansiKerningTab = new java.util.HashMap();
TTFDirTabEntry dirTab = (TTFDirTabEntry)dirTabs.get("kern");
if (dirTab != null) {
seekTab(in, "kern", 2);
for (int n = in.readTTFUShort(); n > 0; n--) {
in.skip(2 * 2);
int k = in.readTTFUShort();
if (!((k & 1) != 0) || (k & 2) != 0 || (k & 4) != 0) {
return;
}
if ((k >> 8) != 0) {
continue;
}
k = in.readTTFUShort();
in.skip(3 * 2);
while (k-- > 0) {
int i = in.readTTFUShort();
int j = in.readTTFUShort();
int kpx = in.readTTFShort();
if (kpx != 0) {
// CID kerning table entry, using unicode indexes
final Integer iObj = glyphToUnicode(i);
final Integer u2 = glyphToUnicode(j);
if(iObj==null) {
// happens for many fonts (Ubuntu font set),
// stray entries in the kerning table??
log.warn("Unicode index (1) not found for glyph " + i);
} else if(u2==null) {
log.warn("Unicode index (2) not found for glyph " + i);
} else {
Map adjTab = (Map)kerningTab.get(iObj);
if (adjTab == null) {
adjTab = new java.util.HashMap();
}
adjTab.put(u2,new Integer(kpx));
kerningTab.put(iObj, adjTab);
}
}
}
}
// Create winAnsiEncoded kerning table from kerningTab
// (could probably be simplified, for now we remap back to CID indexes and then to winAnsi)
Iterator ae = kerningTab.keySet().iterator();
while (ae.hasNext()) {
Integer unicodeKey1 = (Integer)ae.next();
Integer cidKey1 = unicodeToGlyph(unicodeKey1.intValue());
Map akpx = new java.util.HashMap();
Map ckpx = (Map)kerningTab.get(unicodeKey1);
Iterator aee = ckpx.keySet().iterator();
while (aee.hasNext()) {
Integer unicodeKey2 = (Integer)aee.next();
Integer cidKey2 = unicodeToGlyph(unicodeKey2.intValue());
Integer kern = (Integer)ckpx.get(unicodeKey2);
Iterator uniMap = mtxTab[cidKey2.intValue()].getUnicodeIndex().listIterator();
while (uniMap.hasNext()) {
Integer unicodeKey = (Integer)uniMap.next();
Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue());
for (int u = 0; u < ansiKeys.length; u++) {
akpx.put(ansiKeys[u], kern);
}
}
}
if (akpx.size() > 0) {
Iterator uniMap = mtxTab[cidKey1.intValue()].getUnicodeIndex().listIterator();
while (uniMap.hasNext()) {
Integer unicodeKey = (Integer)uniMap.next();
Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue());
for (int u = 0; u < ansiKeys.length; u++) {
ansiKerningTab.put(ansiKeys[u], akpx);
}
}
}
}
}
} } | public class class_name {
private final void readKerning(FontFileReader in) throws IOException {
// Read kerning
kerningTab = new java.util.HashMap();
ansiKerningTab = new java.util.HashMap();
TTFDirTabEntry dirTab = (TTFDirTabEntry)dirTabs.get("kern");
if (dirTab != null) {
seekTab(in, "kern", 2);
for (int n = in.readTTFUShort(); n > 0; n--) {
in.skip(2 * 2);
int k = in.readTTFUShort();
if (!((k & 1) != 0) || (k & 2) != 0 || (k & 4) != 0) {
return; // depends on control dependency: [if], data = [none]
}
if ((k >> 8) != 0) {
continue;
}
k = in.readTTFUShort();
in.skip(3 * 2);
while (k-- > 0) {
int i = in.readTTFUShort();
int j = in.readTTFUShort();
int kpx = in.readTTFShort();
if (kpx != 0) {
// CID kerning table entry, using unicode indexes
final Integer iObj = glyphToUnicode(i);
final Integer u2 = glyphToUnicode(j);
if(iObj==null) {
// happens for many fonts (Ubuntu font set),
// stray entries in the kerning table??
log.warn("Unicode index (1) not found for glyph " + i); // depends on control dependency: [if], data = [none]
} else if(u2==null) {
log.warn("Unicode index (2) not found for glyph " + i); // depends on control dependency: [if], data = [none]
} else {
Map adjTab = (Map)kerningTab.get(iObj);
if (adjTab == null) {
adjTab = new java.util.HashMap(); // depends on control dependency: [if], data = [none]
}
adjTab.put(u2,new Integer(kpx)); // depends on control dependency: [if], data = [(u2]
kerningTab.put(iObj, adjTab); // depends on control dependency: [if], data = [none]
}
}
}
}
// Create winAnsiEncoded kerning table from kerningTab
// (could probably be simplified, for now we remap back to CID indexes and then to winAnsi)
Iterator ae = kerningTab.keySet().iterator();
while (ae.hasNext()) {
Integer unicodeKey1 = (Integer)ae.next();
Integer cidKey1 = unicodeToGlyph(unicodeKey1.intValue());
Map akpx = new java.util.HashMap();
Map ckpx = (Map)kerningTab.get(unicodeKey1);
Iterator aee = ckpx.keySet().iterator();
while (aee.hasNext()) {
Integer unicodeKey2 = (Integer)aee.next();
Integer cidKey2 = unicodeToGlyph(unicodeKey2.intValue());
Integer kern = (Integer)ckpx.get(unicodeKey2);
Iterator uniMap = mtxTab[cidKey2.intValue()].getUnicodeIndex().listIterator();
while (uniMap.hasNext()) {
Integer unicodeKey = (Integer)uniMap.next();
Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue());
for (int u = 0; u < ansiKeys.length; u++) {
akpx.put(ansiKeys[u], kern);
}
}
}
if (akpx.size() > 0) {
Iterator uniMap = mtxTab[cidKey1.intValue()].getUnicodeIndex().listIterator();
while (uniMap.hasNext()) {
Integer unicodeKey = (Integer)uniMap.next();
Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue());
for (int u = 0; u < ansiKeys.length; u++) {
ansiKerningTab.put(ansiKeys[u], akpx); // depends on control dependency: [for], data = [u]
}
}
}
}
}
} } |
public class class_name {
protected String describe(final Every every, final boolean and) {
String description;
if (every.getPeriod().getValue() > 1) {
description = String.format("%s %s ", bundle.getString(EVERY), nominalValue(every.getPeriod())) + " %p ";
} else {
description = bundle.getString(EVERY) + " %s ";
}
if (every.getExpression() instanceof Between) {
final Between between = (Between) every.getExpression();
description +=
MessageFormat.format(
bundle.getString("between_x_and_y"), nominalValue(between.getFrom()), nominalValue(between.getTo())
) + WHITE_SPACE;
}
return description;
} } | public class class_name {
protected String describe(final Every every, final boolean and) {
String description;
if (every.getPeriod().getValue() > 1) {
description = String.format("%s %s ", bundle.getString(EVERY), nominalValue(every.getPeriod())) + " %p "; // depends on control dependency: [if], data = [none]
} else {
description = bundle.getString(EVERY) + " %s "; // depends on control dependency: [if], data = [none]
}
if (every.getExpression() instanceof Between) {
final Between between = (Between) every.getExpression();
description +=
MessageFormat.format(
bundle.getString("between_x_and_y"), nominalValue(between.getFrom()), nominalValue(between.getTo())
) + WHITE_SPACE; // depends on control dependency: [if], data = [none]
}
return description;
} } |
public class class_name {
List<Action> lookupImplicitAction(ElementPath elementPath, Attributes attributes,
InterpretationContext ec) {
int len = implicitActions.size();
for (int i = 0; i < len; i++) {
ImplicitAction ia = (ImplicitAction) implicitActions.get(i);
if (ia.isApplicable(elementPath, attributes, ec)) {
List<Action> actionList = new ArrayList<Action>(1);
actionList.add(ia);
return actionList;
}
}
return null;
} } | public class class_name {
List<Action> lookupImplicitAction(ElementPath elementPath, Attributes attributes,
InterpretationContext ec) {
int len = implicitActions.size();
for (int i = 0; i < len; i++) {
ImplicitAction ia = (ImplicitAction) implicitActions.get(i);
if (ia.isApplicable(elementPath, attributes, ec)) {
List<Action> actionList = new ArrayList<Action>(1);
actionList.add(ia); // depends on control dependency: [if], data = [none]
return actionList; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
@Override
public D get()
{
try
{
if (field != null)
{
return (D) field.get(getBase());
}
else
{
return (D) getter.invoke(getBase());
}
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex)
{
throw new IllegalArgumentException(ex);
}
} } | public class class_name {
@Override
public D get()
{
try
{
if (field != null)
{
return (D) field.get(getBase());
// depends on control dependency: [if], data = [none]
}
else
{
return (D) getter.invoke(getBase());
// depends on control dependency: [if], data = [none]
}
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex)
{
throw new IllegalArgumentException(ex);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected final void firePropertyChange(String propertyName,
Object oldValue,
Object newValue) {
PropertyChangeSupport aChangeSupport = this.changeSupport;
if (aChangeSupport == null) {
return;
}
aChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
} } | public class class_name {
protected final void firePropertyChange(String propertyName,
Object oldValue,
Object newValue) {
PropertyChangeSupport aChangeSupport = this.changeSupport;
if (aChangeSupport == null) {
return; // depends on control dependency: [if], data = [none]
}
aChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
} } |
public class class_name {
public static <T> void permutations(List<List<T>> result, List<T> args, int index) {
if (index == args.size() - 2) {
List<T> temp1 = new ArrayList<>(args.size());
temp1.addAll(args);
Collections.swap(temp1, index, index + 1);
result.add(temp1);
List<T> temp2 = new ArrayList<>(args.size());
temp2.addAll(args);
result.add(temp2);
return;
}
permutations(result, args, index + 1);
for (int i = index; i < args.size() - 1; i++) {
List<T> temp = new ArrayList<>(args.size());
temp.addAll(args);
Collections.swap(temp, index, i + 1);
permutations(result, temp, index + 1);
}
} } | public class class_name {
public static <T> void permutations(List<List<T>> result, List<T> args, int index) {
if (index == args.size() - 2) {
List<T> temp1 = new ArrayList<>(args.size());
temp1.addAll(args); // depends on control dependency: [if], data = [none]
Collections.swap(temp1, index, index + 1); // depends on control dependency: [if], data = [none]
result.add(temp1); // depends on control dependency: [if], data = [none]
List<T> temp2 = new ArrayList<>(args.size());
temp2.addAll(args); // depends on control dependency: [if], data = [none]
result.add(temp2); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
permutations(result, args, index + 1);
for (int i = index; i < args.size() - 1; i++) {
List<T> temp = new ArrayList<>(args.size());
temp.addAll(args); // depends on control dependency: [for], data = [none]
Collections.swap(temp, index, i + 1); // depends on control dependency: [for], data = [i]
permutations(result, temp, index + 1); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public static Module loadModule(InputStream in) throws IOException {
Module module;
DataInputStream din;
byte[] xm_header, s3m_header, mod_header, output_buffer;
int frames;
din = new DataInputStream(in);
module = null;
xm_header = new byte[ 60 ];
din.readFully( xm_header );
if( FastTracker2.is_xm( xm_header ) ) {
module = FastTracker2.load_xm( xm_header, din );
} else {
s3m_header = new byte[ 96 ];
System.arraycopy( xm_header, 0, s3m_header, 0, 60 );
din.readFully( s3m_header, 60, 36 );
if( ScreamTracker3.is_s3m( s3m_header ) ) {
module = ScreamTracker3.load_s3m( s3m_header, din );
} else {
mod_header = new byte[ 1084 ];
System.arraycopy( s3m_header, 0, mod_header, 0, 96 );
din.readFully( mod_header, 96, 988 );
module = ProTracker.load_mod( mod_header, din );
}
}
din.close();
return module;
} } | public class class_name {
public static Module loadModule(InputStream in) throws IOException {
Module module;
DataInputStream din;
byte[] xm_header, s3m_header, mod_header, output_buffer;
int frames;
din = new DataInputStream(in);
module = null;
xm_header = new byte[ 60 ];
din.readFully( xm_header );
if( FastTracker2.is_xm( xm_header ) ) {
module = FastTracker2.load_xm( xm_header, din );
} else {
s3m_header = new byte[ 96 ];
System.arraycopy( xm_header, 0, s3m_header, 0, 60 );
din.readFully( s3m_header, 60, 36 );
if( ScreamTracker3.is_s3m( s3m_header ) ) {
module = ScreamTracker3.load_s3m( s3m_header, din ); // depends on control dependency: [if], data = [none]
} else {
mod_header = new byte[ 1084 ]; // depends on control dependency: [if], data = [none]
System.arraycopy( s3m_header, 0, mod_header, 0, 96 ); // depends on control dependency: [if], data = [none]
din.readFully( mod_header, 96, 988 ); // depends on control dependency: [if], data = [none]
module = ProTracker.load_mod( mod_header, din ); // depends on control dependency: [if], data = [none]
}
}
din.close();
return module;
} } |
public class class_name {
public void addHistory(History history) {
if (disableHistoryWrite) {
return;
}
PreparedStatement statement = null;
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement("INSERT INTO " + Constants.DB_TABLE_HISTORY +
"(" + Constants.GENERIC_PROFILE_ID + "," + Constants.GENERIC_CLIENT_UUID + "," +
Constants.HISTORY_CREATED_AT + "," + Constants.GENERIC_REQUEST_TYPE + "," +
Constants.HISTORY_REQUEST_URL + "," + Constants.HISTORY_REQUEST_PARAMS + "," +
Constants.HISTORY_REQUEST_POST_DATA + "," + Constants.HISTORY_REQUEST_HEADERS + "," +
Constants.HISTORY_RESPONSE_CODE + "," + Constants.HISTORY_RESPONSE_HEADERS + "," +
Constants.HISTORY_RESPONSE_CONTENT_TYPE + "," + Constants.HISTORY_RESPONSE_DATA + "," +
Constants.HISTORY_ORIGINAL_REQUEST_URL + "," + Constants.HISTORY_ORIGINAL_REQUEST_PARAMS + "," +
Constants.HISTORY_ORIGINAL_REQUEST_POST_DATA + "," + Constants.HISTORY_ORIGINAL_REQUEST_HEADERS + "," +
Constants.HISTORY_ORIGINAL_RESPONSE_CODE + "," + Constants.HISTORY_ORIGINAL_RESPONSE_HEADERS + "," +
Constants.HISTORY_ORIGINAL_RESPONSE_CONTENT_TYPE + "," + Constants.HISTORY_ORIGINAL_RESPONSE_DATA + "," +
Constants.HISTORY_MODIFIED + "," + Constants.HISTORY_REQUEST_SENT + "," +
Constants.HISTORY_REQUEST_BODY_DECODED + "," + Constants.HISTORY_RESPONSE_BODY_DECODED + "," +
Constants.HISTORY_EXTRA_INFO + "," + Constants.HISTORY_RAW_POST_DATA + ")" +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
statement.setInt(1, history.getProfileId());
statement.setString(2, history.getClientUUID());
statement.setString(3, history.getCreatedAt());
statement.setString(4, history.getRequestType());
statement.setString(5, history.getRequestURL());
statement.setString(6, history.getRequestParams());
statement.setString(7, history.getRequestPostData());
statement.setString(8, history.getRequestHeaders());
statement.setString(9, history.getResponseCode());
statement.setString(10, history.getResponseHeaders());
statement.setString(11, history.getResponseContentType());
statement.setString(12, history.getResponseData());
statement.setString(13, history.getOriginalRequestURL());
statement.setString(14, history.getOriginalRequestParams());
statement.setString(15, history.getOriginalRequestPostData());
statement.setString(16, history.getOriginalRequestHeaders());
statement.setString(17, history.getOriginalResponseCode());
statement.setString(18, history.getOriginalResponseHeaders());
statement.setString(19, history.getOriginalResponseContentType());
statement.setString(20, history.getOriginalResponseData());
statement.setBoolean(21, history.isModified());
statement.setBoolean(22, history.getRequestSent());
statement.setBoolean(23, history.getRequestBodyDecoded());
statement.setBoolean(24, history.getResponseBodyDecoded());
statement.setString(25, history.getExtraInfoString());
statement.setBytes(26, history.getRawPostData());
statement.executeUpdate();
// cull history
cullHistory(history.getProfileId(), history.getClientUUID(), maxHistorySize);
} catch (Exception e) {
logger.info(e.getMessage());
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
} } | public class class_name {
public void addHistory(History history) {
if (disableHistoryWrite) {
return; // depends on control dependency: [if], data = [none]
}
PreparedStatement statement = null;
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement("INSERT INTO " + Constants.DB_TABLE_HISTORY +
"(" + Constants.GENERIC_PROFILE_ID + "," + Constants.GENERIC_CLIENT_UUID + "," +
Constants.HISTORY_CREATED_AT + "," + Constants.GENERIC_REQUEST_TYPE + "," +
Constants.HISTORY_REQUEST_URL + "," + Constants.HISTORY_REQUEST_PARAMS + "," +
Constants.HISTORY_REQUEST_POST_DATA + "," + Constants.HISTORY_REQUEST_HEADERS + "," +
Constants.HISTORY_RESPONSE_CODE + "," + Constants.HISTORY_RESPONSE_HEADERS + "," +
Constants.HISTORY_RESPONSE_CONTENT_TYPE + "," + Constants.HISTORY_RESPONSE_DATA + "," +
Constants.HISTORY_ORIGINAL_REQUEST_URL + "," + Constants.HISTORY_ORIGINAL_REQUEST_PARAMS + "," +
Constants.HISTORY_ORIGINAL_REQUEST_POST_DATA + "," + Constants.HISTORY_ORIGINAL_REQUEST_HEADERS + "," +
Constants.HISTORY_ORIGINAL_RESPONSE_CODE + "," + Constants.HISTORY_ORIGINAL_RESPONSE_HEADERS + "," +
Constants.HISTORY_ORIGINAL_RESPONSE_CONTENT_TYPE + "," + Constants.HISTORY_ORIGINAL_RESPONSE_DATA + "," +
Constants.HISTORY_MODIFIED + "," + Constants.HISTORY_REQUEST_SENT + "," +
Constants.HISTORY_REQUEST_BODY_DECODED + "," + Constants.HISTORY_RESPONSE_BODY_DECODED + "," +
Constants.HISTORY_EXTRA_INFO + "," + Constants.HISTORY_RAW_POST_DATA + ")" +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
statement.setInt(1, history.getProfileId());
statement.setString(2, history.getClientUUID());
statement.setString(3, history.getCreatedAt());
statement.setString(4, history.getRequestType());
statement.setString(5, history.getRequestURL());
statement.setString(6, history.getRequestParams());
statement.setString(7, history.getRequestPostData());
statement.setString(8, history.getRequestHeaders());
statement.setString(9, history.getResponseCode());
statement.setString(10, history.getResponseHeaders());
statement.setString(11, history.getResponseContentType());
statement.setString(12, history.getResponseData());
statement.setString(13, history.getOriginalRequestURL());
statement.setString(14, history.getOriginalRequestParams());
statement.setString(15, history.getOriginalRequestPostData());
statement.setString(16, history.getOriginalRequestHeaders());
statement.setString(17, history.getOriginalResponseCode());
statement.setString(18, history.getOriginalResponseHeaders());
statement.setString(19, history.getOriginalResponseContentType());
statement.setString(20, history.getOriginalResponseData());
statement.setBoolean(21, history.isModified());
statement.setBoolean(22, history.getRequestSent());
statement.setBoolean(23, history.getRequestBodyDecoded());
statement.setBoolean(24, history.getResponseBodyDecoded());
statement.setString(25, history.getExtraInfoString());
statement.setBytes(26, history.getRawPostData());
statement.executeUpdate();
// cull history
cullHistory(history.getProfileId(), history.getClientUUID(), maxHistorySize);
} catch (Exception e) {
logger.info(e.getMessage());
} finally {
try {
if (statement != null) {
statement.close(); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private static Chronology of0(String id) {
Chronology chrono = CHRONOS_BY_ID.get(id);
if (chrono == null) {
chrono = CHRONOS_BY_TYPE.get(id);
}
return chrono;
} } | public class class_name {
private static Chronology of0(String id) {
Chronology chrono = CHRONOS_BY_ID.get(id);
if (chrono == null) {
chrono = CHRONOS_BY_TYPE.get(id); // depends on control dependency: [if], data = [none]
}
return chrono;
} } |
public class class_name {
public static void unZip(File inFile, File unzipDir) throws IOException {
Enumeration<? extends ZipEntry> entries;
ZipFile zipFile = new ZipFile(inFile);
try {
entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
InputStream in = zipFile.getInputStream(entry);
try {
File file = new File(unzipDir, entry.getName());
if (!file.getParentFile().mkdirs()) {
if (!file.getParentFile().isDirectory()) {
throw new IOException("Mkdirs failed to create " +
file.getParentFile().toString());
}
}
OutputStream out = new FileOutputStream(file);
try {
byte[] buffer = new byte[8192];
int i;
while ((i = in.read(buffer)) != -1) {
out.write(buffer, 0, i);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
}
} finally {
zipFile.close();
}
} } | public class class_name {
public static void unZip(File inFile, File unzipDir) throws IOException {
Enumeration<? extends ZipEntry> entries;
ZipFile zipFile = new ZipFile(inFile);
try {
entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
InputStream in = zipFile.getInputStream(entry);
try {
File file = new File(unzipDir, entry.getName());
if (!file.getParentFile().mkdirs()) {
if (!file.getParentFile().isDirectory()) {
throw new IOException("Mkdirs failed to create " +
file.getParentFile().toString());
}
}
OutputStream out = new FileOutputStream(file);
try {
byte[] buffer = new byte[8192];
int i;
while ((i = in.read(buffer)) != -1) {
out.write(buffer, 0, i); // depends on control dependency: [while], data = [none]
}
} finally {
out.close();
}
} finally {
in.close();
}
}
}
} finally {
zipFile.close();
}
} } |
public class class_name {
public static String capitalize(final String property) {
final String rest = property.substring(1);
// Funky rule so that names like 'pNAME' will still work.
if (Character.isLowerCase(property.charAt(0)) && (rest.length() > 0) && isUpperCase(rest.charAt(0))) {
return property;
}
return property.substring(0, 1).toUpperCase() + rest;
} } | public class class_name {
public static String capitalize(final String property) {
final String rest = property.substring(1);
// Funky rule so that names like 'pNAME' will still work.
if (Character.isLowerCase(property.charAt(0)) && (rest.length() > 0) && isUpperCase(rest.charAt(0))) {
return property; // depends on control dependency: [if], data = [none]
}
return property.substring(0, 1).toUpperCase() + rest;
} } |
public class class_name {
public void bindView(final MessageCenterFragment fragment, final MessageCenterRecyclerViewAdapter adapter, final Composer composer) {
title.setText(composer.title);
title.setContentDescription(composer.title);
closeButton.setOnClickListener(guarded(new View.OnClickListener() {
public void onClick(View view) {
if (!TextUtils.isEmpty(message.getText().toString().trim()) || !images.isEmpty()) {
Bundle bundle = new Bundle();
bundle.putString("message", composer.closeBody);
bundle.putString("positive", composer.closeDiscard);
bundle.putString("negative", composer.closeCancel);
ApptentiveAlertDialog.show(fragment, bundle, Constants.REQUEST_CODE_CLOSE_COMPOSING_CONFIRMATION);
} else {
if (adapter.getListener() != null) {
adapter.getListener().onCancelComposing();
}
}
}
}));
sendButton.setContentDescription(composer.sendButton);
sendButton.setOnClickListener(guarded(new View.OnClickListener() {
public void onClick(View view) {
if (adapter.getListener() != null) {
adapter.getListener().onFinishComposing();
}
}
}));
message.setHint(composer.messageHint);
message.removeTextChangedListener(textWatcher);
textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (adapter.getListener() != null) {
adapter.getListener().beforeComposingTextChanged(charSequence);
}
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
if (adapter.getListener() != null) {
adapter.getListener().onComposingTextChanged(charSequence);
}
}
@Override
public void afterTextChanged(Editable editable) {
if (adapter.getListener() != null) {
adapter.getListener().afterComposingTextChanged(editable.toString());
}
Linkify.addLinks(editable, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS | Linkify.EMAIL_ADDRESSES | Linkify.MAP_ADDRESSES);
}
};
message.addTextChangedListener(textWatcher);
attachButton.setOnClickListener(guarded(new View.OnClickListener() {
public void onClick(View view) {
if (adapter.getListener() != null) {
adapter.getListener().onAttachImage();
}
}
}));
attachments.setupUi();
attachments.setupLayoutListener();
attachments.setListener(new ApptentiveImageGridView.ImageItemClickedListener() {
@Override
public void onClick(int position, ImageItem image) {
if (adapter.getListener() != null) {
adapter.getListener().onClickAttachment(position, image);
}
}
});
attachments.setAdapterIndicator(R.drawable.apptentive_remove_button);
attachments.setImageIndicatorCallback(fragment);
//Initialize image attachments band with empty data
clearImageAttachmentBand();
attachments.setVisibility(View.GONE);
attachments.setData(new ArrayList<ImageItem>());
setAttachButtonState();
if (adapter.getListener() != null) {
adapter.getListener().onComposingViewCreated(this, message, attachments);
}
} } | public class class_name {
public void bindView(final MessageCenterFragment fragment, final MessageCenterRecyclerViewAdapter adapter, final Composer composer) {
title.setText(composer.title);
title.setContentDescription(composer.title);
closeButton.setOnClickListener(guarded(new View.OnClickListener() {
public void onClick(View view) {
if (!TextUtils.isEmpty(message.getText().toString().trim()) || !images.isEmpty()) {
Bundle bundle = new Bundle();
bundle.putString("message", composer.closeBody); // depends on control dependency: [if], data = [none]
bundle.putString("positive", composer.closeDiscard); // depends on control dependency: [if], data = [none]
bundle.putString("negative", composer.closeCancel); // depends on control dependency: [if], data = [none]
ApptentiveAlertDialog.show(fragment, bundle, Constants.REQUEST_CODE_CLOSE_COMPOSING_CONFIRMATION); // depends on control dependency: [if], data = [none]
} else {
if (adapter.getListener() != null) {
adapter.getListener().onCancelComposing(); // depends on control dependency: [if], data = [none]
}
}
}
}));
sendButton.setContentDescription(composer.sendButton);
sendButton.setOnClickListener(guarded(new View.OnClickListener() {
public void onClick(View view) {
if (adapter.getListener() != null) {
adapter.getListener().onFinishComposing(); // depends on control dependency: [if], data = [none]
}
}
}));
message.setHint(composer.messageHint);
message.removeTextChangedListener(textWatcher);
textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (adapter.getListener() != null) {
adapter.getListener().beforeComposingTextChanged(charSequence); // depends on control dependency: [if], data = [none]
}
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
if (adapter.getListener() != null) {
adapter.getListener().onComposingTextChanged(charSequence); // depends on control dependency: [if], data = [none]
}
}
@Override
public void afterTextChanged(Editable editable) {
if (adapter.getListener() != null) {
adapter.getListener().afterComposingTextChanged(editable.toString()); // depends on control dependency: [if], data = [none]
}
Linkify.addLinks(editable, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS | Linkify.EMAIL_ADDRESSES | Linkify.MAP_ADDRESSES);
}
};
message.addTextChangedListener(textWatcher);
attachButton.setOnClickListener(guarded(new View.OnClickListener() {
public void onClick(View view) {
if (adapter.getListener() != null) {
adapter.getListener().onAttachImage(); // depends on control dependency: [if], data = [none]
}
}
}));
attachments.setupUi();
attachments.setupLayoutListener();
attachments.setListener(new ApptentiveImageGridView.ImageItemClickedListener() {
@Override
public void onClick(int position, ImageItem image) {
if (adapter.getListener() != null) {
adapter.getListener().onClickAttachment(position, image); // depends on control dependency: [if], data = [none]
}
}
});
attachments.setAdapterIndicator(R.drawable.apptentive_remove_button);
attachments.setImageIndicatorCallback(fragment);
//Initialize image attachments band with empty data
clearImageAttachmentBand();
attachments.setVisibility(View.GONE);
attachments.setData(new ArrayList<ImageItem>());
setAttachButtonState();
if (adapter.getListener() != null) {
adapter.getListener().onComposingViewCreated(this, message, attachments); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static protected String escapeForRegExp(String s){
String r = s;
if (r != null && r.length() > 0){
for (String c: new String[]{"\\", "|", "&", "?", "*", "+", "{", "}",
"[", "]", "~", ".", "#", "@", "\"", "(", ")", "<", ">",
"^"}){
r = r.replace(c, "\\" + c);
}
}
return r;
} } | public class class_name {
static protected String escapeForRegExp(String s){
String r = s;
if (r != null && r.length() > 0){
for (String c: new String[]{"\\", "|", "&", "?", "*", "+", "{", "}",
"[", "]", "~", ".", "#", "@", "\"", "(", ")", "<", ">",
"^"}){
r = r.replace(c, "\\" + c);
// depends on control dependency: [for], data = [c]
}
}
return r;
} } |
public class class_name {
public void writeState(FacesContext context,
Object state) throws IOException {
SerializedView view;
if (state instanceof SerializedView) {
view = (SerializedView) state;
}
else {
if (state instanceof Object[]) {
Object[] stateArray = (Object[])state;
if (2 == stateArray.length) {
StateManager stateManager =
context.getApplication().getStateManager();
view = stateManager.new SerializedView(stateArray[0],
stateArray[1]);
} else {
//PENDING - I18N
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, "State is not an expected array of length 2.");
}
throw new IOException("State is not an expected array of length 2.");
}
} else {
//PENDING - I18N
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, "State is not an expected array of length 2.");
}
throw new IOException("State is not an expected array of length 2.");
}
}
writeState(context, view);
} } | public class class_name {
public void writeState(FacesContext context,
Object state) throws IOException {
SerializedView view;
if (state instanceof SerializedView) {
view = (SerializedView) state;
}
else {
if (state instanceof Object[]) {
Object[] stateArray = (Object[])state;
if (2 == stateArray.length) {
StateManager stateManager =
context.getApplication().getStateManager();
view = stateManager.new SerializedView(stateArray[0],
stateArray[1]); // depends on control dependency: [if], data = [none]
} else {
//PENDING - I18N
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, "State is not an expected array of length 2."); // depends on control dependency: [if], data = [none]
}
throw new IOException("State is not an expected array of length 2.");
}
} else {
//PENDING - I18N
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, "State is not an expected array of length 2."); // depends on control dependency: [if], data = [none]
}
throw new IOException("State is not an expected array of length 2.");
}
}
writeState(context, view);
} } |
public class class_name {
public void marshall(ConfigRuleComplianceSummaryFilters configRuleComplianceSummaryFilters, ProtocolMarshaller protocolMarshaller) {
if (configRuleComplianceSummaryFilters == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(configRuleComplianceSummaryFilters.getAccountId(), ACCOUNTID_BINDING);
protocolMarshaller.marshall(configRuleComplianceSummaryFilters.getAwsRegion(), AWSREGION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ConfigRuleComplianceSummaryFilters configRuleComplianceSummaryFilters, ProtocolMarshaller protocolMarshaller) {
if (configRuleComplianceSummaryFilters == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(configRuleComplianceSummaryFilters.getAccountId(), ACCOUNTID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(configRuleComplianceSummaryFilters.getAwsRegion(), AWSREGION_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 List<WorkerSlot> getAvailableSlots() {
List<WorkerSlot> slots = new ArrayList<>();
for (SupervisorDetails supervisor : this.supervisors.values()) {
slots.addAll(this.getAvailableSlots(supervisor));
}
return slots;
} } | public class class_name {
public List<WorkerSlot> getAvailableSlots() {
List<WorkerSlot> slots = new ArrayList<>();
for (SupervisorDetails supervisor : this.supervisors.values()) {
slots.addAll(this.getAvailableSlots(supervisor)); // depends on control dependency: [for], data = [supervisor]
}
return slots;
} } |
public class class_name {
public Set<Role> findRoles(final User user)
{
final Set<Role> result = new HashSet<Role>();
for(final RoleMapping mapping : this.getRoleMappings())
{
final Object source = mapping.getSource();
if((user != null) && user.equals(source))
{
// TODO: Fix this hardcoding when Restlet implements equals for Role objects again
RestletUtilRole standardRole = this.getRoleByName(mapping.getTarget().getName());
if(standardRole != null)
{
result.add(standardRole.getRole());
}
else
{
result.add(mapping.getTarget());
}
}
}
return result;
} } | public class class_name {
public Set<Role> findRoles(final User user)
{
final Set<Role> result = new HashSet<Role>();
for(final RoleMapping mapping : this.getRoleMappings())
{
final Object source = mapping.getSource();
if((user != null) && user.equals(source))
{
// TODO: Fix this hardcoding when Restlet implements equals for Role objects again
RestletUtilRole standardRole = this.getRoleByName(mapping.getTarget().getName());
if(standardRole != null)
{
result.add(standardRole.getRole()); // depends on control dependency: [if], data = [(standardRole]
}
else
{
result.add(mapping.getTarget()); // depends on control dependency: [if], data = [none]
}
}
}
return result;
} } |
public class class_name {
public void addType(final UUID... _uuid)
throws EFapsException
{
final Set<Type> typesTmp = new HashSet<>();
for (final UUID uuid : _uuid) {
typesTmp.add(Type.get(uuid));
}
addType(typesTmp.toArray(new Type[typesTmp.size()]));
} } | public class class_name {
public void addType(final UUID... _uuid)
throws EFapsException
{
final Set<Type> typesTmp = new HashSet<>();
for (final UUID uuid : _uuid) {
typesTmp.add(Type.get(uuid)); // depends on control dependency: [for], data = [uuid]
}
addType(typesTmp.toArray(new Type[typesTmp.size()]));
} } |
public class class_name {
private Map<String, String> buildShortNameToFullNameMap(Set<String> classSet) {
Map<String, String> result = new HashMap<>();
for (String className : classSet) {
String shortClassName = getShortClassName(className);
result.put(shortClassName, className);
}
return result;
} } | public class class_name {
private Map<String, String> buildShortNameToFullNameMap(Set<String> classSet) {
Map<String, String> result = new HashMap<>();
for (String className : classSet) {
String shortClassName = getShortClassName(className);
result.put(shortClassName, className); // depends on control dependency: [for], data = [className]
}
return result;
} } |
public class class_name {
public SqlBuilder having(String having) {
if (StrUtil.isNotBlank(having)) {
sql.append(" HAVING ").append(having);
}
return this;
} } | public class class_name {
public SqlBuilder having(String having) {
if (StrUtil.isNotBlank(having)) {
sql.append(" HAVING ").append(having);
// depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public static Locale localeFromIcuLocaleId(String localeId) {
// @ == ULOC_KEYWORD_SEPARATOR_UNICODE (uloc.h).
final int extensionsIndex = localeId.indexOf('@');
Map<Character, String> extensionsMap = Collections.EMPTY_MAP;
Map<String, String> unicodeKeywordsMap = Collections.EMPTY_MAP;
Set<String> unicodeAttributeSet = Collections.EMPTY_SET;
if (extensionsIndex != -1) {
extensionsMap = new HashMap<Character, String>();
unicodeKeywordsMap = new HashMap<String, String>();
unicodeAttributeSet = new HashSet<String>();
// ICU sends us a semi-colon (ULOC_KEYWORD_ITEM_SEPARATOR) delimited string
// containing all "keywords" it could parse. An ICU keyword is a key-value pair
// separated by an "=" (ULOC_KEYWORD_ASSIGN).
//
// Each keyword item can be one of three things :
// - A unicode extension attribute list: In this case the item key is "attribute"
// and the value is a hyphen separated list of unicode attributes.
// - A unicode extension keyword: In this case, the item key will be larger than
// 1 char in length, and the value will be the unicode extension value.
// - A BCP-47 extension subtag: In this case, the item key will be exactly one
// char in length, and the value will be a sequence of unparsed subtags that
// represent the extension.
//
// Note that this implies that unicode extension keywords are "promoted" to
// to the same namespace as the top level extension subtags and their values.
// There can't be any collisions in practice because the BCP-47 spec imposes
// restrictions on their lengths.
final String extensionsString = localeId.substring(extensionsIndex + 1);
final String[] extensions = extensionsString.split(";");
for (String extension : extensions) {
// This is the special key for the unicode attributes
if (extension.startsWith("attribute=")) {
String unicodeAttributeValues = extension.substring("attribute=".length());
for (String unicodeAttribute : unicodeAttributeValues.split("-")) {
unicodeAttributeSet.add(unicodeAttribute);
}
} else {
final int separatorIndex = extension.indexOf('=');
if (separatorIndex == 1) {
// This is a BCP-47 extension subtag.
final String value = extension.substring(2);
final char extensionId = extension.charAt(0);
extensionsMap.put(extensionId, value);
} else {
// This is a unicode extension keyword.
unicodeKeywordsMap.put(extension.substring(0, separatorIndex),
extension.substring(separatorIndex + 1));
}
}
}
}
final String[] outputArray = new String[] { "", "", "", "" };
if (extensionsIndex == -1) {
parseLangScriptRegionAndVariants(localeId, outputArray);
} else {
parseLangScriptRegionAndVariants(localeId.substring(0, extensionsIndex),
outputArray);
}
Locale.Builder builder = new Locale.Builder();
builder.setLanguage(outputArray[IDX_LANGUAGE]);
builder.setRegion(outputArray[IDX_REGION]);
builder.setVariant(outputArray[IDX_VARIANT]);
builder.setScript(outputArray[IDX_SCRIPT]);
for (String attribute : unicodeAttributeSet) {
builder.addUnicodeLocaleAttribute(attribute);
}
for (Entry<String, String> keyword : unicodeKeywordsMap.entrySet()) {
builder.setUnicodeLocaleKeyword(keyword.getKey(), keyword.getValue());
}
for (Entry<Character, String> extension : extensionsMap.entrySet()) {
builder.setExtension(extension.getKey(), extension.getValue());
}
return builder.build();
} } | public class class_name {
public static Locale localeFromIcuLocaleId(String localeId) {
// @ == ULOC_KEYWORD_SEPARATOR_UNICODE (uloc.h).
final int extensionsIndex = localeId.indexOf('@');
Map<Character, String> extensionsMap = Collections.EMPTY_MAP;
Map<String, String> unicodeKeywordsMap = Collections.EMPTY_MAP;
Set<String> unicodeAttributeSet = Collections.EMPTY_SET;
if (extensionsIndex != -1) {
extensionsMap = new HashMap<Character, String>(); // depends on control dependency: [if], data = [none]
unicodeKeywordsMap = new HashMap<String, String>(); // depends on control dependency: [if], data = [none]
unicodeAttributeSet = new HashSet<String>(); // depends on control dependency: [if], data = [none]
// ICU sends us a semi-colon (ULOC_KEYWORD_ITEM_SEPARATOR) delimited string
// containing all "keywords" it could parse. An ICU keyword is a key-value pair
// separated by an "=" (ULOC_KEYWORD_ASSIGN).
//
// Each keyword item can be one of three things :
// - A unicode extension attribute list: In this case the item key is "attribute"
// and the value is a hyphen separated list of unicode attributes.
// - A unicode extension keyword: In this case, the item key will be larger than
// 1 char in length, and the value will be the unicode extension value.
// - A BCP-47 extension subtag: In this case, the item key will be exactly one
// char in length, and the value will be a sequence of unparsed subtags that
// represent the extension.
//
// Note that this implies that unicode extension keywords are "promoted" to
// to the same namespace as the top level extension subtags and their values.
// There can't be any collisions in practice because the BCP-47 spec imposes
// restrictions on their lengths.
final String extensionsString = localeId.substring(extensionsIndex + 1);
final String[] extensions = extensionsString.split(";");
for (String extension : extensions) {
// This is the special key for the unicode attributes
if (extension.startsWith("attribute=")) {
String unicodeAttributeValues = extension.substring("attribute=".length());
for (String unicodeAttribute : unicodeAttributeValues.split("-")) {
unicodeAttributeSet.add(unicodeAttribute); // depends on control dependency: [for], data = [unicodeAttribute]
}
} else {
final int separatorIndex = extension.indexOf('=');
if (separatorIndex == 1) {
// This is a BCP-47 extension subtag.
final String value = extension.substring(2);
final char extensionId = extension.charAt(0);
extensionsMap.put(extensionId, value); // depends on control dependency: [if], data = [none]
} else {
// This is a unicode extension keyword.
unicodeKeywordsMap.put(extension.substring(0, separatorIndex),
extension.substring(separatorIndex + 1)); // depends on control dependency: [if], data = [none]
}
}
}
}
final String[] outputArray = new String[] { "", "", "", "" };
if (extensionsIndex == -1) {
parseLangScriptRegionAndVariants(localeId, outputArray); // depends on control dependency: [if], data = [none]
} else {
parseLangScriptRegionAndVariants(localeId.substring(0, extensionsIndex),
outputArray); // depends on control dependency: [if], data = [none]
}
Locale.Builder builder = new Locale.Builder();
builder.setLanguage(outputArray[IDX_LANGUAGE]);
builder.setRegion(outputArray[IDX_REGION]);
builder.setVariant(outputArray[IDX_VARIANT]);
builder.setScript(outputArray[IDX_SCRIPT]);
for (String attribute : unicodeAttributeSet) {
builder.addUnicodeLocaleAttribute(attribute); // depends on control dependency: [for], data = [attribute]
}
for (Entry<String, String> keyword : unicodeKeywordsMap.entrySet()) {
builder.setUnicodeLocaleKeyword(keyword.getKey(), keyword.getValue()); // depends on control dependency: [for], data = [keyword]
}
for (Entry<Character, String> extension : extensionsMap.entrySet()) {
builder.setExtension(extension.getKey(), extension.getValue()); // depends on control dependency: [for], data = [extension]
}
return builder.build();
} } |
public class class_name {
public final void setSelected(boolean selected) {
if (isExclusiveGroupMember()) {
boolean oldState = isSelected();
exclusiveController.handleSelectionRequest(this, selected);
// set back button state if controller didn't change this command;
// needed b/c of natural button check box toggling in swing
if (oldState == isSelected()) {
Iterator iter = buttonIterator();
while (iter.hasNext()) {
AbstractButton button = (AbstractButton)iter.next();
button.setSelected(isSelected());
}
}
}
else {
requestSetSelection(selected);
}
} } | public class class_name {
public final void setSelected(boolean selected) {
if (isExclusiveGroupMember()) {
boolean oldState = isSelected();
exclusiveController.handleSelectionRequest(this, selected); // depends on control dependency: [if], data = [none]
// set back button state if controller didn't change this command;
// needed b/c of natural button check box toggling in swing
if (oldState == isSelected()) {
Iterator iter = buttonIterator();
while (iter.hasNext()) {
AbstractButton button = (AbstractButton)iter.next();
button.setSelected(isSelected()); // depends on control dependency: [while], data = [none]
}
}
}
else {
requestSetSelection(selected); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void hideOnlyChannels(Object... channels){
for(LogRecordHandler handler : handlers){
if(handler instanceof VisibilityHandler){
VisibilityHandler visHandler = (VisibilityHandler) handler;
visHandler.showAll();
for (Object channel : channels) {
visHandler.alsoHide(channel);
}
}
}
} } | public class class_name {
public static void hideOnlyChannels(Object... channels){
for(LogRecordHandler handler : handlers){
if(handler instanceof VisibilityHandler){
VisibilityHandler visHandler = (VisibilityHandler) handler;
visHandler.showAll();
// depends on control dependency: [if], data = [none]
for (Object channel : channels) {
visHandler.alsoHide(channel);
// depends on control dependency: [for], data = [channel]
}
}
}
} } |
public class class_name {
protected Object getValue(String propertyName, Type propertyType, boolean optional, String defaultString) {
Object value = null;
assertNotClosed();
SourcedValue sourced = getSourcedValue(propertyName, propertyType);
if (sourced != null) {
value = sourced.getValue();
} else {
if (optional) {
value = convertValue(defaultString, propertyType);
} else {
throw new NoSuchElementException(Tr.formatMessage(tc, "no.such.element.CWMCG0015E", propertyName));
}
}
return value;
} } | public class class_name {
protected Object getValue(String propertyName, Type propertyType, boolean optional, String defaultString) {
Object value = null;
assertNotClosed();
SourcedValue sourced = getSourcedValue(propertyName, propertyType);
if (sourced != null) {
value = sourced.getValue(); // depends on control dependency: [if], data = [none]
} else {
if (optional) {
value = convertValue(defaultString, propertyType); // depends on control dependency: [if], data = [none]
} else {
throw new NoSuchElementException(Tr.formatMessage(tc, "no.such.element.CWMCG0015E", propertyName));
}
}
return value;
} } |
public class class_name {
private Object defaultToOutput(EvaluationContext ctx, FEEL feel) {
Map<String, Object> values = ctx.getAllValues();
if ( outputs.size() == 1 ) {
Object value = feel.evaluate( outputs.get( 0 ).getDefaultValue(), values );
return value;
} else {
// zip outputEntries with its name:
return IntStream.range( 0, outputs.size() ).boxed()
.collect( toMap( i -> outputs.get( i ).getName(), i -> feel.evaluate( outputs.get( i ).getDefaultValue(), values ) ) );
}
} } | public class class_name {
private Object defaultToOutput(EvaluationContext ctx, FEEL feel) {
Map<String, Object> values = ctx.getAllValues();
if ( outputs.size() == 1 ) {
Object value = feel.evaluate( outputs.get( 0 ).getDefaultValue(), values );
return value; // depends on control dependency: [if], data = [none]
} else {
// zip outputEntries with its name:
return IntStream.range( 0, outputs.size() ).boxed()
.collect( toMap( i -> outputs.get( i ).getName(), i -> feel.evaluate( outputs.get( i ).getDefaultValue(), values ) ) ); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean match( VersionID vid )
{
if ( _isCompound )
{
if ( !_rest.match( vid ) )
{
return false;
}
}
return ( _usePrefixMatch )
? this.isPrefixMatch( vid )
: ( _useGreaterThan ) ? vid.isGreaterThanOrEqual( this ) : matchTuple( vid );
} } | public class class_name {
public boolean match( VersionID vid )
{
if ( _isCompound )
{
if ( !_rest.match( vid ) )
{
return false; // depends on control dependency: [if], data = [none]
}
}
return ( _usePrefixMatch )
? this.isPrefixMatch( vid )
: ( _useGreaterThan ) ? vid.isGreaterThanOrEqual( this ) : matchTuple( vid );
} } |
public class class_name {
public static ResourceBundle getResourceBundle() {
final Locale currentLocale = getCurrentLocale();
if (Locale.ENGLISH.getLanguage().equals(currentLocale.getLanguage())) {
// there is no translations_en.properties because translations.properties is in English
// but if user is English, do not let getBundle fallback on server's default locale
return ResourceBundle.getBundle(RESOURCE_BUNDLE_BASE_NAME, ROOT_LOCALE);
}
// and if user is not English, use the bundle if it exists for his/her Locale
// or the bundle for the server's default locale if it exists
// or default (English) bundle otherwise
return ResourceBundle.getBundle(RESOURCE_BUNDLE_BASE_NAME, currentLocale);
} } | public class class_name {
public static ResourceBundle getResourceBundle() {
final Locale currentLocale = getCurrentLocale();
if (Locale.ENGLISH.getLanguage().equals(currentLocale.getLanguage())) {
// there is no translations_en.properties because translations.properties is in English
// but if user is English, do not let getBundle fallback on server's default locale
return ResourceBundle.getBundle(RESOURCE_BUNDLE_BASE_NAME, ROOT_LOCALE);
// depends on control dependency: [if], data = [none]
}
// and if user is not English, use the bundle if it exists for his/her Locale
// or the bundle for the server's default locale if it exists
// or default (English) bundle otherwise
return ResourceBundle.getBundle(RESOURCE_BUNDLE_BASE_NAME, currentLocale);
} } |
public class class_name {
public Double parseDefault(String input, Double defaultValue) {
if (input == null) {
return defaultValue;
}
Double answer = defaultValue;
try {
answer = Double.parseDouble(input);
} catch (NumberFormatException ignored) {
}
return answer;
} } | public class class_name {
public Double parseDefault(String input, Double defaultValue) {
if (input == null) {
return defaultValue; // depends on control dependency: [if], data = [none]
}
Double answer = defaultValue;
try {
answer = Double.parseDouble(input); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException ignored) {
} // depends on control dependency: [catch], data = [none]
return answer;
} } |
public class class_name {
protected long edgeCount() {
long degreeSum = 0L;
for (N node : nodes()) {
degreeSum += degree(node);
}
// According to the degree sum formula, this is equal to twice the number of edges.
checkState((degreeSum & 1) == 0);
return degreeSum >>> 1;
} } | public class class_name {
protected long edgeCount() {
long degreeSum = 0L;
for (N node : nodes()) {
degreeSum += degree(node); // depends on control dependency: [for], data = [node]
}
// According to the degree sum formula, this is equal to twice the number of edges.
checkState((degreeSum & 1) == 0);
return degreeSum >>> 1;
} } |
public class class_name {
private Object getEnumSet(Class c, JsonObject<String, Object> jsonObj)
{
Object[] items = jsonObj.getArray();
if (items == null || items.length == 0)
{
return newInstance(c, jsonObj);
}
JsonObject item = (JsonObject) items[0];
String type = item.getType();
Class enumClass = MetaUtils.classForName(type, reader.getClassLoader());
EnumSet enumSet = null;
for (Object objectItem : items)
{
item = (JsonObject) objectItem;
Enum enumItem = (Enum) getEnum(enumClass, item);
if (enumSet == null)
{ // Lazy init the EnumSet
enumSet = EnumSet.of(enumItem);
}
else
{
enumSet.add(enumItem);
}
}
return enumSet;
} } | public class class_name {
private Object getEnumSet(Class c, JsonObject<String, Object> jsonObj)
{
Object[] items = jsonObj.getArray();
if (items == null || items.length == 0)
{
return newInstance(c, jsonObj); // depends on control dependency: [if], data = [none]
}
JsonObject item = (JsonObject) items[0];
String type = item.getType();
Class enumClass = MetaUtils.classForName(type, reader.getClassLoader());
EnumSet enumSet = null;
for (Object objectItem : items)
{
item = (JsonObject) objectItem; // depends on control dependency: [for], data = [objectItem]
Enum enumItem = (Enum) getEnum(enumClass, item); // depends on control dependency: [for], data = [none]
if (enumSet == null)
{ // Lazy init the EnumSet
enumSet = EnumSet.of(enumItem); // depends on control dependency: [if], data = [none]
}
else
{
enumSet.add(enumItem); // depends on control dependency: [if], data = [none]
}
}
return enumSet;
} } |
public class class_name {
void processEvent(Event e) {
assert !_processed;
// Event e = _events[idx];
if (e.isSend()) {
_sends.put(e, new ArrayList<TimelineSnapshot.Event>());
for (Event otherE : _events) {
if ((otherE != null) && (otherE != e) && (!otherE.equals(e)) && otherE._blocked
&& otherE.match(e)) {
_edges.put(otherE, e);
_sends.get(e).add(otherE);
otherE._blocked = false;
}
}
} else { // look for matching send, otherwise set _blocked
assert !_edges.containsKey(e);
int senderIdx = e.packH2O().index();
if (senderIdx < 0) { // binary search did not find member, should not happen?
// no possible sender - return and do not block
Log.warn("no sender found! port = " + e.portPack() + ", ip = " + e.addrPack().toString());
return;
}
Event senderCnd = _events[senderIdx];
if (senderCnd != null) {
if (isSenderRecvPair(senderCnd, e)) {
_edges.put(e, senderCnd.clone());
_sends.get(senderCnd).add(e);
return;
}
senderCnd = senderCnd.clone();
while (senderCnd.prev()) {
if (isSenderRecvPair(senderCnd, e)) {
_edges.put(e, senderCnd);
_sends.get(senderCnd).add(e);
return;
}
}
}
e._blocked = true;
}
assert (e == null) || (e._eventIdx < TimeLine.MAX_EVENTS);
} } | public class class_name {
void processEvent(Event e) {
assert !_processed;
// Event e = _events[idx];
if (e.isSend()) {
_sends.put(e, new ArrayList<TimelineSnapshot.Event>()); // depends on control dependency: [if], data = [none]
for (Event otherE : _events) {
if ((otherE != null) && (otherE != e) && (!otherE.equals(e)) && otherE._blocked
&& otherE.match(e)) {
_edges.put(otherE, e); // depends on control dependency: [if], data = [none]
_sends.get(e).add(otherE); // depends on control dependency: [if], data = [none]
otherE._blocked = false; // depends on control dependency: [if], data = [none]
}
}
} else { // look for matching send, otherwise set _blocked
assert !_edges.containsKey(e); // depends on control dependency: [if], data = [none]
int senderIdx = e.packH2O().index();
if (senderIdx < 0) { // binary search did not find member, should not happen?
// no possible sender - return and do not block
Log.warn("no sender found! port = " + e.portPack() + ", ip = " + e.addrPack().toString()); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
Event senderCnd = _events[senderIdx];
if (senderCnd != null) {
if (isSenderRecvPair(senderCnd, e)) {
_edges.put(e, senderCnd.clone()); // depends on control dependency: [if], data = [none]
_sends.get(senderCnd).add(e); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
senderCnd = senderCnd.clone(); // depends on control dependency: [if], data = [none]
while (senderCnd.prev()) {
if (isSenderRecvPair(senderCnd, e)) {
_edges.put(e, senderCnd); // depends on control dependency: [if], data = [none]
_sends.get(senderCnd).add(e); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
}
e._blocked = true; // depends on control dependency: [if], data = [none]
}
assert (e == null) || (e._eventIdx < TimeLine.MAX_EVENTS);
} } |
public class class_name {
public void marshall(VideoDetail videoDetail, ProtocolMarshaller protocolMarshaller) {
if (videoDetail == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(videoDetail.getHeightInPx(), HEIGHTINPX_BINDING);
protocolMarshaller.marshall(videoDetail.getWidthInPx(), WIDTHINPX_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(VideoDetail videoDetail, ProtocolMarshaller protocolMarshaller) {
if (videoDetail == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(videoDetail.getHeightInPx(), HEIGHTINPX_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(videoDetail.getWidthInPx(), WIDTHINPX_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 File siblingDirectory(final File f, final String siblingDirName) {
checkNotNull(f);
checkNotNull(siblingDirName);
checkArgument(!siblingDirName.isEmpty());
final File parent = f.getParentFile();
if (parent != null) {
return new File(parent, siblingDirName);
} else {
throw new RuntimeException(String
.format("Cannot create sibling directory %s of %s because the latter has no parent.",
siblingDirName, f));
}
} } | public class class_name {
public static File siblingDirectory(final File f, final String siblingDirName) {
checkNotNull(f);
checkNotNull(siblingDirName);
checkArgument(!siblingDirName.isEmpty());
final File parent = f.getParentFile();
if (parent != null) {
return new File(parent, siblingDirName); // depends on control dependency: [if], data = [(parent]
} else {
throw new RuntimeException(String
.format("Cannot create sibling directory %s of %s because the latter has no parent.",
siblingDirName, f));
}
} } |
public class class_name {
final void closeAndRemoveAllDatabaseHandles() {
for (Database databaseHandle : this.databaseHandles) {
try {
databaseHandle.close();
} catch (EnvironmentFailureException | IllegalStateException ex) {
LOGGER.log(Level.SEVERE,
"Error closing databases", ex);
}
}
this.databaseHandles.clear();
} } | public class class_name {
final void closeAndRemoveAllDatabaseHandles() {
for (Database databaseHandle : this.databaseHandles) {
try {
databaseHandle.close(); // depends on control dependency: [try], data = [none]
} catch (EnvironmentFailureException | IllegalStateException ex) {
LOGGER.log(Level.SEVERE,
"Error closing databases", ex);
} // depends on control dependency: [catch], data = [none]
}
this.databaseHandles.clear();
} } |
public class class_name {
public boolean isNewerThan(VersionComparator comparator) {
if (this.major > comparator.getMajor()) {
return true;
} else if (this.major == comparator.getMajor() && this.minor > comparator.getMinor()) {
return true;
} else if (this.major == comparator.getMajor() && this.minor == comparator.getMinor() && this.revision > comparator.getRevision()) {
return true;
} else if (this.major == comparator.getMajor() && this.minor == comparator.getMinor() && this.revision == comparator.getRevision() && this.prereleaseNumber > comparator.getPrereleaseNumber()) {
return true;
}
return false;
} } | public class class_name {
public boolean isNewerThan(VersionComparator comparator) {
if (this.major > comparator.getMajor()) {
return true; // depends on control dependency: [if], data = [none]
} else if (this.major == comparator.getMajor() && this.minor > comparator.getMinor()) {
return true; // depends on control dependency: [if], data = [none]
} else if (this.major == comparator.getMajor() && this.minor == comparator.getMinor() && this.revision > comparator.getRevision()) {
return true; // depends on control dependency: [if], data = [none]
} else if (this.major == comparator.getMajor() && this.minor == comparator.getMinor() && this.revision == comparator.getRevision() && this.prereleaseNumber > comparator.getPrereleaseNumber()) {
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public static void upgradeProcessInstanceByNodeNames(
KieRuntime kruntime,
Long fromProcessId,
String toProcessId,
Map<String, String> nodeNamesMapping) {
Map<String, Long> nodeIdMapping = new HashMap<String, Long>();
String fromProcessIdString = kruntime.getProcessInstance(fromProcessId).getProcessId();
Process processFrom = kruntime.getKieBase().getProcess(fromProcessIdString);
Process processTo = kruntime.getKieBase().getProcess(toProcessId);
for (Map.Entry<String, String> entry : nodeNamesMapping.entrySet()) {
String from = null;
Long to = null;
if (processFrom instanceof WorkflowProcess) {
from = getNodeId(((WorkflowProcess) processFrom).getNodes(), entry.getKey(), true);
} else if (processFrom instanceof RuleFlowProcess) {
from = getNodeId(((RuleFlowProcess) processFrom).getNodes(), entry.getKey(), true);
} else if (processFrom != null) {
throw new IllegalArgumentException("Suported processes are WorkflowProcess and RuleFlowProcess, it was:" + processFrom.getClass());
} else {
throw new IllegalArgumentException("Can not find process with id: " + fromProcessIdString);
}
if (processTo instanceof WorkflowProcess) {
to = Long.valueOf(getNodeId(((WorkflowProcess) processTo).getNodes(), entry.getValue(), false));
} else if (processTo instanceof RuleFlowProcess) {
to = Long.valueOf(getNodeId(((RuleFlowProcess) processTo).getNodes(), entry.getValue(), false));
} else if (processTo != null) {
throw new IllegalArgumentException("Suported processes are WorkflowProcess and RuleFlowProcess, it was:" + processTo.getClass());
} else {
throw new IllegalArgumentException("Can not find process with id: " + toProcessId);
}
nodeIdMapping.put(from, to);
}
upgradeProcessInstance(kruntime, fromProcessId, toProcessId, nodeIdMapping);
} } | public class class_name {
public static void upgradeProcessInstanceByNodeNames(
KieRuntime kruntime,
Long fromProcessId,
String toProcessId,
Map<String, String> nodeNamesMapping) {
Map<String, Long> nodeIdMapping = new HashMap<String, Long>();
String fromProcessIdString = kruntime.getProcessInstance(fromProcessId).getProcessId();
Process processFrom = kruntime.getKieBase().getProcess(fromProcessIdString);
Process processTo = kruntime.getKieBase().getProcess(toProcessId);
for (Map.Entry<String, String> entry : nodeNamesMapping.entrySet()) {
String from = null;
Long to = null;
if (processFrom instanceof WorkflowProcess) {
from = getNodeId(((WorkflowProcess) processFrom).getNodes(), entry.getKey(), true); // depends on control dependency: [if], data = [none]
} else if (processFrom instanceof RuleFlowProcess) {
from = getNodeId(((RuleFlowProcess) processFrom).getNodes(), entry.getKey(), true); // depends on control dependency: [if], data = [none]
} else if (processFrom != null) {
throw new IllegalArgumentException("Suported processes are WorkflowProcess and RuleFlowProcess, it was:" + processFrom.getClass());
} else {
throw new IllegalArgumentException("Can not find process with id: " + fromProcessIdString);
}
if (processTo instanceof WorkflowProcess) {
to = Long.valueOf(getNodeId(((WorkflowProcess) processTo).getNodes(), entry.getValue(), false)); // depends on control dependency: [if], data = [none]
} else if (processTo instanceof RuleFlowProcess) {
to = Long.valueOf(getNodeId(((RuleFlowProcess) processTo).getNodes(), entry.getValue(), false)); // depends on control dependency: [if], data = [none]
} else if (processTo != null) {
throw new IllegalArgumentException("Suported processes are WorkflowProcess and RuleFlowProcess, it was:" + processTo.getClass());
} else {
throw new IllegalArgumentException("Can not find process with id: " + toProcessId);
}
nodeIdMapping.put(from, to); // depends on control dependency: [for], data = [none]
}
upgradeProcessInstance(kruntime, fromProcessId, toProcessId, nodeIdMapping);
} } |
public class class_name {
protected void markMerge(int regionA, int regionB) {
int dA = mergeList.data[regionA];
int dB = mergeList.data[regionB];
// Quick check to see if they reference the same node
if( dA == dB ) {
return;
}
// search down to the root node (set-find)
int rootA = regionA;
while( dA != rootA ) {
rootA = dA;
dA = mergeList.data[rootA];
}
int rootB = regionB;
while( dB != rootB ) {
rootB = dB;
dB = mergeList.data[rootB];
}
// make rootA the parent. This allows the quick test to pass in the future
mergeList.data[regionA] = rootA;
mergeList.data[regionB] = rootA;
mergeList.data[rootB] = rootA;
} } | public class class_name {
protected void markMerge(int regionA, int regionB) {
int dA = mergeList.data[regionA];
int dB = mergeList.data[regionB];
// Quick check to see if they reference the same node
if( dA == dB ) {
return; // depends on control dependency: [if], data = [none]
}
// search down to the root node (set-find)
int rootA = regionA;
while( dA != rootA ) {
rootA = dA; // depends on control dependency: [while], data = [none]
dA = mergeList.data[rootA]; // depends on control dependency: [while], data = [none]
}
int rootB = regionB;
while( dB != rootB ) {
rootB = dB; // depends on control dependency: [while], data = [none]
dB = mergeList.data[rootB]; // depends on control dependency: [while], data = [none]
}
// make rootA the parent. This allows the quick test to pass in the future
mergeList.data[regionA] = rootA;
mergeList.data[regionB] = rootA;
mergeList.data[rootB] = rootA;
} } |
public class class_name {
private List<HashMap<String, String>> createSegmentListFromMessage(String msg) {
List<HashMap<String, String>> segmentList = new ArrayList<HashMap<String, String>>();
boolean quoteNext = false;
int startPosi = 0;
for (int i = 0; i < msg.length(); i++) {
char ch = msg.charAt(i);
if (!quoteNext && ch == '@') {
// skip binary values
int idx = msg.indexOf("@", i + 1);
String len_st = msg.substring(i + 1, idx);
i += Integer.parseInt(len_st) + 1 + len_st.length();
} else if (!quoteNext && ch == '\'') {
// segment-ende gefunden
HashMap<String, String> segmentInfo = new HashMap<>();
segmentInfo.put("code", msg.substring(startPosi, msg.indexOf(":", startPosi)));
segmentInfo.put("start", Integer.toString(startPosi));
segmentInfo.put("length", Integer.toString(i - startPosi + 1));
segmentList.add(segmentInfo);
startPosi = i + 1;
}
quoteNext = !quoteNext && ch == '?';
}
return segmentList;
} } | public class class_name {
private List<HashMap<String, String>> createSegmentListFromMessage(String msg) {
List<HashMap<String, String>> segmentList = new ArrayList<HashMap<String, String>>();
boolean quoteNext = false;
int startPosi = 0;
for (int i = 0; i < msg.length(); i++) {
char ch = msg.charAt(i);
if (!quoteNext && ch == '@') {
// skip binary values
int idx = msg.indexOf("@", i + 1); // depends on control dependency: [if], data = [none]
String len_st = msg.substring(i + 1, idx);
i += Integer.parseInt(len_st) + 1 + len_st.length(); // depends on control dependency: [if], data = [none]
} else if (!quoteNext && ch == '\'') {
// segment-ende gefunden
HashMap<String, String> segmentInfo = new HashMap<>();
segmentInfo.put("code", msg.substring(startPosi, msg.indexOf(":", startPosi))); // depends on control dependency: [if], data = [none]
segmentInfo.put("start", Integer.toString(startPosi)); // depends on control dependency: [if], data = [none]
segmentInfo.put("length", Integer.toString(i - startPosi + 1)); // depends on control dependency: [if], data = [none]
segmentList.add(segmentInfo); // depends on control dependency: [if], data = [none]
startPosi = i + 1; // depends on control dependency: [if], data = [none]
}
quoteNext = !quoteNext && ch == '?'; // depends on control dependency: [for], data = [none]
}
return segmentList;
} } |
public class class_name {
public static <T> List<T> getList(final ContentValues[] values, final Class<T> klass) {
final List<T> objects = new ArrayList<T>();
for (int i = 0; i < values.length; i++) {
final T object = getObject(values[i], klass);
if (object != null) {
objects.add(object);
}
}
return objects;
} } | public class class_name {
public static <T> List<T> getList(final ContentValues[] values, final Class<T> klass) {
final List<T> objects = new ArrayList<T>();
for (int i = 0; i < values.length; i++) {
final T object = getObject(values[i], klass);
if (object != null) {
objects.add(object); // depends on control dependency: [if], data = [(object]
}
}
return objects;
} } |
public class class_name {
public void marshall(MatchedPlayerSession matchedPlayerSession, ProtocolMarshaller protocolMarshaller) {
if (matchedPlayerSession == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(matchedPlayerSession.getPlayerId(), PLAYERID_BINDING);
protocolMarshaller.marshall(matchedPlayerSession.getPlayerSessionId(), PLAYERSESSIONID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(MatchedPlayerSession matchedPlayerSession, ProtocolMarshaller protocolMarshaller) {
if (matchedPlayerSession == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(matchedPlayerSession.getPlayerId(), PLAYERID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(matchedPlayerSession.getPlayerSessionId(), PLAYERSESSIONID_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 {
@Override
protected PersistedNodeData loadNodeRecord(QPath parentPath, String cname, String cid, String cpid, int cindex,
int cversion, int cnordernumb, AccessControlList parentACL) throws RepositoryException, SQLException
{
ResultSet ptProp = findNodeMainPropertiesByParentIdentifierCQ(cid);
try
{
Map<String, SortedSet<TempPropertyData>> properties = new HashMap<String, SortedSet<TempPropertyData>>();
while (ptProp.next())
{
String key = ptProp.getString(COLUMN_NAME);
SortedSet<TempPropertyData> values = properties.get(key);
if (values == null)
{
values = new TreeSet<TempPropertyData>();
properties.put(key, values);
}
values.add(new TempPropertyData(ptProp));
}
return loadNodeRecord(parentPath, cname, cid, cpid, cindex, cversion, cnordernumb, properties, parentACL);
}
catch (IOException e)
{
throw new RepositoryException(e);
}
finally
{
try
{
ptProp.close();
}
catch (SQLException e)
{
LOG.error("Can't close the ResultSet: " + e.getMessage());
}
}
} } | public class class_name {
@Override
protected PersistedNodeData loadNodeRecord(QPath parentPath, String cname, String cid, String cpid, int cindex,
int cversion, int cnordernumb, AccessControlList parentACL) throws RepositoryException, SQLException
{
ResultSet ptProp = findNodeMainPropertiesByParentIdentifierCQ(cid);
try
{
Map<String, SortedSet<TempPropertyData>> properties = new HashMap<String, SortedSet<TempPropertyData>>();
while (ptProp.next())
{
String key = ptProp.getString(COLUMN_NAME);
SortedSet<TempPropertyData> values = properties.get(key);
if (values == null)
{
values = new TreeSet<TempPropertyData>(); // depends on control dependency: [if], data = [none]
properties.put(key, values); // depends on control dependency: [if], data = [none]
}
values.add(new TempPropertyData(ptProp)); // depends on control dependency: [while], data = [none]
}
return loadNodeRecord(parentPath, cname, cid, cpid, cindex, cversion, cnordernumb, properties, parentACL);
}
catch (IOException e)
{
throw new RepositoryException(e);
}
finally
{
try
{
ptProp.close(); // depends on control dependency: [try], data = [none]
}
catch (SQLException e)
{
LOG.error("Can't close the ResultSet: " + e.getMessage());
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public static Type getPropertyType(Class<?> beanClass, String field) {
try {
return INSTANCE.findPropertyType(beanClass, field);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw handleReflectionException(beanClass, field, e);
}
} } | public class class_name {
public static Type getPropertyType(Class<?> beanClass, String field) {
try {
return INSTANCE.findPropertyType(beanClass, field); // depends on control dependency: [try], data = [none]
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw handleReflectionException(beanClass, field, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public final void shutdown() {
try {
onComplete();
executor.shutdown();
requestTaskExecutor.shutdown();
}
catch (Throwable t) {
onError(Operators.onOperatorError(t, currentContext()));
}
} } | public class class_name {
public final void shutdown() {
try {
onComplete(); // depends on control dependency: [try], data = [none]
executor.shutdown(); // depends on control dependency: [try], data = [none]
requestTaskExecutor.shutdown(); // depends on control dependency: [try], data = [none]
}
catch (Throwable t) {
onError(Operators.onOperatorError(t, currentContext()));
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError,
boolean ignoreFailedDrops, String commentPrefix, String separator, String blockCommentStartDelimiter,
String blockCommentEndDelimiter) throws ScriptException {
try {
if (logger.isInfoEnabled()) {
logger.info("Executing SQL script from " + resource);
}
long startTime = System.currentTimeMillis();
String script;
try {
script = readScript(resource, commentPrefix, separator);
} catch (IOException ex) {
throw new CannotReadScriptException(resource, ex);
}
if (separator == null) {
separator = DEFAULT_STATEMENT_SEPARATOR;
}
if (!EOF_STATEMENT_SEPARATOR.equals(separator) && !containsSqlScriptDelimiters(script, separator)) {
separator = FALLBACK_STATEMENT_SEPARATOR;
}
List<String> statements = new LinkedList<String>();
splitSqlScript(resource, script, separator, commentPrefix, blockCommentStartDelimiter,
blockCommentEndDelimiter, statements);
int stmtNumber = 0;
Statement stmt = connection.createStatement();
try {
for (String statement : statements) {
stmtNumber++;
try {
stmt.execute(statement);
int rowsAffected = stmt.getUpdateCount();
if (logger.isDebugEnabled()) {
logger.debug(rowsAffected + " returned as update count for SQL: " + statement);
SQLWarning warningToLog = stmt.getWarnings();
while (warningToLog != null) {
logger.debug("SQLWarning ignored: SQL state '" + warningToLog.getSQLState()
+ "', error code '" + warningToLog.getErrorCode() + "', message ["
+ warningToLog.getMessage() + "]");
warningToLog = warningToLog.getNextWarning();
}
}
} catch (SQLException ex) {
boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
if (continueOnError || (dropStatement && ignoreFailedDrops)) {
if (logger.isDebugEnabled()) {
logger.debug(ScriptStatementFailedException.buildErrorMessage(statement, stmtNumber,
resource), ex);
}
} else {
throw new ScriptStatementFailedException(statement, stmtNumber, resource, ex);
}
}
}
} finally {
try {
stmt.close();
} catch (Throwable ex) {
logger.debug("Could not close JDBC Statement", ex);
}
}
long elapsedTime = System.currentTimeMillis() - startTime;
if (logger.isInfoEnabled()) {
logger.info("Executed SQL script from " + resource + " in " + elapsedTime + " ms.");
}
} catch (Exception ex) {
if (ex instanceof ScriptException) {
throw (ScriptException) ex;
}
throw new UncategorizedScriptException("Failed to execute database script from resource [" + resource + "]",
ex);
}
} } | public class class_name {
public static void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError,
boolean ignoreFailedDrops, String commentPrefix, String separator, String blockCommentStartDelimiter,
String blockCommentEndDelimiter) throws ScriptException {
try {
if (logger.isInfoEnabled()) {
logger.info("Executing SQL script from " + resource);
}
long startTime = System.currentTimeMillis();
String script;
try {
script = readScript(resource, commentPrefix, separator);
} catch (IOException ex) {
throw new CannotReadScriptException(resource, ex);
}
if (separator == null) {
separator = DEFAULT_STATEMENT_SEPARATOR;
}
if (!EOF_STATEMENT_SEPARATOR.equals(separator) && !containsSqlScriptDelimiters(script, separator)) {
separator = FALLBACK_STATEMENT_SEPARATOR;
}
List<String> statements = new LinkedList<String>();
splitSqlScript(resource, script, separator, commentPrefix, blockCommentStartDelimiter,
blockCommentEndDelimiter, statements);
int stmtNumber = 0;
Statement stmt = connection.createStatement();
try {
for (String statement : statements) {
stmtNumber++; // depends on control dependency: [for], data = [none]
try {
stmt.execute(statement); // depends on control dependency: [try], data = [none]
int rowsAffected = stmt.getUpdateCount();
if (logger.isDebugEnabled()) {
logger.debug(rowsAffected + " returned as update count for SQL: " + statement); // depends on control dependency: [if], data = [none]
SQLWarning warningToLog = stmt.getWarnings();
while (warningToLog != null) {
logger.debug("SQLWarning ignored: SQL state '" + warningToLog.getSQLState()
+ "', error code '" + warningToLog.getErrorCode() + "', message ["
+ warningToLog.getMessage() + "]"); // depends on control dependency: [while], data = [none]
warningToLog = warningToLog.getNextWarning(); // depends on control dependency: [while], data = [none]
}
}
} catch (SQLException ex) {
boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
if (continueOnError || (dropStatement && ignoreFailedDrops)) {
if (logger.isDebugEnabled()) {
logger.debug(ScriptStatementFailedException.buildErrorMessage(statement, stmtNumber,
resource), ex); // depends on control dependency: [if], data = [none]
}
} else {
throw new ScriptStatementFailedException(statement, stmtNumber, resource, ex);
}
} // depends on control dependency: [catch], data = [none]
}
} finally {
try {
stmt.close(); // depends on control dependency: [try], data = [none]
} catch (Throwable ex) {
logger.debug("Could not close JDBC Statement", ex);
} // depends on control dependency: [catch], data = [none]
}
long elapsedTime = System.currentTimeMillis() - startTime;
if (logger.isInfoEnabled()) {
logger.info("Executed SQL script from " + resource + " in " + elapsedTime + " ms.");
}
} catch (Exception ex) {
if (ex instanceof ScriptException) {
throw (ScriptException) ex;
}
throw new UncategorizedScriptException("Failed to execute database script from resource [" + resource + "]",
ex);
}
} } |
public class class_name {
public static String replace(final String message, final KeyValue... keyValue) {
if (keyValue == null) {
return message;
}
final Map<String, String> map = new HashMap<String, String>();
for (final KeyValue kv : keyValue) {
if (kv.getValue() instanceof Collection) {
final StringBuffer sb = new StringBuffer();
final Collection<?> coll = (Collection<?>) kv.getValue();
int count = 0;
for (final Object entry : coll) {
if (count > 0) {
sb.append(", ");
}
sb.append(nullSafeAsString(entry));
count++;
}
map.put(kv.getKey(), sb.toString());
} else {
map.put(kv.getKey(), kv.getValueString());
}
}
return replaceVars(message, map);
} } | public class class_name {
public static String replace(final String message, final KeyValue... keyValue) {
if (keyValue == null) {
return message;
// depends on control dependency: [if], data = [none]
}
final Map<String, String> map = new HashMap<String, String>();
for (final KeyValue kv : keyValue) {
if (kv.getValue() instanceof Collection) {
final StringBuffer sb = new StringBuffer();
final Collection<?> coll = (Collection<?>) kv.getValue();
int count = 0;
for (final Object entry : coll) {
if (count > 0) {
sb.append(", ");
// depends on control dependency: [if], data = [none]
}
sb.append(nullSafeAsString(entry));
// depends on control dependency: [for], data = [entry]
count++;
// depends on control dependency: [for], data = [none]
}
map.put(kv.getKey(), sb.toString());
// depends on control dependency: [if], data = [none]
} else {
map.put(kv.getKey(), kv.getValueString());
// depends on control dependency: [if], data = [none]
}
}
return replaceVars(message, map);
} } |
public class class_name {
static DirectQuickSelectSketch writableWrap(final WritableMemory srcMem, final long seed) {
final int preambleLongs = extractPreLongs(srcMem); //byte 0
final int lgNomLongs = extractLgNomLongs(srcMem); //byte 3
final int lgArrLongs = extractLgArrLongs(srcMem); //byte 4
UpdateSketch.checkUnionQuickSelectFamily(srcMem, preambleLongs, lgNomLongs);
checkMemIntegrity(srcMem, seed, preambleLongs, lgNomLongs, lgArrLongs);
final int lgRF = extractLgResizeFactor(srcMem); //byte 0
final ResizeFactor myRF = ResizeFactor.getRF(lgRF);
if ((myRF == ResizeFactor.X1)
&& (lgArrLongs != Util.startingSubMultiple(lgNomLongs + 1, myRF, MIN_LG_ARR_LONGS))) {
insertLgResizeFactor(srcMem, ResizeFactor.X2.lg());
}
final DirectQuickSelectSketch dqss =
new DirectQuickSelectSketch(seed, srcMem);
dqss.hashTableThreshold_ = setHashTableThreshold(lgNomLongs, lgArrLongs);
return dqss;
} } | public class class_name {
static DirectQuickSelectSketch writableWrap(final WritableMemory srcMem, final long seed) {
final int preambleLongs = extractPreLongs(srcMem); //byte 0
final int lgNomLongs = extractLgNomLongs(srcMem); //byte 3
final int lgArrLongs = extractLgArrLongs(srcMem); //byte 4
UpdateSketch.checkUnionQuickSelectFamily(srcMem, preambleLongs, lgNomLongs);
checkMemIntegrity(srcMem, seed, preambleLongs, lgNomLongs, lgArrLongs);
final int lgRF = extractLgResizeFactor(srcMem); //byte 0
final ResizeFactor myRF = ResizeFactor.getRF(lgRF);
if ((myRF == ResizeFactor.X1)
&& (lgArrLongs != Util.startingSubMultiple(lgNomLongs + 1, myRF, MIN_LG_ARR_LONGS))) {
insertLgResizeFactor(srcMem, ResizeFactor.X2.lg()); // depends on control dependency: [if], data = [none]
}
final DirectQuickSelectSketch dqss =
new DirectQuickSelectSketch(seed, srcMem);
dqss.hashTableThreshold_ = setHashTableThreshold(lgNomLongs, lgArrLongs);
return dqss;
} } |
public class class_name {
public void setQualificationRequests(java.util.Collection<QualificationRequest> qualificationRequests) {
if (qualificationRequests == null) {
this.qualificationRequests = null;
return;
}
this.qualificationRequests = new java.util.ArrayList<QualificationRequest>(qualificationRequests);
} } | public class class_name {
public void setQualificationRequests(java.util.Collection<QualificationRequest> qualificationRequests) {
if (qualificationRequests == null) {
this.qualificationRequests = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.qualificationRequests = new java.util.ArrayList<QualificationRequest>(qualificationRequests);
} } |
public class class_name {
public static List<String> getValues(String csvRow) {
List<String> values = new ArrayList<String>();
StringReader in = new StringReader(csvRow);
String value;
try {
value = nextValue(in);
while (true) {
values.add(value);
value = nextValue(in);
}
} catch (IOException e) {
// TODO handle case of final null value better?
if (csvRow.lastIndexOf(',') == csvRow.length() - 1)
values.add(null);
return values;
}
} } | public class class_name {
public static List<String> getValues(String csvRow) {
List<String> values = new ArrayList<String>();
StringReader in = new StringReader(csvRow);
String value;
try {
value = nextValue(in); // depends on control dependency: [try], data = [none]
while (true) {
values.add(value); // depends on control dependency: [while], data = [none]
value = nextValue(in); // depends on control dependency: [while], data = [none]
}
} catch (IOException e) {
// TODO handle case of final null value better?
if (csvRow.lastIndexOf(',') == csvRow.length() - 1)
values.add(null);
return values;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static InputStream getRequiredResourceAsStream(Class<?> clzz, String location) {
InputStream resourceStream = clzz.getResourceAsStream(location);
if (resourceStream == null) {
// Try with a leading "/"
if (!location.startsWith("/")) {
resourceStream = clzz.getResourceAsStream("/" + location);
}
if (resourceStream == null) {
throw new RuntimeException("Resource file was not found at location " + location);
}
}
return resourceStream;
} } | public class class_name {
public static InputStream getRequiredResourceAsStream(Class<?> clzz, String location) {
InputStream resourceStream = clzz.getResourceAsStream(location);
if (resourceStream == null) {
// Try with a leading "/"
if (!location.startsWith("/")) {
resourceStream = clzz.getResourceAsStream("/" + location); // depends on control dependency: [if], data = [none]
}
if (resourceStream == null) {
throw new RuntimeException("Resource file was not found at location " + location);
}
}
return resourceStream;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public void setWriterPostProcessor(String writerPostProcessor) {
if (writePostProcessors == null) {
writePostProcessors = new LinkedList<>();
}
try {
writePostProcessors.add((Class<IPostProcessor>) Class.forName(writerPostProcessor));
} catch (Exception e) {
log.debug("Write post process implementation: {} was not found", writerPostProcessor);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public void setWriterPostProcessor(String writerPostProcessor) {
if (writePostProcessors == null) {
writePostProcessors = new LinkedList<>(); // depends on control dependency: [if], data = [none]
}
try {
writePostProcessors.add((Class<IPostProcessor>) Class.forName(writerPostProcessor)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
log.debug("Write post process implementation: {} was not found", writerPostProcessor);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public final int getNumberOfCommandLineArgs() {
if (commandLine == null) {
return 0;
}
List<?> args = commandLine.getArgList();
if (args == null) {
return 0;
}
return args.size();
} } | public class class_name {
public final int getNumberOfCommandLineArgs() {
if (commandLine == null) {
return 0; // depends on control dependency: [if], data = [none]
}
List<?> args = commandLine.getArgList();
if (args == null) {
return 0; // depends on control dependency: [if], data = [none]
}
return args.size();
} } |
public class class_name {
public static List<String> getParamNames(Constructor<?> constructor) {
try {
int size = constructor.getParameterTypes().length;
if (size == 0)
return new ArrayList<String>(0);
List<String> list = ClassMetaReader.getParamNames(constructor.getDeclaringClass()).get(ClassMetaReader.getKey(constructor));
if (list != null && list.size() != size)
return list.subList(0, size);
return list;
} catch (Throwable e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static List<String> getParamNames(Constructor<?> constructor) {
try {
int size = constructor.getParameterTypes().length;
if (size == 0)
return new ArrayList<String>(0);
List<String> list = ClassMetaReader.getParamNames(constructor.getDeclaringClass()).get(ClassMetaReader.getKey(constructor));
if (list != null && list.size() != size)
return list.subList(0, size);
return list; // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public final Collection<SNIMatcher> getSNIMatchers() {
if (sniMatchers != null) {
if (!sniMatchers.isEmpty()) {
return Collections.<SNIMatcher>unmodifiableList(
new ArrayList<>(sniMatchers.values()));
} else {
return Collections.<SNIMatcher>emptyList();
}
}
return null;
} } | public class class_name {
public final Collection<SNIMatcher> getSNIMatchers() {
if (sniMatchers != null) {
if (!sniMatchers.isEmpty()) {
return Collections.<SNIMatcher>unmodifiableList(
new ArrayList<>(sniMatchers.values())); // depends on control dependency: [if], data = [none]
} else {
return Collections.<SNIMatcher>emptyList(); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public User incrementInvalidLoginForUser(User userParam)
{
if(userParam != null && this.serviceTicket != null)
{
userParam.setServiceTicket(this.serviceTicket);
}
return new User(this.postJson(
userParam,
WS.Path.User.Version1.incrementInvalidLogin()));
} } | public class class_name {
public User incrementInvalidLoginForUser(User userParam)
{
if(userParam != null && this.serviceTicket != null)
{
userParam.setServiceTicket(this.serviceTicket); // depends on control dependency: [if], data = [none]
}
return new User(this.postJson(
userParam,
WS.Path.User.Version1.incrementInvalidLogin()));
} } |
public class class_name {
public static boolean sleep(long milliseconds, int nanoseconds) {
try {
Thread.sleep(milliseconds, nanoseconds);
return true;
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
} } | public class class_name {
public static boolean sleep(long milliseconds, int nanoseconds) {
try {
Thread.sleep(milliseconds, nanoseconds); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public String build(final InternalKnowledgePackage pkg,
final FunctionDescr functionDescr,
final TypeResolver typeResolver,
final Map<String, LineMappings> lineMappings,
final List<KnowledgeBuilderResult> errors) {
final Map<String, Object> vars = new HashMap<String, Object>();
vars.put("package",
pkg.getName());
vars.put("imports",
pkg.getImports().keySet());
final List<String> staticImports = new LinkedList<String>();
for (String staticImport : pkg.getStaticImports()) {
if (!staticImport.endsWith(functionDescr.getName())) {
staticImports.add(staticImport);
}
}
vars.put("staticImports",
staticImports);
vars.put("className",
StringUtils.ucFirst(functionDescr.getName()));
vars.put("methodName",
functionDescr.getName());
vars.put("returnType",
functionDescr.getReturnType());
vars.put("parameterTypes",
functionDescr.getParameterTypes());
vars.put("parameterNames",
functionDescr.getParameterNames());
vars.put("hashCode",
functionDescr.getText().hashCode());
// Check that all the parameters are resolvable
final List<String> names = functionDescr.getParameterNames();
final List<String> types = functionDescr.getParameterTypes();
for (int i = 0, size = names.size(); i < size; i++) {
try {
typeResolver.resolveType(types.get(i));
} catch (final ClassNotFoundException e) {
errors.add(new FunctionError(functionDescr,
e,
"Unable to resolve type " + types.get(i) + " while building function."));
break;
}
}
vars.put("text",
functionDescr.getText());
final String text = String.valueOf(TemplateRuntime.eval(template, null, new MapVariableResolverFactory(vars)));
final BufferedReader reader = new BufferedReader(new StringReader(text));
final String lineStartsWith = " public static " + functionDescr.getReturnType() + " " + functionDescr.getName();
try {
String line;
int offset = 0;
while ((line = reader.readLine()) != null) {
offset++;
if (line.startsWith(lineStartsWith)) {
break;
}
}
functionDescr.setOffset(offset);
} catch (final IOException e) {
// won't ever happen, it's just reading over a string.
throw new RuntimeException("Error determining start offset with function");
}
final String name = pkg.getName() + "." + StringUtils.ucFirst(functionDescr.getName());
final LineMappings mapping = new LineMappings(name);
mapping.setStartLine(functionDescr.getLine());
mapping.setOffset(functionDescr.getOffset());
lineMappings.put(name,
mapping);
return text;
} } | public class class_name {
public String build(final InternalKnowledgePackage pkg,
final FunctionDescr functionDescr,
final TypeResolver typeResolver,
final Map<String, LineMappings> lineMappings,
final List<KnowledgeBuilderResult> errors) {
final Map<String, Object> vars = new HashMap<String, Object>();
vars.put("package",
pkg.getName());
vars.put("imports",
pkg.getImports().keySet());
final List<String> staticImports = new LinkedList<String>();
for (String staticImport : pkg.getStaticImports()) {
if (!staticImport.endsWith(functionDescr.getName())) {
staticImports.add(staticImport); // depends on control dependency: [if], data = [none]
}
}
vars.put("staticImports",
staticImports);
vars.put("className",
StringUtils.ucFirst(functionDescr.getName()));
vars.put("methodName",
functionDescr.getName());
vars.put("returnType",
functionDescr.getReturnType());
vars.put("parameterTypes",
functionDescr.getParameterTypes());
vars.put("parameterNames",
functionDescr.getParameterNames());
vars.put("hashCode",
functionDescr.getText().hashCode());
// Check that all the parameters are resolvable
final List<String> names = functionDescr.getParameterNames();
final List<String> types = functionDescr.getParameterTypes();
for (int i = 0, size = names.size(); i < size; i++) {
try {
typeResolver.resolveType(types.get(i)); // depends on control dependency: [try], data = [none]
} catch (final ClassNotFoundException e) {
errors.add(new FunctionError(functionDescr,
e,
"Unable to resolve type " + types.get(i) + " while building function."));
break;
} // depends on control dependency: [catch], data = [none]
}
vars.put("text",
functionDescr.getText());
final String text = String.valueOf(TemplateRuntime.eval(template, null, new MapVariableResolverFactory(vars)));
final BufferedReader reader = new BufferedReader(new StringReader(text));
final String lineStartsWith = " public static " + functionDescr.getReturnType() + " " + functionDescr.getName();
try {
String line;
int offset = 0;
while ((line = reader.readLine()) != null) {
offset++; // depends on control dependency: [while], data = [none]
if (line.startsWith(lineStartsWith)) {
break;
}
}
functionDescr.setOffset(offset); // depends on control dependency: [try], data = [none]
} catch (final IOException e) {
// won't ever happen, it's just reading over a string.
throw new RuntimeException("Error determining start offset with function");
} // depends on control dependency: [catch], data = [none]
final String name = pkg.getName() + "." + StringUtils.ucFirst(functionDescr.getName());
final LineMappings mapping = new LineMappings(name);
mapping.setStartLine(functionDescr.getLine());
mapping.setOffset(functionDescr.getOffset());
lineMappings.put(name,
mapping);
return text;
} } |
public class class_name {
public static <T> List<Tag<T>> fromMap(Map<? extends String, T> tagsMap) {
ImmutableList.Builder<Tag<T>> tagsBuilder = ImmutableList.builder();
for (Map.Entry<? extends String, T> entry : tagsMap.entrySet()) {
tagsBuilder.add(new Tag<>(entry));
}
return tagsBuilder.build();
} } | public class class_name {
public static <T> List<Tag<T>> fromMap(Map<? extends String, T> tagsMap) {
ImmutableList.Builder<Tag<T>> tagsBuilder = ImmutableList.builder();
for (Map.Entry<? extends String, T> entry : tagsMap.entrySet()) {
tagsBuilder.add(new Tag<>(entry)); // depends on control dependency: [for], data = [entry]
}
return tagsBuilder.build();
} } |
public class class_name {
@Override
public void publish() {
try {
String destination = String.format(DESTINATION, vip);
executePost(destination, createJsonFromConfig(config));
} catch (JSONException e) {
/* forget it */
}
} } | public class class_name {
@Override
public void publish() {
try {
String destination = String.format(DESTINATION, vip);
executePost(destination, createJsonFromConfig(config)); // depends on control dependency: [try], data = [none]
} catch (JSONException e) {
/* forget it */
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public String retrieveData(String token) {
try {
RetrievedContent data = this.s3StorageProvider.getContent(this.hiddenSpaceName, token);
return IOUtil.readStringFromStream(data.getContentStream());
} catch (NotFoundException ex) {
return null;
} catch (Exception ex) {
throw new DuraCloudRuntimeException(ex);
}
} } | public class class_name {
public String retrieveData(String token) {
try {
RetrievedContent data = this.s3StorageProvider.getContent(this.hiddenSpaceName, token);
return IOUtil.readStringFromStream(data.getContentStream());
// depends on control dependency: [try], data = [none]
} catch (NotFoundException ex) {
return null;
} catch (Exception ex) {
// depends on control dependency: [catch], data = [none]
throw new DuraCloudRuntimeException(ex);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private boolean isQuery(HttpServerExchange serverExchange) {
if (serverExchange.getRequestMethod().toString().equalsIgnoreCase("GET") || serverExchange.getRequestMethod().toString().equalsIgnoreCase("HEAD")) {
// all GET requests are considered queries
return true;
} else if (serverExchange.getRequestMethod().toString().equalsIgnoreCase("POST")) {
// some POST requests may be queries we need to check.
if (postQuery != null && postQuery.matcher(serverExchange.getRelativePath()).find()) {
return true;
} else {
return false;
}
} else {
return false;
}
} } | public class class_name {
private boolean isQuery(HttpServerExchange serverExchange) {
if (serverExchange.getRequestMethod().toString().equalsIgnoreCase("GET") || serverExchange.getRequestMethod().toString().equalsIgnoreCase("HEAD")) {
// all GET requests are considered queries
return true; // depends on control dependency: [if], data = [none]
} else if (serverExchange.getRequestMethod().toString().equalsIgnoreCase("POST")) {
// some POST requests may be queries we need to check.
if (postQuery != null && postQuery.matcher(serverExchange.getRelativePath()).find()) {
return true; // depends on control dependency: [if], data = [none]
} else {
return false; // depends on control dependency: [if], data = [none]
}
} else {
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void cacheResult(List<CommerceDiscountRule> commerceDiscountRules) {
for (CommerceDiscountRule commerceDiscountRule : commerceDiscountRules) {
if (entityCache.getResult(
CommerceDiscountRuleModelImpl.ENTITY_CACHE_ENABLED,
CommerceDiscountRuleImpl.class,
commerceDiscountRule.getPrimaryKey()) == null) {
cacheResult(commerceDiscountRule);
}
else {
commerceDiscountRule.resetOriginalValues();
}
}
} } | public class class_name {
@Override
public void cacheResult(List<CommerceDiscountRule> commerceDiscountRules) {
for (CommerceDiscountRule commerceDiscountRule : commerceDiscountRules) {
if (entityCache.getResult(
CommerceDiscountRuleModelImpl.ENTITY_CACHE_ENABLED,
CommerceDiscountRuleImpl.class,
commerceDiscountRule.getPrimaryKey()) == null) {
cacheResult(commerceDiscountRule); // depends on control dependency: [if], data = [none]
}
else {
commerceDiscountRule.resetOriginalValues(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static <T extends Comparable<? super T>> void descDeep(final T[] comparableArray) {
if (ArrayUtils.isEmpty(comparableArray)) {
return;
}
descByReflex(comparableArray);
} } | public class class_name {
public static <T extends Comparable<? super T>> void descDeep(final T[] comparableArray) {
if (ArrayUtils.isEmpty(comparableArray)) {
return; // depends on control dependency: [if], data = [none]
}
descByReflex(comparableArray);
} } |
public class class_name {
public Source withSourceDetails(SourceDetail... sourceDetails) {
if (this.sourceDetails == null) {
setSourceDetails(new com.amazonaws.internal.SdkInternalList<SourceDetail>(sourceDetails.length));
}
for (SourceDetail ele : sourceDetails) {
this.sourceDetails.add(ele);
}
return this;
} } | public class class_name {
public Source withSourceDetails(SourceDetail... sourceDetails) {
if (this.sourceDetails == null) {
setSourceDetails(new com.amazonaws.internal.SdkInternalList<SourceDetail>(sourceDetails.length)); // depends on control dependency: [if], data = [none]
}
for (SourceDetail ele : sourceDetails) {
this.sourceDetails.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@Override
public Date getScheduleTime() {
if (nextScheduleTimeAdd < 0) {
return null;
}
long current = System.currentTimeMillis();
Date nextSchedule = new Date(current + nextScheduleTimeAdd);
logger.debug("Next schedule for job {} is set to {}", this.getClass().getSimpleName(), nextSchedule);
return nextSchedule;
} } | public class class_name {
@Override
public Date getScheduleTime() {
if (nextScheduleTimeAdd < 0) {
return null; // depends on control dependency: [if], data = [none]
}
long current = System.currentTimeMillis();
Date nextSchedule = new Date(current + nextScheduleTimeAdd);
logger.debug("Next schedule for job {} is set to {}", this.getClass().getSimpleName(), nextSchedule);
return nextSchedule;
} } |
public class class_name {
public void signal(String conditionId, int maxSignalCount, String objectName) {
if (waiters == null) {
return;
}
Set<WaitersInfo.ConditionWaiter> waiters;
WaitersInfo condition = this.waiters.get(conditionId);
if (condition == null) {
return;
} else {
waiters = condition.getWaiters();
}
if (waiters == null) {
return;
}
Iterator<WaitersInfo.ConditionWaiter> iterator = waiters.iterator();
for (int i = 0; iterator.hasNext() && i < maxSignalCount; i++) {
WaitersInfo.ConditionWaiter waiter = iterator.next();
ConditionKey signalKey = new ConditionKey(objectName,
key, conditionId, waiter.getCaller(), waiter.getThreadId());
registerSignalKey(signalKey);
iterator.remove();
}
if (!condition.hasWaiter()) {
this.waiters.remove(conditionId);
}
} } | public class class_name {
public void signal(String conditionId, int maxSignalCount, String objectName) {
if (waiters == null) {
return; // depends on control dependency: [if], data = [none]
}
Set<WaitersInfo.ConditionWaiter> waiters;
WaitersInfo condition = this.waiters.get(conditionId);
if (condition == null) {
return; // depends on control dependency: [if], data = [none]
} else {
waiters = condition.getWaiters(); // depends on control dependency: [if], data = [none]
}
if (waiters == null) {
return; // depends on control dependency: [if], data = [none]
}
Iterator<WaitersInfo.ConditionWaiter> iterator = waiters.iterator();
for (int i = 0; iterator.hasNext() && i < maxSignalCount; i++) {
WaitersInfo.ConditionWaiter waiter = iterator.next();
ConditionKey signalKey = new ConditionKey(objectName,
key, conditionId, waiter.getCaller(), waiter.getThreadId());
registerSignalKey(signalKey); // depends on control dependency: [for], data = [none]
iterator.remove(); // depends on control dependency: [for], data = [none]
}
if (!condition.hasWaiter()) {
this.waiters.remove(conditionId); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private Object readEmbeddedProperty(String column) {
String[] split = split( column );
Node embeddedNode = node;
for ( int i = 0; i < split.length - 1; i++ ) {
String relType = split[i];
Iterator<Relationship> rels = embeddedNode.getRelationships( Direction.OUTGOING, withName( relType ) ).iterator();
if ( rels.hasNext() ) {
embeddedNode = rels.next().getEndNode();
}
else {
return null;
}
}
return readProperty( embeddedNode, split[split.length - 1] );
} } | public class class_name {
private Object readEmbeddedProperty(String column) {
String[] split = split( column );
Node embeddedNode = node;
for ( int i = 0; i < split.length - 1; i++ ) {
String relType = split[i];
Iterator<Relationship> rels = embeddedNode.getRelationships( Direction.OUTGOING, withName( relType ) ).iterator();
if ( rels.hasNext() ) {
embeddedNode = rels.next().getEndNode(); // depends on control dependency: [if], data = [none]
}
else {
return null; // depends on control dependency: [if], data = [none]
}
}
return readProperty( embeddedNode, split[split.length - 1] );
} } |
public class class_name {
@Override
public void close() throws IOException {
List<Exception> closeExceptions = new ArrayList<>(delegates.size());
for (Writer delegate : delegates) {
try {
delegate.close();
} catch (IOException | RuntimeException closeException) {
closeExceptions.add(closeException);
}
}
if (!closeExceptions.isEmpty()) {
throw mergeExceptions("closing", closeExceptions);
}
} } | public class class_name {
@Override
public void close() throws IOException {
List<Exception> closeExceptions = new ArrayList<>(delegates.size());
for (Writer delegate : delegates) {
try {
delegate.close(); // depends on control dependency: [try], data = [none]
} catch (IOException | RuntimeException closeException) {
closeExceptions.add(closeException);
} // depends on control dependency: [catch], data = [none]
}
if (!closeExceptions.isEmpty()) {
throw mergeExceptions("closing", closeExceptions);
}
} } |
public class class_name {
public void disableSearchTab() {
if (m_resultsTab != null) {
m_tabbedPanel.disableTab(m_resultsTab, Messages.get().key(Messages.GUI_GALLERY_NO_PARAMS_0));
}
} } | public class class_name {
public void disableSearchTab() {
if (m_resultsTab != null) {
m_tabbedPanel.disableTab(m_resultsTab, Messages.get().key(Messages.GUI_GALLERY_NO_PARAMS_0)); // depends on control dependency: [if], data = [(m_resultsTab]
}
} } |
public class class_name {
private void go() throws IOException {
long start = System.currentTimeMillis();
System.out.println("Decompressing image file: " + inputFile + " to "
+ outputFile);
DataInputStream in = null;
DataOutputStream out = null;
try {
// setup in
PositionTrackingInputStream ptis = new PositionTrackingInputStream(
new FileInputStream(new File(inputFile)));
in = new DataInputStream(ptis);
// read header information
int imgVersion = in.readInt();
if (!LayoutVersion.supports(Feature.FSIMAGE_COMPRESSION, imgVersion)) {
System.out
.println("Image is not compressed. No output will be produced.");
return;
}
int namespaceId = in.readInt();
long numFiles = in.readLong();
long genstamp = in.readLong();
long imgTxId = -1;
if (LayoutVersion.supports(Feature.STORED_TXIDS, imgVersion)) {
imgTxId = in.readLong();
}
FSImageCompression compression = FSImageCompression
.readCompressionHeader(new Configuration(), in);
if (compression.isNoOpCompression()) {
System.out
.println("Image is not compressed. No output will be produced.");
return;
}
in = BufferedByteInputStream.wrapInputStream(
compression.unwrapInputStream(in), FSImage.LOAD_SAVE_BUFFER_SIZE,
FSImage.LOAD_SAVE_CHUNK_SIZE);
System.out.println("Starting decompression.");
// setup output
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(
outputFile)));
// write back the uncompressed information
out.writeInt(imgVersion);
out.writeInt(namespaceId);
out.writeLong(numFiles);
out.writeLong(genstamp);
if (LayoutVersion.supports(Feature.STORED_TXIDS, imgVersion)) {
out.writeLong(imgTxId);
}
// no compression
out.writeBoolean(false);
// copy the data
long size = new File(inputFile).length();
// read in 1MB chunks
byte[] block = new byte[1024 * 1024];
while (true) {
int bytesRead = in.read(block);
if (bytesRead <= 0)
break;
out.write(block, 0, bytesRead);
printProgress(ptis.getPos(), size);
}
out.close();
long stop = System.currentTimeMillis();
System.out.println("Input file : " + inputFile + " size: " + size);
System.out.println("Output file: " + outputFile + " size: "
+ new File(outputFile).length());
System.out.println("Decompression completed in " + (stop - start)
+ " ms.");
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
} } | public class class_name {
private void go() throws IOException {
long start = System.currentTimeMillis();
System.out.println("Decompressing image file: " + inputFile + " to "
+ outputFile);
DataInputStream in = null;
DataOutputStream out = null;
try {
// setup in
PositionTrackingInputStream ptis = new PositionTrackingInputStream(
new FileInputStream(new File(inputFile)));
in = new DataInputStream(ptis);
// read header information
int imgVersion = in.readInt();
if (!LayoutVersion.supports(Feature.FSIMAGE_COMPRESSION, imgVersion)) {
System.out
.println("Image is not compressed. No output will be produced."); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
int namespaceId = in.readInt();
long numFiles = in.readLong();
long genstamp = in.readLong();
long imgTxId = -1;
if (LayoutVersion.supports(Feature.STORED_TXIDS, imgVersion)) {
imgTxId = in.readLong(); // depends on control dependency: [if], data = [none]
}
FSImageCompression compression = FSImageCompression
.readCompressionHeader(new Configuration(), in);
if (compression.isNoOpCompression()) {
System.out
.println("Image is not compressed. No output will be produced."); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
in = BufferedByteInputStream.wrapInputStream(
compression.unwrapInputStream(in), FSImage.LOAD_SAVE_BUFFER_SIZE,
FSImage.LOAD_SAVE_CHUNK_SIZE);
System.out.println("Starting decompression.");
// setup output
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(
outputFile)));
// write back the uncompressed information
out.writeInt(imgVersion);
out.writeInt(namespaceId);
out.writeLong(numFiles);
out.writeLong(genstamp);
if (LayoutVersion.supports(Feature.STORED_TXIDS, imgVersion)) {
out.writeLong(imgTxId); // depends on control dependency: [if], data = [none]
}
// no compression
out.writeBoolean(false);
// copy the data
long size = new File(inputFile).length();
// read in 1MB chunks
byte[] block = new byte[1024 * 1024];
while (true) {
int bytesRead = in.read(block);
if (bytesRead <= 0)
break;
out.write(block, 0, bytesRead); // depends on control dependency: [while], data = [none]
printProgress(ptis.getPos(), size); // depends on control dependency: [while], data = [none]
}
out.close();
long stop = System.currentTimeMillis();
System.out.println("Input file : " + inputFile + " size: " + size);
System.out.println("Output file: " + outputFile + " size: "
+ new File(outputFile).length());
System.out.println("Decompression completed in " + (stop - start)
+ " ms.");
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
} } |
public class class_name {
@Override
public void put(String key, String val) {
if (key == null) {
throw new IllegalArgumentException("key cannot be null");
}
Map<String, String> map = inheritableThreadLocal.get();
if (map == null) {
map = new HashMap<>();
inheritableThreadLocal.set(map);
}
map.put(key, val);
} } | public class class_name {
@Override
public void put(String key, String val) {
if (key == null) {
throw new IllegalArgumentException("key cannot be null");
}
Map<String, String> map = inheritableThreadLocal.get();
if (map == null) {
map = new HashMap<>(); // depends on control dependency: [if], data = [none]
inheritableThreadLocal.set(map); // depends on control dependency: [if], data = [(map]
}
map.put(key, val);
} } |
public class class_name {
@Override
public void visitCode(Code obj) {
try {
userValues = new HashMap<>();
loops = new HashMap<>();
isInstanceMethod = !getMethod().isStatic();
super.visitCode(obj);
} finally {
userValues = null;
loops = null;
}
} } | public class class_name {
@Override
public void visitCode(Code obj) {
try {
userValues = new HashMap<>(); // depends on control dependency: [try], data = [none]
loops = new HashMap<>(); // depends on control dependency: [try], data = [none]
isInstanceMethod = !getMethod().isStatic(); // depends on control dependency: [try], data = [none]
super.visitCode(obj); // depends on control dependency: [try], data = [none]
} finally {
userValues = null;
loops = null;
}
} } |
public class class_name {
public static List<CommerceWishListItem> toModels(
CommerceWishListItemSoap[] soapModels) {
if (soapModels == null) {
return null;
}
List<CommerceWishListItem> models = new ArrayList<CommerceWishListItem>(soapModels.length);
for (CommerceWishListItemSoap soapModel : soapModels) {
models.add(toModel(soapModel));
}
return models;
} } | public class class_name {
public static List<CommerceWishListItem> toModels(
CommerceWishListItemSoap[] soapModels) {
if (soapModels == null) {
return null; // depends on control dependency: [if], data = [none]
}
List<CommerceWishListItem> models = new ArrayList<CommerceWishListItem>(soapModels.length);
for (CommerceWishListItemSoap soapModel : soapModels) {
models.add(toModel(soapModel)); // depends on control dependency: [for], data = [soapModel]
}
return models;
} } |
public class class_name {
private void addPostParams(final Request request) {
if (identifier != null) {
request.addPostParam("Identifier", identifier);
}
if (friendlyName != null) {
request.addPostParam("FriendlyName", friendlyName);
}
if (proxyIdentifier != null) {
request.addPostParam("ProxyIdentifier", proxyIdentifier);
}
if (proxyIdentifierSid != null) {
request.addPostParam("ProxyIdentifierSid", proxyIdentifierSid);
}
} } | public class class_name {
private void addPostParams(final Request request) {
if (identifier != null) {
request.addPostParam("Identifier", identifier); // depends on control dependency: [if], data = [none]
}
if (friendlyName != null) {
request.addPostParam("FriendlyName", friendlyName); // depends on control dependency: [if], data = [none]
}
if (proxyIdentifier != null) {
request.addPostParam("ProxyIdentifier", proxyIdentifier); // depends on control dependency: [if], data = [none]
}
if (proxyIdentifierSid != null) {
request.addPostParam("ProxyIdentifierSid", proxyIdentifierSid); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static int origin(Alignment alignment,
int cellOrigin,
int cellSize,
int componentSize) {
if (alignment == RIGHT || alignment == BOTTOM) {
return cellOrigin + cellSize - componentSize;
} else if (alignment == CENTER) {
return cellOrigin + (cellSize - componentSize) / 2;
} else { // left, top, fill
return cellOrigin;
}
} } | public class class_name {
private static int origin(Alignment alignment,
int cellOrigin,
int cellSize,
int componentSize) {
if (alignment == RIGHT || alignment == BOTTOM) {
return cellOrigin + cellSize - componentSize; // depends on control dependency: [if], data = [none]
} else if (alignment == CENTER) {
return cellOrigin + (cellSize - componentSize) / 2; // depends on control dependency: [if], data = [none]
} else { // left, top, fill
return cellOrigin; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected @Nonnull <T> Collection<BeanDefinition> findBeanCandidatesForInstance(@Nonnull T instance) {
ArgumentUtils.requireNonNull("instance", instance);
if (LOG.isDebugEnabled()) {
LOG.debug("Finding candidate beans for instance: {}", instance);
}
Collection<BeanDefinitionReference> beanDefinitionsClasses = this.beanDefinitionsClasses;
return beanCandidateCache.computeIfAbsent(instance.getClass(), aClass -> {
// first traverse component definition classes and load candidates
if (!beanDefinitionsClasses.isEmpty()) {
List<BeanDefinition> candidates = beanDefinitionsClasses
.stream()
.filter(reference -> {
if (reference.isEnabled(this)) {
Class<?> candidateType = reference.getBeanType();
return candidateType != null && candidateType.isInstance(instance);
} else {
return false;
}
})
.map(ref -> ref.load(this))
.filter(candidate -> candidate.isEnabled(this))
.collect(Collectors.toList());
if (candidates.size() > 1) {
// try narrow to exact type
candidates = candidates
.stream()
.filter(candidate ->
!(candidate instanceof NoInjectionBeanDefinition) &&
candidate.getBeanType() == instance.getClass()
)
.collect(Collectors.toList());
return candidates;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Resolved bean candidates {} for instance: {}", candidates, instance);
}
return candidates;
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("No bean candidates found for instance: {}", instance);
}
return Collections.emptySet();
}
});
} } | public class class_name {
protected @Nonnull <T> Collection<BeanDefinition> findBeanCandidatesForInstance(@Nonnull T instance) {
ArgumentUtils.requireNonNull("instance", instance);
if (LOG.isDebugEnabled()) {
LOG.debug("Finding candidate beans for instance: {}", instance); // depends on control dependency: [if], data = [none]
}
Collection<BeanDefinitionReference> beanDefinitionsClasses = this.beanDefinitionsClasses;
return beanCandidateCache.computeIfAbsent(instance.getClass(), aClass -> {
// first traverse component definition classes and load candidates
if (!beanDefinitionsClasses.isEmpty()) {
List<BeanDefinition> candidates = beanDefinitionsClasses
.stream()
.filter(reference -> {
if (reference.isEnabled(this)) {
Class<?> candidateType = reference.getBeanType();
return candidateType != null && candidateType.isInstance(instance);
} else {
return false;
}
})
.map(ref -> ref.load(this))
.filter(candidate -> candidate.isEnabled(this))
.collect(Collectors.toList());
if (candidates.size() > 1) {
// try narrow to exact type
candidates = candidates
.stream()
.filter(candidate ->
!(candidate instanceof NoInjectionBeanDefinition) &&
candidate.getBeanType() == instance.getClass()
)
.collect(Collectors.toList()); // depends on control dependency: [if], data = [none]
return candidates; // depends on control dependency: [if], data = [none]
}
if (LOG.isDebugEnabled()) {
LOG.debug("Resolved bean candidates {} for instance: {}", candidates, instance); // depends on control dependency: [if], data = [none]
}
return candidates;
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("No bean candidates found for instance: {}", instance); // depends on control dependency: [if], data = [none]
}
return Collections.emptySet();
}
});
} } |
public class class_name {
public void marshall(GameSessionConnectionInfo gameSessionConnectionInfo, ProtocolMarshaller protocolMarshaller) {
if (gameSessionConnectionInfo == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(gameSessionConnectionInfo.getGameSessionArn(), GAMESESSIONARN_BINDING);
protocolMarshaller.marshall(gameSessionConnectionInfo.getIpAddress(), IPADDRESS_BINDING);
protocolMarshaller.marshall(gameSessionConnectionInfo.getPort(), PORT_BINDING);
protocolMarshaller.marshall(gameSessionConnectionInfo.getMatchedPlayerSessions(), MATCHEDPLAYERSESSIONS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GameSessionConnectionInfo gameSessionConnectionInfo, ProtocolMarshaller protocolMarshaller) {
if (gameSessionConnectionInfo == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(gameSessionConnectionInfo.getGameSessionArn(), GAMESESSIONARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(gameSessionConnectionInfo.getIpAddress(), IPADDRESS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(gameSessionConnectionInfo.getPort(), PORT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(gameSessionConnectionInfo.getMatchedPlayerSessions(), MATCHEDPLAYERSESSIONS_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 {
@Override
protected String resolvePlaceholder(String placeholder, Properties props) {
String resolvedPlaceholder = super.resolvePlaceholder(placeholder, props);
if (null == resolvedPlaceholder) {
LOGGER.trace("could not resolve place holder for key: " + placeholder + ". Please check your configuration files.");
return resolvedPlaceholder;
} else {
return resolvedPlaceholder.trim();
}
} } | public class class_name {
@Override
protected String resolvePlaceholder(String placeholder, Properties props) {
String resolvedPlaceholder = super.resolvePlaceholder(placeholder, props);
if (null == resolvedPlaceholder) {
LOGGER.trace("could not resolve place holder for key: " + placeholder + ". Please check your configuration files."); // depends on control dependency: [if], data = [none]
return resolvedPlaceholder; // depends on control dependency: [if], data = [none]
} else {
return resolvedPlaceholder.trim(); // depends on control dependency: [if], data = [none]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.