code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public void marshall(GetSecurityConfigurationsRequest getSecurityConfigurationsRequest, ProtocolMarshaller protocolMarshaller) {
if (getSecurityConfigurationsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getSecurityConfigurationsRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(getSecurityConfigurationsRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetSecurityConfigurationsRequest getSecurityConfigurationsRequest, ProtocolMarshaller protocolMarshaller) {
if (getSecurityConfigurationsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getSecurityConfigurationsRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getSecurityConfigurationsRequest.getNextToken(), NEXTTOKEN_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 Level getLoggingLevelFromProperties() {
if (levelFromProperties == null) {
final String verboseLevel = JanusConfig.getSystemProperty(JanusConfig.VERBOSE_LEVEL_NAME, JanusConfig.VERBOSE_LEVEL_VALUE);
levelFromProperties = parseLoggingLevel(verboseLevel);
}
return levelFromProperties;
} } | public class class_name {
public static Level getLoggingLevelFromProperties() {
if (levelFromProperties == null) {
final String verboseLevel = JanusConfig.getSystemProperty(JanusConfig.VERBOSE_LEVEL_NAME, JanusConfig.VERBOSE_LEVEL_VALUE);
levelFromProperties = parseLoggingLevel(verboseLevel); // depends on control dependency: [if], data = [none]
}
return levelFromProperties;
} } |
public class class_name {
boolean isEntirelyUnresolvable() {
if (this == NONE) {
return false;
}
ResolvableType[] generics = getGenerics();
for (ResolvableType generic : generics) {
if (!generic.isUnresolvableTypeVariable() && !generic.isWildcardWithoutBounds()) {
return false;
}
}
return true;
} } | public class class_name {
boolean isEntirelyUnresolvable() {
if (this == NONE) {
return false; // depends on control dependency: [if], data = [none]
}
ResolvableType[] generics = getGenerics();
for (ResolvableType generic : generics) {
if (!generic.isUnresolvableTypeVariable() && !generic.isWildcardWithoutBounds()) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public Optional<ArrayPositionSetter> create(final Class<?> beanClass, final String fieldName) {
ArgUtils.notNull(beanClass, "beanClass");
ArgUtils.notEmpty(fieldName, "fieldName");
// フィールド Map positionsの場合
Optional<ArrayPositionSetter> arrayPositionSetter = createMapField(beanClass, fieldName);
if(arrayPositionSetter.isPresent()) {
return arrayPositionSetter;
}
// setter メソッドの場合
arrayPositionSetter = createMethod(beanClass, fieldName);
if(arrayPositionSetter.isPresent()) {
return arrayPositionSetter;
}
// フィールド + positionの場合
arrayPositionSetter = createField(beanClass, fieldName);
if(arrayPositionSetter.isPresent()) {
return arrayPositionSetter;
}
return Optional.empty();
} } | public class class_name {
public Optional<ArrayPositionSetter> create(final Class<?> beanClass, final String fieldName) {
ArgUtils.notNull(beanClass, "beanClass");
ArgUtils.notEmpty(fieldName, "fieldName");
// フィールド Map positionsの場合
Optional<ArrayPositionSetter> arrayPositionSetter = createMapField(beanClass, fieldName);
if(arrayPositionSetter.isPresent()) {
return arrayPositionSetter;
// depends on control dependency: [if], data = [none]
}
// setter メソッドの場合
arrayPositionSetter = createMethod(beanClass, fieldName);
if(arrayPositionSetter.isPresent()) {
return arrayPositionSetter;
// depends on control dependency: [if], data = [none]
}
// フィールド + positionの場合
arrayPositionSetter = createField(beanClass, fieldName);
if(arrayPositionSetter.isPresent()) {
return arrayPositionSetter;
// depends on control dependency: [if], data = [none]
}
return Optional.empty();
} } |
public class class_name {
public KeyVerifyParameters withDigest(byte[] digest) {
if (digest == null) {
this.digest = null;
} else {
this.digest = Base64Url.encode(digest);
}
return this;
} } | public class class_name {
public KeyVerifyParameters withDigest(byte[] digest) {
if (digest == null) {
this.digest = null; // depends on control dependency: [if], data = [none]
} else {
this.digest = Base64Url.encode(digest); // depends on control dependency: [if], data = [(digest]
}
return this;
} } |
public class class_name {
public static ViewHolder obtain(View view) {
if (view.getTag() instanceof ViewHolder) {
return (ViewHolder) view.getTag();
}
return new ViewHolder(view);
} } | public class class_name {
public static ViewHolder obtain(View view) {
if (view.getTag() instanceof ViewHolder) {
return (ViewHolder) view.getTag(); // depends on control dependency: [if], data = [none]
}
return new ViewHolder(view);
} } |
public class class_name {
public Dataset<String, String> getDataset(Dataset<String, String> oldData, Index<String> goodFeatures) {
//public Dataset getDataset(List data, Collection goodFeatures) {
//makeAnswerArraysAndTagIndex(data);
int[][] oldDataArray = oldData.getDataArray();
int[] oldLabelArray = oldData.getLabelsArray();
Index<String> oldFeatureIndex = oldData.featureIndex;
int[] oldToNewFeatureMap = new int[oldFeatureIndex.size()];
int[][] newDataArray = new int[oldDataArray.length][];
System.err.print("Building reduced dataset...");
int size = oldFeatureIndex.size();
int max = 0;
for (int i = 0; i < size; i++) {
oldToNewFeatureMap[i] = goodFeatures.indexOf(oldFeatureIndex.get(i));
if (oldToNewFeatureMap[i] > max) {
max = oldToNewFeatureMap[i];
}
}
for (int i = 0; i < oldDataArray.length; i++) {
int[] data = oldDataArray[i];
size = 0;
for (int j = 0; j < data.length; j++) {
if (oldToNewFeatureMap[data[j]] > 0) {
size++;
}
}
int[] newData = new int[size];
int index = 0;
for (int j = 0; j < data.length; j++) {
int f = oldToNewFeatureMap[data[j]];
if (f > 0) {
newData[index++] = f;
}
}
newDataArray[i] = newData;
}
Dataset<String, String> train = new Dataset<String, String>(oldData.labelIndex, oldLabelArray, goodFeatures, newDataArray, newDataArray.length);
System.err.println("done.");
if (flags.featThreshFile != null) {
System.err.println("applying thresholds...");
List<Pair<Pattern,Integer>> thresh = getThresholds(flags.featThreshFile);
train.applyFeatureCountThreshold(thresh);
} else if (flags.featureThreshold > 1) {
System.err.println("Removing Features with counts < " + flags.featureThreshold);
train.applyFeatureCountThreshold(flags.featureThreshold);
}
train.summaryStatistics();
return train;
} } | public class class_name {
public Dataset<String, String> getDataset(Dataset<String, String> oldData, Index<String> goodFeatures) {
//public Dataset getDataset(List data, Collection goodFeatures) {
//makeAnswerArraysAndTagIndex(data);
int[][] oldDataArray = oldData.getDataArray();
int[] oldLabelArray = oldData.getLabelsArray();
Index<String> oldFeatureIndex = oldData.featureIndex;
int[] oldToNewFeatureMap = new int[oldFeatureIndex.size()];
int[][] newDataArray = new int[oldDataArray.length][];
System.err.print("Building reduced dataset...");
int size = oldFeatureIndex.size();
int max = 0;
for (int i = 0; i < size; i++) {
oldToNewFeatureMap[i] = goodFeatures.indexOf(oldFeatureIndex.get(i));
// depends on control dependency: [for], data = [i]
if (oldToNewFeatureMap[i] > max) {
max = oldToNewFeatureMap[i];
// depends on control dependency: [if], data = [none]
}
}
for (int i = 0; i < oldDataArray.length; i++) {
int[] data = oldDataArray[i];
size = 0;
// depends on control dependency: [for], data = [none]
for (int j = 0; j < data.length; j++) {
if (oldToNewFeatureMap[data[j]] > 0) {
size++;
// depends on control dependency: [if], data = [none]
}
}
int[] newData = new int[size];
int index = 0;
for (int j = 0; j < data.length; j++) {
int f = oldToNewFeatureMap[data[j]];
if (f > 0) {
newData[index++] = f;
// depends on control dependency: [if], data = [none]
}
}
newDataArray[i] = newData;
// depends on control dependency: [for], data = [i]
}
Dataset<String, String> train = new Dataset<String, String>(oldData.labelIndex, oldLabelArray, goodFeatures, newDataArray, newDataArray.length);
System.err.println("done.");
if (flags.featThreshFile != null) {
System.err.println("applying thresholds...");
// depends on control dependency: [if], data = [none]
List<Pair<Pattern,Integer>> thresh = getThresholds(flags.featThreshFile);
train.applyFeatureCountThreshold(thresh);
// depends on control dependency: [if], data = [none]
} else if (flags.featureThreshold > 1) {
System.err.println("Removing Features with counts < " + flags.featureThreshold);
// depends on control dependency: [if], data = [none]
train.applyFeatureCountThreshold(flags.featureThreshold);
// depends on control dependency: [if], data = [(flags.featureThreshold]
}
train.summaryStatistics();
return train;
} } |
public class class_name {
public void offer(final byte[] request, final HttpException e) {
if (!e.isClientError()) {
resendQueue.offer(new HttpResendQueueItem(request));
}
} } | public class class_name {
public void offer(final byte[] request, final HttpException e) {
if (!e.isClientError()) {
resendQueue.offer(new HttpResendQueueItem(request)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public XCalElement child(ICalDataType dataType) {
String localName = dataType.getName().toLowerCase();
for (Element child : children()) {
if (localName.equals(child.getLocalName()) && XCAL_NS.equals(child.getNamespaceURI())) {
return new XCalElement(child);
}
}
return null;
} } | public class class_name {
public XCalElement child(ICalDataType dataType) {
String localName = dataType.getName().toLowerCase();
for (Element child : children()) {
if (localName.equals(child.getLocalName()) && XCAL_NS.equals(child.getNamespaceURI())) {
return new XCalElement(child); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
@Override
public String[] decode(long generation, String tableName, List<VoltType> types, List<String> names, String[] to, Object[] fields) throws RuntimeException {
Preconditions.checkArgument(
fields != null && fields.length > m_firstFieldOffset,
"null or inapropriately sized export row array"
);
/*
* Builds a list of string formatters that reflects the row
* column types.
*/
StringFieldDecoder [] fieldDecoders;
if (!m_fieldDecoders.containsKey(generation)) {
int fieldCount = 0;
Map<String, DecodeType> typeMap = getTypeMap(generation, types, names);
ImmutableList.Builder<StringFieldDecoder> lb = ImmutableList.builder();
for (org.voltdb.exportclient.decode.DecodeType dt: typeMap.values()) {
lb.add(dt.accept(decodingVisitor, fieldCount++, null));
}
fieldDecoders = lb.build().toArray(new StringFieldDecoder[0]);
m_fieldDecoders.put(generation, fieldDecoders);
} else {
fieldDecoders = m_fieldDecoders.get(generation);
}
if (to == null || to.length < fieldDecoders.length) {
to = new String[fieldDecoders.length];
}
for (
int i = m_firstFieldOffset, j = 0;
i < fields.length && j < fieldDecoders.length;
++i, ++j
) {
fieldDecoders[j].decode(to, fields[i]);
}
return to;
} } | public class class_name {
@Override
public String[] decode(long generation, String tableName, List<VoltType> types, List<String> names, String[] to, Object[] fields) throws RuntimeException {
Preconditions.checkArgument(
fields != null && fields.length > m_firstFieldOffset,
"null or inapropriately sized export row array"
);
/*
* Builds a list of string formatters that reflects the row
* column types.
*/
StringFieldDecoder [] fieldDecoders;
if (!m_fieldDecoders.containsKey(generation)) {
int fieldCount = 0;
Map<String, DecodeType> typeMap = getTypeMap(generation, types, names);
ImmutableList.Builder<StringFieldDecoder> lb = ImmutableList.builder();
for (org.voltdb.exportclient.decode.DecodeType dt: typeMap.values()) {
lb.add(dt.accept(decodingVisitor, fieldCount++, null)); // depends on control dependency: [for], data = [dt]
}
fieldDecoders = lb.build().toArray(new StringFieldDecoder[0]);
m_fieldDecoders.put(generation, fieldDecoders);
} else {
fieldDecoders = m_fieldDecoders.get(generation);
}
if (to == null || to.length < fieldDecoders.length) {
to = new String[fieldDecoders.length];
}
for (
int i = m_firstFieldOffset, j = 0;
i < fields.length && j < fieldDecoders.length;
++i, ++j
) {
fieldDecoders[j].decode(to, fields[i]);
}
return to;
} } |
public class class_name {
private AttributeDefinitionSpecification[] getADs(boolean isRequired) {
AttributeDefinitionSpecification[] retVal = null;
Vector<AttributeDefinitionSpecification> vector = new Vector<AttributeDefinitionSpecification>();
for (Map.Entry<String, AttributeDefinitionSpecification> entry : attributes.entrySet()) {
AttributeDefinitionSpecification ad = entry.getValue();
if (isRequired == ad.isRequired()) {
vector.add(ad);
}
}
retVal = new AttributeDefinitionSpecification[vector.size()];
vector.toArray(retVal);
return retVal;
} } | public class class_name {
private AttributeDefinitionSpecification[] getADs(boolean isRequired) {
AttributeDefinitionSpecification[] retVal = null;
Vector<AttributeDefinitionSpecification> vector = new Vector<AttributeDefinitionSpecification>();
for (Map.Entry<String, AttributeDefinitionSpecification> entry : attributes.entrySet()) {
AttributeDefinitionSpecification ad = entry.getValue();
if (isRequired == ad.isRequired()) {
vector.add(ad); // depends on control dependency: [if], data = [none]
}
}
retVal = new AttributeDefinitionSpecification[vector.size()];
vector.toArray(retVal);
return retVal;
} } |
public class class_name {
@InternalApi
int computeDeadlineSeconds() {
int sec = ackLatencyDistribution.getPercentile(PERCENTILE_FOR_ACK_DEADLINE_UPDATES);
// Use Ints.constrainToRange when we get guava 21.
if (sec < Subscriber.MIN_ACK_DEADLINE_SECONDS) {
sec = Subscriber.MIN_ACK_DEADLINE_SECONDS;
} else if (sec > Subscriber.MAX_ACK_DEADLINE_SECONDS) {
sec = Subscriber.MAX_ACK_DEADLINE_SECONDS;
}
return sec;
} } | public class class_name {
@InternalApi
int computeDeadlineSeconds() {
int sec = ackLatencyDistribution.getPercentile(PERCENTILE_FOR_ACK_DEADLINE_UPDATES);
// Use Ints.constrainToRange when we get guava 21.
if (sec < Subscriber.MIN_ACK_DEADLINE_SECONDS) {
sec = Subscriber.MIN_ACK_DEADLINE_SECONDS; // depends on control dependency: [if], data = [none]
} else if (sec > Subscriber.MAX_ACK_DEADLINE_SECONDS) {
sec = Subscriber.MAX_ACK_DEADLINE_SECONDS; // depends on control dependency: [if], data = [none]
}
return sec;
} } |
public class class_name {
public static synchronized MongoClient create(final MongoClientSettings mongoClientSettings) {
if (mongoEmbeddedLibrary == null) {
throw new MongoClientEmbeddedException("The mongo embedded library must be initialized first.");
}
try {
Cluster cluster = new EmbeddedCluster(mongoEmbeddedLibrary, mongoClientSettings);
return new MongoClientImpl(cluster, mongoClientSettings.getWrappedMongoClientSettings(), null);
} catch (Exception e) {
throw new MongoClientEmbeddedException(format("Could not create a new embedded cluster.%n"
+ "Please ensure any existing MongoClients are fully closed before trying to create a new one.%n"
+ "Server error message: %s", e.getMessage()), e);
}
} } | public class class_name {
public static synchronized MongoClient create(final MongoClientSettings mongoClientSettings) {
if (mongoEmbeddedLibrary == null) {
throw new MongoClientEmbeddedException("The mongo embedded library must be initialized first.");
}
try {
Cluster cluster = new EmbeddedCluster(mongoEmbeddedLibrary, mongoClientSettings);
return new MongoClientImpl(cluster, mongoClientSettings.getWrappedMongoClientSettings(), null); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new MongoClientEmbeddedException(format("Could not create a new embedded cluster.%n"
+ "Please ensure any existing MongoClients are fully closed before trying to create a new one.%n"
+ "Server error message: %s", e.getMessage()), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public final void stop() {
if (this.thread != null) {
try {
if (this.thread != null) {
this.thread.interrupt();
synchronized (this.thread) {
this.thread.notifyAll();
}
}
} finally {
this.thread = null;
}
}
} } | public class class_name {
public final void stop() {
if (this.thread != null) {
try {
if (this.thread != null) {
this.thread.interrupt(); // depends on control dependency: [if], data = [none]
synchronized (this.thread) { // depends on control dependency: [if], data = [(this.thread]
this.thread.notifyAll();
}
}
} finally {
this.thread = null;
}
}
} } |
public class class_name {
public String paramsAsHidden(Collection<String> excludes) {
StringBuffer result = new StringBuffer(512);
Map<String, Object> params = paramValues();
Iterator<Entry<String, Object>> i = params.entrySet().iterator();
while (i.hasNext()) {
Entry<String, Object> entry = i.next();
String param = entry.getKey();
if ((excludes == null) || (!excludes.contains(param))) {
result.append("<input type=\"hidden\" name=\"");
result.append(param);
result.append("\" value=\"");
String encoded = CmsEncoder.encode(
entry.getValue().toString(),
getCms().getRequestContext().getEncoding());
result.append(encoded);
result.append("\">\n");
}
}
return result.toString();
} } | public class class_name {
public String paramsAsHidden(Collection<String> excludes) {
StringBuffer result = new StringBuffer(512);
Map<String, Object> params = paramValues();
Iterator<Entry<String, Object>> i = params.entrySet().iterator();
while (i.hasNext()) {
Entry<String, Object> entry = i.next();
String param = entry.getKey();
if ((excludes == null) || (!excludes.contains(param))) {
result.append("<input type=\"hidden\" name=\""); // depends on control dependency: [if], data = [none]
result.append(param); // depends on control dependency: [if], data = [none]
result.append("\" value=\""); // depends on control dependency: [if], data = [none]
String encoded = CmsEncoder.encode(
entry.getValue().toString(),
getCms().getRequestContext().getEncoding());
result.append(encoded); // depends on control dependency: [if], data = [none]
result.append("\">\n"); // depends on control dependency: [if], data = [none]
}
}
return result.toString();
} } |
public class class_name {
private void init() {
if (managers == null) {
managers = new Managers();
}
if (services == null) {
services = createServices(config, managers);
}
} } | public class class_name {
private void init() {
if (managers == null) {
managers = new Managers();
// depends on control dependency: [if], data = [none]
}
if (services == null) {
services = createServices(config, managers);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private String getLogFolderPath() {
String path = null;
if (OpenCms.getRunLevel() >= OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
path = new File(OpenCms.getSystemInfo().getLogFileRfsPath()).getParent();
// making sure the path ends with the file separator CHAR
if ((path != null) && !path.endsWith(File.separator)) {
path += File.separator;
}
}
return path;
} } | public class class_name {
private String getLogFolderPath() {
String path = null;
if (OpenCms.getRunLevel() >= OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
path = new File(OpenCms.getSystemInfo().getLogFileRfsPath()).getParent(); // depends on control dependency: [if], data = [none]
// making sure the path ends with the file separator CHAR
if ((path != null) && !path.endsWith(File.separator)) {
path += File.separator; // depends on control dependency: [if], data = [none]
}
}
return path;
} } |
public class class_name {
private static RecordType typeFromChar(char recChar) {
for (int i=0; i < numRecChars; i++) {
if (recordChars[i] == recChar) {
return recordTypes[i];
}
}
throw new BitsyException(BitsyErrorCodes.INTERNAL_ERROR, "Unrecognized record type " + recChar);
} } | public class class_name {
private static RecordType typeFromChar(char recChar) {
for (int i=0; i < numRecChars; i++) {
if (recordChars[i] == recChar) {
return recordTypes[i]; // depends on control dependency: [if], data = [none]
}
}
throw new BitsyException(BitsyErrorCodes.INTERNAL_ERROR, "Unrecognized record type " + recChar);
} } |
public class class_name {
protected void doLinkSecondPass(final BuildData buildData,
final Map<SpecTopic, Set<String>> usedIdAttributes) throws BuildProcessingException {
final List<SpecTopic> topics = buildData.getBuildDatabase().getAllSpecTopics();
for (final SpecTopic specTopic : topics) {
final Document doc = specTopic.getXMLDocument();
// Get the XRef links in the topic document
final Set<String> linkIds = new HashSet<String>();
DocBookBuildUtilities.getTopicLinkIds(doc, linkIds);
final Map<String, SpecTopic> invalidLinks = new HashMap<String, SpecTopic>();
for (final String linkId : linkIds) {
// Ignore error links
if (linkId.startsWith(CommonConstants.ERROR_XREF_ID_PREFIX)) continue;
// Find the linked topic
SpecTopic linkedTopic = null;
for (final Map.Entry<SpecTopic, Set<String>> usedIdEntry : usedIdAttributes.entrySet()) {
if (usedIdEntry.getValue().contains(linkId)) {
linkedTopic = usedIdEntry.getKey();
break;
}
}
// If the linked topic has been set as an error, than update the links to point to the topic id
if (linkedTopic != null && buildData.getErrorDatabase().hasErrorData(linkedTopic.getTopic())) {
final TopicErrorData errorData = buildData.getErrorDatabase().getErrorData(linkedTopic.getTopic());
if (errorData.hasFatalErrors()) {
invalidLinks.put(linkId, linkedTopic);
}
}
}
// Go through and fix any invalid links
if (!invalidLinks.isEmpty()) {
final List<Node> linkNodes = XMLUtilities.getChildNodes(doc, "xref", "link");
for (final Node linkNode : linkNodes) {
final String linkId = ((Element) linkNode).getAttribute("linkend");
if (invalidLinks.containsKey(linkId)) {
final SpecTopic linkedTopic = invalidLinks.get(linkId);
((Element) linkNode).setAttribute("linkend", linkedTopic.getUniqueLinkId(buildData.isUseFixedUrls()));
}
}
}
}
} } | public class class_name {
protected void doLinkSecondPass(final BuildData buildData,
final Map<SpecTopic, Set<String>> usedIdAttributes) throws BuildProcessingException {
final List<SpecTopic> topics = buildData.getBuildDatabase().getAllSpecTopics();
for (final SpecTopic specTopic : topics) {
final Document doc = specTopic.getXMLDocument();
// Get the XRef links in the topic document
final Set<String> linkIds = new HashSet<String>();
DocBookBuildUtilities.getTopicLinkIds(doc, linkIds);
final Map<String, SpecTopic> invalidLinks = new HashMap<String, SpecTopic>();
for (final String linkId : linkIds) {
// Ignore error links
if (linkId.startsWith(CommonConstants.ERROR_XREF_ID_PREFIX)) continue;
// Find the linked topic
SpecTopic linkedTopic = null;
for (final Map.Entry<SpecTopic, Set<String>> usedIdEntry : usedIdAttributes.entrySet()) {
if (usedIdEntry.getValue().contains(linkId)) {
linkedTopic = usedIdEntry.getKey(); // depends on control dependency: [if], data = [none]
break;
}
}
// If the linked topic has been set as an error, than update the links to point to the topic id
if (linkedTopic != null && buildData.getErrorDatabase().hasErrorData(linkedTopic.getTopic())) {
final TopicErrorData errorData = buildData.getErrorDatabase().getErrorData(linkedTopic.getTopic());
if (errorData.hasFatalErrors()) {
invalidLinks.put(linkId, linkedTopic); // depends on control dependency: [if], data = [none]
}
}
}
// Go through and fix any invalid links
if (!invalidLinks.isEmpty()) {
final List<Node> linkNodes = XMLUtilities.getChildNodes(doc, "xref", "link");
for (final Node linkNode : linkNodes) {
final String linkId = ((Element) linkNode).getAttribute("linkend");
if (invalidLinks.containsKey(linkId)) {
final SpecTopic linkedTopic = invalidLinks.get(linkId);
((Element) linkNode).setAttribute("linkend", linkedTopic.getUniqueLinkId(buildData.isUseFixedUrls())); // depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
private static Token createThreadContextToken(final String configuration) {
if (configuration == null) {
InternalLogger.log(Level.ERROR, "\"{context}\" requires a key");
return new PlainTextToken("");
} else {
int splitIndex = configuration.indexOf(',');
String key = splitIndex == -1 ? configuration.trim() : configuration.substring(0, splitIndex).trim();
if (key.isEmpty()) {
InternalLogger.log(Level.ERROR, "\"{context}\" requires a key");
return new PlainTextToken("");
} else {
String defaultValue = splitIndex == -1 ? null : configuration.substring(splitIndex + 1).trim();
return defaultValue == null ? new ThreadContextToken(key) : new ThreadContextToken(key, defaultValue);
}
}
} } | public class class_name {
private static Token createThreadContextToken(final String configuration) {
if (configuration == null) {
InternalLogger.log(Level.ERROR, "\"{context}\" requires a key"); // depends on control dependency: [if], data = [none]
return new PlainTextToken(""); // depends on control dependency: [if], data = [none]
} else {
int splitIndex = configuration.indexOf(',');
String key = splitIndex == -1 ? configuration.trim() : configuration.substring(0, splitIndex).trim();
if (key.isEmpty()) {
InternalLogger.log(Level.ERROR, "\"{context}\" requires a key"); // depends on control dependency: [if], data = [none]
return new PlainTextToken(""); // depends on control dependency: [if], data = [none]
} else {
String defaultValue = splitIndex == -1 ? null : configuration.substring(splitIndex + 1).trim();
return defaultValue == null ? new ThreadContextToken(key) : new ThreadContextToken(key, defaultValue); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
protected boolean writeShiftOp(int type, boolean simulate) {
type = type - LEFT_SHIFT;
if (type < 0 || type > 2) return false;
if (!simulate) {
int bytecode = getShiftOperationBytecode(type);
controller.getMethodVisitor().visitInsn(bytecode);
controller.getOperandStack().replace(getNormalOpResultType(), 2);
}
return true;
} } | public class class_name {
protected boolean writeShiftOp(int type, boolean simulate) {
type = type - LEFT_SHIFT;
if (type < 0 || type > 2) return false;
if (!simulate) {
int bytecode = getShiftOperationBytecode(type);
controller.getMethodVisitor().visitInsn(bytecode); // depends on control dependency: [if], data = [none]
controller.getOperandStack().replace(getNormalOpResultType(), 2); // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
protected static Map<String,String> getConfiguration(Properties configuration)
{
//get system configuration
Map<String,String> systemConfig=LibraryConfigurationLoader.getSystemConfiguration();
//create new map
Map<String,String> layeredConfiguration=new HashMap<String,String>(systemConfig);
if(configuration!=null)
{
//convert to map
SpiUtil.copyPropertiesToMap(configuration,layeredConfiguration);
}
return layeredConfiguration;
} } | public class class_name {
protected static Map<String,String> getConfiguration(Properties configuration)
{
//get system configuration
Map<String,String> systemConfig=LibraryConfigurationLoader.getSystemConfiguration();
//create new map
Map<String,String> layeredConfiguration=new HashMap<String,String>(systemConfig);
if(configuration!=null)
{
//convert to map
SpiUtil.copyPropertiesToMap(configuration,layeredConfiguration); // depends on control dependency: [if], data = [(configuration]
}
return layeredConfiguration;
} } |
public class class_name {
public void updateLongRunningFree(Address address, long free)
{
if (trace)
log.tracef("updateLongRunningFree(%s, %d)", address, free);
Map<Address, Long> lr = longRunning.get(address.getWorkManagerId());
if (lr != null)
{
lr.put(address, Long.valueOf(free));
longRunning.put(address.getWorkManagerId(), lr);
}
} } | public class class_name {
public void updateLongRunningFree(Address address, long free)
{
if (trace)
log.tracef("updateLongRunningFree(%s, %d)", address, free);
Map<Address, Long> lr = longRunning.get(address.getWorkManagerId());
if (lr != null)
{
lr.put(address, Long.valueOf(free)); // depends on control dependency: [if], data = [none]
longRunning.put(address.getWorkManagerId(), lr); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private Iterator<String> getIterator() {
final Set<String> copy = getPrefixes();
final Iterator<String> copyIt = copy.iterator();
return new Iterator<String>() {
private String lastOne = null;
@Override
public boolean hasNext() {
return copyIt.hasNext();
}
@Override
public String next() {
if (copyIt.hasNext()) {
lastOne = copyIt.next();
} else {
throw new NoSuchElementException();
}
return lastOne;
}
@Override
public void remove() {
try {
lock.writeLock().lock();
prefixes.remove(lastOne);
} finally {
lock.writeLock().unlock();
}
}
};
} } | public class class_name {
private Iterator<String> getIterator() {
final Set<String> copy = getPrefixes();
final Iterator<String> copyIt = copy.iterator();
return new Iterator<String>() {
private String lastOne = null;
@Override
public boolean hasNext() {
return copyIt.hasNext();
}
@Override
public String next() {
if (copyIt.hasNext()) {
lastOne = copyIt.next(); // depends on control dependency: [if], data = [none]
} else {
throw new NoSuchElementException();
}
return lastOne;
}
@Override
public void remove() {
try {
lock.writeLock().lock(); // depends on control dependency: [try], data = [none]
prefixes.remove(lastOne); // depends on control dependency: [try], data = [none]
} finally {
lock.writeLock().unlock();
}
}
};
} } |
public class class_name {
@Override
public boolean isBoundary(int offset) {
checkOffset(offset, fText);
// the beginning index of the iterator is always a boundary position by definition
if (offset == fText.getBeginIndex()) {
first(); // For side effects on current position, tag values.
return true;
}
if (offset == fText.getEndIndex()) {
last(); // For side effects on current position, tag values.
return true;
}
// otherwise, we can use following() on the position before the specified
// one and return true if the position we get back is the one the user
// specified
// return following(offset - 1) == offset;
// TODO: check whether it is safe to revert to the simpler offset-1 code
// The safe rules may take care of unpaired surrogates ok.
fText.setIndex(offset);
previous32(fText);
int pos = fText.getIndex();
boolean result = following(pos) == offset;
return result;
} } | public class class_name {
@Override
public boolean isBoundary(int offset) {
checkOffset(offset, fText);
// the beginning index of the iterator is always a boundary position by definition
if (offset == fText.getBeginIndex()) {
first(); // For side effects on current position, tag values. // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
if (offset == fText.getEndIndex()) {
last(); // For side effects on current position, tag values. // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
// otherwise, we can use following() on the position before the specified
// one and return true if the position we get back is the one the user
// specified
// return following(offset - 1) == offset;
// TODO: check whether it is safe to revert to the simpler offset-1 code
// The safe rules may take care of unpaired surrogates ok.
fText.setIndex(offset);
previous32(fText);
int pos = fText.getIndex();
boolean result = following(pos) == offset;
return result;
} } |
public class class_name {
public synchronized TicketBucket getTicketBucket(Region region) {
TicketBucket tb = buckets.get(region);
if (tb == null) {
tb = new TicketBucket(rules);
buckets.put(region, tb);
}
return tb;
} } | public class class_name {
public synchronized TicketBucket getTicketBucket(Region region) {
TicketBucket tb = buckets.get(region);
if (tb == null) {
tb = new TicketBucket(rules); // depends on control dependency: [if], data = [none]
buckets.put(region, tb); // depends on control dependency: [if], data = [none]
}
return tb;
} } |
public class class_name {
public void waitInitOpen(String waitForSelector) {
if (waitForSelector == null || waitForSelector.isEmpty()) {
initDynamic();
open();
return;
}
waitInitOpen(waitForSelector, getElement());
} } | public class class_name {
public void waitInitOpen(String waitForSelector) {
if (waitForSelector == null || waitForSelector.isEmpty()) {
initDynamic(); // depends on control dependency: [if], data = [none]
open(); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
waitInitOpen(waitForSelector, getElement());
} } |
public class class_name {
private void submitRevisions(final List<DocumentChange> changes) {
synchronized (changesLock) {
try {
java.net.URI remoteUri = remote.toURI();
for (DocumentChange change : changes) {
// Skip revisions that originally came from the database I'm syncing to:
URL source = change.getSource();
if (source != null && source.toURI().equals(remoteUri))
continue;
RevisionInternal rev = change.getAddedRevision();
if (rev == null)
continue;
if (getLocalDatabase().runFilter(filter, filterParams, rev)) {
if (doneBeginReplicating) {
pauseOrResume();
waitIfPaused();
// if not running state anymore, exit from loop.
if (!isRunning())
break;
RevisionInternal nuRev = rev.copyWithoutBody();
addToInbox(nuRev);
} else {
RevisionInternal nuRev = rev.copyWithoutBody();
queueChanges.add(nuRev);
}
}
}
} catch (java.net.URISyntaxException uriException) {
// Not possible since it would not be an active replicator.
// However, until we refactor everything to use java.net,
// I'm not sure we have a choice but to swallow this.
Log.e(TAG, "Active replicator found with invalid URI", uriException);
}
}
} } | public class class_name {
private void submitRevisions(final List<DocumentChange> changes) {
synchronized (changesLock) {
try {
java.net.URI remoteUri = remote.toURI();
for (DocumentChange change : changes) {
// Skip revisions that originally came from the database I'm syncing to:
URL source = change.getSource();
if (source != null && source.toURI().equals(remoteUri))
continue;
RevisionInternal rev = change.getAddedRevision();
if (rev == null)
continue;
if (getLocalDatabase().runFilter(filter, filterParams, rev)) {
if (doneBeginReplicating) {
pauseOrResume(); // depends on control dependency: [if], data = [none]
waitIfPaused(); // depends on control dependency: [if], data = [none]
// if not running state anymore, exit from loop.
if (!isRunning())
break;
RevisionInternal nuRev = rev.copyWithoutBody();
addToInbox(nuRev); // depends on control dependency: [if], data = [none]
} else {
RevisionInternal nuRev = rev.copyWithoutBody();
queueChanges.add(nuRev); // depends on control dependency: [if], data = [none]
}
}
}
} catch (java.net.URISyntaxException uriException) {
// Not possible since it would not be an active replicator.
// However, until we refactor everything to use java.net,
// I'm not sure we have a choice but to swallow this.
Log.e(TAG, "Active replicator found with invalid URI", uriException);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
@Override
public synchronized void process(CAS tcas) {
final AnnotationComboIterator comboIterator =
new AnnotationComboIterator(tcas, this.sentenceType, this.tokenType);
for (AnnotationIteratorPair annotationIteratorPair : comboIterator) {
final List<AnnotationFS> sentenceTokenAnnotationList = new LinkedList<AnnotationFS>();
final List<String> sentenceTokenList = new LinkedList<String>();
for (AnnotationFS tokenAnnotation : annotationIteratorPair.getSubIterator()) {
sentenceTokenAnnotationList.add(tokenAnnotation);
sentenceTokenList.add(tokenAnnotation.getCoveredText());
}
final List<String> posTags = this.posTagger.tag(sentenceTokenList);
double posProbabilities[] = null;
if (this.probabilityFeature != null) {
posProbabilities = this.posTagger.probs();
}
final Iterator<String> posTagIterator = posTags.iterator();
final Iterator<AnnotationFS> sentenceTokenIterator = sentenceTokenAnnotationList.iterator();
int index = 0;
while (posTagIterator.hasNext() && sentenceTokenIterator.hasNext()) {
final String posTag = posTagIterator.next();
final AnnotationFS tokenAnnotation = sentenceTokenIterator.next();
tokenAnnotation.setStringValue(this.posFeature, posTag);
if (posProbabilities != null) {
tokenAnnotation.setDoubleValue(this.posFeature, posProbabilities[index]);
}
index++;
}
// log tokens with pos
if (this.logger.isLoggable(Level.FINER)) {
final StringBuilder sentenceWithPos = new StringBuilder();
sentenceWithPos.append("\"");
for (final Iterator<AnnotationFS> it = sentenceTokenAnnotationList.iterator(); it.hasNext();) {
final AnnotationFS token = it.next();
sentenceWithPos.append(token.getCoveredText());
sentenceWithPos.append('\\');
sentenceWithPos.append(token.getStringValue(this.posFeature));
sentenceWithPos.append(' ');
}
// delete last whitespace
if (sentenceWithPos.length() > 1) // not 0 because it contains already the " char
sentenceWithPos.setLength(sentenceWithPos.length() - 1);
sentenceWithPos.append("\"");
this.logger.log(Level.FINER, sentenceWithPos.toString());
}
}
} } | public class class_name {
@Override
public synchronized void process(CAS tcas) {
final AnnotationComboIterator comboIterator =
new AnnotationComboIterator(tcas, this.sentenceType, this.tokenType);
for (AnnotationIteratorPair annotationIteratorPair : comboIterator) {
final List<AnnotationFS> sentenceTokenAnnotationList = new LinkedList<AnnotationFS>();
final List<String> sentenceTokenList = new LinkedList<String>();
for (AnnotationFS tokenAnnotation : annotationIteratorPair.getSubIterator()) {
sentenceTokenAnnotationList.add(tokenAnnotation); // depends on control dependency: [for], data = [tokenAnnotation]
sentenceTokenList.add(tokenAnnotation.getCoveredText()); // depends on control dependency: [for], data = [tokenAnnotation]
}
final List<String> posTags = this.posTagger.tag(sentenceTokenList);
double posProbabilities[] = null;
if (this.probabilityFeature != null) {
posProbabilities = this.posTagger.probs(); // depends on control dependency: [if], data = [none]
}
final Iterator<String> posTagIterator = posTags.iterator();
final Iterator<AnnotationFS> sentenceTokenIterator = sentenceTokenAnnotationList.iterator();
int index = 0;
while (posTagIterator.hasNext() && sentenceTokenIterator.hasNext()) {
final String posTag = posTagIterator.next();
final AnnotationFS tokenAnnotation = sentenceTokenIterator.next();
tokenAnnotation.setStringValue(this.posFeature, posTag); // depends on control dependency: [while], data = [none]
if (posProbabilities != null) {
tokenAnnotation.setDoubleValue(this.posFeature, posProbabilities[index]); // depends on control dependency: [if], data = [none]
}
index++; // depends on control dependency: [while], data = [none]
}
// log tokens with pos
if (this.logger.isLoggable(Level.FINER)) {
final StringBuilder sentenceWithPos = new StringBuilder();
sentenceWithPos.append("\""); // depends on control dependency: [if], data = [none]
for (final Iterator<AnnotationFS> it = sentenceTokenAnnotationList.iterator(); it.hasNext();) {
final AnnotationFS token = it.next();
sentenceWithPos.append(token.getCoveredText()); // depends on control dependency: [for], data = [none]
sentenceWithPos.append('\\'); // depends on control dependency: [for], data = [none]
sentenceWithPos.append(token.getStringValue(this.posFeature)); // depends on control dependency: [for], data = [none]
sentenceWithPos.append(' '); // depends on control dependency: [for], data = [none]
}
// delete last whitespace
if (sentenceWithPos.length() > 1) // not 0 because it contains already the " char
sentenceWithPos.setLength(sentenceWithPos.length() - 1);
sentenceWithPos.append("\""); // depends on control dependency: [if], data = [none]
this.logger.log(Level.FINER, sentenceWithPos.toString()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
final JsMsgMap getSystemContextMap() {
if (systemContextMap == null) {
List<String> keys = (List<String>) getApi().getField(JsApiAccess.SYSTEMCONTEXT_NAME);
List<Object> values = (List<Object>) getApi().getField(JsApiAccess.SYSTEMCONTEXT_VALUE);
systemContextMap = new JsMsgMap(keys, values);
}
return systemContextMap;
} } | public class class_name {
final JsMsgMap getSystemContextMap() {
if (systemContextMap == null) {
List<String> keys = (List<String>) getApi().getField(JsApiAccess.SYSTEMCONTEXT_NAME);
List<Object> values = (List<Object>) getApi().getField(JsApiAccess.SYSTEMCONTEXT_VALUE);
systemContextMap = new JsMsgMap(keys, values); // depends on control dependency: [if], data = [none]
}
return systemContextMap;
} } |
public class class_name {
private synchronized void setCreator(ObjectValue newCreator)
{
// Do not set the creator if created by the system class. The System contains
// fields with references to Thread instances which are not Serializable and
// will fail a deep copy with a NotSerializableExpection for Thread
if (newCreator != null
&& newCreator.type.getClassdef() instanceof ASystemClassDefinition)
{
return;
}
// establish transitive reference
newCreator.addChild(this);
} } | public class class_name {
private synchronized void setCreator(ObjectValue newCreator)
{
// Do not set the creator if created by the system class. The System contains
// fields with references to Thread instances which are not Serializable and
// will fail a deep copy with a NotSerializableExpection for Thread
if (newCreator != null
&& newCreator.type.getClassdef() instanceof ASystemClassDefinition)
{
return; // depends on control dependency: [if], data = [none]
}
// establish transitive reference
newCreator.addChild(this);
} } |
public class class_name {
@Override
public Optional<HttpTracing> build(final Environment environment) {
if (!isEnabled()) {
LOGGER.warn("Zipkin tracing is disabled");
return Optional.empty();
}
final ReporterMetrics metricsHandler = new DropwizardReporterMetrics(environment.metrics());
final String endpoint = URI.create(baseUrl).resolve("api/v2/spans").toString();
final URLConnectionSender sender =
URLConnectionSender.newBuilder()
.endpoint(endpoint)
.readTimeout(Math.toIntExact(readTimeout.toMilliseconds()))
.connectTimeout(Math.toIntExact(connectTimeout.toMilliseconds()))
.build();
final AsyncReporter<Span> reporter =
AsyncReporter.builder(sender).metrics(metricsHandler).build();
environment.lifecycle().manage(new ReporterManager(reporter, sender));
LOGGER.info("Sending spans to HTTP collector at: {}", baseUrl);
return buildTracing(environment, reporter);
} } | public class class_name {
@Override
public Optional<HttpTracing> build(final Environment environment) {
if (!isEnabled()) {
LOGGER.warn("Zipkin tracing is disabled"); // depends on control dependency: [if], data = [none]
return Optional.empty(); // depends on control dependency: [if], data = [none]
}
final ReporterMetrics metricsHandler = new DropwizardReporterMetrics(environment.metrics());
final String endpoint = URI.create(baseUrl).resolve("api/v2/spans").toString();
final URLConnectionSender sender =
URLConnectionSender.newBuilder()
.endpoint(endpoint)
.readTimeout(Math.toIntExact(readTimeout.toMilliseconds()))
.connectTimeout(Math.toIntExact(connectTimeout.toMilliseconds()))
.build();
final AsyncReporter<Span> reporter =
AsyncReporter.builder(sender).metrics(metricsHandler).build();
environment.lifecycle().manage(new ReporterManager(reporter, sender));
LOGGER.info("Sending spans to HTTP collector at: {}", baseUrl);
return buildTracing(environment, reporter);
} } |
public class class_name {
private void buildWidget() {
// setTitle(MESSAGES.nearbyFeaturesListTooltip());
setShowEmptyMessage(true);
setWidth100();
setHeight100();
setShowHeader(false);
setShowAllRecords(true);
// List size calculation
setDefaultWidth(400);
setDefaultHeight(300);
setAutoFitData(Autofit.BOTH);
setAutoFitMaxRecords(MAX_ROWS);
setAutoFitFieldWidths(true);
setAutoFitWidthApproach(AutoFitWidthApproach.BOTH);
ListGridField labelField = new ListGridField(LABEL);
ListGridField featIdField = new ListGridField(FEATURE_ID);
ListGridField layerField = new ListGridField(LAYER_ID);
ListGridField layerLabelField = new ListGridField(LAYER_LABEL);
setGroupByField(LAYER_LABEL);
setGroupStartOpen(GroupStartOpen.ALL);
setFields(/* dummyIndentField, */labelField, layerField, featIdField, layerLabelField);
hideField(LAYER_ID);
hideField(FEATURE_ID);
hideField(LAYER_LABEL);
addRecordClickHandler(new RecordClickHandler() {
public void onRecordClick(RecordClickEvent event) {
String fId = event.getRecord().getAttribute(FEATURE_ID);
String lId = event.getRecord().getAttribute(LAYER_ID);
Feature feat = vectorFeatures.get(fId);
if (feat != null) {
featureClickHandler.onClick(feat, feat.getLayer());
} else {
Layer<?> rasterLayer = rasterLayers.get(lId);
feat = rasterFeatures.get(fId);
featureClickHandler.onClick(feat, rasterLayer);
}
}
});
setShowHover(true);
setCanHover(true);
setHoverWidth(200);
setHoverCustomizer(new HoverCustomizer() {
public String hoverHTML(Object value, ListGridRecord record, int rowNum, int colNum) {
String fId = record.getAttribute(FEATURE_ID);
Feature feat = vectorFeatures.get(fId);
StringBuilder tooltip = new StringBuilder();
if (feat != null) {
for (AbstractAttributeInfo a : feat.getLayer().getLayerInfo().getFeatureInfo().getAttributes()) {
if (a instanceof AbstractReadOnlyAttributeInfo &&
((AbstractReadOnlyAttributeInfo) a).isIdentifying()) {
tooltip.append("<b>");
tooltip.append(((AbstractReadOnlyAttributeInfo) a).getLabel());
tooltip.append("</b>: ");
tooltip.append(feat.getAttributeValue(a.getName()));
tooltip.append("<br/>");
}
}
tooltip.append(MESSAGES.nearbyFeaturesListTooltip());
}
return tooltip.toString();
}
});
} } | public class class_name {
private void buildWidget() {
// setTitle(MESSAGES.nearbyFeaturesListTooltip());
setShowEmptyMessage(true);
setWidth100();
setHeight100();
setShowHeader(false);
setShowAllRecords(true);
// List size calculation
setDefaultWidth(400);
setDefaultHeight(300);
setAutoFitData(Autofit.BOTH);
setAutoFitMaxRecords(MAX_ROWS);
setAutoFitFieldWidths(true);
setAutoFitWidthApproach(AutoFitWidthApproach.BOTH);
ListGridField labelField = new ListGridField(LABEL);
ListGridField featIdField = new ListGridField(FEATURE_ID);
ListGridField layerField = new ListGridField(LAYER_ID);
ListGridField layerLabelField = new ListGridField(LAYER_LABEL);
setGroupByField(LAYER_LABEL);
setGroupStartOpen(GroupStartOpen.ALL);
setFields(/* dummyIndentField, */labelField, layerField, featIdField, layerLabelField);
hideField(LAYER_ID);
hideField(FEATURE_ID);
hideField(LAYER_LABEL);
addRecordClickHandler(new RecordClickHandler() {
public void onRecordClick(RecordClickEvent event) {
String fId = event.getRecord().getAttribute(FEATURE_ID);
String lId = event.getRecord().getAttribute(LAYER_ID);
Feature feat = vectorFeatures.get(fId);
if (feat != null) {
featureClickHandler.onClick(feat, feat.getLayer()); // depends on control dependency: [if], data = [(feat]
} else {
Layer<?> rasterLayer = rasterLayers.get(lId);
feat = rasterFeatures.get(fId); // depends on control dependency: [if], data = [none]
featureClickHandler.onClick(feat, rasterLayer); // depends on control dependency: [if], data = [(feat]
}
}
});
setShowHover(true);
setCanHover(true);
setHoverWidth(200);
setHoverCustomizer(new HoverCustomizer() {
public String hoverHTML(Object value, ListGridRecord record, int rowNum, int colNum) {
String fId = record.getAttribute(FEATURE_ID);
Feature feat = vectorFeatures.get(fId);
StringBuilder tooltip = new StringBuilder();
if (feat != null) {
for (AbstractAttributeInfo a : feat.getLayer().getLayerInfo().getFeatureInfo().getAttributes()) {
if (a instanceof AbstractReadOnlyAttributeInfo &&
((AbstractReadOnlyAttributeInfo) a).isIdentifying()) {
tooltip.append("<b>"); // depends on control dependency: [if], data = [none]
tooltip.append(((AbstractReadOnlyAttributeInfo) a).getLabel()); // depends on control dependency: [if], data = [none]
tooltip.append("</b>: "); // depends on control dependency: [if], data = [none]
tooltip.append(feat.getAttributeValue(a.getName())); // depends on control dependency: [if], data = [none]
tooltip.append("<br/>"); // depends on control dependency: [if], data = [none]
}
}
tooltip.append(MESSAGES.nearbyFeaturesListTooltip()); // depends on control dependency: [if], data = [none]
}
return tooltip.toString();
}
});
} } |
public class class_name {
public static LaContainer include(final LaContainer parent, final String path) {
if (!initialized) {
configure();
}
return getProvider().include(parent, path);
} } | public class class_name {
public static LaContainer include(final LaContainer parent, final String path) {
if (!initialized) {
configure(); // depends on control dependency: [if], data = [none]
}
return getProvider().include(parent, path);
} } |
public class class_name {
private String getSQLString(Term term, AliasIndex index, boolean useBrackets) {
if (term == null) {
return "";
}
if (term instanceof ValueConstant) {
ValueConstant ct = (ValueConstant) term;
if (hasIRIDictionary()) {
if (ct.getType().isA(XSD.STRING)) {
int id = getUriid(ct.getValue());
if (id >= 0)
//return jdbcutil.getSQLLexicalForm(String.valueOf(id));
return String.valueOf(id);
}
}
return getSQLLexicalForm(ct);
}
else if (term instanceof IRIConstant) {
IRIConstant uc = (IRIConstant) term;
if (hasIRIDictionary()) {
int id = getUriid(uc.getValue());
return sqladapter.getSQLLexicalFormString(String.valueOf(id));
}
return sqladapter.getSQLLexicalFormString(uc.toString());
}
else if (term instanceof Variable) {
Set<QualifiedAttributeID> columns = index.getColumns((Variable) term);
return columns.iterator().next().getSQLRendering();
}
// If it's not constant, or variable it's a function
Function function = (Function) term;
Predicate functionSymbol = function.getFunctionSymbol();
int size = function.getTerms().size();
if (function.isDataTypeFunction()) {
if (functionSymbol.getExpectedBaseType(0)
.isA(typeFactory.getUnsupportedDatatype())) {
throw new RuntimeException("Unsupported type in the query: "
+ function);
}
// Note: datatype functions are unary.
// The only exception is rdf:langString (represented internally as a binary predicate, with string and
// language tag as arguments), but in this case the first argument only is used for SQL generation.
// atoms of the form integer(x)
return getSQLString(function.getTerm(0), index, false);
}
if (functionSymbol instanceof URITemplatePredicate
|| functionSymbol instanceof BNodePredicate) {
// The atom must be of the form uri("...", x, y)
return getSQLStringForTemplateFunction(function.getTerms(), index);
}
if (operations.containsKey(functionSymbol)) {
String expressionFormat = operations.get(functionSymbol);
switch (function.getArity()) {
case 0:
return expressionFormat;
case 1:
// for unary functions, e.g., NOT, IS NULL, IS NOT NULL
String arg = getSQLString(function.getTerm(0), index, true);
return String.format(expressionFormat, arg);
case 2:
// for binary functions, e.g., AND, OR, EQ, NEQ, GT etc.
String left = getSQLString(function.getTerm(0), index, true);
String right = getSQLString(function.getTerm(1), index, true);
String result = String.format(expressionFormat, left, right);
return useBrackets ? inBrackets(result) : result;
default:
throw new RuntimeException("Cannot translate boolean function: " + functionSymbol);
}
}
if (functionSymbol == ExpressionOperation.IS_TRUE) {
return effectiveBooleanValue(function.getTerm(0), index);
}
if (functionSymbol == ExpressionOperation.REGEX) {
boolean caseinSensitive = false, multiLine = false, dotAllMode = false;
if (function.getArity() == 3) {
String options = function.getTerm(2).toString();
caseinSensitive = options.contains("i");
multiLine = options.contains("m");
dotAllMode = options.contains("s");
}
String column = getSQLString(function.getTerm(0), index, false);
String pattern = getSQLString(function.getTerm(1), index, false);
return sqladapter.sqlRegex(column, pattern, caseinSensitive, multiLine, dotAllMode);
}
/*
* TODO: make sure that SPARQL_LANG are eliminated earlier on
*/
if (functionSymbol == ExpressionOperation.SPARQL_LANG) {
Term subTerm = function.getTerm(0);
if (subTerm instanceof Variable) {
Variable var = (Variable) subTerm;
Optional<QualifiedAttributeID> lang = index.getLangColumn(var);
if (!lang.isPresent())
throw new RuntimeException("Cannot find LANG column for " + var);
return lang.get().getSQLRendering();
}
else {
// Temporary fix
String langString = Optional.of(subTerm)
.filter(t -> t instanceof Function)
.map(t -> ((Function) t).getFunctionSymbol())
.filter(f -> f instanceof DatatypePredicate)
.map(f -> ((DatatypePredicate) f).getReturnedType())
.flatMap(RDFDatatype::getLanguageTag)
.map(LanguageTag::getFullString)
.orElse("");
return sqladapter.getSQLLexicalFormString(langString);
}
}
/*
TODO: replace by a switch
*/
if (functionSymbol.equals(ExpressionOperation.IF_ELSE_NULL)) {
String condition = getSQLString(function.getTerm(0), index, false);
String value = getSQLString(function.getTerm(1), index, false);
return sqladapter.ifElseNull(condition, value);
}
if (functionSymbol == ExpressionOperation.QUEST_CAST) {
String columnName = getSQLString(function.getTerm(0), index, false);
String datatype = ((Constant) function.getTerm(1)).getValue();
int sqlDatatype = datatype.equals(XMLSchema.STRING.stringValue())
? Types.VARCHAR
: Types.LONGVARCHAR;
return isStringColType(function, index) ? columnName : sqladapter.sqlCast(columnName, sqlDatatype);
}
if (functionSymbol == ExpressionOperation.SPARQL_STR) {
String columnName = getSQLString(function.getTerm(0), index, false);
return isStringColType(function, index) ? columnName : sqladapter.sqlCast(columnName, Types.VARCHAR);
}
if (functionSymbol == ExpressionOperation.REPLACE) {
String orig = getSQLString(function.getTerm(0), index, false);
String out_str = getSQLString(function.getTerm(1), index, false);
String in_str = getSQLString(function.getTerm(2), index, false);
// TODO: handle flags
return sqladapter.strReplace(orig, out_str, in_str);
}
if (functionSymbol == ExpressionOperation.CONCAT) {
String left = getSQLString(function.getTerm(0), index, false);
String right = getSQLString(function.getTerm(1), index, false);
return sqladapter.strConcat(new String[]{left, right});
}
if (functionSymbol == ExpressionOperation.STRLEN) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.strLength(literal);
}
if (functionSymbol == ExpressionOperation.YEAR) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateYear(literal);
}
if (functionSymbol == ExpressionOperation.MINUTES) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateMinutes(literal);
}
if (functionSymbol == ExpressionOperation.DAY) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateDay(literal);
}
if (functionSymbol == ExpressionOperation.MONTH) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateMonth(literal);
}
if (functionSymbol == ExpressionOperation.SECONDS) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateSeconds(literal);
}
if (functionSymbol == ExpressionOperation.HOURS) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateHours(literal);
}
if (functionSymbol == ExpressionOperation.TZ) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateTZ(literal);
}
if (functionSymbol == ExpressionOperation.ENCODE_FOR_URI) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.iriSafeEncode(literal);
}
if (functionSymbol == ExpressionOperation.UCASE) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.strUcase(literal);
}
if (functionSymbol == ExpressionOperation.MD5) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.MD5(literal);
}
if (functionSymbol == ExpressionOperation.SHA1) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.SHA1(literal);
}
if (functionSymbol == ExpressionOperation.SHA256) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.SHA256(literal);
}
if (functionSymbol == ExpressionOperation.SHA512) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.SHA512(literal); //TODO FIX
}
if (functionSymbol == ExpressionOperation.LCASE) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.strLcase(literal);
}
if (functionSymbol == ExpressionOperation.SUBSTR2) {
String string = getSQLString(function.getTerm(0), index, false);
String start = getSQLString(function.getTerm(1), index, false);
return sqladapter.strSubstr(string, start);
}
if (functionSymbol == ExpressionOperation.SUBSTR3) {
String string = getSQLString(function.getTerm(0), index, false);
String start = getSQLString(function.getTerm(1), index, false);
String end = getSQLString(function.getTerm(2), index, false);
return sqladapter.strSubstr(string, start, end);
}
if (functionSymbol == ExpressionOperation.STRBEFORE) {
String string = getSQLString(function.getTerm(0), index, false);
String before = getSQLString(function.getTerm(1), index, false);
return sqladapter.strBefore(string, before);
}
if (functionSymbol == ExpressionOperation.STRAFTER) {
String string = getSQLString(function.getTerm(0), index, false);
String after = getSQLString(function.getTerm(1), index, false);
return sqladapter.strAfter(string, after);
}
if (functionSymbol == ExpressionOperation.COUNT) {
if (function.getTerm(0).toString().equals("*")) {
return "COUNT(*)";
}
String columnName = getSQLString(function.getTerm(0), index, false);
//havingCond = true;
return "COUNT(" + columnName + ")";
}
if (functionSymbol == ExpressionOperation.AVG) {
String columnName = getSQLString(function.getTerm(0), index, false);
//havingCond = true;
return "AVG(" + columnName + ")";
}
if (functionSymbol == ExpressionOperation.SUM) {
String columnName = getSQLString(function.getTerm(0), index, false);
//havingCond = true;
return "SUM(" + columnName + ")";
}
throw new RuntimeException("Unexpected function in the query: " + functionSymbol);
} } | public class class_name {
private String getSQLString(Term term, AliasIndex index, boolean useBrackets) {
if (term == null) {
return ""; // depends on control dependency: [if], data = [none]
}
if (term instanceof ValueConstant) {
ValueConstant ct = (ValueConstant) term;
if (hasIRIDictionary()) {
if (ct.getType().isA(XSD.STRING)) {
int id = getUriid(ct.getValue());
if (id >= 0)
//return jdbcutil.getSQLLexicalForm(String.valueOf(id));
return String.valueOf(id);
}
}
return getSQLLexicalForm(ct); // depends on control dependency: [if], data = [none]
}
else if (term instanceof IRIConstant) {
IRIConstant uc = (IRIConstant) term;
if (hasIRIDictionary()) {
int id = getUriid(uc.getValue());
return sqladapter.getSQLLexicalFormString(String.valueOf(id)); // depends on control dependency: [if], data = [none]
}
return sqladapter.getSQLLexicalFormString(uc.toString()); // depends on control dependency: [if], data = [none]
}
else if (term instanceof Variable) {
Set<QualifiedAttributeID> columns = index.getColumns((Variable) term);
return columns.iterator().next().getSQLRendering(); // depends on control dependency: [if], data = [none]
}
// If it's not constant, or variable it's a function
Function function = (Function) term;
Predicate functionSymbol = function.getFunctionSymbol();
int size = function.getTerms().size();
if (function.isDataTypeFunction()) {
if (functionSymbol.getExpectedBaseType(0)
.isA(typeFactory.getUnsupportedDatatype())) {
throw new RuntimeException("Unsupported type in the query: "
+ function);
}
// Note: datatype functions are unary.
// The only exception is rdf:langString (represented internally as a binary predicate, with string and
// language tag as arguments), but in this case the first argument only is used for SQL generation.
// atoms of the form integer(x)
return getSQLString(function.getTerm(0), index, false); // depends on control dependency: [if], data = [none]
}
if (functionSymbol instanceof URITemplatePredicate
|| functionSymbol instanceof BNodePredicate) {
// The atom must be of the form uri("...", x, y)
return getSQLStringForTemplateFunction(function.getTerms(), index); // depends on control dependency: [if], data = [none]
}
if (operations.containsKey(functionSymbol)) {
String expressionFormat = operations.get(functionSymbol);
switch (function.getArity()) {
case 0:
return expressionFormat;
case 1:
// for unary functions, e.g., NOT, IS NULL, IS NOT NULL
String arg = getSQLString(function.getTerm(0), index, true);
return String.format(expressionFormat, arg); // depends on control dependency: [if], data = [none]
case 2:
// for binary functions, e.g., AND, OR, EQ, NEQ, GT etc.
String left = getSQLString(function.getTerm(0), index, true);
String right = getSQLString(function.getTerm(1), index, true);
String result = String.format(expressionFormat, left, right);
return useBrackets ? inBrackets(result) : result; // depends on control dependency: [if], data = [none]
default:
throw new RuntimeException("Cannot translate boolean function: " + functionSymbol);
}
}
if (functionSymbol == ExpressionOperation.IS_TRUE) {
return effectiveBooleanValue(function.getTerm(0), index);
}
if (functionSymbol == ExpressionOperation.REGEX) {
boolean caseinSensitive = false, multiLine = false, dotAllMode = false;
if (function.getArity() == 3) {
String options = function.getTerm(2).toString();
caseinSensitive = options.contains("i"); // depends on control dependency: [if], data = [none]
multiLine = options.contains("m"); // depends on control dependency: [if], data = [none]
dotAllMode = options.contains("s"); // depends on control dependency: [if], data = [none]
}
String column = getSQLString(function.getTerm(0), index, false);
String pattern = getSQLString(function.getTerm(1), index, false);
return sqladapter.sqlRegex(column, pattern, caseinSensitive, multiLine, dotAllMode);
}
/*
* TODO: make sure that SPARQL_LANG are eliminated earlier on
*/
if (functionSymbol == ExpressionOperation.SPARQL_LANG) {
Term subTerm = function.getTerm(0);
if (subTerm instanceof Variable) {
Variable var = (Variable) subTerm;
Optional<QualifiedAttributeID> lang = index.getLangColumn(var);
if (!lang.isPresent())
throw new RuntimeException("Cannot find LANG column for " + var);
return lang.get().getSQLRendering(); // depends on control dependency: [if], data = [none]
}
else {
// Temporary fix
String langString = Optional.of(subTerm)
.filter(t -> t instanceof Function)
.map(t -> ((Function) t).getFunctionSymbol())
.filter(f -> f instanceof DatatypePredicate)
.map(f -> ((DatatypePredicate) f).getReturnedType())
.flatMap(RDFDatatype::getLanguageTag)
.map(LanguageTag::getFullString)
.orElse("");
return sqladapter.getSQLLexicalFormString(langString); // depends on control dependency: [if], data = [none]
}
}
/*
TODO: replace by a switch
*/
if (functionSymbol.equals(ExpressionOperation.IF_ELSE_NULL)) {
String condition = getSQLString(function.getTerm(0), index, false);
String value = getSQLString(function.getTerm(1), index, false);
return sqladapter.ifElseNull(condition, value);
}
if (functionSymbol == ExpressionOperation.QUEST_CAST) {
String columnName = getSQLString(function.getTerm(0), index, false);
String datatype = ((Constant) function.getTerm(1)).getValue();
int sqlDatatype = datatype.equals(XMLSchema.STRING.stringValue())
? Types.VARCHAR
: Types.LONGVARCHAR;
return isStringColType(function, index) ? columnName : sqladapter.sqlCast(columnName, sqlDatatype);
}
if (functionSymbol == ExpressionOperation.SPARQL_STR) {
String columnName = getSQLString(function.getTerm(0), index, false);
return isStringColType(function, index) ? columnName : sqladapter.sqlCast(columnName, Types.VARCHAR);
}
if (functionSymbol == ExpressionOperation.REPLACE) {
String orig = getSQLString(function.getTerm(0), index, false);
String out_str = getSQLString(function.getTerm(1), index, false);
String in_str = getSQLString(function.getTerm(2), index, false);
// TODO: handle flags
return sqladapter.strReplace(orig, out_str, in_str);
}
if (functionSymbol == ExpressionOperation.CONCAT) {
String left = getSQLString(function.getTerm(0), index, false);
String right = getSQLString(function.getTerm(1), index, false);
return sqladapter.strConcat(new String[]{left, right});
}
if (functionSymbol == ExpressionOperation.STRLEN) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.strLength(literal);
}
if (functionSymbol == ExpressionOperation.YEAR) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateYear(literal);
}
if (functionSymbol == ExpressionOperation.MINUTES) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateMinutes(literal);
}
if (functionSymbol == ExpressionOperation.DAY) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateDay(literal);
}
if (functionSymbol == ExpressionOperation.MONTH) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateMonth(literal);
}
if (functionSymbol == ExpressionOperation.SECONDS) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateSeconds(literal);
}
if (functionSymbol == ExpressionOperation.HOURS) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateHours(literal);
}
if (functionSymbol == ExpressionOperation.TZ) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.dateTZ(literal);
}
if (functionSymbol == ExpressionOperation.ENCODE_FOR_URI) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.iriSafeEncode(literal);
}
if (functionSymbol == ExpressionOperation.UCASE) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.strUcase(literal);
}
if (functionSymbol == ExpressionOperation.MD5) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.MD5(literal);
}
if (functionSymbol == ExpressionOperation.SHA1) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.SHA1(literal);
}
if (functionSymbol == ExpressionOperation.SHA256) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.SHA256(literal);
}
if (functionSymbol == ExpressionOperation.SHA512) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.SHA512(literal); //TODO FIX
}
if (functionSymbol == ExpressionOperation.LCASE) {
String literal = getSQLString(function.getTerm(0), index, false);
return sqladapter.strLcase(literal);
}
if (functionSymbol == ExpressionOperation.SUBSTR2) {
String string = getSQLString(function.getTerm(0), index, false);
String start = getSQLString(function.getTerm(1), index, false);
return sqladapter.strSubstr(string, start);
}
if (functionSymbol == ExpressionOperation.SUBSTR3) {
String string = getSQLString(function.getTerm(0), index, false);
String start = getSQLString(function.getTerm(1), index, false);
String end = getSQLString(function.getTerm(2), index, false);
return sqladapter.strSubstr(string, start, end);
}
if (functionSymbol == ExpressionOperation.STRBEFORE) {
String string = getSQLString(function.getTerm(0), index, false);
String before = getSQLString(function.getTerm(1), index, false);
return sqladapter.strBefore(string, before);
}
if (functionSymbol == ExpressionOperation.STRAFTER) {
String string = getSQLString(function.getTerm(0), index, false);
String after = getSQLString(function.getTerm(1), index, false);
return sqladapter.strAfter(string, after);
}
if (functionSymbol == ExpressionOperation.COUNT) {
if (function.getTerm(0).toString().equals("*")) {
return "COUNT(*)"; // depends on control dependency: [if], data = [none]
}
String columnName = getSQLString(function.getTerm(0), index, false);
//havingCond = true;
return "COUNT(" + columnName + ")";
}
if (functionSymbol == ExpressionOperation.AVG) {
String columnName = getSQLString(function.getTerm(0), index, false);
//havingCond = true;
return "AVG(" + columnName + ")";
}
if (functionSymbol == ExpressionOperation.SUM) {
String columnName = getSQLString(function.getTerm(0), index, false);
//havingCond = true;
return "SUM(" + columnName + ")";
}
throw new RuntimeException("Unexpected function in the query: " + functionSymbol);
} } |
public class class_name {
public void marshall(ListMembersRequest listMembersRequest, ProtocolMarshaller protocolMarshaller) {
if (listMembersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listMembersRequest.getDetectorId(), DETECTORID_BINDING);
protocolMarshaller.marshall(listMembersRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(listMembersRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listMembersRequest.getOnlyAssociated(), ONLYASSOCIATED_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ListMembersRequest listMembersRequest, ProtocolMarshaller protocolMarshaller) {
if (listMembersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listMembersRequest.getDetectorId(), DETECTORID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listMembersRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listMembersRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listMembersRequest.getOnlyAssociated(), ONLYASSOCIATED_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 {
protected String getColumn(OgmEntityPersister persister, List<String> propertyPath) {
Iterator<String> pathIterator = propertyPath.iterator();
String propertyName = pathIterator.next();
Type propertyType = persister.getPropertyType( propertyName );
if ( !pathIterator.hasNext() ) {
if ( isElementCollection( propertyType ) ) {
Joinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );
OgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;
// Collection of elements
return collectionPersister.getElementColumnNames()[0];
}
return persister.getPropertyColumnNames( propertyName )[0];
}
else if ( propertyType.isComponentType() ) {
// Embedded property
String componentPropertyName = StringHelper.join( propertyPath, "." );
return persister.getPropertyColumnNames( componentPropertyName )[0];
}
else if ( propertyType.isAssociationType() ) {
Joinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );
if ( associatedJoinable.isCollection() ) {
OgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;
if ( collectionPersister.getType().isComponentType() ) {
StringBuilder columnNameBuilder = new StringBuilder( propertyName );
columnNameBuilder.append( "." );
// Collection of embeddables
appendComponentCollectionPath( columnNameBuilder, collectionPersister, pathIterator );
return columnNameBuilder.toString();
}
}
}
throw new UnsupportedOperationException( "Unrecognized property type: " + propertyType );
} } | public class class_name {
protected String getColumn(OgmEntityPersister persister, List<String> propertyPath) {
Iterator<String> pathIterator = propertyPath.iterator();
String propertyName = pathIterator.next();
Type propertyType = persister.getPropertyType( propertyName );
if ( !pathIterator.hasNext() ) {
if ( isElementCollection( propertyType ) ) {
Joinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );
OgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;
// Collection of elements
return collectionPersister.getElementColumnNames()[0]; // depends on control dependency: [if], data = [none]
}
return persister.getPropertyColumnNames( propertyName )[0]; // depends on control dependency: [if], data = [none]
}
else if ( propertyType.isComponentType() ) {
// Embedded property
String componentPropertyName = StringHelper.join( propertyPath, "." );
return persister.getPropertyColumnNames( componentPropertyName )[0]; // depends on control dependency: [if], data = [none]
}
else if ( propertyType.isAssociationType() ) {
Joinable associatedJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( persister.getFactory() );
if ( associatedJoinable.isCollection() ) {
OgmCollectionPersister collectionPersister = (OgmCollectionPersister) associatedJoinable;
if ( collectionPersister.getType().isComponentType() ) {
StringBuilder columnNameBuilder = new StringBuilder( propertyName );
columnNameBuilder.append( "." ); // depends on control dependency: [if], data = [none]
// Collection of embeddables
appendComponentCollectionPath( columnNameBuilder, collectionPersister, pathIterator ); // depends on control dependency: [if], data = [none]
return columnNameBuilder.toString(); // depends on control dependency: [if], data = [none]
}
}
}
throw new UnsupportedOperationException( "Unrecognized property type: " + propertyType );
} } |
public class class_name {
@Nullable
private static Object valueOf(String value, Class<?> cls) {
if (cls == Boolean.TYPE) {
return Boolean.valueOf(value);
}
if (cls == Character.TYPE) {
return value.length() >= 1 ? value.charAt(0) : defaultValue(char.class);
}
if (cls == Byte.TYPE) {
return Byte.valueOf(value);
}
if (cls == Short.TYPE) {
return Short.valueOf(value);
}
if (cls == Integer.TYPE) {
return Integer.valueOf(value);
}
if (cls == Long.TYPE) {
return Long.valueOf(value);
}
if (cls == Float.TYPE) {
return Float.valueOf(value);
}
if (cls == Double.TYPE) {
return Double.valueOf(value);
}
return null;
} } | public class class_name {
@Nullable
private static Object valueOf(String value, Class<?> cls) {
if (cls == Boolean.TYPE) {
return Boolean.valueOf(value); // depends on control dependency: [if], data = [none]
}
if (cls == Character.TYPE) {
return value.length() >= 1 ? value.charAt(0) : defaultValue(char.class); // depends on control dependency: [if], data = [none]
}
if (cls == Byte.TYPE) {
return Byte.valueOf(value); // depends on control dependency: [if], data = [none]
}
if (cls == Short.TYPE) {
return Short.valueOf(value); // depends on control dependency: [if], data = [none]
}
if (cls == Integer.TYPE) {
return Integer.valueOf(value); // depends on control dependency: [if], data = [none]
}
if (cls == Long.TYPE) {
return Long.valueOf(value); // depends on control dependency: [if], data = [none]
}
if (cls == Float.TYPE) {
return Float.valueOf(value); // depends on control dependency: [if], data = [none]
}
if (cls == Double.TYPE) {
return Double.valueOf(value); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
private void lstPropertiesKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_lstPropertiesKeyPressed
int code = evt.getKeyCode();
if (code == KeyEvent.VK_DELETE) {
deleteMappingItem();
}
} } | public class class_name {
private void lstPropertiesKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_lstPropertiesKeyPressed
int code = evt.getKeyCode();
if (code == KeyEvent.VK_DELETE) {
deleteMappingItem(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Cell getCell(Properties attributes) {
Cell cell = new Cell();
String value;
cell.setHorizontalAlignment(attributes
.getProperty(ElementTags.HORIZONTALALIGN));
cell.setVerticalAlignment(attributes
.getProperty(ElementTags.VERTICALALIGN));
value = attributes.getProperty(ElementTags.WIDTH);
if (value != null) {
cell.setWidth(value);
}
value = attributes.getProperty(ElementTags.COLSPAN);
if (value != null) {
cell.setColspan(Integer.parseInt(value));
}
value = attributes.getProperty(ElementTags.ROWSPAN);
if (value != null) {
cell.setRowspan(Integer.parseInt(value));
}
value = attributes.getProperty(ElementTags.LEADING);
if (value != null) {
cell.setLeading(Float.parseFloat(value + "f"));
}
cell.setHeader(Utilities.checkTrueOrFalse(attributes,
ElementTags.HEADER));
if (Utilities.checkTrueOrFalse(attributes, ElementTags.NOWRAP)) {
cell.setMaxLines(1);
}
setRectangleProperties(cell, attributes);
return cell;
} } | public class class_name {
public static Cell getCell(Properties attributes) {
Cell cell = new Cell();
String value;
cell.setHorizontalAlignment(attributes
.getProperty(ElementTags.HORIZONTALALIGN));
cell.setVerticalAlignment(attributes
.getProperty(ElementTags.VERTICALALIGN));
value = attributes.getProperty(ElementTags.WIDTH);
if (value != null) {
cell.setWidth(value); // depends on control dependency: [if], data = [(value]
}
value = attributes.getProperty(ElementTags.COLSPAN);
if (value != null) {
cell.setColspan(Integer.parseInt(value)); // depends on control dependency: [if], data = [(value]
}
value = attributes.getProperty(ElementTags.ROWSPAN);
if (value != null) {
cell.setRowspan(Integer.parseInt(value)); // depends on control dependency: [if], data = [(value]
}
value = attributes.getProperty(ElementTags.LEADING);
if (value != null) {
cell.setLeading(Float.parseFloat(value + "f")); // depends on control dependency: [if], data = [(value]
}
cell.setHeader(Utilities.checkTrueOrFalse(attributes,
ElementTags.HEADER));
if (Utilities.checkTrueOrFalse(attributes, ElementTags.NOWRAP)) {
cell.setMaxLines(1); // depends on control dependency: [if], data = [none]
}
setRectangleProperties(cell, attributes);
return cell;
} } |
public class class_name {
@Deprecated
public static Matrix[] svd(File matrix, Algorithm alg,
Format format, int dimensions) {
try {
File converted = null;
switch (alg) {
case SVDLIBC: {
// check whether the input matrix is in an SVDLIBC-acceptable
// format already and if not convert
switch (format) {
case SVDLIBC_DENSE_BINARY:
case SVDLIBC_DENSE_TEXT:
case SVDLIBC_SPARSE_TEXT:
case SVDLIBC_SPARSE_BINARY:
converted = matrix;
break;
default:
SVD_LOGGER.fine("converting input matrix format " +
"from" + format + " to SVDLIBC " +
"ready format");
converted = MatrixIO.convertFormat(
matrix, format, Format.SVDLIBC_SPARSE_BINARY);
format = Format.SVDLIBC_SPARSE_BINARY;
break;
}
return svdlibc(converted, dimensions, format);
}
case JAMA: {
@SuppressWarnings("deprecation")
double[][] inputMatrix =
MatrixIO.readMatrixArray(matrix, format);
return jamaSVD(inputMatrix, dimensions);
}
case MATLAB:
// If the format of the input matrix isn't immediately useable
// by Matlab convert it
if (!format.equals(Format.MATLAB_SPARSE)) {
matrix = MatrixIO.convertFormat(
matrix, format, Format.MATLAB_SPARSE);
}
return matlabSVDS(matrix, dimensions);
case OCTAVE:
// If the format of the input matrix isn't immediately useable
// by Octave convert it
if (!format.equals(Format.MATLAB_SPARSE)) {
matrix = MatrixIO.convertFormat(
matrix, format, Format.MATLAB_SPARSE);
}
return octaveSVDS(matrix, dimensions);
case COLT: {
@SuppressWarnings("deprecation")
double[][] m = MatrixIO.readMatrixArray(matrix, format);
return coltSVD(m, Matrices.isDense(format), dimensions);
}
case ANY:
return svd(matrix, getFastestAvailableAlgorithm(), format, dimensions);
}
} catch (IOException ioe) {
SVD_LOGGER.log(Level.SEVERE, "convertFormat", ioe);
}
// required for compilation
throw new UnsupportedOperationException("Unknown algorithm: " + alg);
} } | public class class_name {
@Deprecated
public static Matrix[] svd(File matrix, Algorithm alg,
Format format, int dimensions) {
try {
File converted = null;
switch (alg) {
case SVDLIBC: {
// check whether the input matrix is in an SVDLIBC-acceptable
// format already and if not convert
switch (format) {
case SVDLIBC_DENSE_BINARY:
case SVDLIBC_DENSE_TEXT:
case SVDLIBC_SPARSE_TEXT:
case SVDLIBC_SPARSE_BINARY:
converted = matrix;
break;
default:
SVD_LOGGER.fine("converting input matrix format " +
"from" + format + " to SVDLIBC " +
"ready format");
converted = MatrixIO.convertFormat(
matrix, format, Format.SVDLIBC_SPARSE_BINARY);
format = Format.SVDLIBC_SPARSE_BINARY;
break;
}
return svdlibc(converted, dimensions, format);
}
case JAMA: {
@SuppressWarnings("deprecation")
double[][] inputMatrix =
MatrixIO.readMatrixArray(matrix, format);
return jamaSVD(inputMatrix, dimensions);
}
case MATLAB:
// If the format of the input matrix isn't immediately useable
// by Matlab convert it
if (!format.equals(Format.MATLAB_SPARSE)) {
matrix = MatrixIO.convertFormat(
matrix, format, Format.MATLAB_SPARSE); // depends on control dependency: [if], data = [none]
}
return matlabSVDS(matrix, dimensions);
case OCTAVE:
// If the format of the input matrix isn't immediately useable
// by Octave convert it
if (!format.equals(Format.MATLAB_SPARSE)) {
matrix = MatrixIO.convertFormat(
matrix, format, Format.MATLAB_SPARSE); // depends on control dependency: [if], data = [none]
}
return octaveSVDS(matrix, dimensions);
case COLT: {
@SuppressWarnings("deprecation")
double[][] m = MatrixIO.readMatrixArray(matrix, format);
return coltSVD(m, Matrices.isDense(format), dimensions);
}
case ANY:
return svd(matrix, getFastestAvailableAlgorithm(), format, dimensions);
}
} catch (IOException ioe) {
SVD_LOGGER.log(Level.SEVERE, "convertFormat", ioe);
}
// required for compilation
throw new UnsupportedOperationException("Unknown algorithm: " + alg);
} } |
public class class_name {
public static <T, E extends Exception> void flattOp(final T[][] a, Try.Consumer<T[], E> op) throws E {
if (N.isNullOrEmpty(a)) {
return;
}
final T[] tmp = flattenn(a);
op.accept(tmp);
int idx = 0;
for (T[] e : a) {
if (N.notNullOrEmpty(e)) {
N.copy(tmp, idx, e, 0, e.length);
idx += e.length;
}
}
} } | public class class_name {
public static <T, E extends Exception> void flattOp(final T[][] a, Try.Consumer<T[], E> op) throws E {
if (N.isNullOrEmpty(a)) {
return;
}
final T[] tmp = flattenn(a);
op.accept(tmp);
int idx = 0;
for (T[] e : a) {
if (N.notNullOrEmpty(e)) {
N.copy(tmp, idx, e, 0, e.length);
// depends on control dependency: [if], data = [none]
idx += e.length;
// depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public Object get(String key) {
if (!StringUtil.isEmpty(key)) {
if (pendingInstanceData.containsKey(key)) {
return pendingInstanceData.get(key);
}
if (instanceData.containsKey(key)) {
return instanceData.get(key);
}
}
return null;
} } | public class class_name {
public Object get(String key) {
if (!StringUtil.isEmpty(key)) {
if (pendingInstanceData.containsKey(key)) {
return pendingInstanceData.get(key); // depends on control dependency: [if], data = [none]
}
if (instanceData.containsKey(key)) {
return instanceData.get(key); // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
private InputStream getResourceStream(File file, String resourceName) {
try {
JarFile jarFile = (JarFile) jarFiles.get(file);
if (jarFile == null && file.isDirectory()) {
File resource = new File(file, resourceName);
if (resource.exists()) {
return Files.newInputStream(resource.toPath());
}
} else {
if (jarFile == null) {
if (file.exists()) {
jarFile = new JarFile(file);
jarFiles.put(file, jarFile);
} else {
return null;
}
//to eliminate a race condition, retrieve the entry
//that is in the hash table under that filename
jarFile = (JarFile) jarFiles.get(file);
}
JarEntry entry = jarFile.getJarEntry(resourceName);
if (entry != null) {
return jarFile.getInputStream(entry);
}
}
} catch (Exception e) {
log("Ignoring Exception " + e.getClass().getName() + ": " + e.getMessage()
+ " reading resource " + resourceName + " from " + file, Project.MSG_VERBOSE);
}
return null;
} } | public class class_name {
private InputStream getResourceStream(File file, String resourceName) {
try {
JarFile jarFile = (JarFile) jarFiles.get(file);
if (jarFile == null && file.isDirectory()) {
File resource = new File(file, resourceName);
if (resource.exists()) {
return Files.newInputStream(resource.toPath()); // depends on control dependency: [if], data = [none]
}
} else {
if (jarFile == null) {
if (file.exists()) {
jarFile = new JarFile(file); // depends on control dependency: [if], data = [none]
jarFiles.put(file, jarFile); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
//to eliminate a race condition, retrieve the entry
//that is in the hash table under that filename
jarFile = (JarFile) jarFiles.get(file); // depends on control dependency: [if], data = [none]
}
JarEntry entry = jarFile.getJarEntry(resourceName);
if (entry != null) {
return jarFile.getInputStream(entry); // depends on control dependency: [if], data = [(entry]
}
}
} catch (Exception e) {
log("Ignoring Exception " + e.getClass().getName() + ": " + e.getMessage()
+ " reading resource " + resourceName + " from " + file, Project.MSG_VERBOSE);
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
public static boolean isBlank(Object o) {
if (o instanceof CharSequence) {
CharSequence cs = (CharSequence) o;
return cs == null || new StringBuilder(cs.length()).append(cs).toString()
.trim().isEmpty();
}
if (o instanceof Iterable) {
Iterable<?> iter = (Iterable<?>) o;
return iter == null || !iter.iterator().hasNext();
}
if (o instanceof Iterator) {
Iterator<?> iter = (Iterator<?>) o;
return iter == null || !iter.hasNext();
}
if (o instanceof Map) {
Map<?, ?> map = (Map<?, ?>) o;
return map == null || map.isEmpty();
}
if (o instanceof Boolean) {
Boolean bool = (Boolean) o;
return bool == null || bool.equals(Boolean.FALSE);
}
return o == null;
} } | public class class_name {
public static boolean isBlank(Object o) {
if (o instanceof CharSequence) {
CharSequence cs = (CharSequence) o;
return cs == null || new StringBuilder(cs.length()).append(cs).toString()
.trim().isEmpty(); // depends on control dependency: [if], data = [none]
}
if (o instanceof Iterable) {
Iterable<?> iter = (Iterable<?>) o;
return iter == null || !iter.iterator().hasNext(); // depends on control dependency: [if], data = [none]
}
if (o instanceof Iterator) {
Iterator<?> iter = (Iterator<?>) o;
return iter == null || !iter.hasNext(); // depends on control dependency: [if], data = [none]
}
if (o instanceof Map) {
Map<?, ?> map = (Map<?, ?>) o; // depends on control dependency: [if], data = [none]
return map == null || map.isEmpty(); // depends on control dependency: [if], data = [none]
}
if (o instanceof Boolean) {
Boolean bool = (Boolean) o;
return bool == null || bool.equals(Boolean.FALSE); // depends on control dependency: [if], data = [none]
}
return o == null;
} } |
public class class_name {
public Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>> listOwnershipIdentifiersNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listOwnershipIdentifiersNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>>>() {
@Override
public Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<DomainOwnershipIdentifierInner>> result = listOwnershipIdentifiersNextDelegate(response);
return Observable.just(new ServiceResponse<Page<DomainOwnershipIdentifierInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>> listOwnershipIdentifiersNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listOwnershipIdentifiersNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>>>() {
@Override
public Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<DomainOwnershipIdentifierInner>> result = listOwnershipIdentifiersNextDelegate(response);
return Observable.just(new ServiceResponse<Page<DomainOwnershipIdentifierInner>>(result.body(), result.response())); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
@Override
public String toCompressedString() {
String result;
if(hasNoStringCache() || (result = stringCache.compressedString) == null) {
if(hasZone()) {
stringCache.compressedString = result = toNormalizedString(IPv6StringCache.compressedParams);
} else {
result = getSection().toCompressedString();//the cache is shared so no need to update it here
}
}
return result;
} } | public class class_name {
@Override
public String toCompressedString() {
String result;
if(hasNoStringCache() || (result = stringCache.compressedString) == null) {
if(hasZone()) {
stringCache.compressedString = result = toNormalizedString(IPv6StringCache.compressedParams); // depends on control dependency: [if], data = [none]
} else {
result = getSection().toCompressedString();//the cache is shared so no need to update it here // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
public static void solve(DMatrixSparseCSC G, boolean lower,
DMatrixSparseCSC B, DMatrixSparseCSC X,
@Nullable int pinv[] ,
@Nullable DGrowArray g_x, @Nullable IGrowArray g_xi, @Nullable IGrowArray g_w)
{
double[] x = UtilEjml.adjust(g_x,G.numRows);
if( g_xi == null ) g_xi = new IGrowArray();
int[] xi = UtilEjml.adjust(g_xi,G.numRows);
int[] w = UtilEjml.adjust(g_w,G.numCols*2, G.numCols);
X.nz_length = 0;
X.col_idx[0] = 0;
X.indicesSorted = false;
for (int colB = 0; colB < B.numCols; colB++) {
int top = solveColB(G,lower,B,colB, x, pinv,g_xi, w);
int nz_count = X.numRows-top;
if( X.nz_values.length < X.nz_length + nz_count) {
X.growMaxLength(X.nz_length*2 + nz_count,true);
}
for (int p = top; p < X.numRows; p++,X.nz_length++) {
X.nz_rows[X.nz_length] = xi[p];
X.nz_values[X.nz_length] = x[xi[p]];
}
X.col_idx[colB+1] = X.nz_length;
}
} } | public class class_name {
public static void solve(DMatrixSparseCSC G, boolean lower,
DMatrixSparseCSC B, DMatrixSparseCSC X,
@Nullable int pinv[] ,
@Nullable DGrowArray g_x, @Nullable IGrowArray g_xi, @Nullable IGrowArray g_w)
{
double[] x = UtilEjml.adjust(g_x,G.numRows);
if( g_xi == null ) g_xi = new IGrowArray();
int[] xi = UtilEjml.adjust(g_xi,G.numRows);
int[] w = UtilEjml.adjust(g_w,G.numCols*2, G.numCols);
X.nz_length = 0;
X.col_idx[0] = 0;
X.indicesSorted = false;
for (int colB = 0; colB < B.numCols; colB++) {
int top = solveColB(G,lower,B,colB, x, pinv,g_xi, w);
int nz_count = X.numRows-top;
if( X.nz_values.length < X.nz_length + nz_count) {
X.growMaxLength(X.nz_length*2 + nz_count,true); // depends on control dependency: [if], data = [none]
}
for (int p = top; p < X.numRows; p++,X.nz_length++) {
X.nz_rows[X.nz_length] = xi[p]; // depends on control dependency: [for], data = [p]
X.nz_values[X.nz_length] = x[xi[p]]; // depends on control dependency: [for], data = [p]
}
X.col_idx[colB+1] = X.nz_length; // depends on control dependency: [for], data = [colB]
}
} } |
public class class_name {
public static Selector expressionSelector(String expr, BeanFactory beanFactory) {
StandardEvaluationContext evalCtx = new StandardEvaluationContext();
if(null != beanFactory) {
evalCtx.setBeanResolver(new BeanFactoryResolver(beanFactory));
}
return expressionSelector(expr, evalCtx);
} } | public class class_name {
public static Selector expressionSelector(String expr, BeanFactory beanFactory) {
StandardEvaluationContext evalCtx = new StandardEvaluationContext();
if(null != beanFactory) {
evalCtx.setBeanResolver(new BeanFactoryResolver(beanFactory)); // depends on control dependency: [if], data = [beanFactory)]
}
return expressionSelector(expr, evalCtx);
} } |
public class class_name {
public static void set(final Object bean, final String property, Object value) {
try {
if (property.indexOf(".") >= 0) {
final String firstProperty = property.substring(0, property.indexOf("."));
Object subBean = ClassMockUtils.get(bean, firstProperty);
if (subBean == null) {
subBean = ClassMockUtils.getPropertyClass(bean.getClass(), firstProperty).newInstance();
ClassMockUtils.set(bean, firstProperty, subBean);
}
final String newProperty = property.substring(property.indexOf(".") + 1);
ClassMockUtils.set(subBean, newProperty, value);
return;
}
Method setterMethod = null;
for (final Method method : bean.getClass().getMethods()) {
if (method.getName().equals(ClassMockUtils.propertyToSetter(property))) {
setterMethod = method;
break;
}
}
if (setterMethod != null) {
final Class<?> type = setterMethod.getParameterTypes()[0];
if (type == null) {
throw new RuntimeException("The setter method of " + property + " does not have a parameter.");
} else if (type.isArray() && !type.getComponentType().isPrimitive()) {
final Object[] array = (Object[]) Array.newInstance(type.getComponentType(), ((Object[]) value).length);
for (int i = 0; i < array.length; i++) {
array[i] = type.getComponentType().cast(((Object[]) value)[i]);
}
setterMethod.invoke(bean, new Object[] { array });
} else {
if ((value instanceof String) && ((type == Integer.class) || (type == int.class))) {
value = Integer.parseInt((String) value);
} else if ((value instanceof String) && ((type == Long.class) || (type == long.class))) {
value = Long.parseLong((String) value);
} else if ((value instanceof String) && ((type == Byte.class) || (type == byte.class))) {
value = Byte.parseByte((String) value);
} else if ((value instanceof String) && ((type == Short.class) || (type == short.class))) {
value = Short.parseShort((String) value);
} else if ((value instanceof String) && ((type == Float.class) || (type == float.class))) {
value = Float.parseFloat((String) value);
} else if ((value instanceof String) && ((type == Double.class) || (type == double.class))) {
value = Double.parseDouble((String) value);
} else if ((value instanceof String) && ((type == Boolean.class) || (type == boolean.class))) {
value = Boolean.parseBoolean((String) value);
}
setterMethod.invoke(bean, value);
}
}
} catch (final Exception e) {
throw new RuntimeException("Can't set property " + property + " in the class " + bean.getClass().getName());
}
} } | public class class_name {
public static void set(final Object bean, final String property, Object value) {
try {
if (property.indexOf(".") >= 0) {
final String firstProperty = property.substring(0, property.indexOf("."));
Object subBean = ClassMockUtils.get(bean, firstProperty);
if (subBean == null) {
subBean = ClassMockUtils.getPropertyClass(bean.getClass(), firstProperty).newInstance(); // depends on control dependency: [if], data = [none]
ClassMockUtils.set(bean, firstProperty, subBean); // depends on control dependency: [if], data = [none]
}
final String newProperty = property.substring(property.indexOf(".") + 1);
ClassMockUtils.set(subBean, newProperty, value); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
Method setterMethod = null;
for (final Method method : bean.getClass().getMethods()) {
if (method.getName().equals(ClassMockUtils.propertyToSetter(property))) {
setterMethod = method; // depends on control dependency: [if], data = [none]
break;
}
}
if (setterMethod != null) {
final Class<?> type = setterMethod.getParameterTypes()[0];
if (type == null) {
throw new RuntimeException("The setter method of " + property + " does not have a parameter.");
} else if (type.isArray() && !type.getComponentType().isPrimitive()) {
final Object[] array = (Object[]) Array.newInstance(type.getComponentType(), ((Object[]) value).length);
for (int i = 0; i < array.length; i++) {
array[i] = type.getComponentType().cast(((Object[]) value)[i]); // depends on control dependency: [for], data = [i]
}
setterMethod.invoke(bean, new Object[] { array }); // depends on control dependency: [if], data = [none]
} else {
if ((value instanceof String) && ((type == Integer.class) || (type == int.class))) {
value = Integer.parseInt((String) value); // depends on control dependency: [if], data = [none]
} else if ((value instanceof String) && ((type == Long.class) || (type == long.class))) {
value = Long.parseLong((String) value); // depends on control dependency: [if], data = [none]
} else if ((value instanceof String) && ((type == Byte.class) || (type == byte.class))) {
value = Byte.parseByte((String) value); // depends on control dependency: [if], data = [none]
} else if ((value instanceof String) && ((type == Short.class) || (type == short.class))) {
value = Short.parseShort((String) value); // depends on control dependency: [if], data = [none]
} else if ((value instanceof String) && ((type == Float.class) || (type == float.class))) {
value = Float.parseFloat((String) value); // depends on control dependency: [if], data = [none]
} else if ((value instanceof String) && ((type == Double.class) || (type == double.class))) {
value = Double.parseDouble((String) value); // depends on control dependency: [if], data = [none]
} else if ((value instanceof String) && ((type == Boolean.class) || (type == boolean.class))) {
value = Boolean.parseBoolean((String) value); // depends on control dependency: [if], data = [none]
}
setterMethod.invoke(bean, value); // depends on control dependency: [if], data = [none]
}
}
} catch (final Exception e) {
throw new RuntimeException("Can't set property " + property + " in the class " + bean.getClass().getName());
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public synchronized void clear() {
if (!validState) {
throw new InvalidStateException();
}
try {
bufOutput.clear();
fcOutput.position(0).truncate(0).force(true);
offsetOutputUncommited = offsetOutputCommited = fcOutput.position();
if (callback != null) {
callback.synched(offsetOutputCommited);
}
close();
open();
} catch (Exception e) {
log.error("Exception in clear()", e);
}
} } | public class class_name {
public synchronized void clear() {
if (!validState) {
throw new InvalidStateException();
}
try {
bufOutput.clear(); // depends on control dependency: [try], data = [none]
fcOutput.position(0).truncate(0).force(true); // depends on control dependency: [try], data = [none]
offsetOutputUncommited = offsetOutputCommited = fcOutput.position(); // depends on control dependency: [try], data = [none]
if (callback != null) {
callback.synched(offsetOutputCommited); // depends on control dependency: [if], data = [none]
}
close(); // depends on control dependency: [try], data = [none]
open(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
log.error("Exception in clear()", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Double getDouble(final String key, final Double def) {
Double val = getDouble(key);
if (val == null) {
if (map.containsKey(key)) {
return null;
}
return def;
}
return val;
} } | public class class_name {
public Double getDouble(final String key, final Double def) {
Double val = getDouble(key);
if (val == null) {
if (map.containsKey(key)) {
return null; // depends on control dependency: [if], data = [none]
}
return def; // depends on control dependency: [if], data = [none]
}
return val;
} } |
public class class_name {
private void channelActiveSideEffects(final ChannelHandlerContext ctx) {
long interval = env().keepAliveInterval();
if (env().continuousKeepAliveEnabled()) {
continuousKeepAliveFuture = ctx.executor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (shouldSendKeepAlive()) {
createAndWriteKeepAlive(ctx);
}
}
}, interval, interval, TimeUnit.MILLISECONDS);
}
} } | public class class_name {
private void channelActiveSideEffects(final ChannelHandlerContext ctx) {
long interval = env().keepAliveInterval();
if (env().continuousKeepAliveEnabled()) {
continuousKeepAliveFuture = ctx.executor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (shouldSendKeepAlive()) {
createAndWriteKeepAlive(ctx); // depends on control dependency: [if], data = [none]
}
}
}, interval, interval, TimeUnit.MILLISECONDS); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public boolean onTap(LatLong tapLatLong, Point layerXY, Point tapXY) {
for (int i = layers.size() - 1; i >= 0; i--) {
Layer layer = layers.get(i);
if (layer.onTap(tapLatLong, layerXY, tapXY)) {
return true;
}
}
return false;
} } | public class class_name {
@Override
public boolean onTap(LatLong tapLatLong, Point layerXY, Point tapXY) {
for (int i = layers.size() - 1; i >= 0; i--) {
Layer layer = layers.get(i);
if (layer.onTap(tapLatLong, layerXY, tapXY)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public void marshall(GetCommentsForComparedCommitRequest getCommentsForComparedCommitRequest, ProtocolMarshaller protocolMarshaller) {
if (getCommentsForComparedCommitRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getCommentsForComparedCommitRequest.getRepositoryName(), REPOSITORYNAME_BINDING);
protocolMarshaller.marshall(getCommentsForComparedCommitRequest.getBeforeCommitId(), BEFORECOMMITID_BINDING);
protocolMarshaller.marshall(getCommentsForComparedCommitRequest.getAfterCommitId(), AFTERCOMMITID_BINDING);
protocolMarshaller.marshall(getCommentsForComparedCommitRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(getCommentsForComparedCommitRequest.getMaxResults(), MAXRESULTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetCommentsForComparedCommitRequest getCommentsForComparedCommitRequest, ProtocolMarshaller protocolMarshaller) {
if (getCommentsForComparedCommitRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getCommentsForComparedCommitRequest.getRepositoryName(), REPOSITORYNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getCommentsForComparedCommitRequest.getBeforeCommitId(), BEFORECOMMITID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getCommentsForComparedCommitRequest.getAfterCommitId(), AFTERCOMMITID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getCommentsForComparedCommitRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getCommentsForComparedCommitRequest.getMaxResults(), MAXRESULTS_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 {
protected void addProcessedData(List<List<CRFDatum<Collection<String>, String>>> processedData, int[][][][] data,
int[][] labels, int offset) {
for (int i = 0, pdSize = processedData.size(); i < pdSize; i++) {
int dataIndex = i + offset;
List<CRFDatum<Collection<String>, String>> document = processedData.get(i);
int dsize = document.size();
labels[dataIndex] = new int[dsize];
data[dataIndex] = new int[dsize][][];
for (int j = 0; j < dsize; j++) {
CRFDatum<Collection<String>, String> crfDatum = document.get(j);
// add label, they are offset by extra context
labels[dataIndex][j] = classIndex.indexOf(crfDatum.label());
// add features
List<Collection<String>> cliques = crfDatum.asFeatures();
int csize = cliques.size();
data[dataIndex][j] = new int[csize][];
for (int k = 0; k < csize; k++) {
Collection<String> features = cliques.get(k);
// Debug only: Remove
// if (j < windowSize) {
// System.err.println("addProcessedData: Features Size: " +
// features.size());
// }
data[dataIndex][j][k] = new int[features.size()];
int m = 0;
try {
for (String feature : features) {
// System.err.println("feature " + feature);
// if (featureIndex.indexOf(feature)) ;
if (featureIndex == null) {
System.out.println("Feature is NULL!");
}
data[dataIndex][j][k][m] = featureIndex.indexOf(feature);
m++;
}
} catch (Exception e) {
e.printStackTrace();
System.err.printf("[index=%d, j=%d, k=%d, m=%d]\n", dataIndex, j, k, m);
System.err.println("data.length " + data.length);
System.err.println("data[dataIndex].length " + data[dataIndex].length);
System.err.println("data[dataIndex][j].length " + data[dataIndex][j].length);
System.err.println("data[dataIndex][j][k].length " + data[dataIndex][j].length);
System.err.println("data[dataIndex][j][k][m] " + data[dataIndex][j][k][m]);
return;
}
}
}
}
} } | public class class_name {
protected void addProcessedData(List<List<CRFDatum<Collection<String>, String>>> processedData, int[][][][] data,
int[][] labels, int offset) {
for (int i = 0, pdSize = processedData.size(); i < pdSize; i++) {
int dataIndex = i + offset;
List<CRFDatum<Collection<String>, String>> document = processedData.get(i);
int dsize = document.size();
labels[dataIndex] = new int[dsize];
data[dataIndex] = new int[dsize][][];
for (int j = 0; j < dsize; j++) {
CRFDatum<Collection<String>, String> crfDatum = document.get(j);
// add label, they are offset by extra context
labels[dataIndex][j] = classIndex.indexOf(crfDatum.label());
// add features
List<Collection<String>> cliques = crfDatum.asFeatures();
int csize = cliques.size();
data[dataIndex][j] = new int[csize][];
for (int k = 0; k < csize; k++) {
Collection<String> features = cliques.get(k);
// Debug only: Remove
// if (j < windowSize) {
// System.err.println("addProcessedData: Features Size: " +
// features.size());
// }
data[dataIndex][j][k] = new int[features.size()];
int m = 0;
try {
for (String feature : features) {
// System.err.println("feature " + feature);
// if (featureIndex.indexOf(feature)) ;
if (featureIndex == null) {
System.out.println("Feature is NULL!");
// depends on control dependency: [if], data = [none]
}
data[dataIndex][j][k][m] = featureIndex.indexOf(feature);
// depends on control dependency: [for], data = [feature]
m++;
// depends on control dependency: [for], data = [none]
}
} catch (Exception e) {
e.printStackTrace();
System.err.printf("[index=%d, j=%d, k=%d, m=%d]\n", dataIndex, j, k, m);
System.err.println("data.length " + data.length);
System.err.println("data[dataIndex].length " + data[dataIndex].length);
System.err.println("data[dataIndex][j].length " + data[dataIndex][j].length);
System.err.println("data[dataIndex][j][k].length " + data[dataIndex][j].length);
System.err.println("data[dataIndex][j][k][m] " + data[dataIndex][j][k][m]);
return;
}
}
}
}
} } |
public class class_name {
static private long skipForward(InputStream is, long toSkip)
throws IOException {
long eachSkip = 0;
long skipped = 0;
while (skipped != toSkip) {
eachSkip = is.skip(toSkip - skipped);
// check if EOF is reached
if (eachSkip <= 0) {
if (is.read() == -1) {
return skipped ;
} else {
skipped++;
}
}
skipped += eachSkip;
}
return skipped;
} } | public class class_name {
static private long skipForward(InputStream is, long toSkip)
throws IOException {
long eachSkip = 0;
long skipped = 0;
while (skipped != toSkip) {
eachSkip = is.skip(toSkip - skipped);
// check if EOF is reached
if (eachSkip <= 0) {
if (is.read() == -1) {
return skipped ; // depends on control dependency: [if], data = [none]
} else {
skipped++; // depends on control dependency: [if], data = [none]
}
}
skipped += eachSkip;
}
return skipped;
} } |
public class class_name {
public static Set<String> getAvailableLocaleSuffixes() {
Set<String> availableLocaleSuffixes = new HashSet<>();
Locale[] availableLocales = Locale.getAvailableLocales();
for (Locale locale : availableLocales) {
StringBuilder sb = new StringBuilder();
if (locale != null) {
String language = locale.getLanguage();
String country = locale.getCountry();
String variant = locale.getVariant();
if (StringUtils.isNotEmpty(variant)) {
sb.append(language).append('_').append(country).append('_').append(variant);
} else if (StringUtils.isNotEmpty(country)) {
sb.append(language).append('_').append(country);
} else {
sb.append(language);
}
}
availableLocaleSuffixes.add(sb.toString());
}
return availableLocaleSuffixes;
} } | public class class_name {
public static Set<String> getAvailableLocaleSuffixes() {
Set<String> availableLocaleSuffixes = new HashSet<>();
Locale[] availableLocales = Locale.getAvailableLocales();
for (Locale locale : availableLocales) {
StringBuilder sb = new StringBuilder();
if (locale != null) {
String language = locale.getLanguage();
String country = locale.getCountry();
String variant = locale.getVariant();
if (StringUtils.isNotEmpty(variant)) {
sb.append(language).append('_').append(country).append('_').append(variant); // depends on control dependency: [if], data = [none]
} else if (StringUtils.isNotEmpty(country)) {
sb.append(language).append('_').append(country); // depends on control dependency: [if], data = [none]
} else {
sb.append(language); // depends on control dependency: [if], data = [none]
}
}
availableLocaleSuffixes.add(sb.toString()); // depends on control dependency: [for], data = [none]
}
return availableLocaleSuffixes;
} } |
public class class_name {
private void addAdditionalNamenodesFromConf(final Props props) {
final String sparkConfDir = getSparkLibConf()[1];
final File sparkConfFile = new File(sparkConfDir, "spark-defaults.conf");
try {
final InputStreamReader inReader =
new InputStreamReader(new FileInputStream(sparkConfFile), StandardCharsets.UTF_8);
// Use Properties to avoid needing Spark on our classpath
final Properties sparkProps = new Properties();
sparkProps.load(inReader);
inReader.close();
final String additionalNamenodes =
sparkProps.getProperty(SPARK_CONF_ADDITIONAL_NAMENODES);
if (additionalNamenodes != null && additionalNamenodes.length() > 0) {
getLog().info("Found property " + SPARK_CONF_ADDITIONAL_NAMENODES +
" = " + additionalNamenodes + "; setting additional namenodes");
HadoopJobUtils.addAdditionalNamenodesToProps(props, additionalNamenodes);
}
} catch (final IOException e) {
getLog().warn("Unable to load Spark configuration; not adding any additional " +
"namenode delegation tokens.", e);
}
} } | public class class_name {
private void addAdditionalNamenodesFromConf(final Props props) {
final String sparkConfDir = getSparkLibConf()[1];
final File sparkConfFile = new File(sparkConfDir, "spark-defaults.conf");
try {
final InputStreamReader inReader =
new InputStreamReader(new FileInputStream(sparkConfFile), StandardCharsets.UTF_8);
// Use Properties to avoid needing Spark on our classpath
final Properties sparkProps = new Properties();
sparkProps.load(inReader); // depends on control dependency: [try], data = [none]
inReader.close(); // depends on control dependency: [try], data = [none]
final String additionalNamenodes =
sparkProps.getProperty(SPARK_CONF_ADDITIONAL_NAMENODES);
if (additionalNamenodes != null && additionalNamenodes.length() > 0) {
getLog().info("Found property " + SPARK_CONF_ADDITIONAL_NAMENODES +
" = " + additionalNamenodes + "; setting additional namenodes"); // depends on control dependency: [if], data = [none]
HadoopJobUtils.addAdditionalNamenodesToProps(props, additionalNamenodes); // depends on control dependency: [if], data = [none]
}
} catch (final IOException e) {
getLog().warn("Unable to load Spark configuration; not adding any additional " +
"namenode delegation tokens.", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <C extends Configurable> C getConfiguration(Class<C> klass, Properties properties) {
//Initialize configuration object
C configuration;
try {
Constructor<C> constructor = klass.getDeclaredConstructor();
constructor.setAccessible(true);
configuration = constructor.newInstance();
}
catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
throw new RuntimeException(ex);
}
configuration.load(properties);
return configuration;
} } | public class class_name {
public static <C extends Configurable> C getConfiguration(Class<C> klass, Properties properties) {
//Initialize configuration object
C configuration;
try {
Constructor<C> constructor = klass.getDeclaredConstructor();
constructor.setAccessible(true); // depends on control dependency: [try], data = [none]
configuration = constructor.newInstance(); // depends on control dependency: [try], data = [none]
}
catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
throw new RuntimeException(ex);
} // depends on control dependency: [catch], data = [none]
configuration.load(properties);
return configuration;
} } |
public class class_name {
@Override
public int doEndTag() throws JspException {
charEncoding = value;
if ((charEncoding == null)
&& (pageContext.getRequest().getCharacterEncoding() == null)) {
// Use charset from session-scoped attribute
charEncoding = (String)
pageContext.getAttribute(REQUEST_CHAR_SET,
PageContext.SESSION_SCOPE);
if (charEncoding == null) {
// Use default encoding
charEncoding = DEFAULT_ENCODING;
}
}
/*
* If char encoding was already set in the request, we don't need to
* set it again.
*/
if (charEncoding != null) {
try {
pageContext.getRequest().setCharacterEncoding(charEncoding);
} catch (UnsupportedEncodingException uee) {
throw new JspTagException(uee.toString(), uee);
}
}
return EVAL_PAGE;
} } | public class class_name {
@Override
public int doEndTag() throws JspException {
charEncoding = value;
if ((charEncoding == null)
&& (pageContext.getRequest().getCharacterEncoding() == null)) {
// Use charset from session-scoped attribute
charEncoding = (String)
pageContext.getAttribute(REQUEST_CHAR_SET,
PageContext.SESSION_SCOPE);
if (charEncoding == null) {
// Use default encoding
charEncoding = DEFAULT_ENCODING; // depends on control dependency: [if], data = [none]
}
}
/*
* If char encoding was already set in the request, we don't need to
* set it again.
*/
if (charEncoding != null) {
try {
pageContext.getRequest().setCharacterEncoding(charEncoding);
} catch (UnsupportedEncodingException uee) {
throw new JspTagException(uee.toString(), uee);
}
}
return EVAL_PAGE;
} } |
public class class_name {
private ValidationMessage<Origin> reportError(ValidationResult result, Feature feature, String messageId, Object ... params) {
ValidationMessage<Origin> message =
EntryValidations.createMessage(feature.getOrigin(), Severity.ERROR, messageId, params);
if (SequenceEntryUtils.isQualifierAvailable(Qualifier.LOCUS_TAG_QUALIFIER_NAME, feature)) {
Qualifier locusTag = SequenceEntryUtils.getQualifier(Qualifier.LOCUS_TAG_QUALIFIER_NAME, feature);
message.appendCuratorMessage("locus tag = " + locusTag.getValue());
}
if (SequenceEntryUtils.isQualifierAvailable(Qualifier.GENE_QUALIFIER_NAME, feature)) {
Qualifier geneName = SequenceEntryUtils.getQualifier(Qualifier.GENE_QUALIFIER_NAME, feature);
message.appendCuratorMessage("gene = " + geneName.getValue());
}
result.append(message);
return message;
} } | public class class_name {
private ValidationMessage<Origin> reportError(ValidationResult result, Feature feature, String messageId, Object ... params) {
ValidationMessage<Origin> message =
EntryValidations.createMessage(feature.getOrigin(), Severity.ERROR, messageId, params);
if (SequenceEntryUtils.isQualifierAvailable(Qualifier.LOCUS_TAG_QUALIFIER_NAME, feature)) {
Qualifier locusTag = SequenceEntryUtils.getQualifier(Qualifier.LOCUS_TAG_QUALIFIER_NAME, feature);
message.appendCuratorMessage("locus tag = " + locusTag.getValue()); // depends on control dependency: [if], data = [none]
}
if (SequenceEntryUtils.isQualifierAvailable(Qualifier.GENE_QUALIFIER_NAME, feature)) {
Qualifier geneName = SequenceEntryUtils.getQualifier(Qualifier.GENE_QUALIFIER_NAME, feature);
message.appendCuratorMessage("gene = " + geneName.getValue()); // depends on control dependency: [if], data = [none]
}
result.append(message);
return message;
} } |
public class class_name {
@Override
public void removeByG_A(long groupId, boolean active) {
for (CommerceCurrency commerceCurrency : findByG_A(groupId, active,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceCurrency);
}
} } | public class class_name {
@Override
public void removeByG_A(long groupId, boolean active) {
for (CommerceCurrency commerceCurrency : findByG_A(groupId, active,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceCurrency); // depends on control dependency: [for], data = [commerceCurrency]
}
} } |
public class class_name {
public static Partition fromString(String strForm) {
if (strForm == null || strForm.isEmpty()) throw new IllegalArgumentException("null or empty string provided");
Partition p = new Partition();
int index = 0;
if (strForm.charAt(0) == '[') {
index++;
}
int endIndex;
if (strForm.charAt(strForm.length() - 1) == ']') {
endIndex = strForm.length() - 2;
} else {
endIndex = strForm.length() - 1;
}
int currentCell = -1;
int numStart = -1;
while (index <= endIndex) {
char c = strForm.charAt(index);
if (Character.isDigit(c)) {
if (numStart == -1) {
numStart = index;
}
} else if (c == ',') {
int element = Integer.parseInt(strForm.substring(numStart, index));
if (currentCell == -1) {
p.addCell(element);
currentCell = 0;
} else {
p.addToCell(currentCell, element);
}
numStart = -1;
} else if (c == '|') {
int element = Integer.parseInt(strForm.substring(numStart, index));
if (currentCell == -1) {
p.addCell(element);
currentCell = 0;
} else {
p.addToCell(currentCell, element);
}
currentCell++;
p.addCell();
numStart = -1;
}
index++;
}
int lastElement = Integer.parseInt(strForm.substring(numStart, endIndex + 1));
p.addToCell(currentCell, lastElement);
return p;
} } | public class class_name {
public static Partition fromString(String strForm) {
if (strForm == null || strForm.isEmpty()) throw new IllegalArgumentException("null or empty string provided");
Partition p = new Partition();
int index = 0;
if (strForm.charAt(0) == '[') {
index++; // depends on control dependency: [if], data = [none]
}
int endIndex;
if (strForm.charAt(strForm.length() - 1) == ']') {
endIndex = strForm.length() - 2; // depends on control dependency: [if], data = [none]
} else {
endIndex = strForm.length() - 1; // depends on control dependency: [if], data = [none]
}
int currentCell = -1;
int numStart = -1;
while (index <= endIndex) {
char c = strForm.charAt(index);
if (Character.isDigit(c)) {
if (numStart == -1) {
numStart = index; // depends on control dependency: [if], data = [none]
}
} else if (c == ',') {
int element = Integer.parseInt(strForm.substring(numStart, index));
if (currentCell == -1) {
p.addCell(element); // depends on control dependency: [if], data = [none]
currentCell = 0; // depends on control dependency: [if], data = [none]
} else {
p.addToCell(currentCell, element); // depends on control dependency: [if], data = [(currentCell]
}
numStart = -1; // depends on control dependency: [if], data = [none]
} else if (c == '|') {
int element = Integer.parseInt(strForm.substring(numStart, index));
if (currentCell == -1) {
p.addCell(element); // depends on control dependency: [if], data = [none]
currentCell = 0; // depends on control dependency: [if], data = [none]
} else {
p.addToCell(currentCell, element); // depends on control dependency: [if], data = [(currentCell]
}
currentCell++; // depends on control dependency: [if], data = [none]
p.addCell(); // depends on control dependency: [if], data = [none]
numStart = -1; // depends on control dependency: [if], data = [none]
}
index++; // depends on control dependency: [while], data = [none]
}
int lastElement = Integer.parseInt(strForm.substring(numStart, endIndex + 1));
p.addToCell(currentCell, lastElement);
return p;
} } |
public class class_name {
public void addReadFields(FieldSet readFields) {
if(this.readFields == null) {
this.readFields = new FieldSet(readFields);
} else {
this.readFields.addAll(readFields);
}
} } | public class class_name {
public void addReadFields(FieldSet readFields) {
if(this.readFields == null) {
this.readFields = new FieldSet(readFields); // depends on control dependency: [if], data = [none]
} else {
this.readFields.addAll(readFields); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setIndexFields(java.util.Collection<IndexFieldStatus> indexFields) {
if (indexFields == null) {
this.indexFields = null;
return;
}
this.indexFields = new com.amazonaws.internal.SdkInternalList<IndexFieldStatus>(indexFields);
} } | public class class_name {
public void setIndexFields(java.util.Collection<IndexFieldStatus> indexFields) {
if (indexFields == null) {
this.indexFields = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.indexFields = new com.amazonaws.internal.SdkInternalList<IndexFieldStatus>(indexFields);
} } |
public class class_name {
public Hoarde<T> each(BiConsumer<T, Integer> init) {
for (int i = 0; i < actors.length; i++) {
init.accept( (T) actors[i], i );
}
return this;
} } | public class class_name {
public Hoarde<T> each(BiConsumer<T, Integer> init) {
for (int i = 0; i < actors.length; i++) {
init.accept( (T) actors[i], i ); // depends on control dependency: [for], data = [i]
}
return this;
} } |
public class class_name {
protected Artifact resolveArtifact(final Artifact artifact, final boolean transitive) throws MojoExecutionException {
assert artifact != null;
try {
if (transitive) {
artifactResolver.resolveTransitively(
Collections.singleton(artifact),
project.getArtifact(),
project.getRemoteArtifactRepositories(),
artifactRepository,
artifactMetadataSource);
}
else {
artifactResolver.resolve(
artifact,
project.getRemoteArtifactRepositories(),
artifactRepository);
}
}
catch (ArtifactResolutionException e) {
throw new MojoExecutionException("Unable to resolve artifact", e);
}
catch (ArtifactNotFoundException e) {
throw new MojoExecutionException("Unable to find artifact", e);
}
return artifact;
} } | public class class_name {
protected Artifact resolveArtifact(final Artifact artifact, final boolean transitive) throws MojoExecutionException {
assert artifact != null;
try {
if (transitive) {
artifactResolver.resolveTransitively(
Collections.singleton(artifact),
project.getArtifact(),
project.getRemoteArtifactRepositories(),
artifactRepository,
artifactMetadataSource); // depends on control dependency: [if], data = [none]
}
else {
artifactResolver.resolve(
artifact,
project.getRemoteArtifactRepositories(),
artifactRepository); // depends on control dependency: [if], data = [none]
}
}
catch (ArtifactResolutionException e) {
throw new MojoExecutionException("Unable to resolve artifact", e);
}
catch (ArtifactNotFoundException e) {
throw new MojoExecutionException("Unable to find artifact", e);
}
return artifact;
} } |
public class class_name {
@PostConstruct
public void buildRepository() {
try {
LOGGER.info("Using repo config (classpath): {}", repositoryConfiguration.getURL());
getPropertiesLoader().loadSystemProperties();
final RepositoryConfiguration config =
RepositoryConfiguration.read(repositoryConfiguration.getURL());
repository = modeShapeEngine.deploy(config);
// next line ensures that repository starts before the factory is used.
final org.modeshape.common.collection.Problems problems =
repository.getStartupProblems();
for (final org.modeshape.common.collection.Problem p : problems) {
LOGGER.error("ModeShape Start Problem: {}", p.getMessageString());
// TODO determine problems that should be runtime errors
}
} catch (final Exception e) {
throw new RepositoryRuntimeException(e);
}
} } | public class class_name {
@PostConstruct
public void buildRepository() {
try {
LOGGER.info("Using repo config (classpath): {}", repositoryConfiguration.getURL()); // depends on control dependency: [try], data = [none]
getPropertiesLoader().loadSystemProperties(); // depends on control dependency: [try], data = [none]
final RepositoryConfiguration config =
RepositoryConfiguration.read(repositoryConfiguration.getURL());
repository = modeShapeEngine.deploy(config); // depends on control dependency: [try], data = [none]
// next line ensures that repository starts before the factory is used.
final org.modeshape.common.collection.Problems problems =
repository.getStartupProblems();
for (final org.modeshape.common.collection.Problem p : problems) {
LOGGER.error("ModeShape Start Problem: {}", p.getMessageString()); // depends on control dependency: [for], data = [p]
// TODO determine problems that should be runtime errors
}
} catch (final Exception e) {
throw new RepositoryRuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void calcAsas(int nSpherePoints, int nThreads, int cofactorSizeToUse) {
// asa/bsa calculation
// NOTE in principle it is more efficient to calculate asas only once per unique chain
// BUT! the rolling ball algorithm gives slightly different values for same molecule in different
// rotations (due to sampling depending on orientation of axes grid).
// Both NACCESS and our own implementation behave like that.
// That's why we calculate ASAs for each rotation-unique molecule, otherwise
// we get discrepancies (not very big but annoying) which lead to things like negative (small) bsa values
Map<String, Atom[]> uniqAsaChains = new TreeMap<>();
Map<String, double[]> chainAsas = new TreeMap<>();
List<StructureInterface> redundancyReducedList;
if (clustersNcs != null) {
redundancyReducedList = new ArrayList<>();
for (StructureInterfaceCluster ncsCluster : clustersNcs) {
// we use the first one in list as the only one for which we calculate ASAs
redundancyReducedList.add(ncsCluster.getMembers().get(0));
}
} else {
redundancyReducedList = list;
}
// first we gather rotation-unique chains (in terms of AU id and transform id)
for (StructureInterface interf:redundancyReducedList) {
String molecId1 = interf.getMoleculeIds().getFirst()+interf.getTransforms().getFirst().getTransformId();
String molecId2 = interf.getMoleculeIds().getSecond()+interf.getTransforms().getSecond().getTransformId();
uniqAsaChains.put(molecId1, interf.getFirstAtomsForAsa(cofactorSizeToUse));
uniqAsaChains.put(molecId2, interf.getSecondAtomsForAsa(cofactorSizeToUse));
}
logger.debug("Will calculate uncomplexed ASA for {} orientation-unique chains.", uniqAsaChains.size());
long start = System.currentTimeMillis();
// we only need to calculate ASA for that subset (any translation of those will have same values)
for (String molecId:uniqAsaChains.keySet()) {
logger.debug("Calculating uncomplexed ASA for molecId {}, with {} atoms", molecId, uniqAsaChains.get(molecId).length);
AsaCalculator asaCalc = new AsaCalculator(uniqAsaChains.get(molecId),
AsaCalculator.DEFAULT_PROBE_SIZE, nSpherePoints, nThreads);
double[] atomAsas = asaCalc.calculateAsas();
chainAsas.put(molecId, atomAsas);
}
long end = System.currentTimeMillis();
logger.debug("Calculated uncomplexed ASA for {} orientation-unique chains. Time: {} s", uniqAsaChains.size(), ((end-start)/1000.0));
logger.debug ("Will calculate complexed ASA for {} pairwise complexes.", redundancyReducedList.size());
start = System.currentTimeMillis();
// now we calculate the ASAs for each of the complexes
for (StructureInterface interf:redundancyReducedList) {
String molecId1 = interf.getMoleculeIds().getFirst()+interf.getTransforms().getFirst().getTransformId();
String molecId2 = interf.getMoleculeIds().getSecond()+interf.getTransforms().getSecond().getTransformId();
logger.debug("Calculating complexed ASAs for interface {} between molecules {} and {}", interf.getId(), molecId1, molecId2);
interf.setAsas(chainAsas.get(molecId1), chainAsas.get(molecId2), nSpherePoints, nThreads, cofactorSizeToUse);
}
end = System.currentTimeMillis();
logger.debug("Calculated complexes ASA for {} pairwise complexes. Time: {} s", redundancyReducedList.size(), ((end-start)/1000.0));
// now let's populate the interface area value for the NCS-redundant ones from the reference interface (first one in list)
if (clustersNcs!=null) {
if (chainOrigNamesMap==null) {
logger.warn("No chainOrigNamesMap is set. Considering NCS interfaces in same order as reference. This is likely a bug.");
}
for (StructureInterfaceCluster ncsCluster : clustersNcs) {
StructureInterface refInterf = ncsCluster.getMembers().get(0);
String refMolecId1 = refInterf.getMoleculeIds().getFirst();
for (int i=1;i<ncsCluster.getMembers().size();i++) {
StructureInterface member = ncsCluster.getMembers().get(i);
member.setTotalArea(refInterf.getTotalArea());
String molecId1 = member.getMoleculeIds().getFirst();
if (areMolecIdsSameOrder(refMolecId1, molecId1)) {
// we add the reference interface GroupAsas as the GroupAsas for all other members, like that
// ResidueNumbers won't match in their chain ids, but otherwise all info is there without using a lot of memory
member.setFirstGroupAsas(refInterf.getFirstGroupAsas());
member.setSecondGroupAsas(refInterf.getSecondGroupAsas());
} else {
member.setFirstGroupAsas(refInterf.getSecondGroupAsas());
member.setSecondGroupAsas(refInterf.getFirstGroupAsas());
}
}
}
}
// finally we sort based on the ChainInterface.comparable() (based in interfaceArea)
sort();
} } | public class class_name {
public void calcAsas(int nSpherePoints, int nThreads, int cofactorSizeToUse) {
// asa/bsa calculation
// NOTE in principle it is more efficient to calculate asas only once per unique chain
// BUT! the rolling ball algorithm gives slightly different values for same molecule in different
// rotations (due to sampling depending on orientation of axes grid).
// Both NACCESS and our own implementation behave like that.
// That's why we calculate ASAs for each rotation-unique molecule, otherwise
// we get discrepancies (not very big but annoying) which lead to things like negative (small) bsa values
Map<String, Atom[]> uniqAsaChains = new TreeMap<>();
Map<String, double[]> chainAsas = new TreeMap<>();
List<StructureInterface> redundancyReducedList;
if (clustersNcs != null) {
redundancyReducedList = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (StructureInterfaceCluster ncsCluster : clustersNcs) {
// we use the first one in list as the only one for which we calculate ASAs
redundancyReducedList.add(ncsCluster.getMembers().get(0)); // depends on control dependency: [for], data = [ncsCluster]
}
} else {
redundancyReducedList = list; // depends on control dependency: [if], data = [none]
}
// first we gather rotation-unique chains (in terms of AU id and transform id)
for (StructureInterface interf:redundancyReducedList) {
String molecId1 = interf.getMoleculeIds().getFirst()+interf.getTransforms().getFirst().getTransformId();
String molecId2 = interf.getMoleculeIds().getSecond()+interf.getTransforms().getSecond().getTransformId();
uniqAsaChains.put(molecId1, interf.getFirstAtomsForAsa(cofactorSizeToUse)); // depends on control dependency: [for], data = [interf]
uniqAsaChains.put(molecId2, interf.getSecondAtomsForAsa(cofactorSizeToUse)); // depends on control dependency: [for], data = [interf]
}
logger.debug("Will calculate uncomplexed ASA for {} orientation-unique chains.", uniqAsaChains.size());
long start = System.currentTimeMillis();
// we only need to calculate ASA for that subset (any translation of those will have same values)
for (String molecId:uniqAsaChains.keySet()) {
logger.debug("Calculating uncomplexed ASA for molecId {}, with {} atoms", molecId, uniqAsaChains.get(molecId).length); // depends on control dependency: [for], data = [molecId]
AsaCalculator asaCalc = new AsaCalculator(uniqAsaChains.get(molecId),
AsaCalculator.DEFAULT_PROBE_SIZE, nSpherePoints, nThreads);
double[] atomAsas = asaCalc.calculateAsas();
chainAsas.put(molecId, atomAsas); // depends on control dependency: [for], data = [molecId]
}
long end = System.currentTimeMillis();
logger.debug("Calculated uncomplexed ASA for {} orientation-unique chains. Time: {} s", uniqAsaChains.size(), ((end-start)/1000.0));
logger.debug ("Will calculate complexed ASA for {} pairwise complexes.", redundancyReducedList.size());
start = System.currentTimeMillis();
// now we calculate the ASAs for each of the complexes
for (StructureInterface interf:redundancyReducedList) {
String molecId1 = interf.getMoleculeIds().getFirst()+interf.getTransforms().getFirst().getTransformId();
String molecId2 = interf.getMoleculeIds().getSecond()+interf.getTransforms().getSecond().getTransformId();
logger.debug("Calculating complexed ASAs for interface {} between molecules {} and {}", interf.getId(), molecId1, molecId2); // depends on control dependency: [for], data = [interf]
interf.setAsas(chainAsas.get(molecId1), chainAsas.get(molecId2), nSpherePoints, nThreads, cofactorSizeToUse); // depends on control dependency: [for], data = [interf]
}
end = System.currentTimeMillis();
logger.debug("Calculated complexes ASA for {} pairwise complexes. Time: {} s", redundancyReducedList.size(), ((end-start)/1000.0));
// now let's populate the interface area value for the NCS-redundant ones from the reference interface (first one in list)
if (clustersNcs!=null) {
if (chainOrigNamesMap==null) {
logger.warn("No chainOrigNamesMap is set. Considering NCS interfaces in same order as reference. This is likely a bug.");
}
for (StructureInterfaceCluster ncsCluster : clustersNcs) {
StructureInterface refInterf = ncsCluster.getMembers().get(0);
String refMolecId1 = refInterf.getMoleculeIds().getFirst();
for (int i=1;i<ncsCluster.getMembers().size();i++) {
StructureInterface member = ncsCluster.getMembers().get(i);
member.setTotalArea(refInterf.getTotalArea());
String molecId1 = member.getMoleculeIds().getFirst();
if (areMolecIdsSameOrder(refMolecId1, molecId1)) {
// we add the reference interface GroupAsas as the GroupAsas for all other members, like that
// ResidueNumbers won't match in their chain ids, but otherwise all info is there without using a lot of memory
member.setFirstGroupAsas(refInterf.getFirstGroupAsas());
member.setSecondGroupAsas(refInterf.getSecondGroupAsas());
} else {
member.setFirstGroupAsas(refInterf.getSecondGroupAsas());
member.setSecondGroupAsas(refInterf.getFirstGroupAsas());
}
}
}
}
// finally we sort based on the ChainInterface.comparable() (based in interfaceArea)
sort();
} } |
public class class_name {
@Nonnull
@ReturnsMutableCopy
public Matrix getD ()
{
final Matrix aNewMatrix = new Matrix (m_nDim, m_nDim);
final double [] [] aNewArray = aNewMatrix.internalGetArray ();
for (int nRow = 0; nRow < m_nDim; nRow++)
{
final double [] aDstRow = aNewArray[nRow];
Arrays.fill (aDstRow, 0.0);
aDstRow[nRow] = m_aEVd[nRow];
final double dEVe = m_aEVe[nRow];
if (dEVe > 0)
aDstRow[nRow + 1] = dEVe;
else
if (dEVe < 0)
aDstRow[nRow - 1] = dEVe;
}
return aNewMatrix;
} } | public class class_name {
@Nonnull
@ReturnsMutableCopy
public Matrix getD ()
{
final Matrix aNewMatrix = new Matrix (m_nDim, m_nDim);
final double [] [] aNewArray = aNewMatrix.internalGetArray ();
for (int nRow = 0; nRow < m_nDim; nRow++)
{
final double [] aDstRow = aNewArray[nRow];
Arrays.fill (aDstRow, 0.0); // depends on control dependency: [for], data = [none]
aDstRow[nRow] = m_aEVd[nRow]; // depends on control dependency: [for], data = [nRow]
final double dEVe = m_aEVe[nRow];
if (dEVe > 0)
aDstRow[nRow + 1] = dEVe;
else
if (dEVe < 0)
aDstRow[nRow - 1] = dEVe;
}
return aNewMatrix;
} } |
public class class_name {
@Override
public void shutdown(ShutdownModeAmp mode)
{
TreeSet<String> serviceNames = new TreeSet<>(_serviceMap.keySet());
// HashSet<ServiceRefAmp> serviceSet = new HashSet<>(_serviceMap.values());
if (mode == ShutdownModeAmp.GRACEFUL) {
save(serviceNames);
}
for (String serviceName : serviceNames) {
try {
ServiceRefAmp serviceRef = _serviceMap.get(serviceName);
serviceRef.shutdown(mode);
} catch (Throwable e) {
log.log(Level.FINE, e.toString(), e);
}
}
} } | public class class_name {
@Override
public void shutdown(ShutdownModeAmp mode)
{
TreeSet<String> serviceNames = new TreeSet<>(_serviceMap.keySet());
// HashSet<ServiceRefAmp> serviceSet = new HashSet<>(_serviceMap.values());
if (mode == ShutdownModeAmp.GRACEFUL) {
save(serviceNames); // depends on control dependency: [if], data = [none]
}
for (String serviceName : serviceNames) {
try {
ServiceRefAmp serviceRef = _serviceMap.get(serviceName);
serviceRef.shutdown(mode); // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
log.log(Level.FINE, e.toString(), e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public static void setClassConf(Configuration conf,
String configKey,
Class<?> clazz) {
String existingClass = conf.get(configKey);
String className = clazz.getName();
if (existingClass != null && !existingClass.equals(className)) {
throw new RuntimeException(
"Already registered a different thriftClass for "
+ configKey
+ ". old: " + existingClass
+ " new: " + className);
} else {
conf.set(configKey, className);
}
} } | public class class_name {
public static void setClassConf(Configuration conf,
String configKey,
Class<?> clazz) {
String existingClass = conf.get(configKey);
String className = clazz.getName();
if (existingClass != null && !existingClass.equals(className)) {
throw new RuntimeException(
"Already registered a different thriftClass for "
+ configKey
+ ". old: " + existingClass
+ " new: " + className);
} else {
conf.set(configKey, className); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void sync() throws IOException {
long start = System.currentTimeMillis();
try {
long toWaitFor;
synchronized (this) {
eventStartSync();
/* Record current blockOffset. This might be changed inside
* flushBuffer() where a partial checksum chunk might be flushed.
* After the flush, reset the bytesCurBlock back to its previous value,
* any partial checksum chunk will be sent now and in next packet.
*/
long saveOffset = bytesCurBlock;
DFSOutputStreamPacket oldCurrentPacket = currentPacket;
// flush checksum buffer as an incomplete chunk
flushBuffer(false, shouldKeepPartialChunkData());
// bytesCurBlock potentially incremented if there was buffered data
eventSyncStartWaitAck();
if (DFSClient.LOG.isDebugEnabled()) {
DFSClient.LOG.debug("DFSClient flush() : bytesCurBlock " + bytesCurBlock +
" lastFlushOffset " + lastFlushOffset);
}
// Flush only if we haven't already flushed till this offset.
if (lastFlushOffset != bytesCurBlock) {
assert bytesCurBlock > lastFlushOffset;
// record the valid offset of this flush
lastFlushOffset = bytesCurBlock;
enqueueCurrentPacket();
} else {
// just discard the current packet since it is already been sent.
if (oldCurrentPacket == null && currentPacket != null) {
// If we didn't previously have a packet queued, and now we do,
// but we don't plan on sending it, then we should not
// skip a sequence number for it!
currentSeqno--;
}
currentPacket = null;
}
if (shouldKeepPartialChunkData()) {
// Restore state of stream. Record the last flush offset
// of the last full chunk that was flushed.
//
bytesCurBlock = saveOffset;
}
toWaitFor = lastQueuedSeqno;
}
waitForAckedSeqno(toWaitFor);
eventSyncPktAcked();
// If any new blocks were allocated since the last flush,
// then persist block locations on namenode.
//
boolean willPersist;
synchronized (this) {
willPersist = persistBlocks;
persistBlocks = false;
}
if (willPersist) {
dfsClient.namenode.fsync(src, dfsClient.clientName);
}
long timeval = System.currentTimeMillis() - start;
dfsClient.metrics.incSyncTime(timeval);
eventEndSync();
} catch (IOException e) {
lastException = new IOException("IOException flush:", e);
closed = true;
closeThreads();
throw e;
}
} } | public class class_name {
public void sync() throws IOException {
long start = System.currentTimeMillis();
try {
long toWaitFor;
synchronized (this) {
eventStartSync();
/* Record current blockOffset. This might be changed inside
* flushBuffer() where a partial checksum chunk might be flushed.
* After the flush, reset the bytesCurBlock back to its previous value,
* any partial checksum chunk will be sent now and in next packet.
*/
long saveOffset = bytesCurBlock;
DFSOutputStreamPacket oldCurrentPacket = currentPacket;
// flush checksum buffer as an incomplete chunk
flushBuffer(false, shouldKeepPartialChunkData());
// bytesCurBlock potentially incremented if there was buffered data
eventSyncStartWaitAck();
if (DFSClient.LOG.isDebugEnabled()) {
DFSClient.LOG.debug("DFSClient flush() : bytesCurBlock " + bytesCurBlock +
" lastFlushOffset " + lastFlushOffset); // depends on control dependency: [if], data = [none]
}
// Flush only if we haven't already flushed till this offset.
if (lastFlushOffset != bytesCurBlock) {
assert bytesCurBlock > lastFlushOffset;
// record the valid offset of this flush
lastFlushOffset = bytesCurBlock; // depends on control dependency: [if], data = [none]
enqueueCurrentPacket(); // depends on control dependency: [if], data = [none]
} else {
// just discard the current packet since it is already been sent.
if (oldCurrentPacket == null && currentPacket != null) {
// If we didn't previously have a packet queued, and now we do,
// but we don't plan on sending it, then we should not
// skip a sequence number for it!
currentSeqno--; // depends on control dependency: [if], data = [none]
}
currentPacket = null; // depends on control dependency: [if], data = [none]
}
if (shouldKeepPartialChunkData()) {
// Restore state of stream. Record the last flush offset
// of the last full chunk that was flushed.
//
bytesCurBlock = saveOffset; // depends on control dependency: [if], data = [none]
}
toWaitFor = lastQueuedSeqno;
}
waitForAckedSeqno(toWaitFor);
eventSyncPktAcked();
// If any new blocks were allocated since the last flush,
// then persist block locations on namenode.
//
boolean willPersist;
synchronized (this) {
willPersist = persistBlocks;
persistBlocks = false;
}
if (willPersist) {
dfsClient.namenode.fsync(src, dfsClient.clientName); // depends on control dependency: [if], data = [none]
}
long timeval = System.currentTimeMillis() - start;
dfsClient.metrics.incSyncTime(timeval);
eventEndSync();
} catch (IOException e) {
lastException = new IOException("IOException flush:", e);
closed = true;
closeThreads();
throw e;
}
} } |
public class class_name {
public void setArguments(Method method) {
Parameter[] parameters = method.getParameters();
Class<?>[] parameterTypes = method.getParameterTypes();
Annotation[][] annotations = method.getParameterAnnotations();
async = isAsync(method.getReturnType());
returnType = method.getReturnType();
int index = 0;
Map<String, MethodParameter> arguments = new HashMap<>();
for (Annotation[] ann : annotations) {
String name = null;
ParameterType type = null;
String defaultValue = null;
boolean raw = false;
Class<? extends ValueReader> valueReader = null;
Class<? extends ContextProvider> contextValueProvider = null;
for (Annotation annotation : ann) {
if (annotation instanceof PathParam) {
// find path param ... and set index ...
name = ((PathParam) annotation).value();
type = ParameterType.path;
}
if (annotation instanceof QueryParam) {
// add param
name = ((QueryParam) annotation).value();
type = ParameterType.query;
}
if (annotation instanceof Raw) {
raw = true;
}
if (annotation instanceof FormParam) {
type = ParameterType.form;
name = ((FormParam) annotation).value();
}
if (annotation instanceof CookieParam) {
type = ParameterType.cookie;
name = ((CookieParam) annotation).value();
}
if (annotation instanceof HeaderParam) {
type = ParameterType.header;
name = ((HeaderParam) annotation).value();
}
if (annotation instanceof MatrixParam) {
type = ParameterType.matrix;
name = ((MatrixParam) annotation).value();
}
if (annotation instanceof DefaultValue) {
defaultValue = ((DefaultValue) annotation).value();
}
if (annotation instanceof RequestReader) {
valueReader = ((RequestReader) annotation).value();
}
if (annotation instanceof ContextReader) {
contextValueProvider = ((ContextReader) annotation).value();
}
if (annotation instanceof Context) {
type = ParameterType.context;
name = parameters[index].getName();
}
}
// if no name provided than parameter is considered unknown (it might be request body, but we don't know)
if (name == null) {
// try to find out what parameter type it is ... POST, PUT have a body ...
// regEx path might not have a name ...
MethodParameter param = findParameter(index);
if (param != null) {
Assert.isNull(param.getDataType(), "Duplicate argument type given: " + parameters[index].getName());
param.argument(parameterTypes[index], index); // set missing argument type and index
} else {
if (valueReader == null) {
valueReader = reader; // take reader from method / class definition
} else {
reader = valueReader; // set body reader from field
}
name = parameters[index].getName();
type = ParameterType.unknown;
}
}
// collect only needed params for this method
if (name != null) {
// set context provider from method annotation if fitting
if (contextValueProvider == null && contextProvider != null) {
Type generic = ClassFactory.getGenericType(contextProvider);
if (ClassFactory.checkIfCompatibleTypes(parameterTypes[index], generic)) {
contextValueProvider = contextProvider;
}
}
MethodParameter parameter = provideArgument(name, type, defaultValue, raw, parameterTypes[index], valueReader, contextValueProvider, index);
arguments.put(name, parameter);
}
index++;
}
setUsedArguments(arguments);
} } | public class class_name {
public void setArguments(Method method) {
Parameter[] parameters = method.getParameters();
Class<?>[] parameterTypes = method.getParameterTypes();
Annotation[][] annotations = method.getParameterAnnotations();
async = isAsync(method.getReturnType());
returnType = method.getReturnType();
int index = 0;
Map<String, MethodParameter> arguments = new HashMap<>();
for (Annotation[] ann : annotations) {
String name = null;
ParameterType type = null;
String defaultValue = null;
boolean raw = false;
Class<? extends ValueReader> valueReader = null;
Class<? extends ContextProvider> contextValueProvider = null;
for (Annotation annotation : ann) {
if (annotation instanceof PathParam) {
// find path param ... and set index ...
name = ((PathParam) annotation).value();
type = ParameterType.path;
}
if (annotation instanceof QueryParam) {
// add param
name = ((QueryParam) annotation).value();
type = ParameterType.query;
}
if (annotation instanceof Raw) {
raw = true;
}
if (annotation instanceof FormParam) {
type = ParameterType.form;
name = ((FormParam) annotation).value();
}
if (annotation instanceof CookieParam) {
type = ParameterType.cookie;
name = ((CookieParam) annotation).value();
}
if (annotation instanceof HeaderParam) {
type = ParameterType.header;
name = ((HeaderParam) annotation).value();
}
if (annotation instanceof MatrixParam) {
type = ParameterType.matrix;
name = ((MatrixParam) annotation).value();
}
if (annotation instanceof DefaultValue) {
defaultValue = ((DefaultValue) annotation).value();
}
if (annotation instanceof RequestReader) {
valueReader = ((RequestReader) annotation).value();
}
if (annotation instanceof ContextReader) {
contextValueProvider = ((ContextReader) annotation).value();
}
if (annotation instanceof Context) {
type = ParameterType.context;
name = parameters[index].getName();
}
}
// if no name provided than parameter is considered unknown (it might be request body, but we don't know)
if (name == null) {
// try to find out what parameter type it is ... POST, PUT have a body ...
// regEx path might not have a name ...
MethodParameter param = findParameter(index);
if (param != null) {
Assert.isNull(param.getDataType(), "Duplicate argument type given: " + parameters[index].getName()); // depends on control dependency: [if], data = [(param]
param.argument(parameterTypes[index], index); // set missing argument type and index // depends on control dependency: [if], data = [(param]
} else {
if (valueReader == null) {
valueReader = reader; // take reader from method / class definition // depends on control dependency: [if], data = [none]
} else {
reader = valueReader; // set body reader from field // depends on control dependency: [if], data = [none]
}
name = parameters[index].getName(); // depends on control dependency: [if], data = [none]
type = ParameterType.unknown; // depends on control dependency: [if], data = [none]
}
}
// collect only needed params for this method
if (name != null) {
// set context provider from method annotation if fitting
if (contextValueProvider == null && contextProvider != null) {
Type generic = ClassFactory.getGenericType(contextProvider);
if (ClassFactory.checkIfCompatibleTypes(parameterTypes[index], generic)) {
contextValueProvider = contextProvider; // depends on control dependency: [if], data = [none]
}
}
MethodParameter parameter = provideArgument(name, type, defaultValue, raw, parameterTypes[index], valueReader, contextValueProvider, index);
arguments.put(name, parameter); // depends on control dependency: [if], data = [(name]
}
index++;
}
setUsedArguments(arguments);
} } |
public class class_name {
public void disconnectSocket() {
synchronized (lock) {
if (socketConnection != null) {
socketConnection.setManageReconnection(false);
socketConnection.disconnect();
}
lock.notifyAll();
}
} } | public class class_name {
public void disconnectSocket() {
synchronized (lock) {
if (socketConnection != null) {
socketConnection.setManageReconnection(false); // depends on control dependency: [if], data = [none]
socketConnection.disconnect(); // depends on control dependency: [if], data = [none]
}
lock.notifyAll();
}
} } |
public class class_name {
public static byte[] decodeChecked(String input) {
byte tmp[] = decode(input);
if (tmp == null || tmp.length < 4) {
return null;
}
byte[] bytes = copyOfRange(tmp, 0, tmp.length - 4);
byte[] checksum = copyOfRange(tmp, tmp.length - 4, tmp.length);
tmp = HashUtils.doubleSha256(bytes);
byte[] hash = copyOfRange(tmp, 0, 4);
if (!Arrays.equals(checksum, hash)) {
return null;
}
return bytes;
} } | public class class_name {
public static byte[] decodeChecked(String input) {
byte tmp[] = decode(input);
if (tmp == null || tmp.length < 4) {
return null; // depends on control dependency: [if], data = [none]
}
byte[] bytes = copyOfRange(tmp, 0, tmp.length - 4);
byte[] checksum = copyOfRange(tmp, tmp.length - 4, tmp.length);
tmp = HashUtils.doubleSha256(bytes);
byte[] hash = copyOfRange(tmp, 0, 4);
if (!Arrays.equals(checksum, hash)) {
return null; // depends on control dependency: [if], data = [none]
}
return bytes;
} } |
public class class_name {
public static void configureLogback( ServletContext servletContext, File logDirFallback, String vHostName, Logger log ) throws FileNotFoundException, MalformedURLException, IOException {
log.debug("Reconfiguring Logback!");
String systemLogDir = System.getProperty(LOG_DIRECTORY_OVERRIDE, System.getProperty(JBOSS_LOG_DIR));
if (systemLogDir != null) {
systemLogDir += "/" + vHostName;
}
File logDir = FileSystemManager.getWritableDirectoryWithFailovers(systemLogDir,servletContext.getInitParameter(LOG_DIR_INIT_PARAM), logDirFallback.getAbsolutePath());
if(logDir != null) {
log.debug("Resetting logback context.");
URL configFile = servletContext.getResource("/WEB-INF/context-logback.xml");
log.debug("Configuring logback with file, {}", configFile);
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.stop();
context.reset();
context.putProperty("logDir", logDir.getCanonicalPath());
configurator.doConfigure(configFile);
} catch (JoranException je) {
// StatusPrinter will handle this
} finally {
context.start();
log.debug("Done resetting logback.");
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
} } | public class class_name {
public static void configureLogback( ServletContext servletContext, File logDirFallback, String vHostName, Logger log ) throws FileNotFoundException, MalformedURLException, IOException {
log.debug("Reconfiguring Logback!");
String systemLogDir = System.getProperty(LOG_DIRECTORY_OVERRIDE, System.getProperty(JBOSS_LOG_DIR));
if (systemLogDir != null) {
systemLogDir += "/" + vHostName;
}
File logDir = FileSystemManager.getWritableDirectoryWithFailovers(systemLogDir,servletContext.getInitParameter(LOG_DIR_INIT_PARAM), logDirFallback.getAbsolutePath());
if(logDir != null) {
log.debug("Resetting logback context.");
URL configFile = servletContext.getResource("/WEB-INF/context-logback.xml");
log.debug("Configuring logback with file, {}", configFile);
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context); // depends on control dependency: [try], data = [none]
context.stop(); // depends on control dependency: [try], data = [none]
context.reset(); // depends on control dependency: [try], data = [none]
context.putProperty("logDir", logDir.getCanonicalPath()); // depends on control dependency: [try], data = [none]
configurator.doConfigure(configFile); // depends on control dependency: [try], data = [none]
} catch (JoranException je) {
// StatusPrinter will handle this
} finally { // depends on control dependency: [catch], data = [none]
context.start();
log.debug("Done resetting logback.");
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
} } |
public class class_name {
public boolean setFieldProperty(String field, String name, Object value, int inst[]) {
if (writer == null)
throw new RuntimeException("This AcroFields instance is read-only.");
try {
Item item = (Item)fields.get(field);
if (item == null)
return false;
InstHit hit = new InstHit(inst);
PdfDictionary merged;
PdfString da;
if (name.equalsIgnoreCase("textfont")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k );
da = merged.getAsString(PdfName.DA);
PdfDictionary dr = merged.getAsDict(PdfName.DR);
if (da != null && dr != null) {
Object dao[] = splitDAelements(da.toUnicodeString());
PdfAppearance cb = new PdfAppearance();
if (dao[DA_FONT] != null) {
BaseFont bf = (BaseFont)value;
PdfName psn = (PdfName)PdfAppearance.stdFieldFontNames.get(bf.getPostscriptFontName());
if (psn == null) {
psn = new PdfName(bf.getPostscriptFontName());
}
PdfDictionary fonts = dr.getAsDict(PdfName.FONT);
if (fonts == null) {
fonts = new PdfDictionary();
dr.put(PdfName.FONT, fonts);
}
PdfIndirectReference fref = (PdfIndirectReference)fonts.get(psn);
PdfDictionary top = reader.getCatalog().getAsDict(PdfName.ACROFORM);
markUsed(top);
dr = top.getAsDict(PdfName.DR);
if (dr == null) {
dr = new PdfDictionary();
top.put(PdfName.DR, dr);
}
markUsed(dr);
PdfDictionary fontsTop = dr.getAsDict(PdfName.FONT);
if (fontsTop == null) {
fontsTop = new PdfDictionary();
dr.put(PdfName.FONT, fontsTop);
}
markUsed(fontsTop);
PdfIndirectReference frefTop = (PdfIndirectReference)fontsTop.get(psn);
if (frefTop != null) {
if (fref == null)
fonts.put(psn, frefTop);
}
else if (fref == null) {
FontDetails fd;
if (bf.getFontType() == BaseFont.FONT_TYPE_DOCUMENT) {
fd = new FontDetails(null, ((DocumentFont)bf).getIndirectReference(), bf);
}
else {
bf.setSubset(false);
fd = writer.addSimple(bf);
localFonts.put(psn.toString().substring(1), bf);
}
fontsTop.put(psn, fd.getIndirectReference());
fonts.put(psn, fd.getIndirectReference());
}
ByteBuffer buf = cb.getInternalBuffer();
buf.append(psn.getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf ");
if (dao[DA_COLOR] != null)
cb.setColorFill((Color)dao[DA_COLOR]);
PdfString s = new PdfString(cb.toString());
item.getMerged(k).put(PdfName.DA, s);
item.getWidget(k).put(PdfName.DA, s);
markUsed(item.getWidget(k));
}
}
}
}
}
else if (name.equalsIgnoreCase("textcolor")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k );
da = merged.getAsString(PdfName.DA);
if (da != null) {
Object dao[] = splitDAelements(da.toUnicodeString());
PdfAppearance cb = new PdfAppearance();
if (dao[DA_FONT] != null) {
ByteBuffer buf = cb.getInternalBuffer();
buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf ");
cb.setColorFill((Color)value);
PdfString s = new PdfString(cb.toString());
item.getMerged(k).put(PdfName.DA, s);
item.getWidget(k).put(PdfName.DA, s);
markUsed(item.getWidget(k));
}
}
}
}
}
else if (name.equalsIgnoreCase("textsize")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k );
da = merged.getAsString(PdfName.DA);
if (da != null) {
Object dao[] = splitDAelements(da.toUnicodeString());
PdfAppearance cb = new PdfAppearance();
if (dao[DA_FONT] != null) {
ByteBuffer buf = cb.getInternalBuffer();
buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)value).floatValue()).append(" Tf ");
if (dao[DA_COLOR] != null)
cb.setColorFill((Color)dao[DA_COLOR]);
PdfString s = new PdfString(cb.toString());
item.getMerged(k).put(PdfName.DA, s);
item.getWidget(k).put(PdfName.DA, s);
markUsed(item.getWidget(k));
}
}
}
}
}
else if (name.equalsIgnoreCase("bgcolor") || name.equalsIgnoreCase("bordercolor")) {
PdfName dname = (name.equalsIgnoreCase("bgcolor") ? PdfName.BG : PdfName.BC);
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k );
PdfDictionary mk = merged.getAsDict(PdfName.MK);
if (mk == null) {
if (value == null)
return true;
mk = new PdfDictionary();
item.getMerged(k).put(PdfName.MK, mk);
item.getWidget(k).put(PdfName.MK, mk);
markUsed(item.getWidget(k));
} else {
markUsed( mk );
}
if (value == null)
mk.remove(dname);
else
mk.put(dname, PdfFormField.getMKColor((Color)value));
}
}
}
else
return false;
return true;
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
} } | public class class_name {
public boolean setFieldProperty(String field, String name, Object value, int inst[]) {
if (writer == null)
throw new RuntimeException("This AcroFields instance is read-only.");
try {
Item item = (Item)fields.get(field);
if (item == null)
return false;
InstHit hit = new InstHit(inst);
PdfDictionary merged;
PdfString da;
if (name.equalsIgnoreCase("textfont")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k ); // depends on control dependency: [if], data = [none]
da = merged.getAsString(PdfName.DA); // depends on control dependency: [if], data = [none]
PdfDictionary dr = merged.getAsDict(PdfName.DR);
if (da != null && dr != null) {
Object dao[] = splitDAelements(da.toUnicodeString());
PdfAppearance cb = new PdfAppearance();
if (dao[DA_FONT] != null) {
BaseFont bf = (BaseFont)value;
PdfName psn = (PdfName)PdfAppearance.stdFieldFontNames.get(bf.getPostscriptFontName());
if (psn == null) {
psn = new PdfName(bf.getPostscriptFontName()); // depends on control dependency: [if], data = [none]
}
PdfDictionary fonts = dr.getAsDict(PdfName.FONT);
if (fonts == null) {
fonts = new PdfDictionary(); // depends on control dependency: [if], data = [none]
dr.put(PdfName.FONT, fonts); // depends on control dependency: [if], data = [none]
}
PdfIndirectReference fref = (PdfIndirectReference)fonts.get(psn);
PdfDictionary top = reader.getCatalog().getAsDict(PdfName.ACROFORM);
markUsed(top); // depends on control dependency: [if], data = [none]
dr = top.getAsDict(PdfName.DR); // depends on control dependency: [if], data = [none]
if (dr == null) {
dr = new PdfDictionary(); // depends on control dependency: [if], data = [none]
top.put(PdfName.DR, dr); // depends on control dependency: [if], data = [none]
}
markUsed(dr); // depends on control dependency: [if], data = [none]
PdfDictionary fontsTop = dr.getAsDict(PdfName.FONT);
if (fontsTop == null) {
fontsTop = new PdfDictionary(); // depends on control dependency: [if], data = [none]
dr.put(PdfName.FONT, fontsTop); // depends on control dependency: [if], data = [none]
}
markUsed(fontsTop); // depends on control dependency: [if], data = [none]
PdfIndirectReference frefTop = (PdfIndirectReference)fontsTop.get(psn);
if (frefTop != null) {
if (fref == null)
fonts.put(psn, frefTop);
}
else if (fref == null) {
FontDetails fd;
if (bf.getFontType() == BaseFont.FONT_TYPE_DOCUMENT) {
fd = new FontDetails(null, ((DocumentFont)bf).getIndirectReference(), bf); // depends on control dependency: [if], data = [none]
}
else {
bf.setSubset(false); // depends on control dependency: [if], data = [none]
fd = writer.addSimple(bf); // depends on control dependency: [if], data = [none]
localFonts.put(psn.toString().substring(1), bf); // depends on control dependency: [if], data = [none]
}
fontsTop.put(psn, fd.getIndirectReference()); // depends on control dependency: [if], data = [none]
fonts.put(psn, fd.getIndirectReference()); // depends on control dependency: [if], data = [none]
}
ByteBuffer buf = cb.getInternalBuffer();
buf.append(psn.getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf "); // depends on control dependency: [if], data = [none]
if (dao[DA_COLOR] != null)
cb.setColorFill((Color)dao[DA_COLOR]);
PdfString s = new PdfString(cb.toString());
item.getMerged(k).put(PdfName.DA, s); // depends on control dependency: [if], data = [none]
item.getWidget(k).put(PdfName.DA, s); // depends on control dependency: [if], data = [none]
markUsed(item.getWidget(k)); // depends on control dependency: [if], data = [none]
}
}
}
}
}
else if (name.equalsIgnoreCase("textcolor")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k ); // depends on control dependency: [if], data = [none]
da = merged.getAsString(PdfName.DA); // depends on control dependency: [if], data = [none]
if (da != null) {
Object dao[] = splitDAelements(da.toUnicodeString());
PdfAppearance cb = new PdfAppearance();
if (dao[DA_FONT] != null) {
ByteBuffer buf = cb.getInternalBuffer();
buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf "); // depends on control dependency: [if], data = [none]
cb.setColorFill((Color)value); // depends on control dependency: [if], data = [none]
PdfString s = new PdfString(cb.toString());
item.getMerged(k).put(PdfName.DA, s); // depends on control dependency: [if], data = [none]
item.getWidget(k).put(PdfName.DA, s); // depends on control dependency: [if], data = [none]
markUsed(item.getWidget(k)); // depends on control dependency: [if], data = [none]
}
}
}
}
}
else if (name.equalsIgnoreCase("textsize")) {
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k ); // depends on control dependency: [if], data = [none]
da = merged.getAsString(PdfName.DA); // depends on control dependency: [if], data = [none]
if (da != null) {
Object dao[] = splitDAelements(da.toUnicodeString());
PdfAppearance cb = new PdfAppearance();
if (dao[DA_FONT] != null) {
ByteBuffer buf = cb.getInternalBuffer();
buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)value).floatValue()).append(" Tf "); // depends on control dependency: [if], data = [none]
if (dao[DA_COLOR] != null)
cb.setColorFill((Color)dao[DA_COLOR]);
PdfString s = new PdfString(cb.toString());
item.getMerged(k).put(PdfName.DA, s); // depends on control dependency: [if], data = [none]
item.getWidget(k).put(PdfName.DA, s); // depends on control dependency: [if], data = [none]
markUsed(item.getWidget(k)); // depends on control dependency: [if], data = [none]
}
}
}
}
}
else if (name.equalsIgnoreCase("bgcolor") || name.equalsIgnoreCase("bordercolor")) {
PdfName dname = (name.equalsIgnoreCase("bgcolor") ? PdfName.BG : PdfName.BC);
for (int k = 0; k < item.size(); ++k) {
if (hit.isHit(k)) {
merged = item.getMerged( k ); // depends on control dependency: [if], data = [none]
PdfDictionary mk = merged.getAsDict(PdfName.MK);
if (mk == null) {
if (value == null)
return true;
mk = new PdfDictionary(); // depends on control dependency: [if], data = [none]
item.getMerged(k).put(PdfName.MK, mk); // depends on control dependency: [if], data = [none]
item.getWidget(k).put(PdfName.MK, mk); // depends on control dependency: [if], data = [none]
markUsed(item.getWidget(k)); // depends on control dependency: [if], data = [none]
} else {
markUsed( mk ); // depends on control dependency: [if], data = [none]
}
if (value == null)
mk.remove(dname);
else
mk.put(dname, PdfFormField.getMKColor((Color)value));
}
}
}
else
return false;
return true; // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
throw new ExceptionConverter(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static FullTypeInfo getFullTemplateType(Type type, int templatePosition) {
if (type instanceof ParameterizedType) {
return getFullTemplateType(((ParameterizedType) type).getActualTypeArguments()[templatePosition]);
} else {
throw new IllegalArgumentException();
}
} } | public class class_name {
public static FullTypeInfo getFullTemplateType(Type type, int templatePosition) {
if (type instanceof ParameterizedType) {
return getFullTemplateType(((ParameterizedType) type).getActualTypeArguments()[templatePosition]); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException();
}
} } |
public class class_name {
public void waitForOperaIdle(long timeout) {
if (captureIdleEvents && capturedIdleEvents > 0) {
logger.finer("Captured " + capturedIdleEvents + " idle event(s)");
// reset
captureIdleEvents = false;
capturedIdleEvents = 0;
return;
}
// If we're waiting for an Idle event, then we don't need to capture them anymore. If we've
// reached this far then capturedIdleEvents is already 0.
captureIdleEvents = false;
waitAndParseResult(timeout, 0 /*0 = no window id!*/, null, ResponseType.OPERA_IDLE);
} } | public class class_name {
public void waitForOperaIdle(long timeout) {
if (captureIdleEvents && capturedIdleEvents > 0) {
logger.finer("Captured " + capturedIdleEvents + " idle event(s)"); // depends on control dependency: [if], data = [none]
// reset
captureIdleEvents = false; // depends on control dependency: [if], data = [none]
capturedIdleEvents = 0; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// If we're waiting for an Idle event, then we don't need to capture them anymore. If we've
// reached this far then capturedIdleEvents is already 0.
captureIdleEvents = false;
waitAndParseResult(timeout, 0 /*0 = no window id!*/, null, ResponseType.OPERA_IDLE);
} } |
public class class_name {
protected void putJobImpl(Executable job)
{
JobItem posted = new JobItem(job);
if (m_currentJob == null)
{
// The queue is empty, set the current job to process and
// wake up the thread waiting in method getJob
m_currentJob = posted;
notifyAll();
}
else
{
JobItem item = m_currentJob;
// The queue is not empty, find the end of the queue ad add the
// posted job at the end
while (item.m_next != null) {item = item.m_next;}
item.m_next = posted;
}
} } | public class class_name {
protected void putJobImpl(Executable job)
{
JobItem posted = new JobItem(job);
if (m_currentJob == null)
{
// The queue is empty, set the current job to process and
// wake up the thread waiting in method getJob
m_currentJob = posted; // depends on control dependency: [if], data = [none]
notifyAll(); // depends on control dependency: [if], data = [none]
}
else
{
JobItem item = m_currentJob;
// The queue is not empty, find the end of the queue ad add the
// posted job at the end
while (item.m_next != null) {item = item.m_next;} // depends on control dependency: [while], data = [none]
item.m_next = posted; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean hasSingleActions() {
Iterator<CmsListColumnDefinition> itCols = m_columns.elementList().iterator();
while (itCols.hasNext()) {
CmsListColumnDefinition col = itCols.next();
if (!col.getDefaultActions().isEmpty() || !col.getDirectActions().isEmpty()) {
return true;
}
}
return false;
} } | public class class_name {
public boolean hasSingleActions() {
Iterator<CmsListColumnDefinition> itCols = m_columns.elementList().iterator();
while (itCols.hasNext()) {
CmsListColumnDefinition col = itCols.next();
if (!col.getDefaultActions().isEmpty() || !col.getDirectActions().isEmpty()) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public List<String> getQualityCSV(String name) {
QuotedQualityCSV values = null;
for (HttpField f : this) {
if (f.getName().equalsIgnoreCase(name)) {
if (values == null)
values = new QuotedQualityCSV();
values.addValue(f.getValue());
}
}
return values == null ? Collections.emptyList() : values.getValues();
} } | public class class_name {
public List<String> getQualityCSV(String name) {
QuotedQualityCSV values = null;
for (HttpField f : this) {
if (f.getName().equalsIgnoreCase(name)) {
if (values == null)
values = new QuotedQualityCSV();
values.addValue(f.getValue()); // depends on control dependency: [if], data = [none]
}
}
return values == null ? Collections.emptyList() : values.getValues();
} } |
public class class_name {
public Module getModule(final DbModule dbModule) {
final Module module = DataModelFactory.createModule(dbModule.getName(), dbModule.getVersion());
module.setPromoted(dbModule.isPromoted());
module.setSubmodule(dbModule.isSubmodule());
module.setCreatedDateTime(dbModule.getCreatedDateTime());
module.setUpdatedDateTime(dbModule.getUpdatedDateTime());
// Artifacts
for (final String gavc : dbModule.getArtifacts()) {
// Artifacts
final DbArtifact dbArtifact = repositoryHandler.getArtifact(gavc);
if (null != dbArtifact) {
final Artifact artifact = getArtifact(dbArtifact);
module.addArtifact(artifact);
}
}
// Dependencies
for (final DbDependency dbDependency : dbModule.getDependencies()) {
// Dependencies
final Dependency dependency = getDependency(dbDependency, module.getName(), module.getVersion());
dependency.setSourceName(module.getName());
dependency.setSourceVersion(module.getVersion());
module.addDependency(dependency);
}
// Submodules
for (final DbModule dbSubmodule : dbModule.getSubmodules()) {
module.addSubmodule(getModule(dbSubmodule));
}
return module;
} } | public class class_name {
public Module getModule(final DbModule dbModule) {
final Module module = DataModelFactory.createModule(dbModule.getName(), dbModule.getVersion());
module.setPromoted(dbModule.isPromoted());
module.setSubmodule(dbModule.isSubmodule());
module.setCreatedDateTime(dbModule.getCreatedDateTime());
module.setUpdatedDateTime(dbModule.getUpdatedDateTime());
// Artifacts
for (final String gavc : dbModule.getArtifacts()) {
// Artifacts
final DbArtifact dbArtifact = repositoryHandler.getArtifact(gavc);
if (null != dbArtifact) {
final Artifact artifact = getArtifact(dbArtifact);
module.addArtifact(artifact); // depends on control dependency: [if], data = [none]
}
}
// Dependencies
for (final DbDependency dbDependency : dbModule.getDependencies()) {
// Dependencies
final Dependency dependency = getDependency(dbDependency, module.getName(), module.getVersion());
dependency.setSourceName(module.getName()); // depends on control dependency: [for], data = [none]
dependency.setSourceVersion(module.getVersion()); // depends on control dependency: [for], data = [none]
module.addDependency(dependency); // depends on control dependency: [for], data = [none]
}
// Submodules
for (final DbModule dbSubmodule : dbModule.getSubmodules()) {
module.addSubmodule(getModule(dbSubmodule)); // depends on control dependency: [for], data = [dbSubmodule]
}
return module;
} } |
public class class_name {
public String getStyle() {
final Object result = getStateHelper().eval(PropertyKeys.style, null);
if (result == null) {
return null;
}
return result.toString();
} } | public class class_name {
public String getStyle() {
final Object result = getStateHelper().eval(PropertyKeys.style, null);
if (result == null) {
return null; // depends on control dependency: [if], data = [none]
}
return result.toString();
} } |
public class class_name {
public TypeElement searchClass(TypeElement klass, String className) {
// search by qualified name first
TypeElement te = configuration.docEnv.getElementUtils().getTypeElement(className);
if (te != null) {
return te;
}
// search inner classes
for (TypeElement ite : utils.getClasses(klass)) {
TypeElement innerClass = searchClass(ite, className);
if (innerClass != null) {
return innerClass;
}
}
// check in this package
te = utils.findClassInPackageElement(utils.containingPackage(klass), className);
if (te != null) {
return te;
}
ClassSymbol tsym = (ClassSymbol)klass;
// make sure that this symbol has been completed
// TODO: do we need this anymore ?
if (tsym.completer != null) {
tsym.complete();
}
// search imports
if (tsym.sourcefile != null) {
//### This information is available only for source classes.
Env<AttrContext> compenv = toolEnv.getEnv(tsym);
if (compenv == null) {
return null;
}
Names names = tsym.name.table.names;
Scope s = compenv.toplevel.namedImportScope;
for (Symbol sym : s.getSymbolsByName(names.fromString(className))) {
if (sym.kind == TYP) {
return (TypeElement)sym;
}
}
s = compenv.toplevel.starImportScope;
for (Symbol sym : s.getSymbolsByName(names.fromString(className))) {
if (sym.kind == TYP) {
return (TypeElement)sym;
}
}
}
return null; // not found
} } | public class class_name {
public TypeElement searchClass(TypeElement klass, String className) {
// search by qualified name first
TypeElement te = configuration.docEnv.getElementUtils().getTypeElement(className);
if (te != null) {
return te; // depends on control dependency: [if], data = [none]
}
// search inner classes
for (TypeElement ite : utils.getClasses(klass)) {
TypeElement innerClass = searchClass(ite, className);
if (innerClass != null) {
return innerClass; // depends on control dependency: [if], data = [none]
}
}
// check in this package
te = utils.findClassInPackageElement(utils.containingPackage(klass), className);
if (te != null) {
return te; // depends on control dependency: [if], data = [none]
}
ClassSymbol tsym = (ClassSymbol)klass;
// make sure that this symbol has been completed
// TODO: do we need this anymore ?
if (tsym.completer != null) {
tsym.complete(); // depends on control dependency: [if], data = [none]
}
// search imports
if (tsym.sourcefile != null) {
//### This information is available only for source classes.
Env<AttrContext> compenv = toolEnv.getEnv(tsym);
if (compenv == null) {
return null; // depends on control dependency: [if], data = [none]
}
Names names = tsym.name.table.names;
Scope s = compenv.toplevel.namedImportScope;
for (Symbol sym : s.getSymbolsByName(names.fromString(className))) {
if (sym.kind == TYP) {
return (TypeElement)sym; // depends on control dependency: [if], data = [none]
}
}
s = compenv.toplevel.starImportScope; // depends on control dependency: [if], data = [none]
for (Symbol sym : s.getSymbolsByName(names.fromString(className))) {
if (sym.kind == TYP) {
return (TypeElement)sym; // depends on control dependency: [if], data = [none]
}
}
}
return null; // not found
} } |
public class class_name {
public static Map<DataSourceWrapper, List<ShardRouteInfo>> groupRouteInfosByDataSource(DDRDataSource ddrDataSource,
boolean readOnly,
List<ShardRouteInfo> routeInfos) {
if (routeInfos == null || routeInfos.isEmpty()) {
return Collections.EMPTY_MAP;
}
Map<DataSourceWrapper, List<ShardRouteInfo>> result = new LinkedHashMap<>();
Map<String, DataSourceWrapper> dataSourceWrapperMap = new HashMap<>();
for (ShardRouteInfo routeInfo : routeInfos) {
DataSourceWrapper dataSourceWrapper = dataSourceWrapperMap.get(routeInfo.getScName());
if (dataSourceWrapper == null) {
DataSourceParam param = new DataSourceParam();
Set<String> schemas = new HashSet<>();
schemas.add(routeInfo.getScName());
param.setScNames(schemas);
param.setReadOnly(readOnly);
dataSourceWrapper = ddrDataSource.getDataSource(param);
for (String scName : dataSourceWrapper.getSchemas()) {
Object preValue = dataSourceWrapperMap.put(scName, dataSourceWrapper);
if (preValue != null) {
throw new IllegalStateException("Duplicate dataSource binding on schema: " + scName);
}
}
}
List<ShardRouteInfo> list = result.get(dataSourceWrapper);
if (list == null) {
list = new ArrayList<>();
result.put(dataSourceWrapper, list);
}
list.add(routeInfo);
}
return result;
} } | public class class_name {
public static Map<DataSourceWrapper, List<ShardRouteInfo>> groupRouteInfosByDataSource(DDRDataSource ddrDataSource,
boolean readOnly,
List<ShardRouteInfo> routeInfos) {
if (routeInfos == null || routeInfos.isEmpty()) {
return Collections.EMPTY_MAP; // depends on control dependency: [if], data = [none]
}
Map<DataSourceWrapper, List<ShardRouteInfo>> result = new LinkedHashMap<>();
Map<String, DataSourceWrapper> dataSourceWrapperMap = new HashMap<>();
for (ShardRouteInfo routeInfo : routeInfos) {
DataSourceWrapper dataSourceWrapper = dataSourceWrapperMap.get(routeInfo.getScName());
if (dataSourceWrapper == null) {
DataSourceParam param = new DataSourceParam();
Set<String> schemas = new HashSet<>();
schemas.add(routeInfo.getScName()); // depends on control dependency: [if], data = [none]
param.setScNames(schemas); // depends on control dependency: [if], data = [none]
param.setReadOnly(readOnly); // depends on control dependency: [if], data = [none]
dataSourceWrapper = ddrDataSource.getDataSource(param); // depends on control dependency: [if], data = [none]
for (String scName : dataSourceWrapper.getSchemas()) {
Object preValue = dataSourceWrapperMap.put(scName, dataSourceWrapper);
if (preValue != null) {
throw new IllegalStateException("Duplicate dataSource binding on schema: " + scName);
}
}
}
List<ShardRouteInfo> list = result.get(dataSourceWrapper);
if (list == null) {
list = new ArrayList<>(); // depends on control dependency: [if], data = [none]
result.put(dataSourceWrapper, list); // depends on control dependency: [if], data = [none]
}
list.add(routeInfo); // depends on control dependency: [for], data = [routeInfo]
}
return result;
} } |
public class class_name {
public void setResourceTags(java.util.Collection<ResourceTag> resourceTags) {
if (resourceTags == null) {
this.resourceTags = null;
return;
}
this.resourceTags = new com.amazonaws.internal.SdkInternalList<ResourceTag>(resourceTags);
} } | public class class_name {
public void setResourceTags(java.util.Collection<ResourceTag> resourceTags) {
if (resourceTags == null) {
this.resourceTags = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.resourceTags = new com.amazonaws.internal.SdkInternalList<ResourceTag>(resourceTags);
} } |
public class class_name {
public static boolean resourceExists(String path, AbstractLaContainerBuilder builder) {
InputStream is;
try {
is = builder.getResourceResolver().getInputStream(path);
} catch (IORuntimeException ex) {
if (ex.getCause() instanceof FileNotFoundException) {
return false;
} else {
throw ex;
}
}
if (is == null) {
return false;
} else {
try {
is.close();
} catch (IOException ignore) {}
return true;
}
} } | public class class_name {
public static boolean resourceExists(String path, AbstractLaContainerBuilder builder) {
InputStream is;
try {
is = builder.getResourceResolver().getInputStream(path); // depends on control dependency: [try], data = [none]
} catch (IORuntimeException ex) {
if (ex.getCause() instanceof FileNotFoundException) {
return false; // depends on control dependency: [if], data = [none]
} else {
throw ex;
}
} // depends on control dependency: [catch], data = [none]
if (is == null) {
return false; // depends on control dependency: [if], data = [none]
} else {
try {
is.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ignore) {} // depends on control dependency: [catch], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void start()
{
_lifecycle.toActive();
_exitCode.set(null);
if (! _isEmbedded) {
// _activeService.compareAndSet(null, this);
_activeService.set(this);
}
if (! CurrentTime.isTest() && ! _isEmbedded) {
_failSafeHaltThread = new FailSafeHaltThread();
_failSafeHaltThread.start();
_failSafeMemoryFreeThread = new FailSafeMemoryFreeThread();
_failSafeMemoryFreeThread.start();
}
if (! _isEmbedded) {
_shutdownThread = new ShutdownThread();
_shutdownThread.setDaemon(true);
_shutdownThread.start();
}
} } | public class class_name {
@Override
public void start()
{
_lifecycle.toActive();
_exitCode.set(null);
if (! _isEmbedded) {
// _activeService.compareAndSet(null, this);
_activeService.set(this); // depends on control dependency: [if], data = [none]
}
if (! CurrentTime.isTest() && ! _isEmbedded) {
_failSafeHaltThread = new FailSafeHaltThread(); // depends on control dependency: [if], data = [none]
_failSafeHaltThread.start(); // depends on control dependency: [if], data = [none]
_failSafeMemoryFreeThread = new FailSafeMemoryFreeThread(); // depends on control dependency: [if], data = [none]
_failSafeMemoryFreeThread.start(); // depends on control dependency: [if], data = [none]
}
if (! _isEmbedded) {
_shutdownThread = new ShutdownThread(); // depends on control dependency: [if], data = [none]
_shutdownThread.setDaemon(true); // depends on control dependency: [if], data = [none]
_shutdownThread.start(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void body(Data data, Body body) throws TemplateException {
boolean parseLiteral = true;
// Comment
comment(data.srcCode, false);
// Tag
// is Tag Beginning
if (data.srcCode.isCurrent('<')) {
// return if end tag and inside tag
if (data.srcCode.isNext('/')) {
// lucee.print.ln("early return");
return;
}
parseLiteral = !tag(data, body);
}
// no Tag
if (parseLiteral) {
literal(data, body);
}
// not at the end
if (!done && data.srcCode.isValidIndex()) body(data, body);
} } | public class class_name {
public void body(Data data, Body body) throws TemplateException {
boolean parseLiteral = true;
// Comment
comment(data.srcCode, false);
// Tag
// is Tag Beginning
if (data.srcCode.isCurrent('<')) {
// return if end tag and inside tag
if (data.srcCode.isNext('/')) {
// lucee.print.ln("early return");
return; // depends on control dependency: [if], data = [none]
}
parseLiteral = !tag(data, body);
}
// no Tag
if (parseLiteral) {
literal(data, body);
}
// not at the end
if (!done && data.srcCode.isValidIndex()) body(data, body);
} } |
public class class_name {
public void setProperties(Object bean, Map map) {
checkInitalised();
for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = entry.getKey().toString();
Object value = entry.getValue();
setProperty(bean, key, value);
}
} } | public class class_name {
public void setProperties(Object bean, Map map) {
checkInitalised();
for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = entry.getKey().toString();
Object value = entry.getValue();
setProperty(bean, key, value); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out)
{
//
// Get the bean and associated beanInfo for the source instance
//
ControlBean control = (ControlBean)oldInstance;
BeanInfo beanInfo;
try
{
beanInfo = Introspector.getBeanInfo(control.getClass());
}
catch (IntrospectionException ie)
{
throw new ControlException("Unable to locate BeanInfo", ie);
}
//
// Cast the encoding stream to an XMLEncoder (only encoding supported) and then set
// the stream owner to the bean being persisted
//
XMLEncoder xmlOut = (XMLEncoder)out;
Object owner = xmlOut.getOwner();
xmlOut.setOwner(control);
try
{
//
// The default implementation of property persistence will use BeanInfo to
// incrementally compare oldInstance property values to newInstance property values.
// Because the bean instance PropertyMap holds only the values that have been
// modified, this process can be optimized by directly writing out only the properties
// found in the map.
//
BeanPropertyMap beanMap = control.getPropertyMap();
PropertyDescriptor [] propDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyKey pk : beanMap.getPropertyKeys())
{
//
// Locate the PropertyDescriptor for the modified property, and use it to write
// the property value to the encoder stream
//
String propName = pk.getPropertyName();
boolean found = false;
for (int i = 0; i < propDescriptors.length; i++)
{
if (propName.equals(propDescriptors[i].getName()))
{
found = true;
// Only write the property if it is not flagged as transient
Object transientVal = propDescriptors[i].getValue("transient");
if (transientVal == null || transientVal.equals(Boolean.FALSE))
{
xmlOut.writeStatement(
new Statement(oldInstance,
propDescriptors[i].getWriteMethod().getName(),
new Object [] {beanMap.getProperty(pk)}));
}
}
}
if (found == false)
{
throw new ControlException("Unknown property in bean PropertyMap: " + pk);
}
}
//
// Get the bean context associated with the bean, and persist any nested controls
//
ControlBeanContext cbc = control.getControlBeanContext();
if (cbc.size() != 0)
{
xmlOut.setPersistenceDelegate(ControlBeanContext.class,
new ContextPersistenceDelegate());
Iterator nestedIter = cbc.iterator();
while (nestedIter.hasNext())
{
Object bean = nestedIter.next();
if (bean instanceof ControlBean)
{
xmlOut.writeStatement(
new Statement(cbc, "add", new Object [] { bean } ));
}
}
}
//
// Restore any listeners associated with the control
//
EventSetDescriptor [] eventSetDescriptors = beanInfo.getEventSetDescriptors();
for (int i = 0; i < eventSetDescriptors.length; i++)
{
EventSetDescriptor esd = eventSetDescriptors[i];
Method listenersMethod = esd.getGetListenerMethod();
String addListenerName = esd.getAddListenerMethod().getName();
if (listenersMethod != null)
{
//
// Get the list of listeners, and then add statements to incrementally
// add them in the same order
//
try
{
Object [] lstnrs = (Object [])listenersMethod.invoke(control,
new Object []{});
for (int j = 0; j < lstnrs.length; j++)
{
//
// If this is a generated EventAdaptor class, then set the delegate
// explicitly
//
if (lstnrs[j] instanceof EventAdaptor)
xmlOut.setPersistenceDelegate(lstnrs[j].getClass(),
new AdaptorPersistenceDelegate());
xmlOut.writeStatement(
new Statement(control, addListenerName, new Object [] {lstnrs[j]}));
}
}
catch (Exception iae)
{
throw new ControlException("Unable to initialize listeners", iae);
}
}
}
//
// See if the control holds an implementation instance, if so, we need to include
// it (and any nested controls or state) in the encoding stream
//
Object impl = control.getImplementation();
if (impl != null)
{
//
// Set the persistence delegate for the impl class to the Impl delegate,
// set the current stream owner to the bean, and then write the implementation
//
Class implClass = impl.getClass();
if (xmlOut.getPersistenceDelegate(implClass) instanceof DefaultPersistenceDelegate)
xmlOut.setPersistenceDelegate(implClass, new ImplPersistenceDelegate());
//
// HACK: This bit of hackery pushes the impl into the persistence stream
// w/out actually requiring it be used as an argument elsewhere, since there
// is no public API on the bean that takes an impl instance as an argument.
//
xmlOut.writeStatement(
new Statement(impl, "toString", null));
}
}
finally
{
// Restore the previous encoding stream owner
xmlOut.setOwner(owner);
}
} } | public class class_name {
protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out)
{
//
// Get the bean and associated beanInfo for the source instance
//
ControlBean control = (ControlBean)oldInstance;
BeanInfo beanInfo;
try
{
beanInfo = Introspector.getBeanInfo(control.getClass()); // depends on control dependency: [try], data = [none]
}
catch (IntrospectionException ie)
{
throw new ControlException("Unable to locate BeanInfo", ie);
} // depends on control dependency: [catch], data = [none]
//
// Cast the encoding stream to an XMLEncoder (only encoding supported) and then set
// the stream owner to the bean being persisted
//
XMLEncoder xmlOut = (XMLEncoder)out;
Object owner = xmlOut.getOwner();
xmlOut.setOwner(control);
try
{
//
// The default implementation of property persistence will use BeanInfo to
// incrementally compare oldInstance property values to newInstance property values.
// Because the bean instance PropertyMap holds only the values that have been
// modified, this process can be optimized by directly writing out only the properties
// found in the map.
//
BeanPropertyMap beanMap = control.getPropertyMap();
PropertyDescriptor [] propDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyKey pk : beanMap.getPropertyKeys())
{
//
// Locate the PropertyDescriptor for the modified property, and use it to write
// the property value to the encoder stream
//
String propName = pk.getPropertyName();
boolean found = false;
for (int i = 0; i < propDescriptors.length; i++)
{
if (propName.equals(propDescriptors[i].getName()))
{
found = true; // depends on control dependency: [if], data = [none]
// Only write the property if it is not flagged as transient
Object transientVal = propDescriptors[i].getValue("transient");
if (transientVal == null || transientVal.equals(Boolean.FALSE))
{
xmlOut.writeStatement(
new Statement(oldInstance,
propDescriptors[i].getWriteMethod().getName(),
new Object [] {beanMap.getProperty(pk)})); // depends on control dependency: [if], data = [none]
}
}
}
if (found == false)
{
throw new ControlException("Unknown property in bean PropertyMap: " + pk);
}
}
//
// Get the bean context associated with the bean, and persist any nested controls
//
ControlBeanContext cbc = control.getControlBeanContext();
if (cbc.size() != 0)
{
xmlOut.setPersistenceDelegate(ControlBeanContext.class,
new ContextPersistenceDelegate()); // depends on control dependency: [if], data = [none]
Iterator nestedIter = cbc.iterator();
while (nestedIter.hasNext())
{
Object bean = nestedIter.next();
if (bean instanceof ControlBean)
{
xmlOut.writeStatement(
new Statement(cbc, "add", new Object [] { bean } )); // depends on control dependency: [if], data = [none]
}
}
}
//
// Restore any listeners associated with the control
//
EventSetDescriptor [] eventSetDescriptors = beanInfo.getEventSetDescriptors();
for (int i = 0; i < eventSetDescriptors.length; i++)
{
EventSetDescriptor esd = eventSetDescriptors[i];
Method listenersMethod = esd.getGetListenerMethod();
String addListenerName = esd.getAddListenerMethod().getName();
if (listenersMethod != null)
{
//
// Get the list of listeners, and then add statements to incrementally
// add them in the same order
//
try
{
Object [] lstnrs = (Object [])listenersMethod.invoke(control,
new Object []{});
for (int j = 0; j < lstnrs.length; j++)
{
//
// If this is a generated EventAdaptor class, then set the delegate
// explicitly
//
if (lstnrs[j] instanceof EventAdaptor)
xmlOut.setPersistenceDelegate(lstnrs[j].getClass(),
new AdaptorPersistenceDelegate());
xmlOut.writeStatement(
new Statement(control, addListenerName, new Object [] {lstnrs[j]})); // depends on control dependency: [for], data = [none]
}
}
catch (Exception iae)
{
throw new ControlException("Unable to initialize listeners", iae);
} // depends on control dependency: [catch], data = [none]
}
}
//
// See if the control holds an implementation instance, if so, we need to include
// it (and any nested controls or state) in the encoding stream
//
Object impl = control.getImplementation();
if (impl != null)
{
//
// Set the persistence delegate for the impl class to the Impl delegate,
// set the current stream owner to the bean, and then write the implementation
//
Class implClass = impl.getClass();
if (xmlOut.getPersistenceDelegate(implClass) instanceof DefaultPersistenceDelegate)
xmlOut.setPersistenceDelegate(implClass, new ImplPersistenceDelegate());
//
// HACK: This bit of hackery pushes the impl into the persistence stream
// w/out actually requiring it be used as an argument elsewhere, since there
// is no public API on the bean that takes an impl instance as an argument.
//
xmlOut.writeStatement(
new Statement(impl, "toString", null)); // depends on control dependency: [if], data = [none]
}
}
finally
{
// Restore the previous encoding stream owner
xmlOut.setOwner(owner);
}
} } |
public class class_name {
public static <T> boolean isContainString(List<T> stringObjects,
Object stringObject) {
if (ListUtil.isEmpty(stringObjects) || stringObject == null) {
return false;
}
for (T tempStringObject : stringObjects) {
if (stringObject.toString().equals(tempStringObject.toString())) {
return true;
}
}
return false;
} } | public class class_name {
public static <T> boolean isContainString(List<T> stringObjects,
Object stringObject) {
if (ListUtil.isEmpty(stringObjects) || stringObject == null) {
return false; // depends on control dependency: [if], data = [none]
}
for (T tempStringObject : stringObjects) {
if (stringObject.toString().equals(tempStringObject.toString())) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
protected BooleanQuery.Builder appendResourceTypeFilter(
CmsObject cms,
BooleanQuery.Builder filter,
List<String> resourceTypes) {
if ((resourceTypes != null) && (resourceTypes.size() > 0)) {
// add query resource types (if required)
filter.add(
new BooleanClause(
getMultiTermQueryFilter(CmsSearchField.FIELD_TYPE, resourceTypes),
BooleanClause.Occur.MUST));
}
return filter;
} } | public class class_name {
protected BooleanQuery.Builder appendResourceTypeFilter(
CmsObject cms,
BooleanQuery.Builder filter,
List<String> resourceTypes) {
if ((resourceTypes != null) && (resourceTypes.size() > 0)) {
// add query resource types (if required)
filter.add(
new BooleanClause(
getMultiTermQueryFilter(CmsSearchField.FIELD_TYPE, resourceTypes),
BooleanClause.Occur.MUST)); // depends on control dependency: [if], data = [none]
}
return filter;
} } |
public class class_name {
@Override
public String[] getValue() {
Object data = getData();
if (data == null) {
return null;
}
String[] array = null;
// Array data
if (data instanceof String[]) {
array = (String[]) data;
} else if (data instanceof List) { // List data
List<?> list = (List<?>) data;
array = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
Object item = list.get(i);
array[i] = item == null ? "" : item.toString();
}
} else { // Object
array = new String[]{data.toString()};
}
return removeEmptyStrings(array);
} } | public class class_name {
@Override
public String[] getValue() {
Object data = getData();
if (data == null) {
return null; // depends on control dependency: [if], data = [none]
}
String[] array = null;
// Array data
if (data instanceof String[]) {
array = (String[]) data; // depends on control dependency: [if], data = [none]
} else if (data instanceof List) { // List data
List<?> list = (List<?>) data;
array = new String[list.size()]; // depends on control dependency: [if], data = [none]
for (int i = 0; i < list.size(); i++) {
Object item = list.get(i);
array[i] = item == null ? "" : item.toString(); // depends on control dependency: [for], data = [i]
}
} else { // Object
array = new String[]{data.toString()}; // depends on control dependency: [if], data = [none]
}
return removeEmptyStrings(array);
} } |
public class class_name {
private static String getCellFontColor(final Font font) {
short[] rgbfix = { TieConstants.RGB_MAX, TieConstants.RGB_MAX,
TieConstants.RGB_MAX };
if (font instanceof XSSFFont) {
XSSFColor color = ((XSSFFont) font).getXSSFColor();
if (color != null) {
rgbfix = ColorUtility.getTripletFromXSSFColor(color);
}
}
if (rgbfix[0] != TieConstants.RGB_MAX) {
return "color:rgb(" + FacesUtility.strJoin(rgbfix, ",") + ");";
}
return "";
} } | public class class_name {
private static String getCellFontColor(final Font font) {
short[] rgbfix = { TieConstants.RGB_MAX, TieConstants.RGB_MAX,
TieConstants.RGB_MAX };
if (font instanceof XSSFFont) {
XSSFColor color = ((XSSFFont) font).getXSSFColor();
if (color != null) {
rgbfix = ColorUtility.getTripletFromXSSFColor(color);
// depends on control dependency: [if], data = [(color]
}
}
if (rgbfix[0] != TieConstants.RGB_MAX) {
return "color:rgb(" + FacesUtility.strJoin(rgbfix, ",") + ");";
// depends on control dependency: [if], data = [none]
}
return "";
} } |
public class class_name {
public static boolean closeServerSocket(ServerSocket serverSocket)
{
boolean closed = true;
try
{
if (serverSocket != null && !serverSocket.isClosed())
{
serverSocket.close();
serverSocket = null;
}
}
catch (final IOException e)
{
LOGGER.error("IOException occured by trying to close the server socket.", e);
closed = false;
}
finally
{
try
{
if (serverSocket != null && !serverSocket.isClosed())
{
serverSocket.close();
}
}
catch (final IOException e)
{
LOGGER.error("IOException occured by trying to close the server socket.", e);
closed = false;
}
}
return closed;
} } | public class class_name {
public static boolean closeServerSocket(ServerSocket serverSocket)
{
boolean closed = true;
try
{
if (serverSocket != null && !serverSocket.isClosed())
{
serverSocket.close();
// depends on control dependency: [if], data = [none]
serverSocket = null;
// depends on control dependency: [if], data = [none]
}
}
catch (final IOException e)
{
LOGGER.error("IOException occured by trying to close the server socket.", e);
closed = false;
}
// depends on control dependency: [catch], data = [none]
finally
{
try
{
if (serverSocket != null && !serverSocket.isClosed())
{
serverSocket.close();
// depends on control dependency: [if], data = [none]
}
}
catch (final IOException e)
{
LOGGER.error("IOException occured by trying to close the server socket.", e);
closed = false;
}
// depends on control dependency: [catch], data = [none]
}
return closed;
} } |
public class class_name {
protected String getCore() {
try {
return m_configObject.getString(JSON_KEY_CORE);
} catch (JSONException e) {
if (null == m_baseConfig) {
if (LOG.isInfoEnabled()) {
LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_CORE_SPECIFIED_0), e);
}
return null;
} else {
return m_baseConfig.getGeneralConfig().getSolrCore();
}
}
} } | public class class_name {
protected String getCore() {
try {
return m_configObject.getString(JSON_KEY_CORE); // depends on control dependency: [try], data = [none]
} catch (JSONException e) {
if (null == m_baseConfig) {
if (LOG.isInfoEnabled()) {
LOG.info(Messages.get().getBundle().key(Messages.LOG_NO_CORE_SPECIFIED_0), e); // depends on control dependency: [if], data = [none]
}
return null; // depends on control dependency: [if], data = [none]
} else {
return m_baseConfig.getGeneralConfig().getSolrCore(); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.