code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public QueryRule createShouldQueryRule(String multiOntologyTermIri) {
QueryRule shouldQueryRule = new QueryRule(new ArrayList<>());
shouldQueryRule.setOperator(Operator.SHOULD);
for (String ontologyTermIri : multiOntologyTermIri.split(COMMA_CHAR)) {
OntologyTerm ontologyTerm = ontologyService.getOntologyTerm(ontologyTermIri);
List<String> queryTerms = parseOntologyTermQueries(ontologyTerm);
Double termFrequency = getBestInverseDocumentFrequency(queryTerms);
shouldQueryRule
.getNestedRules()
.add(createBoostedDisMaxQueryRuleForTerms(queryTerms, termFrequency));
}
return shouldQueryRule;
} } | public class class_name {
public QueryRule createShouldQueryRule(String multiOntologyTermIri) {
QueryRule shouldQueryRule = new QueryRule(new ArrayList<>());
shouldQueryRule.setOperator(Operator.SHOULD);
for (String ontologyTermIri : multiOntologyTermIri.split(COMMA_CHAR)) {
OntologyTerm ontologyTerm = ontologyService.getOntologyTerm(ontologyTermIri);
List<String> queryTerms = parseOntologyTermQueries(ontologyTerm);
Double termFrequency = getBestInverseDocumentFrequency(queryTerms);
shouldQueryRule
.getNestedRules()
.add(createBoostedDisMaxQueryRuleForTerms(queryTerms, termFrequency)); // depends on control dependency: [for], data = [none]
}
return shouldQueryRule;
} } |
public class class_name {
public void marshall(CreateEvaluationRequest createEvaluationRequest, ProtocolMarshaller protocolMarshaller) {
if (createEvaluationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createEvaluationRequest.getEvaluationId(), EVALUATIONID_BINDING);
protocolMarshaller.marshall(createEvaluationRequest.getEvaluationName(), EVALUATIONNAME_BINDING);
protocolMarshaller.marshall(createEvaluationRequest.getMLModelId(), MLMODELID_BINDING);
protocolMarshaller.marshall(createEvaluationRequest.getEvaluationDataSourceId(), EVALUATIONDATASOURCEID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateEvaluationRequest createEvaluationRequest, ProtocolMarshaller protocolMarshaller) {
if (createEvaluationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createEvaluationRequest.getEvaluationId(), EVALUATIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createEvaluationRequest.getEvaluationName(), EVALUATIONNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createEvaluationRequest.getMLModelId(), MLMODELID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createEvaluationRequest.getEvaluationDataSourceId(), EVALUATIONDATASOURCEID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void updateEntityAndLang(final File inputFile) {
//directory case
if (inputFile.isDirectory()) {
final File[] files = inputFile.listFiles();
if (files != null) {
for (final File file : files) {
updateEntityAndLang(file);
}
}
}
//html file case
else if (FileUtils.isHTMLFile(inputFile.getName())) {
//do converting work
convertEntityAndCharset(inputFile, ATTRIBUTE_FORMAT_VALUE_HTML);
}
//hhp/hhc/hhk file case
else if (FileUtils.isHHPFile(inputFile.getName()) ||
FileUtils.isHHCFile(inputFile.getName()) ||
FileUtils.isHHKFile(inputFile.getName())) {
//do converting work
convertEntityAndCharset(inputFile, ATTRIBUTE_FORMAT_VALUE_WINDOWS);
//update language setting of hhp file
final String fileName = inputFile.getAbsolutePath();
final File outputFile = new File(fileName + FILE_EXTENSION_TEMP);
//get new charset
final String charset = charsetMap.get(ATTRIBUTE_FORMAT_VALUE_WINDOWS);
BufferedReader reader = null;
BufferedWriter writer = null;
try {
//prepare for the input and output
final FileInputStream inputStream = new FileInputStream(inputFile);
final InputStreamReader streamReader = new InputStreamReader(inputStream, charset);
//wrapped into reader
reader = new BufferedReader(streamReader);
final FileOutputStream outputStream = new FileOutputStream(outputFile);
//convert charset
final OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream, charset);
//wrapped into writer
writer = new BufferedWriter(streamWriter);
String value = reader.readLine();
while(value != null) {
if (value.contains(tag1)) {
value = replaceXmlTag(value, tag1);
} else if (value.contains(tag2)) {
value = replaceXmlTag(value, tag2);
} else if (value.contains(tag3)) {
value = replaceXmlTag(value, tag3);
}
//meta tag contains charset found
if (value.contains("Language=")) {
String newValue = langMap.get(langcode);
if (newValue == null) {
newValue = langMap.get(langcode.split("-")[0]);
}
if (newValue != null) {
writer.write("Language=" + newValue);
writer.write(LINE_SEPARATOR);
} else {
throw new IllegalArgumentException("Unsupported language code '" + langcode + "', unable to map to a Locale ID.");
}
} else {
//other values
writer.write(value);
writer.write(LINE_SEPARATOR);
}
value = reader.readLine();
}
} catch (final FileNotFoundException e) {
logger.error(e.getMessage(), e) ;
} catch (final UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (final IOException e) {
logger.error(e.getMessage(), e) ;
} finally {
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
logger.error("Failed to close input stream: " + e.getMessage());
}
}
if (writer != null) {
try {
writer.close();
} catch (final IOException e) {
logger.error("Failed to close output stream: " + e.getMessage());
}
}
}
try {
deleteQuietly(inputFile);
moveFile(outputFile, inputFile);
} catch (final Exception e) {
logger.error("Failed to replace " + inputFile + ": " + e.getMessage());
}
}
} } | public class class_name {
private void updateEntityAndLang(final File inputFile) {
//directory case
if (inputFile.isDirectory()) {
final File[] files = inputFile.listFiles();
if (files != null) {
for (final File file : files) {
updateEntityAndLang(file); // depends on control dependency: [for], data = [file]
}
}
}
//html file case
else if (FileUtils.isHTMLFile(inputFile.getName())) {
//do converting work
convertEntityAndCharset(inputFile, ATTRIBUTE_FORMAT_VALUE_HTML);
}
//hhp/hhc/hhk file case
else if (FileUtils.isHHPFile(inputFile.getName()) ||
FileUtils.isHHCFile(inputFile.getName()) ||
FileUtils.isHHKFile(inputFile.getName())) {
//do converting work
convertEntityAndCharset(inputFile, ATTRIBUTE_FORMAT_VALUE_WINDOWS);
//update language setting of hhp file
final String fileName = inputFile.getAbsolutePath();
final File outputFile = new File(fileName + FILE_EXTENSION_TEMP);
//get new charset
final String charset = charsetMap.get(ATTRIBUTE_FORMAT_VALUE_WINDOWS);
BufferedReader reader = null;
BufferedWriter writer = null;
try {
//prepare for the input and output
final FileInputStream inputStream = new FileInputStream(inputFile);
final InputStreamReader streamReader = new InputStreamReader(inputStream, charset);
//wrapped into reader
reader = new BufferedReader(streamReader);
final FileOutputStream outputStream = new FileOutputStream(outputFile);
//convert charset
final OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream, charset);
//wrapped into writer
writer = new BufferedWriter(streamWriter);
String value = reader.readLine();
while(value != null) {
if (value.contains(tag1)) {
value = replaceXmlTag(value, tag1); // depends on control dependency: [if], data = [none]
} else if (value.contains(tag2)) {
value = replaceXmlTag(value, tag2); // depends on control dependency: [if], data = [none]
} else if (value.contains(tag3)) {
value = replaceXmlTag(value, tag3); // depends on control dependency: [if], data = [none]
}
//meta tag contains charset found
if (value.contains("Language=")) {
String newValue = langMap.get(langcode);
if (newValue == null) {
newValue = langMap.get(langcode.split("-")[0]); // depends on control dependency: [if], data = [none]
}
if (newValue != null) {
writer.write("Language=" + newValue); // depends on control dependency: [if], data = [none]
writer.write(LINE_SEPARATOR); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Unsupported language code '" + langcode + "', unable to map to a Locale ID.");
}
} else {
//other values
writer.write(value); // depends on control dependency: [if], data = [none]
writer.write(LINE_SEPARATOR); // depends on control dependency: [if], data = [none]
}
value = reader.readLine(); // depends on control dependency: [while], data = [none]
}
} catch (final FileNotFoundException e) {
logger.error(e.getMessage(), e) ;
} catch (final UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (final IOException e) {
logger.error(e.getMessage(), e) ;
} finally {
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
logger.error("Failed to close input stream: " + e.getMessage());
}
}
if (writer != null) {
try {
writer.close();
} catch (final IOException e) {
logger.error("Failed to close output stream: " + e.getMessage());
}
}
}
try {
deleteQuietly(inputFile);
moveFile(outputFile, inputFile);
} catch (final Exception e) {
logger.error("Failed to replace " + inputFile + ": " + e.getMessage());
}
}
} } |
public class class_name {
public ProjectDetails withResources(Resource... resources) {
if (this.resources == null) {
setResources(new java.util.ArrayList<Resource>(resources.length));
}
for (Resource ele : resources) {
this.resources.add(ele);
}
return this;
} } | public class class_name {
public ProjectDetails withResources(Resource... resources) {
if (this.resources == null) {
setResources(new java.util.ArrayList<Resource>(resources.length)); // depends on control dependency: [if], data = [none]
}
for (Resource ele : resources) {
this.resources.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@XmlTransient
public String getElasticSearchFieldType()
{
Type fieldType = this.getTypeAsEnum();
if(fieldType == null)
{
return null;
}
//Get the fieldType by Fluid field fieldType...
switch (fieldType)
{
case ParagraphText:
return ElasticSearchType.TEXT;
case Text:
String metaData = this.getTypeMetaData();
if(metaData == null || metaData.isEmpty())
{
return ElasticSearchType.TEXT;
}
if(LATITUDE_AND_LONGITUDE.equals(metaData))
{
return ElasticSearchType.GEO_POINT;
}
return ElasticSearchType.TEXT;
case TrueFalse:
return ElasticSearchType.BOOLEAN;
case DateTime:
return ElasticSearchType.DATE;
case Decimal:
return ElasticSearchType.DOUBLE;
case MultipleChoice:
return ElasticSearchType.KEYWORD;
}
return null;
} } | public class class_name {
@XmlTransient
public String getElasticSearchFieldType()
{
Type fieldType = this.getTypeAsEnum();
if(fieldType == null)
{
return null; // depends on control dependency: [if], data = [none]
}
//Get the fieldType by Fluid field fieldType...
switch (fieldType)
{
case ParagraphText:
return ElasticSearchType.TEXT;
case Text:
String metaData = this.getTypeMetaData();
if(metaData == null || metaData.isEmpty())
{
return ElasticSearchType.TEXT; // depends on control dependency: [if], data = [none]
}
if(LATITUDE_AND_LONGITUDE.equals(metaData))
{
return ElasticSearchType.GEO_POINT; // depends on control dependency: [if], data = [none]
}
return ElasticSearchType.TEXT;
case TrueFalse:
return ElasticSearchType.BOOLEAN;
case DateTime:
return ElasticSearchType.DATE;
case Decimal:
return ElasticSearchType.DOUBLE;
case MultipleChoice:
return ElasticSearchType.KEYWORD;
}
return null;
} } |
public class class_name {
private List<Type> closureMin(List<Type> cl) {
ListBuffer<Type> classes = new ListBuffer<>();
ListBuffer<Type> interfaces = new ListBuffer<>();
Set<Type> toSkip = new HashSet<>();
while (!cl.isEmpty()) {
Type current = cl.head;
boolean keep = !toSkip.contains(current);
if (keep && current.hasTag(TYPEVAR)) {
// skip lower-bounded variables with a subtype in cl.tail
for (Type t : cl.tail) {
if (isSubtypeNoCapture(t, current)) {
keep = false;
break;
}
}
}
if (keep) {
if (current.isInterface())
interfaces.append(current);
else
classes.append(current);
for (Type t : cl.tail) {
// skip supertypes of 'current' in cl.tail
if (isSubtypeNoCapture(current, t))
toSkip.add(t);
}
}
cl = cl.tail;
}
return classes.appendList(interfaces).toList();
} } | public class class_name {
private List<Type> closureMin(List<Type> cl) {
ListBuffer<Type> classes = new ListBuffer<>();
ListBuffer<Type> interfaces = new ListBuffer<>();
Set<Type> toSkip = new HashSet<>();
while (!cl.isEmpty()) {
Type current = cl.head;
boolean keep = !toSkip.contains(current);
if (keep && current.hasTag(TYPEVAR)) {
// skip lower-bounded variables with a subtype in cl.tail
for (Type t : cl.tail) {
if (isSubtypeNoCapture(t, current)) {
keep = false; // depends on control dependency: [if], data = [none]
break;
}
}
}
if (keep) {
if (current.isInterface())
interfaces.append(current);
else
classes.append(current);
for (Type t : cl.tail) {
// skip supertypes of 'current' in cl.tail
if (isSubtypeNoCapture(current, t))
toSkip.add(t);
}
}
cl = cl.tail; // depends on control dependency: [while], data = [none]
}
return classes.appendList(interfaces).toList();
} } |
public class class_name {
public static double computeAbsoluteDistance(Map<String, Double> h1, Map<String, Double> h2) {
double distance = 0;
final Set<String> keySet = new HashSet();
keySet.addAll(h1.keySet());
keySet.addAll(h2.keySet());
for (String key : keySet) {
double v1 = 0.0;
double v2 = 0.0;
if (h1.get(key) != null) {
v1 = h1.get(key);
}
if (h2.get(key) != null) {
v2 = h2.get(key);
}
distance += Math.abs(v1 - v2);
}
return distance;
} } | public class class_name {
public static double computeAbsoluteDistance(Map<String, Double> h1, Map<String, Double> h2) {
double distance = 0;
final Set<String> keySet = new HashSet();
keySet.addAll(h1.keySet());
keySet.addAll(h2.keySet());
for (String key : keySet) {
double v1 = 0.0;
double v2 = 0.0;
if (h1.get(key) != null) {
v1 = h1.get(key); // depends on control dependency: [if], data = [none]
}
if (h2.get(key) != null) {
v2 = h2.get(key); // depends on control dependency: [if], data = [none]
}
distance += Math.abs(v1 - v2); // depends on control dependency: [for], data = [none]
}
return distance;
} } |
public class class_name {
public boolean popTable() {
if (currentLevel > 0) {
//Remove all the variable having a level equals to currentLevel
for (Iterator<Map.Entry<String, Integer>> ite = level.entrySet().iterator(); ite.hasNext(); ) {
Map.Entry<String, Integer> e = ite.next();
if (e.getValue() == currentLevel) {
ite.remove();
type.remove(e.getKey());
}
}
currentLevel--;
return true;
}
return false;
} } | public class class_name {
public boolean popTable() {
if (currentLevel > 0) {
//Remove all the variable having a level equals to currentLevel
for (Iterator<Map.Entry<String, Integer>> ite = level.entrySet().iterator(); ite.hasNext(); ) {
Map.Entry<String, Integer> e = ite.next();
if (e.getValue() == currentLevel) {
ite.remove(); // depends on control dependency: [if], data = [none]
type.remove(e.getKey()); // depends on control dependency: [if], data = [none]
}
}
currentLevel--; // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public static String subst(String string, Map dictionary)
{
LOGGER.entering(CLASS_NAME, "subst", new Object[]{string, dictionary});
Pattern pattern = Pattern.compile(VARIABLE_PATTERN);
Matcher matcher = pattern.matcher(string);
while (matcher.find())
{
String value = (String)dictionary.get(matcher.group(1));
if (value == null) value = "";
string = string.replace(matcher.group(0), value);
matcher.reset(string);
}
matcher.reset();
LOGGER.exiting(CLASS_NAME, "subst", string);
return string;
} } | public class class_name {
public static String subst(String string, Map dictionary)
{
LOGGER.entering(CLASS_NAME, "subst", new Object[]{string, dictionary});
Pattern pattern = Pattern.compile(VARIABLE_PATTERN);
Matcher matcher = pattern.matcher(string);
while (matcher.find())
{
String value = (String)dictionary.get(matcher.group(1));
if (value == null) value = "";
string = string.replace(matcher.group(0), value);
matcher.reset(string); // depends on control dependency: [while], data = [none]
}
matcher.reset();
LOGGER.exiting(CLASS_NAME, "subst", string);
return string;
} } |
public class class_name {
private boolean anyStringContainsNewLine(final String[] data) {
boolean returnVal = false;
for (int i = 0; i < data.length; i++) {
if (Util.containsNewlines(data[i])) {
returnVal = true;
}
}
return returnVal;
} } | public class class_name {
private boolean anyStringContainsNewLine(final String[] data) {
boolean returnVal = false;
for (int i = 0; i < data.length; i++) {
if (Util.containsNewlines(data[i])) {
returnVal = true; // depends on control dependency: [if], data = [none]
}
}
return returnVal;
} } |
public class class_name {
public void startBundle(Bundle bundle)
{
if (bundle != null)
if ((bundle.getState() != Bundle.ACTIVE) && (bundle.getState() != Bundle.STARTING))
{
try {
bundle.start();
} catch (BundleException e) {
e.printStackTrace();
}
}
} } | public class class_name {
public void startBundle(Bundle bundle)
{
if (bundle != null)
if ((bundle.getState() != Bundle.ACTIVE) && (bundle.getState() != Bundle.STARTING))
{
try {
bundle.start(); // depends on control dependency: [try], data = [none]
} catch (BundleException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
static int readInt(final DataInput in) throws IOException {
int b = in.readByte() & 0xFF;
int n = b & 0x7F;
if (b > 0x7F) {
b = in.readByte() & 0xFF;
n ^= (b & 0x7F) << 7;
if (b > 0x7F) {
b = in.readByte() & 0xFF;
n ^= (b & 0x7F) << 14;
if (b > 0x7F) {
b = in.readByte() & 0xFF;
n ^= (b & 0x7F) << 21;
if (b > 0x7F) {
b = in.readByte() & 0xFF;
n ^= (b & 0x7F) << 28;
if (b > 0x7F) {
throw new IOException("Invalid int encoding.");
}
}
}
}
}
return (n >>> 1)^-(n & 1);
} } | public class class_name {
static int readInt(final DataInput in) throws IOException {
int b = in.readByte() & 0xFF;
int n = b & 0x7F;
if (b > 0x7F) {
b = in.readByte() & 0xFF;
n ^= (b & 0x7F) << 7;
if (b > 0x7F) {
b = in.readByte() & 0xFF; // depends on control dependency: [if], data = [none]
n ^= (b & 0x7F) << 14; // depends on control dependency: [if], data = [(b]
if (b > 0x7F) {
b = in.readByte() & 0xFF; // depends on control dependency: [if], data = [none]
n ^= (b & 0x7F) << 21; // depends on control dependency: [if], data = [(b]
if (b > 0x7F) {
b = in.readByte() & 0xFF; // depends on control dependency: [if], data = [none]
n ^= (b & 0x7F) << 28; // depends on control dependency: [if], data = [(b]
if (b > 0x7F) {
throw new IOException("Invalid int encoding.");
}
}
}
}
}
return (n >>> 1)^-(n & 1);
} } |
public class class_name {
public void readBondBlock(IAtomContainer readData) throws CDKException {
logger.info("Reading BOND block");
boolean foundEND = false;
while (isReady() && !foundEND) {
String command = readCommand(readLine());
if ("END BOND".equals(command)) {
foundEND = true;
} else {
logger.debug("Parsing bond from: " + command);
StringTokenizer tokenizer = new StringTokenizer(command);
IBond bond = readData.getBuilder().newBond();
// parse the index
try {
String indexString = tokenizer.nextToken();
bond.setID(indexString);
} catch (Exception exception) {
String error = "Error while parsing bond index";
logger.error(error);
logger.debug(exception);
throw new CDKException(error, exception);
}
// parse the order
try {
String orderString = tokenizer.nextToken();
int order = Integer.parseInt(orderString);
if (order >= 4) {
logger.warn("Query order types are not supported (yet). File a bug if you need it");
} else {
bond.setOrder(BondManipulator.createBondOrder((double) order));
}
} catch (Exception exception) {
String error = "Error while parsing bond index";
logger.error(error);
logger.debug(exception);
throw new CDKException(error, exception);
}
// parse index atom 1
try {
String indexAtom1String = tokenizer.nextToken();
int indexAtom1 = Integer.parseInt(indexAtom1String);
IAtom atom1 = readData.getAtom(indexAtom1 - 1);
bond.setAtom(atom1, 0);
} catch (Exception exception) {
String error = "Error while parsing index atom 1 in bond";
logger.error(error);
logger.debug(exception);
throw new CDKException(error, exception);
}
// parse index atom 2
try {
String indexAtom2String = tokenizer.nextToken();
int indexAtom2 = Integer.parseInt(indexAtom2String);
IAtom atom2 = readData.getAtom(indexAtom2 - 1);
bond.setAtom(atom2, 1);
} catch (Exception exception) {
String error = "Error while parsing index atom 2 in bond";
logger.error(error);
logger.debug(exception);
throw new CDKException(error, exception);
}
List<IAtom> endpts = new ArrayList<>();
String attach = null;
// the rest are key=value fields
if (command.indexOf('=') != -1) {
Map<String, String> options = parseOptions(exhaustStringTokenizer(tokenizer));
for (String key : options.keySet()) {
String value = options.get(key);
try {
switch (key) {
case "CFG":
int configuration = Integer.parseInt(value);
if (configuration == 0) {
bond.setStereo(IBond.Stereo.NONE);
} else if (configuration == 1) {
bond.setStereo(IBond.Stereo.UP);
} else if (configuration == 2) {
bond.setStereo((IBond.Stereo) CDKConstants.UNSET);
} else if (configuration == 3) {
bond.setStereo(IBond.Stereo.DOWN);
}
break;
case "ENDPTS":
String[] endptStr = value.split(" ");
// skip first value that is count
for (int i = 1; i < endptStr.length; i++) {
endpts.add(readData.getAtom(Integer.parseInt(endptStr[i]) - 1));
}
break;
case "ATTACH":
attach = value;
break;
default:
logger.warn("Not parsing key: " + key);
break;
}
} catch (Exception exception) {
String error = "Error while parsing key/value " + key + "=" + value + ": "
+ exception.getMessage();
logger.error(error);
logger.debug(exception);
throw new CDKException(error, exception);
}
}
}
// storing bond
readData.addBond(bond);
// storing positional variation
if ("ANY".equals(attach)) {
Sgroup sgroup = new Sgroup();
sgroup.setType(SgroupType.ExtMulticenter);
sgroup.addAtom(bond.getBegin()); // could be other end?
sgroup.addBond(bond);
for (IAtom endpt : endpts)
sgroup.addAtom(endpt);
List<Sgroup> sgroups = readData.getProperty(CDKConstants.CTAB_SGROUPS);
if (sgroups == null)
readData.setProperty(CDKConstants.CTAB_SGROUPS, sgroups = new ArrayList<>(4));
sgroups.add(sgroup);
}
logger.debug("Added bond: " + bond);
}
}
} } | public class class_name {
public void readBondBlock(IAtomContainer readData) throws CDKException {
logger.info("Reading BOND block");
boolean foundEND = false;
while (isReady() && !foundEND) {
String command = readCommand(readLine());
if ("END BOND".equals(command)) {
foundEND = true; // depends on control dependency: [if], data = [none]
} else {
logger.debug("Parsing bond from: " + command); // depends on control dependency: [if], data = [none]
StringTokenizer tokenizer = new StringTokenizer(command);
IBond bond = readData.getBuilder().newBond();
// parse the index
try {
String indexString = tokenizer.nextToken();
bond.setID(indexString); // depends on control dependency: [try], data = [none]
} catch (Exception exception) {
String error = "Error while parsing bond index";
logger.error(error);
logger.debug(exception);
throw new CDKException(error, exception);
} // depends on control dependency: [catch], data = [none]
// parse the order
try {
String orderString = tokenizer.nextToken();
int order = Integer.parseInt(orderString);
if (order >= 4) {
logger.warn("Query order types are not supported (yet). File a bug if you need it"); // depends on control dependency: [if], data = [none]
} else {
bond.setOrder(BondManipulator.createBondOrder((double) order)); // depends on control dependency: [if], data = [none]
}
} catch (Exception exception) {
String error = "Error while parsing bond index";
logger.error(error);
logger.debug(exception);
throw new CDKException(error, exception);
} // depends on control dependency: [catch], data = [none]
// parse index atom 1
try {
String indexAtom1String = tokenizer.nextToken();
int indexAtom1 = Integer.parseInt(indexAtom1String);
IAtom atom1 = readData.getAtom(indexAtom1 - 1);
bond.setAtom(atom1, 0); // depends on control dependency: [try], data = [none]
} catch (Exception exception) {
String error = "Error while parsing index atom 1 in bond";
logger.error(error);
logger.debug(exception);
throw new CDKException(error, exception);
} // depends on control dependency: [catch], data = [none]
// parse index atom 2
try {
String indexAtom2String = tokenizer.nextToken();
int indexAtom2 = Integer.parseInt(indexAtom2String);
IAtom atom2 = readData.getAtom(indexAtom2 - 1);
bond.setAtom(atom2, 1); // depends on control dependency: [try], data = [none]
} catch (Exception exception) {
String error = "Error while parsing index atom 2 in bond";
logger.error(error);
logger.debug(exception);
throw new CDKException(error, exception);
} // depends on control dependency: [catch], data = [none]
List<IAtom> endpts = new ArrayList<>();
String attach = null;
// the rest are key=value fields
if (command.indexOf('=') != -1) {
Map<String, String> options = parseOptions(exhaustStringTokenizer(tokenizer));
for (String key : options.keySet()) {
String value = options.get(key);
try {
switch (key) {
case "CFG":
int configuration = Integer.parseInt(value);
if (configuration == 0) {
bond.setStereo(IBond.Stereo.NONE); // depends on control dependency: [if], data = [none]
} else if (configuration == 1) {
bond.setStereo(IBond.Stereo.UP); // depends on control dependency: [if], data = [none]
} else if (configuration == 2) {
bond.setStereo((IBond.Stereo) CDKConstants.UNSET); // depends on control dependency: [if], data = [none]
} else if (configuration == 3) {
bond.setStereo(IBond.Stereo.DOWN); // depends on control dependency: [if], data = [none]
}
break;
case "ENDPTS":
String[] endptStr = value.split(" ");
// skip first value that is count
for (int i = 1; i < endptStr.length; i++) {
endpts.add(readData.getAtom(Integer.parseInt(endptStr[i]) - 1)); // depends on control dependency: [for], data = [i]
}
break;
case "ATTACH":
attach = value;
break;
default:
logger.warn("Not parsing key: " + key);
break;
}
} catch (Exception exception) {
String error = "Error while parsing key/value " + key + "=" + value + ": "
+ exception.getMessage();
logger.error(error);
logger.debug(exception);
throw new CDKException(error, exception);
} // depends on control dependency: [catch], data = [none]
}
}
// storing bond
readData.addBond(bond); // depends on control dependency: [if], data = [none]
// storing positional variation
if ("ANY".equals(attach)) {
Sgroup sgroup = new Sgroup();
sgroup.setType(SgroupType.ExtMulticenter); // depends on control dependency: [if], data = [none]
sgroup.addAtom(bond.getBegin()); // could be other end? // depends on control dependency: [if], data = [none]
sgroup.addBond(bond); // depends on control dependency: [if], data = [none]
for (IAtom endpt : endpts)
sgroup.addAtom(endpt);
List<Sgroup> sgroups = readData.getProperty(CDKConstants.CTAB_SGROUPS);
if (sgroups == null)
readData.setProperty(CDKConstants.CTAB_SGROUPS, sgroups = new ArrayList<>(4));
sgroups.add(sgroup); // depends on control dependency: [if], data = [none]
}
logger.debug("Added bond: " + bond); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public Optional<Project> getOptionalProject(String namespace, String project) {
try {
return (Optional.ofNullable(getProject(namespace, project)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
} } | public class class_name {
public Optional<Project> getOptionalProject(String namespace, String project) {
try {
return (Optional.ofNullable(getProject(namespace, project))); // depends on control dependency: [try], data = [none]
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected CmsAliasImportResult processAliasLine(CmsObject cms, String siteRoot, String line, String separator) {
Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
line = line.trim();
// ignore empty lines or comments starting with #
if (CmsStringUtil.isEmptyOrWhitespaceOnly(line) || line.startsWith("#")) {
return null;
}
CSVParser parser = new CSVParser(separator.charAt(0));
String[] tokens = null;
try {
tokens = parser.parseLine(line);
for (int i = 0; i < tokens.length; i++) {
tokens[i] = tokens[i].trim();
}
} catch (IOException e) {
return new CmsAliasImportResult(
line,
CmsAliasImportStatus.aliasParseError,
messageImportInvalidFormat(locale));
}
int numTokens = tokens.length;
String alias = null;
String vfsPath = null;
if (numTokens >= 2) {
alias = tokens[0];
vfsPath = tokens[1];
}
CmsAliasMode mode = CmsAliasMode.permanentRedirect;
if (numTokens >= 3) {
try {
mode = CmsAliasMode.valueOf(tokens[2].trim());
} catch (Exception e) {
return new CmsAliasImportResult(
line,
CmsAliasImportStatus.aliasParseError,
messageImportInvalidFormat(locale));
}
}
boolean isRewrite = false;
if (numTokens == 4) {
if (!tokens[3].equals("rewrite")) {
return new CmsAliasImportResult(
line,
CmsAliasImportStatus.aliasParseError,
messageImportInvalidFormat(locale));
} else {
isRewrite = true;
}
}
if ((numTokens < 2) || (numTokens > 4)) {
return new CmsAliasImportResult(
line,
CmsAliasImportStatus.aliasParseError,
messageImportInvalidFormat(locale));
}
CmsAliasImportResult returnValue = null;
if (isRewrite) {
returnValue = processRewriteImport(cms, siteRoot, alias, vfsPath, mode);
} else {
returnValue = processAliasImport(cms, siteRoot, alias, vfsPath, mode);
}
returnValue.setLine(line);
return returnValue;
} } | public class class_name {
protected CmsAliasImportResult processAliasLine(CmsObject cms, String siteRoot, String line, String separator) {
Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
line = line.trim();
// ignore empty lines or comments starting with #
if (CmsStringUtil.isEmptyOrWhitespaceOnly(line) || line.startsWith("#")) {
return null;
// depends on control dependency: [if], data = [none]
}
CSVParser parser = new CSVParser(separator.charAt(0));
String[] tokens = null;
try {
tokens = parser.parseLine(line);
// depends on control dependency: [try], data = [none]
for (int i = 0; i < tokens.length; i++) {
tokens[i] = tokens[i].trim();
// depends on control dependency: [for], data = [i]
}
} catch (IOException e) {
return new CmsAliasImportResult(
line,
CmsAliasImportStatus.aliasParseError,
messageImportInvalidFormat(locale));
}
// depends on control dependency: [catch], data = [none]
int numTokens = tokens.length;
String alias = null;
String vfsPath = null;
if (numTokens >= 2) {
alias = tokens[0];
// depends on control dependency: [if], data = [none]
vfsPath = tokens[1];
// depends on control dependency: [if], data = [none]
}
CmsAliasMode mode = CmsAliasMode.permanentRedirect;
if (numTokens >= 3) {
try {
mode = CmsAliasMode.valueOf(tokens[2].trim());
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
return new CmsAliasImportResult(
line,
CmsAliasImportStatus.aliasParseError,
messageImportInvalidFormat(locale));
}
// depends on control dependency: [catch], data = [none]
}
boolean isRewrite = false;
if (numTokens == 4) {
if (!tokens[3].equals("rewrite")) {
return new CmsAliasImportResult(
line,
CmsAliasImportStatus.aliasParseError,
messageImportInvalidFormat(locale));
// depends on control dependency: [if], data = [none]
} else {
isRewrite = true;
// depends on control dependency: [if], data = [none]
}
}
if ((numTokens < 2) || (numTokens > 4)) {
return new CmsAliasImportResult(
line,
CmsAliasImportStatus.aliasParseError,
messageImportInvalidFormat(locale));
// depends on control dependency: [if], data = [none]
}
CmsAliasImportResult returnValue = null;
if (isRewrite) {
returnValue = processRewriteImport(cms, siteRoot, alias, vfsPath, mode);
// depends on control dependency: [if], data = [none]
} else {
returnValue = processAliasImport(cms, siteRoot, alias, vfsPath, mode);
// depends on control dependency: [if], data = [none]
}
returnValue.setLine(line);
return returnValue;
} } |
public class class_name {
public static Object callMethod(Object o, String method, Object[] params)
{
// Get the objects class.
Class cls = o.getClass();
// Get the classes of the parameters.
Class[] paramClasses = new Class[params.length];
for (int i = 0; i < params.length; i++)
{
paramClasses[i] = params[i].getClass();
}
try
{
// Try to find the matching method on the class.
Method m = cls.getMethod(method, paramClasses);
// Invoke it with the parameters.
return m.invoke(o, params);
}
catch (NoSuchMethodException e)
{
throw new IllegalStateException(e);
}
catch (IllegalAccessException e)
{
throw new IllegalStateException(e);
}
catch (InvocationTargetException e)
{
throw new IllegalStateException(e);
}
} } | public class class_name {
public static Object callMethod(Object o, String method, Object[] params)
{
// Get the objects class.
Class cls = o.getClass();
// Get the classes of the parameters.
Class[] paramClasses = new Class[params.length];
for (int i = 0; i < params.length; i++)
{
paramClasses[i] = params[i].getClass(); // depends on control dependency: [for], data = [i]
}
try
{
// Try to find the matching method on the class.
Method m = cls.getMethod(method, paramClasses);
// Invoke it with the parameters.
return m.invoke(o, params); // depends on control dependency: [try], data = [none]
}
catch (NoSuchMethodException e)
{
throw new IllegalStateException(e);
} // depends on control dependency: [catch], data = [none]
catch (IllegalAccessException e)
{
throw new IllegalStateException(e);
} // depends on control dependency: [catch], data = [none]
catch (InvocationTargetException e)
{
throw new IllegalStateException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Segment createSegment(SegmentDescriptor descriptor) {
switch (storage.level()) {
case MEMORY:
return createMemorySegment(descriptor);
case MAPPED:
if (descriptor.version() == 1) {
return createMappedSegment(descriptor);
} else {
return createDiskSegment(descriptor);
}
case DISK:
return createDiskSegment(descriptor);
default:
throw new AssertionError();
}
} } | public class class_name {
public Segment createSegment(SegmentDescriptor descriptor) {
switch (storage.level()) {
case MEMORY:
return createMemorySegment(descriptor);
case MAPPED:
if (descriptor.version() == 1) {
return createMappedSegment(descriptor); // depends on control dependency: [if], data = [none]
} else {
return createDiskSegment(descriptor); // depends on control dependency: [if], data = [none]
}
case DISK:
return createDiskSegment(descriptor);
default:
throw new AssertionError();
}
} } |
public class class_name {
@NonNull public CharSequence getQuery() {
if (searchView != null) {
return searchView.getQuery();
} else if (supportView != null) {
return supportView.getQuery();
}
throw new IllegalStateException(ERROR_NO_SEARCHVIEW);
} } | public class class_name {
@NonNull public CharSequence getQuery() {
if (searchView != null) {
return searchView.getQuery(); // depends on control dependency: [if], data = [none]
} else if (supportView != null) {
return supportView.getQuery(); // depends on control dependency: [if], data = [none]
}
throw new IllegalStateException(ERROR_NO_SEARCHVIEW);
} } |
public class class_name {
public void marshall(ListGatewaysRequest listGatewaysRequest, ProtocolMarshaller protocolMarshaller) {
if (listGatewaysRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listGatewaysRequest.getGatewayGroupArn(), GATEWAYGROUPARN_BINDING);
protocolMarshaller.marshall(listGatewaysRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listGatewaysRequest.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(ListGatewaysRequest listGatewaysRequest, ProtocolMarshaller protocolMarshaller) {
if (listGatewaysRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listGatewaysRequest.getGatewayGroupArn(), GATEWAYGROUPARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listGatewaysRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listGatewaysRequest.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 {
public int isCompliantWithRequestContentType(Request request) {
if (acceptedMediaTypes == null || acceptedMediaTypes.isEmpty() || request == null) {
return 2;
} else {
String content = request.contentMimeType();
if (content == null) {
return 2;
} else {
// For all consume, check whether we accept it
MediaType contentMimeType = MediaType.parse(request.contentMimeType());
for (MediaType type : acceptedMediaTypes) {
if (contentMimeType.is(type)) {
if (type.hasWildcard()) {
return 1;
} else {
return 2;
}
}
}
return 0;
}
}
} } | public class class_name {
public int isCompliantWithRequestContentType(Request request) {
if (acceptedMediaTypes == null || acceptedMediaTypes.isEmpty() || request == null) {
return 2; // depends on control dependency: [if], data = [none]
} else {
String content = request.contentMimeType();
if (content == null) {
return 2; // depends on control dependency: [if], data = [none]
} else {
// For all consume, check whether we accept it
MediaType contentMimeType = MediaType.parse(request.contentMimeType());
for (MediaType type : acceptedMediaTypes) {
if (contentMimeType.is(type)) {
if (type.hasWildcard()) {
return 1; // depends on control dependency: [if], data = [none]
} else {
return 2; // depends on control dependency: [if], data = [none]
}
}
}
return 0; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
static String getMimeEncoding(String encoding)
{
if (null == encoding)
{
try
{
// Get the default system character encoding. This may be
// incorrect if they passed in a writer, but right now there
// seems to be no way to get the encoding from a writer.
encoding = System.getProperty("file.encoding", "UTF8");
if (null != encoding)
{
/*
* See if the mime type is equal to UTF8. If you don't
* do that, then convertJava2MimeEncoding will convert
* 8859_1 to "ISO-8859-1", which is not what we want,
* I think, and I don't think I want to alter the tables
* to convert everything to UTF-8.
*/
String jencoding =
(encoding.equalsIgnoreCase("Cp1252")
|| encoding.equalsIgnoreCase("ISO8859_1")
|| encoding.equalsIgnoreCase("8859_1")
|| encoding.equalsIgnoreCase("UTF8"))
? DEFAULT_MIME_ENCODING
: convertJava2MimeEncoding(encoding);
encoding =
(null != jencoding) ? jencoding : DEFAULT_MIME_ENCODING;
}
else
{
encoding = DEFAULT_MIME_ENCODING;
}
}
catch (SecurityException se)
{
encoding = DEFAULT_MIME_ENCODING;
}
}
else
{
encoding = convertJava2MimeEncoding(encoding);
}
return encoding;
} } | public class class_name {
static String getMimeEncoding(String encoding)
{
if (null == encoding)
{
try
{
// Get the default system character encoding. This may be
// incorrect if they passed in a writer, but right now there
// seems to be no way to get the encoding from a writer.
encoding = System.getProperty("file.encoding", "UTF8"); // depends on control dependency: [try], data = [none]
if (null != encoding)
{
/*
* See if the mime type is equal to UTF8. If you don't
* do that, then convertJava2MimeEncoding will convert
* 8859_1 to "ISO-8859-1", which is not what we want,
* I think, and I don't think I want to alter the tables
* to convert everything to UTF-8.
*/
String jencoding =
(encoding.equalsIgnoreCase("Cp1252")
|| encoding.equalsIgnoreCase("ISO8859_1")
|| encoding.equalsIgnoreCase("8859_1")
|| encoding.equalsIgnoreCase("UTF8"))
? DEFAULT_MIME_ENCODING
: convertJava2MimeEncoding(encoding);
encoding =
(null != jencoding) ? jencoding : DEFAULT_MIME_ENCODING; // depends on control dependency: [if], data = [none]
}
else
{
encoding = DEFAULT_MIME_ENCODING; // depends on control dependency: [if], data = [none]
}
}
catch (SecurityException se)
{
encoding = DEFAULT_MIME_ENCODING;
} // depends on control dependency: [catch], data = [none]
}
else
{
encoding = convertJava2MimeEncoding(encoding); // depends on control dependency: [if], data = [encoding)]
}
return encoding;
} } |
public class class_name {
protected void auditQueryEvent(
boolean systemIsSource, // System Type
IHETransactionEventTypeCodes transaction, RFC3881EventOutcomeCodes eventOutcome, // Event
String auditSourceId, String auditSourceEnterpriseSiteId, // Audit Source
String sourceUserId, String sourceAltUserId, String sourceUserName, String sourceNetworkId, // Source Participant
String humanRequestor, // Human Participant
String humanRequestorName, // Human Participant name
boolean humanAfterDestination,
String registryEndpointUri, String registryAltUserId, // Destination Participant
String storedQueryUUID, String adhocQueryRequestPayload, String homeCommunityId, // Payload Object Participant
String patientId, // Patient Object Participant
List<CodedValueType> purposesOfUse, List<CodedValueType> userRoles)
{
QueryEvent queryEvent = new QueryEvent(systemIsSource, eventOutcome, transaction, purposesOfUse);
queryEvent.setAuditSourceId(auditSourceId, auditSourceEnterpriseSiteId);
queryEvent.addSourceActiveParticipant(sourceUserId, sourceAltUserId, sourceUserName, sourceNetworkId, true);
if (humanAfterDestination) {
queryEvent.addDestinationActiveParticipant(registryEndpointUri, registryAltUserId, null, EventUtils.getAddressForUrl(registryEndpointUri, false), false);
}
if(!EventUtils.isEmptyOrNull(humanRequestorName)) {
queryEvent.addHumanRequestorActiveParticipant(humanRequestorName, null, humanRequestorName, userRoles);
}
if (! humanAfterDestination) {
queryEvent.addDestinationActiveParticipant(registryEndpointUri, registryAltUserId, null, EventUtils.getAddressForUrl(registryEndpointUri, false), false);
}
if (!EventUtils.isEmptyOrNull(patientId)) {
queryEvent.addPatientParticipantObject(patientId);
}
byte[] queryRequestPayloadBytes = null;
if (!EventUtils.isEmptyOrNull(adhocQueryRequestPayload)) {
queryRequestPayloadBytes = adhocQueryRequestPayload.getBytes();
}
queryEvent.addQueryParticipantObject(storedQueryUUID, homeCommunityId, queryRequestPayloadBytes, null, transaction);
audit(queryEvent);
} } | public class class_name {
protected void auditQueryEvent(
boolean systemIsSource, // System Type
IHETransactionEventTypeCodes transaction, RFC3881EventOutcomeCodes eventOutcome, // Event
String auditSourceId, String auditSourceEnterpriseSiteId, // Audit Source
String sourceUserId, String sourceAltUserId, String sourceUserName, String sourceNetworkId, // Source Participant
String humanRequestor, // Human Participant
String humanRequestorName, // Human Participant name
boolean humanAfterDestination,
String registryEndpointUri, String registryAltUserId, // Destination Participant
String storedQueryUUID, String adhocQueryRequestPayload, String homeCommunityId, // Payload Object Participant
String patientId, // Patient Object Participant
List<CodedValueType> purposesOfUse, List<CodedValueType> userRoles)
{
QueryEvent queryEvent = new QueryEvent(systemIsSource, eventOutcome, transaction, purposesOfUse);
queryEvent.setAuditSourceId(auditSourceId, auditSourceEnterpriseSiteId);
queryEvent.addSourceActiveParticipant(sourceUserId, sourceAltUserId, sourceUserName, sourceNetworkId, true);
if (humanAfterDestination) {
queryEvent.addDestinationActiveParticipant(registryEndpointUri, registryAltUserId, null, EventUtils.getAddressForUrl(registryEndpointUri, false), false); // depends on control dependency: [if], data = [none]
}
if(!EventUtils.isEmptyOrNull(humanRequestorName)) {
queryEvent.addHumanRequestorActiveParticipant(humanRequestorName, null, humanRequestorName, userRoles); // depends on control dependency: [if], data = [none]
}
if (! humanAfterDestination) {
queryEvent.addDestinationActiveParticipant(registryEndpointUri, registryAltUserId, null, EventUtils.getAddressForUrl(registryEndpointUri, false), false); // depends on control dependency: [if], data = [none]
}
if (!EventUtils.isEmptyOrNull(patientId)) {
queryEvent.addPatientParticipantObject(patientId); // depends on control dependency: [if], data = [none]
}
byte[] queryRequestPayloadBytes = null;
if (!EventUtils.isEmptyOrNull(adhocQueryRequestPayload)) {
queryRequestPayloadBytes = adhocQueryRequestPayload.getBytes(); // depends on control dependency: [if], data = [none]
}
queryEvent.addQueryParticipantObject(storedQueryUUID, homeCommunityId, queryRequestPayloadBytes, null, transaction);
audit(queryEvent);
} } |
public class class_name {
@Override
public void stop() {
if (!stopped.compareAndSet(false, true)) return;
sweep();
int retries = 0;
while (count() > 1 && ++retries < 10) {
try { Thread.sleep(10L); } catch (Exception e) {}
}
scheduler.close();
} } | public class class_name {
@Override
public void stop() {
if (!stopped.compareAndSet(false, true)) return;
sweep();
int retries = 0;
while (count() > 1 && ++retries < 10) {
try { Thread.sleep(10L); } catch (Exception e) {} // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none]
}
scheduler.close();
} } |
public class class_name {
@Override
public void visitMaxs(int maxStack, int maxLocals) {
if (localScopes != null) {
for (VariableScope scope : localScopes) {
super.visitLocalVariable(
"xxxxx$" + scope.index, scope.desc, null, scope.start, scope.end, scope.index);
}
}
super.visitMaxs(maxStack, maxLocals);
} } | public class class_name {
@Override
public void visitMaxs(int maxStack, int maxLocals) {
if (localScopes != null) {
for (VariableScope scope : localScopes) {
super.visitLocalVariable(
"xxxxx$" + scope.index, scope.desc, null, scope.start, scope.end, scope.index); // depends on control dependency: [for], data = [none]
}
}
super.visitMaxs(maxStack, maxLocals);
} } |
public class class_name {
public void marshall(CreateFleetRequest createFleetRequest, ProtocolMarshaller protocolMarshaller) {
if (createFleetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createFleetRequest.getFleetName(), FLEETNAME_BINDING);
protocolMarshaller.marshall(createFleetRequest.getDisplayName(), DISPLAYNAME_BINDING);
protocolMarshaller.marshall(createFleetRequest.getOptimizeForEndUserLocation(), OPTIMIZEFORENDUSERLOCATION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateFleetRequest createFleetRequest, ProtocolMarshaller protocolMarshaller) {
if (createFleetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createFleetRequest.getFleetName(), FLEETNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createFleetRequest.getDisplayName(), DISPLAYNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createFleetRequest.getOptimizeForEndUserLocation(), OPTIMIZEFORENDUSERLOCATION_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void addMemberHeader(TypeElement fieldType, String fieldTypeStr,
String fieldDimensions, String fieldName, Content contentTree) {
Content nameContent = new RawHtml(fieldName);
Content heading = HtmlTree.HEADING(HtmlConstants.MEMBER_HEADING, nameContent);
contentTree.addContent(heading);
Content pre = new HtmlTree(HtmlTag.PRE);
if (fieldType == null) {
pre.addContent(fieldTypeStr);
} else {
Content fieldContent = writer.getLink(new LinkInfoImpl(
configuration, LinkInfoImpl.Kind.SERIAL_MEMBER, fieldType));
pre.addContent(fieldContent);
}
pre.addContent(fieldDimensions + " ");
pre.addContent(fieldName);
contentTree.addContent(pre);
} } | public class class_name {
public void addMemberHeader(TypeElement fieldType, String fieldTypeStr,
String fieldDimensions, String fieldName, Content contentTree) {
Content nameContent = new RawHtml(fieldName);
Content heading = HtmlTree.HEADING(HtmlConstants.MEMBER_HEADING, nameContent);
contentTree.addContent(heading);
Content pre = new HtmlTree(HtmlTag.PRE);
if (fieldType == null) {
pre.addContent(fieldTypeStr); // depends on control dependency: [if], data = [(fieldType]
} else {
Content fieldContent = writer.getLink(new LinkInfoImpl(
configuration, LinkInfoImpl.Kind.SERIAL_MEMBER, fieldType));
pre.addContent(fieldContent); // depends on control dependency: [if], data = [none]
}
pre.addContent(fieldDimensions + " ");
pre.addContent(fieldName);
contentTree.addContent(pre);
} } |
public class class_name {
protected List<Boolean> getVisibilities(String key) {
List<Boolean> result = new ArrayList<Boolean>();
for (CmsContainerConfiguration config : m_parentConfigurations) {
result.add(config.getVisibility().get(key));
}
return result;
} } | public class class_name {
protected List<Boolean> getVisibilities(String key) {
List<Boolean> result = new ArrayList<Boolean>();
for (CmsContainerConfiguration config : m_parentConfigurations) {
result.add(config.getVisibility().get(key));
// depends on control dependency: [for], data = [config]
}
return result;
} } |
public class class_name {
public static URI newURIQuietly(final String uriString)
{
try
{
final URI uri = newURI(uriString);
return uri;
}
catch (final URISyntaxException e)
{
throw new CompilerRuntimeException(
"Given String " + uriString + " does not match to an uri", e);
}
} } | public class class_name {
public static URI newURIQuietly(final String uriString)
{
try
{
final URI uri = newURI(uriString);
return uri;
// depends on control dependency: [try], data = [none]
}
catch (final URISyntaxException e)
{
throw new CompilerRuntimeException(
"Given String " + uriString + " does not match to an uri", e);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
AudienceSegmentServiceInterface audienceSegmentService =
adManagerServices.get(session, AudienceSegmentServiceInterface.class);
// Create a statement to select audience segments.
StatementBuilder statementBuilder = new StatementBuilder()
.where("type = :type")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("type", AudienceSegmentType.FIRST_PARTY.toString());
// Retrieve a small amount of audience segments at a time, paging through
// until all audience segments have been retrieved.
int totalResultSetSize = 0;
do {
AudienceSegmentPage page =
audienceSegmentService.getAudienceSegmentsByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
// Print out some information for each audience segment.
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (AudienceSegment audienceSegment : page.getResults()) {
System.out.printf(
"%d) Audience segment with ID %d, name '%s', and size %d was found.%n",
i++,
audienceSegment.getId(),
audienceSegment.getName(),
audienceSegment.getSize()
);
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} } | public class class_name {
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
AudienceSegmentServiceInterface audienceSegmentService =
adManagerServices.get(session, AudienceSegmentServiceInterface.class);
// Create a statement to select audience segments.
StatementBuilder statementBuilder = new StatementBuilder()
.where("type = :type")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("type", AudienceSegmentType.FIRST_PARTY.toString());
// Retrieve a small amount of audience segments at a time, paging through
// until all audience segments have been retrieved.
int totalResultSetSize = 0;
do {
AudienceSegmentPage page =
audienceSegmentService.getAudienceSegmentsByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
// Print out some information for each audience segment.
totalResultSetSize = page.getTotalResultSetSize(); // depends on control dependency: [if], data = [none]
int i = page.getStartIndex();
for (AudienceSegment audienceSegment : page.getResults()) {
System.out.printf(
"%d) Audience segment with ID %d, name '%s', and size %d was found.%n", // depends on control dependency: [for], data = [none]
i++,
audienceSegment.getId(),
audienceSegment.getName(),
audienceSegment.getSize()
);
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} } |
public class class_name {
public void setStateChanges(java.util.Collection<AssessmentRunStateChange> stateChanges) {
if (stateChanges == null) {
this.stateChanges = null;
return;
}
this.stateChanges = new java.util.ArrayList<AssessmentRunStateChange>(stateChanges);
} } | public class class_name {
public void setStateChanges(java.util.Collection<AssessmentRunStateChange> stateChanges) {
if (stateChanges == null) {
this.stateChanges = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.stateChanges = new java.util.ArrayList<AssessmentRunStateChange>(stateChanges);
} } |
public class class_name {
private void setMultipart(String contentType) {
String[] dataBoundary = HttpPostRequestDecoder.getMultipartDataBoundary(contentType);
if (dataBoundary != null) {
multipartDataBoundary = dataBoundary[0];
if (dataBoundary.length > 1 && dataBoundary[1] != null) {
charset = Charset.forName(dataBoundary[1]);
}
} else {
multipartDataBoundary = null;
}
currentStatus = MultiPartStatus.HEADERDELIMITER;
} } | public class class_name {
private void setMultipart(String contentType) {
String[] dataBoundary = HttpPostRequestDecoder.getMultipartDataBoundary(contentType);
if (dataBoundary != null) {
multipartDataBoundary = dataBoundary[0]; // depends on control dependency: [if], data = [none]
if (dataBoundary.length > 1 && dataBoundary[1] != null) {
charset = Charset.forName(dataBoundary[1]); // depends on control dependency: [if], data = [none]
}
} else {
multipartDataBoundary = null; // depends on control dependency: [if], data = [none]
}
currentStatus = MultiPartStatus.HEADERDELIMITER;
} } |
public class class_name {
private Map<String, Criteria> getCriterias(Map<String, String[]> params) {
Map<String, Criteria> result = new HashMap<String, Criteria>();
for (Map.Entry<String, String[]> param : params.entrySet()) {
for (Criteria criteria : FILTER_CRITERIAS) {
if (criteria.getName().equals(param.getKey())) {
try {
Criteria[] parsedCriterias = criteria.parseValue(param.getValue()[0]);
for (Criteria parsedCriteria : parsedCriterias) {
result.put(parsedCriteria.getName(), parsedCriteria);
}
} catch (Exception e) {
// Exception happened during paring
LOG.log(Level.SEVERE, "Error parsing parameter " + param.getKey(), e);
}
break;
}
}
}
return result;
} } | public class class_name {
private Map<String, Criteria> getCriterias(Map<String, String[]> params) {
Map<String, Criteria> result = new HashMap<String, Criteria>();
for (Map.Entry<String, String[]> param : params.entrySet()) {
for (Criteria criteria : FILTER_CRITERIAS) {
if (criteria.getName().equals(param.getKey())) {
try {
Criteria[] parsedCriterias = criteria.parseValue(param.getValue()[0]);
for (Criteria parsedCriteria : parsedCriterias) {
result.put(parsedCriteria.getName(), parsedCriteria); // depends on control dependency: [for], data = [parsedCriteria]
}
} catch (Exception e) {
// Exception happened during paring
LOG.log(Level.SEVERE, "Error parsing parameter " + param.getKey(), e);
} // depends on control dependency: [catch], data = [none]
break;
}
}
}
return result;
} } |
public class class_name {
public static String getAdiVarna(String str)
{
if (str.length() == 0) return null;
String adiVarna = String.valueOf(str.charAt(0));
if (str.length() > 1 && str.charAt(1) == '3') // for pluta
{
adiVarna += String.valueOf(str.charAt(1));
}
return adiVarna;
} } | public class class_name {
public static String getAdiVarna(String str)
{
if (str.length() == 0) return null;
String adiVarna = String.valueOf(str.charAt(0));
if (str.length() > 1 && str.charAt(1) == '3') // for pluta
{
adiVarna += String.valueOf(str.charAt(1)); // depends on control dependency: [if], data = [none]
}
return adiVarna;
} } |
public class class_name {
private void refreshValue() {
try {
refreshableValueHolder
.compareAndSet(refreshableValueHolder.get(), refreshCallable.call());
} catch (AmazonServiceException ase) {
// Preserve the original ASE
throw ase;
} catch (AmazonClientException ace) {
// Preserve the original ACE
throw ace;
} catch (Exception e) {
throw new AmazonClientException(e);
}
} } | public class class_name {
private void refreshValue() {
try {
refreshableValueHolder
.compareAndSet(refreshableValueHolder.get(), refreshCallable.call()); // depends on control dependency: [try], data = [none]
} catch (AmazonServiceException ase) {
// Preserve the original ASE
throw ase;
} catch (AmazonClientException ace) { // depends on control dependency: [catch], data = [none]
// Preserve the original ACE
throw ace;
} catch (Exception e) { // depends on control dependency: [catch], data = [none]
throw new AmazonClientException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource,
DatabaseTableConfig<T> tableConfig) {
if (connectionSource == null) {
throw new IllegalArgumentException("connectionSource argument cannot be null");
}
TableConfigConnectionSource key = new TableConfigConnectionSource(connectionSource, tableConfig);
Dao<?, ?> dao = lookupDao(key);
if (dao == null) {
return null;
} else {
@SuppressWarnings("unchecked")
D castDao = (D) dao;
return castDao;
}
} } | public class class_name {
public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource,
DatabaseTableConfig<T> tableConfig) {
if (connectionSource == null) {
throw new IllegalArgumentException("connectionSource argument cannot be null");
}
TableConfigConnectionSource key = new TableConfigConnectionSource(connectionSource, tableConfig);
Dao<?, ?> dao = lookupDao(key);
if (dao == null) {
return null; // depends on control dependency: [if], data = [none]
} else {
@SuppressWarnings("unchecked")
D castDao = (D) dao;
return castDao; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static IDifference difference(IChemObject first, IChemObject second) {
if (!(first instanceof IAtom && second instanceof IAtom)) {
return null;
}
IAtom firstElem = (IAtom) first;
IAtom secondElem = (IAtom) second;
ChemObjectDifference totalDiff = new ChemObjectDifference("AtomDiff");
totalDiff.addChild(IntegerDifference.construct("H", firstElem.getImplicitHydrogenCount(),
secondElem.getImplicitHydrogenCount()));
totalDiff
.addChild(IntegerDifference.construct("SP", firstElem.getStereoParity(), secondElem.getStereoParity()));
totalDiff.addChild(Point2dDifference.construct("2D", firstElem.getPoint2d(), secondElem.getPoint2d()));
totalDiff.addChild(Point3dDifference.construct("3D", firstElem.getPoint3d(), secondElem.getPoint3d()));
totalDiff.addChild(Point3dDifference.construct("F3D", firstElem.getFractionalPoint3d(),
secondElem.getFractionalPoint3d()));
totalDiff.addChild(DoubleDifference.construct("C", firstElem.getCharge(), secondElem.getCharge()));
totalDiff.addChild(AtomTypeDiff.difference(first, second));
if (totalDiff.childCount() > 0) {
return totalDiff;
} else {
return null;
}
} } | public class class_name {
public static IDifference difference(IChemObject first, IChemObject second) {
if (!(first instanceof IAtom && second instanceof IAtom)) {
return null; // depends on control dependency: [if], data = [none]
}
IAtom firstElem = (IAtom) first;
IAtom secondElem = (IAtom) second;
ChemObjectDifference totalDiff = new ChemObjectDifference("AtomDiff");
totalDiff.addChild(IntegerDifference.construct("H", firstElem.getImplicitHydrogenCount(),
secondElem.getImplicitHydrogenCount()));
totalDiff
.addChild(IntegerDifference.construct("SP", firstElem.getStereoParity(), secondElem.getStereoParity()));
totalDiff.addChild(Point2dDifference.construct("2D", firstElem.getPoint2d(), secondElem.getPoint2d()));
totalDiff.addChild(Point3dDifference.construct("3D", firstElem.getPoint3d(), secondElem.getPoint3d()));
totalDiff.addChild(Point3dDifference.construct("F3D", firstElem.getFractionalPoint3d(),
secondElem.getFractionalPoint3d()));
totalDiff.addChild(DoubleDifference.construct("C", firstElem.getCharge(), secondElem.getCharge()));
totalDiff.addChild(AtomTypeDiff.difference(first, second));
if (totalDiff.childCount() > 0) {
return totalDiff; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
void prune(int depth) {
if (isImmutable)
throw new IllegalStateException("PolicyNode is immutable");
// if we have no children, we can't prune below us...
if (mChildren.size() == 0)
return;
Iterator<PolicyNodeImpl> it = mChildren.iterator();
while (it.hasNext()) {
PolicyNodeImpl node = it.next();
node.prune(depth);
// now that we've called prune on the child, see if we should
// remove it from the tree
if ((node.mChildren.size() == 0) && (depth > mDepth + 1))
it.remove();
}
} } | public class class_name {
void prune(int depth) {
if (isImmutable)
throw new IllegalStateException("PolicyNode is immutable");
// if we have no children, we can't prune below us...
if (mChildren.size() == 0)
return;
Iterator<PolicyNodeImpl> it = mChildren.iterator();
while (it.hasNext()) {
PolicyNodeImpl node = it.next();
node.prune(depth); // depends on control dependency: [while], data = [none]
// now that we've called prune on the child, see if we should
// remove it from the tree
if ((node.mChildren.size() == 0) && (depth > mDepth + 1))
it.remove();
}
} } |
public class class_name {
public Collection<AgentProjectInfo> createProjects() {
List<DependencyInfo> packages = new LinkedList<>();
Collection<AgentProjectInfo> projectInfos = new LinkedList<>();
InputStream inputStream = null;
byte[] bytes = null;
Process process = null;
logger.info("File System Agent is resolving package manger dependencies only");
//For each flavor command check installed packages
for (LinuxPkgManagerCommand linuxPkgManagerCommand : LinuxPkgManagerCommand.values()) {
try {
logger.debug("Trying to run command {}", linuxPkgManagerCommand.getCommand());
process = Runtime.getRuntime().exec(linuxPkgManagerCommand.getCommand());
inputStream = process.getInputStream();
if (inputStream.read() == -1) {
logger.error("Unable to execute - {} , unix flavor does not support this command ", linuxPkgManagerCommand.getCommand());
} else {
bytes = ByteStreams.toByteArray(inputStream);
//Get the installed packages (name,version,architecture) from inputStream
logger.info("Succeed to run the command - {} ", linuxPkgManagerCommand.getCommand());
switch (linuxPkgManagerCommand) {
case DEBIAN:
logger.debug("Getting Debian installed Packages");
createDebianProject(bytes, packages);
break;
case RPM:
logger.debug("Getting RPM installed Packages");
createRpmProject(bytes, packages);
break;
case ARCH_LINUX:
logger.debug("Getting Arch Linux installed Packages");
createArchLinuxProject(bytes, packages);
break;
case ALPINE:
logger.debug("Getting Alpine installed Packages");
createAlpineProject(bytes, packages);
break;
default:
break;
}
}
// Create new AgentProjectInfo object and add it into a list of AgentProjectInfo
if (packages.size() > 0) {
logger.debug("Creating new AgentProjectInfo object");
AgentProjectInfo projectInfo = new AgentProjectInfo();
projectInfo.setDependencies(packages);
projectInfos.add(projectInfo);
packages = new LinkedList<>();
} else {
logger.info("Couldn't find unix package manager dependencies");
}
} catch (IOException e) {
logger.warn("Couldn't resolve : {}", linuxPkgManagerCommand.name());
}
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
logger.error("InputStream exception : {}", e.getMessage());
}
return projectInfos;
} } | public class class_name {
public Collection<AgentProjectInfo> createProjects() {
List<DependencyInfo> packages = new LinkedList<>();
Collection<AgentProjectInfo> projectInfos = new LinkedList<>();
InputStream inputStream = null;
byte[] bytes = null;
Process process = null;
logger.info("File System Agent is resolving package manger dependencies only");
//For each flavor command check installed packages
for (LinuxPkgManagerCommand linuxPkgManagerCommand : LinuxPkgManagerCommand.values()) {
try {
logger.debug("Trying to run command {}", linuxPkgManagerCommand.getCommand());
process = Runtime.getRuntime().exec(linuxPkgManagerCommand.getCommand());
inputStream = process.getInputStream();
if (inputStream.read() == -1) {
logger.error("Unable to execute - {} , unix flavor does not support this command ", linuxPkgManagerCommand.getCommand()); // depends on control dependency: [if], data = [none]
} else {
bytes = ByteStreams.toByteArray(inputStream); // depends on control dependency: [if], data = [none]
//Get the installed packages (name,version,architecture) from inputStream
logger.info("Succeed to run the command - {} ", linuxPkgManagerCommand.getCommand()); // depends on control dependency: [if], data = [none]
switch (linuxPkgManagerCommand) {
case DEBIAN:
logger.debug("Getting Debian installed Packages");
createDebianProject(bytes, packages);
break;
case RPM:
logger.debug("Getting RPM installed Packages");
createRpmProject(bytes, packages);
break;
case ARCH_LINUX:
logger.debug("Getting Arch Linux installed Packages");
createArchLinuxProject(bytes, packages);
break;
case ALPINE:
logger.debug("Getting Alpine installed Packages");
createAlpineProject(bytes, packages);
break;
default:
break;
}
}
// Create new AgentProjectInfo object and add it into a list of AgentProjectInfo
if (packages.size() > 0) {
logger.debug("Creating new AgentProjectInfo object"); // depends on control dependency: [if], data = [none]
AgentProjectInfo projectInfo = new AgentProjectInfo();
projectInfo.setDependencies(packages); // depends on control dependency: [if], data = [none]
projectInfos.add(projectInfo); // depends on control dependency: [if], data = [none]
packages = new LinkedList<>(); // depends on control dependency: [if], data = [none]
} else {
logger.info("Couldn't find unix package manager dependencies");
}
} catch (IOException e) {
logger.warn("Couldn't resolve : {}", linuxPkgManagerCommand.name()); // depends on control dependency: [if], data = [none]
}
}
try {
if (inputStream != null) {
inputStream.close(); // depends on control dependency: [if], data = [none]
}
} catch (IOException e) {
logger.error("InputStream exception : {}", e.getMessage());
} // depends on control dependency: [catch], data = [none]
return projectInfos; // depends on control dependency: [for], data = [none]
} } |
public class class_name {
@Override
public void stop() {
if(registrationManager != null){
((RegistrationManagerImpl) registrationManager).stop();
}
if(lookupManager != null){
((LookupManagerImpl) lookupManager).stop();
}
} } | public class class_name {
@Override
public void stop() {
if(registrationManager != null){
((RegistrationManagerImpl) registrationManager).stop(); // depends on control dependency: [if], data = [none]
}
if(lookupManager != null){
((LookupManagerImpl) lookupManager).stop(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static String generatePrivate(String suffix, boolean includeMethodName) {
StackTraceElement stackElement = Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX];
StringBuilder nameBuilder = new StringBuilder(stackElement.getClassName());
if (includeMethodName) {
nameBuilder.append('.').append(stackElement.getMethodName());
}
if (suffix != null) {
nameBuilder.append(suffix);
}
return nameBuilder.toString();
} } | public class class_name {
private static String generatePrivate(String suffix, boolean includeMethodName) {
StackTraceElement stackElement = Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX];
StringBuilder nameBuilder = new StringBuilder(stackElement.getClassName());
if (includeMethodName) {
nameBuilder.append('.').append(stackElement.getMethodName()); // depends on control dependency: [if], data = [none]
}
if (suffix != null) {
nameBuilder.append(suffix); // depends on control dependency: [if], data = [(suffix]
}
return nameBuilder.toString();
} } |
public class class_name {
public void addListener(StageListener listener) {
if (logger.isDebugEnabled()) {
logger.debug("## pipeline[{}] add listener [{}]", getPipelineId(),
ClassUtils.getShortClassName(listener.getClass()));
}
this.listeners.add(listener);
} } | public class class_name {
public void addListener(StageListener listener) {
if (logger.isDebugEnabled()) {
logger.debug("## pipeline[{}] add listener [{}]", getPipelineId(),
ClassUtils.getShortClassName(listener.getClass())); // depends on control dependency: [if], data = [none]
}
this.listeners.add(listener);
} } |
public class class_name {
public java.util.List<String> getAttributeValues() {
if (attributeValues == null) {
attributeValues = new com.amazonaws.internal.SdkInternalList<String>();
}
return attributeValues;
} } | public class class_name {
public java.util.List<String> getAttributeValues() {
if (attributeValues == null) {
attributeValues = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return attributeValues;
} } |
public class class_name {
@Override
public EEnum getIfcWindowPanelPositionEnum() {
if (ifcWindowPanelPositionEnumEEnum == null) {
ifcWindowPanelPositionEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1103);
}
return ifcWindowPanelPositionEnumEEnum;
} } | public class class_name {
@Override
public EEnum getIfcWindowPanelPositionEnum() {
if (ifcWindowPanelPositionEnumEEnum == null) {
ifcWindowPanelPositionEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1103);
// depends on control dependency: [if], data = [none]
}
return ifcWindowPanelPositionEnumEEnum;
} } |
public class class_name {
public Class[] getClasses(final List<Class> classes, final String pckgname)
throws ClassNotFoundException
{
Enumeration resources;
ClassLoader cld;
String path;
try
{
// convert the package name to a path
path = pckgname.replace('.', '/');
cld = ClassUtils.getContextClassLoader();
if (cld == null)
{
throw new ClassNotFoundException("Can't get class loader.");
}
// find the entry points to the classpath
resources = cld.getResources(path);
if (resources == null || !resources.hasMoreElements())
{
throw new ClassNotFoundException("No resource for " + path);
}
}
catch (NullPointerException e)
{
throw (ClassNotFoundException) new ClassNotFoundException(pckgname
+ " (" + pckgname
+ ") does not appear to be a valid package", e);
}
catch (IOException e)
{
throw (ClassNotFoundException) new ClassNotFoundException(pckgname
+ " (" + pckgname
+ ") does not appear to be a valid package", e);
}
// iterate through all resources containing the package in question
while (resources.hasMoreElements())
{
URL resource = (URL) resources.nextElement();
URLConnection connection = null;
try
{
connection = resource.openConnection();
}
catch (IOException e)
{
throw (ClassNotFoundException) new ClassNotFoundException(
pckgname + " (" + pckgname
+ ") does not appear to be a valid package", e);
}
if (connection instanceof JarURLConnection)
{
// iterate trhough all the entries in the jar
JarURLConnection juc = (JarURLConnection) connection;
JarFile jarFile = null;
try
{
jarFile = juc.getJarFile();
}
catch (IOException e)
{
throw (ClassNotFoundException) new ClassNotFoundException(
pckgname + " (" + pckgname
+ ") does not appear to be a valid package",
e);
}
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements())
{
JarEntry jarEntry = entries.nextElement();
String entryName = jarEntry.getName();
if (!entryName.startsWith(path))
{
continue;
}
if (!entryName.toLowerCase().endsWith(".class"))
{
continue;
}
String className = filenameToClassname(entryName);
loadClass(classes, cld, className);
}
}
else
{
// iterate trhough all the children starting with the package name
File file;
try
{
file = new File(connection.getURL().toURI());
}
catch (URISyntaxException e)
{
log().log(Level.WARNING, "error loading directory " + connection, e);
continue;
}
listFilesRecursive(classes, file, cld, pckgname);
}
}
if (classes.size() < 1)
{
throw new ClassNotFoundException(pckgname
+ " does not appear to be a valid package");
}
Class[] resolvedClasses = new Class[classes.size()];
classes.toArray(resolvedClasses);
return resolvedClasses;
} } | public class class_name {
public Class[] getClasses(final List<Class> classes, final String pckgname)
throws ClassNotFoundException
{
Enumeration resources;
ClassLoader cld;
String path;
try
{
// convert the package name to a path
path = pckgname.replace('.', '/');
cld = ClassUtils.getContextClassLoader();
if (cld == null)
{
throw new ClassNotFoundException("Can't get class loader.");
}
// find the entry points to the classpath
resources = cld.getResources(path);
if (resources == null || !resources.hasMoreElements())
{
throw new ClassNotFoundException("No resource for " + path);
}
}
catch (NullPointerException e)
{
throw (ClassNotFoundException) new ClassNotFoundException(pckgname
+ " (" + pckgname
+ ") does not appear to be a valid package", e);
}
catch (IOException e)
{
throw (ClassNotFoundException) new ClassNotFoundException(pckgname
+ " (" + pckgname
+ ") does not appear to be a valid package", e);
}
// iterate through all resources containing the package in question
while (resources.hasMoreElements())
{
URL resource = (URL) resources.nextElement();
URLConnection connection = null;
try
{
connection = resource.openConnection();
}
catch (IOException e)
{
throw (ClassNotFoundException) new ClassNotFoundException(
pckgname + " (" + pckgname
+ ") does not appear to be a valid package", e);
}
if (connection instanceof JarURLConnection)
{
// iterate trhough all the entries in the jar
JarURLConnection juc = (JarURLConnection) connection;
JarFile jarFile = null;
try
{
jarFile = juc.getJarFile(); // depends on control dependency: [try], data = [none]
}
catch (IOException e)
{
throw (ClassNotFoundException) new ClassNotFoundException(
pckgname + " (" + pckgname
+ ") does not appear to be a valid package",
e);
} // depends on control dependency: [catch], data = [none]
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements())
{
JarEntry jarEntry = entries.nextElement();
String entryName = jarEntry.getName();
if (!entryName.startsWith(path))
{
continue;
}
if (!entryName.toLowerCase().endsWith(".class"))
{
continue;
}
String className = filenameToClassname(entryName);
loadClass(classes, cld, className); // depends on control dependency: [while], data = [none]
}
}
else
{
// iterate trhough all the children starting with the package name
File file;
try
{
file = new File(connection.getURL().toURI()); // depends on control dependency: [try], data = [none]
}
catch (URISyntaxException e)
{
log().log(Level.WARNING, "error loading directory " + connection, e);
continue;
} // depends on control dependency: [catch], data = [none]
listFilesRecursive(classes, file, cld, pckgname);
}
}
if (classes.size() < 1)
{
throw new ClassNotFoundException(pckgname
+ " does not appear to be a valid package");
}
Class[] resolvedClasses = new Class[classes.size()];
classes.toArray(resolvedClasses);
return resolvedClasses;
} } |
public class class_name {
public static BufferedReader getReader(Reader reader) {
if (null == reader) {
return null;
}
return (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader);
} } | public class class_name {
public static BufferedReader getReader(Reader reader) {
if (null == reader) {
return null;
// depends on control dependency: [if], data = [none]
}
return (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader);
} } |
public class class_name {
public static CipherRegistry registerCiphers(InputStream source) {
try {
if (source == null) {
throw new IllegalArgumentException("Cipher source not found.");
}
List<String> lines = IOUtils.readLines(source);
int start = -1;
int index = 0;
boolean error = false;
while (index < lines.size()) {
String line = lines.get(index);
if (line.trim().isEmpty()) {
lines.remove(index);
continue;
}
if (line.equals("-----BEGIN CIPHER-----")) {
if (start == -1) {
start = index + 1;
} else {
error = true;
}
} else if (line.equals("-----END CIPHER-----")) {
if (start > 0) {
int length = index - start;
String[] cipher = new String[length];
registerCipher(lines.subList(start, index).toArray(cipher));
start = -1;
} else {
error = true;
}
}
if (error) {
throw new IllegalArgumentException("Unexpected text in cipher: " + line);
}
index++;
}
if (start > 0) {
throw new IllegalArgumentException("Missing end cipher token.");
}
} catch (IOException e) {
throw MiscUtil.toUnchecked(e);
} finally {
IOUtils.closeQuietly(source);
}
return instance;
} } | public class class_name {
public static CipherRegistry registerCiphers(InputStream source) {
try {
if (source == null) {
throw new IllegalArgumentException("Cipher source not found.");
}
List<String> lines = IOUtils.readLines(source);
int start = -1;
int index = 0;
boolean error = false;
while (index < lines.size()) {
String line = lines.get(index);
if (line.trim().isEmpty()) {
lines.remove(index); // depends on control dependency: [if], data = [none]
continue;
}
if (line.equals("-----BEGIN CIPHER-----")) {
if (start == -1) {
start = index + 1; // depends on control dependency: [if], data = [none]
} else {
error = true; // depends on control dependency: [if], data = [none]
}
} else if (line.equals("-----END CIPHER-----")) {
if (start > 0) {
int length = index - start;
String[] cipher = new String[length];
registerCipher(lines.subList(start, index).toArray(cipher)); // depends on control dependency: [if], data = [(start]
start = -1; // depends on control dependency: [if], data = [none]
} else {
error = true; // depends on control dependency: [if], data = [none]
}
}
if (error) {
throw new IllegalArgumentException("Unexpected text in cipher: " + line);
}
index++; // depends on control dependency: [while], data = [none]
}
if (start > 0) {
throw new IllegalArgumentException("Missing end cipher token.");
}
} catch (IOException e) {
throw MiscUtil.toUnchecked(e);
} finally { // depends on control dependency: [catch], data = [none]
IOUtils.closeQuietly(source);
}
return instance;
} } |
public class class_name {
static Injector build(final GuiceRegistry registry,
ClassScannerFactory scannerFactory,
final List<PropertyFile> configs,
final List<GuiceRole> roles,
final GuiceSetup staticSetup,
final boolean autoLoadProperties,
final boolean autoLoadRoles,
final ClassLoader classloader)
{
final ServiceLoader<GuiceRole> loader = ServiceLoader.load(GuiceRole.class);
// Find additional guice roles from jar files using the Service Provider Interface
if (autoLoadRoles)
{
Iterator<GuiceRole> it = loader.iterator();
while (it.hasNext())
{
final GuiceRole role = it.next();
log.debug("Discovered guice role: " + role);
roles.add(role);
}
}
// Make sure that the first most basic level of properties is the system environment variables
configs.add(0, getAllEnvironmentVariables());
// Allow all GuiceRole implementations to add/remove/reorder configuration sources
for (GuiceRole role : roles)
{
log.debug("Adding requested guice role: " + role);
role.adjustConfigurations(configs);
}
GuiceConfig properties = new GuiceConfig();
// Generate a random instance ID for this instance of the guice environment
final String instanceId = SimpleId.alphanumeric(32);
// Make the randomly generated instance id available to others
properties.set(GuiceProperties.INSTANCE_ID, instanceId);
for (PropertyFile config : configs)
properties.setAll(config);
// Load all the core property files?
if (autoLoadProperties)
{
applyConfigs(classloader, properties);
}
// This is a bit of a hack really, but let's insert the GuiceRole for network config if network config is enabled
if (hasNetworkConfiguration(properties))
{
final NetworkConfigGuiceRole role = new NetworkConfigGuiceRole();
roles.add(role);
}
// Read the override configuration property to find the override config file
// Load the override config file and pass that along too.
PropertyFile overrideFile = load(properties.get(GuiceProperties.OVERRIDE_FILE_PROPERTY));
// If there are overrides then rebuild the configuration to reflect it
if (overrideFile != null)
{
log.debug("Applying overrides: " + overrideFile.getFile());
properties.setOverrides(overrideFile.toMap());
}
// Set up the class scanner factory (if the scanner property is set and one has not been provided)
if (scannerFactory == null)
{
List<String> packages = properties.getList(GuiceProperties.SCAN_PACKAGES, Collections.emptyList());
if (packages != null && !packages.isEmpty())
scannerFactory = new ClassScannerFactory(packages.toArray(new String[packages.size()]));
else
throw new IllegalArgumentException("Property " + GuiceProperties.SCAN_PACKAGES + " has not been set!");
}
final GuiceSetup setup;
if (staticSetup == null)
{
// Load the Setup property and load the Setup class
final Class<? extends GuiceSetup> setupClass = getClass(properties, GuiceSetup.class, GuiceProperties.SETUP_PROPERTY);
try
{
if (setupClass == null)
throw new IllegalArgumentException("Could not find a setup class!");
setup = setupClass.newInstance();
log.debug("Constructed GuiceSetup: " + setupClass);
}
catch (InstantiationException | IllegalAccessException e)
{
throw new IllegalArgumentException("Error constructing instance of " + setupClass, e);
}
}
else
{
log.debug("Using static GuiceSetup: " + staticSetup);
setup = staticSetup;
}
return createInjector(registry, scannerFactory, properties, setup, roles);
} } | public class class_name {
static Injector build(final GuiceRegistry registry,
ClassScannerFactory scannerFactory,
final List<PropertyFile> configs,
final List<GuiceRole> roles,
final GuiceSetup staticSetup,
final boolean autoLoadProperties,
final boolean autoLoadRoles,
final ClassLoader classloader)
{
final ServiceLoader<GuiceRole> loader = ServiceLoader.load(GuiceRole.class);
// Find additional guice roles from jar files using the Service Provider Interface
if (autoLoadRoles)
{
Iterator<GuiceRole> it = loader.iterator();
while (it.hasNext())
{
final GuiceRole role = it.next();
log.debug("Discovered guice role: " + role); // depends on control dependency: [while], data = [none]
roles.add(role); // depends on control dependency: [while], data = [none]
}
}
// Make sure that the first most basic level of properties is the system environment variables
configs.add(0, getAllEnvironmentVariables());
// Allow all GuiceRole implementations to add/remove/reorder configuration sources
for (GuiceRole role : roles)
{
log.debug("Adding requested guice role: " + role); // depends on control dependency: [for], data = [role]
role.adjustConfigurations(configs); // depends on control dependency: [for], data = [role]
}
GuiceConfig properties = new GuiceConfig();
// Generate a random instance ID for this instance of the guice environment
final String instanceId = SimpleId.alphanumeric(32);
// Make the randomly generated instance id available to others
properties.set(GuiceProperties.INSTANCE_ID, instanceId);
for (PropertyFile config : configs)
properties.setAll(config);
// Load all the core property files?
if (autoLoadProperties)
{
applyConfigs(classloader, properties); // depends on control dependency: [if], data = [none]
}
// This is a bit of a hack really, but let's insert the GuiceRole for network config if network config is enabled
if (hasNetworkConfiguration(properties))
{
final NetworkConfigGuiceRole role = new NetworkConfigGuiceRole();
roles.add(role); // depends on control dependency: [if], data = [none]
}
// Read the override configuration property to find the override config file
// Load the override config file and pass that along too.
PropertyFile overrideFile = load(properties.get(GuiceProperties.OVERRIDE_FILE_PROPERTY));
// If there are overrides then rebuild the configuration to reflect it
if (overrideFile != null)
{
log.debug("Applying overrides: " + overrideFile.getFile()); // depends on control dependency: [if], data = [none]
properties.setOverrides(overrideFile.toMap()); // depends on control dependency: [if], data = [(overrideFile]
}
// Set up the class scanner factory (if the scanner property is set and one has not been provided)
if (scannerFactory == null)
{
List<String> packages = properties.getList(GuiceProperties.SCAN_PACKAGES, Collections.emptyList());
if (packages != null && !packages.isEmpty())
scannerFactory = new ClassScannerFactory(packages.toArray(new String[packages.size()]));
else
throw new IllegalArgumentException("Property " + GuiceProperties.SCAN_PACKAGES + " has not been set!");
}
final GuiceSetup setup;
if (staticSetup == null)
{
// Load the Setup property and load the Setup class
final Class<? extends GuiceSetup> setupClass = getClass(properties, GuiceSetup.class, GuiceProperties.SETUP_PROPERTY);
try
{
if (setupClass == null)
throw new IllegalArgumentException("Could not find a setup class!");
setup = setupClass.newInstance();
log.debug("Constructed GuiceSetup: " + setupClass);
}
catch (InstantiationException | IllegalAccessException e) // depends on control dependency: [if], data = [none]
{
throw new IllegalArgumentException("Error constructing instance of " + setupClass, e);
}
}
else
{
log.debug("Using static GuiceSetup: " + staticSetup); // depends on control dependency: [if], data = [none]
setup = staticSetup; // depends on control dependency: [if], data = [none]
}
return createInjector(registry, scannerFactory, properties, setup, roles);
} } |
public class class_name {
protected List<Field> getWholeFieldList(Class<?> clazz) {
final List<Field> fieldList = new ArrayList<Field>();
for (Class<?> target = clazz; target != null && target != Object.class; target = target.getSuperclass()) {
final Field[] fields = target.getDeclaredFields();
for (Field method : fields) {
fieldList.add(method);
}
}
return fieldList;
} } | public class class_name {
protected List<Field> getWholeFieldList(Class<?> clazz) {
final List<Field> fieldList = new ArrayList<Field>();
for (Class<?> target = clazz; target != null && target != Object.class; target = target.getSuperclass()) {
final Field[] fields = target.getDeclaredFields();
for (Field method : fields) {
fieldList.add(method); // depends on control dependency: [for], data = [method]
}
}
return fieldList;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public Query select(String selection) {
checkNotEmpty(selection, "Selection must not be empty.");
if (countDots(selection) >= 2) {
throw new IllegalArgumentException("Cannot request children of fields. "
+ "('fields.author'(✔) vs. 'fields.author.name'(✖))");
}
if (selection.startsWith("fields.") && !hasContentTypeSet()) {
throw new IllegalStateException("Cannot use field selection without "
+ "specifying a content type first. Use '.withContentType(\"{typeid}\")' first.");
}
if (selection.startsWith("sys.") || "sys".equals(selection)) {
if (params.containsKey(PARAMETER_SELECT)) {
// nothing to be done here, a select is already present
} else {
params.put(PARAMETER_SELECT, "sys");
}
} else if (params.containsKey(PARAMETER_SELECT)) {
params.put(PARAMETER_SELECT, params.get(PARAMETER_SELECT) + "," + selection);
} else {
params.put(PARAMETER_SELECT, "sys," + selection);
}
return (Query) this;
} } | public class class_name {
@SuppressWarnings("unchecked")
public Query select(String selection) {
checkNotEmpty(selection, "Selection must not be empty.");
if (countDots(selection) >= 2) {
throw new IllegalArgumentException("Cannot request children of fields. "
+ "('fields.author'(✔) vs. 'fields.author.name'(✖))");
}
if (selection.startsWith("fields.") && !hasContentTypeSet()) {
throw new IllegalStateException("Cannot use field selection without "
+ "specifying a content type first. Use '.withContentType(\"{typeid}\")' first.");
}
if (selection.startsWith("sys.") || "sys".equals(selection)) {
if (params.containsKey(PARAMETER_SELECT)) {
// nothing to be done here, a select is already present
} else {
params.put(PARAMETER_SELECT, "sys"); // depends on control dependency: [if], data = [none]
}
} else if (params.containsKey(PARAMETER_SELECT)) {
params.put(PARAMETER_SELECT, params.get(PARAMETER_SELECT) + "," + selection); // depends on control dependency: [if], data = [none]
} else {
params.put(PARAMETER_SELECT, "sys," + selection); // depends on control dependency: [if], data = [none]
}
return (Query) this;
} } |
public class class_name {
public DescribeOrderableClusterOptionsResult withOrderableClusterOptions(OrderableClusterOption... orderableClusterOptions) {
if (this.orderableClusterOptions == null) {
setOrderableClusterOptions(new com.amazonaws.internal.SdkInternalList<OrderableClusterOption>(orderableClusterOptions.length));
}
for (OrderableClusterOption ele : orderableClusterOptions) {
this.orderableClusterOptions.add(ele);
}
return this;
} } | public class class_name {
public DescribeOrderableClusterOptionsResult withOrderableClusterOptions(OrderableClusterOption... orderableClusterOptions) {
if (this.orderableClusterOptions == null) {
setOrderableClusterOptions(new com.amazonaws.internal.SdkInternalList<OrderableClusterOption>(orderableClusterOptions.length)); // depends on control dependency: [if], data = [none]
}
for (OrderableClusterOption ele : orderableClusterOptions) {
this.orderableClusterOptions.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@SuppressWarnings("rawtypes")
public MonetaryAmountFactory getMonetaryAmountFactory() {
MonetaryAmountFactory factory = get(MonetaryAmountFactory.class);
if (factory == null) {
return Monetary.getDefaultAmountFactory();
}
return factory;
} } | public class class_name {
@SuppressWarnings("rawtypes")
public MonetaryAmountFactory getMonetaryAmountFactory() {
MonetaryAmountFactory factory = get(MonetaryAmountFactory.class);
if (factory == null) {
return Monetary.getDefaultAmountFactory(); // depends on control dependency: [if], data = [none]
}
return factory;
} } |
public class class_name {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
this.setControlValue(value);
if (isSelected && !hasFocus) {
this.setForeground(table.getSelectionForeground());
this.setBackground(table.getSelectionBackground());
}
else {
this.setForeground(table.getForeground());
this.setBackground(table.getBackground());
}
return this;
} } | public class class_name {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
this.setControlValue(value);
if (isSelected && !hasFocus) {
this.setForeground(table.getSelectionForeground()); // depends on control dependency: [if], data = [none]
this.setBackground(table.getSelectionBackground()); // depends on control dependency: [if], data = [none]
}
else {
this.setForeground(table.getForeground()); // depends on control dependency: [if], data = [none]
this.setBackground(table.getBackground()); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
private Object readArray(JsonObject object) throws IOException
{
final List<Object> array = new ArrayList();
while (true)
{
final Object o = readValue(object);
if (o != EMPTY_ARRAY)
{
array.add(o);
}
final int c = skipWhitespaceRead();
if (c == ']')
{
break;
}
else if (c != ',')
{
error("Expected ',' or ']' inside array");
}
}
return array.toArray();
} } | public class class_name {
private Object readArray(JsonObject object) throws IOException
{
final List<Object> array = new ArrayList();
while (true)
{
final Object o = readValue(object);
if (o != EMPTY_ARRAY)
{
array.add(o); // depends on control dependency: [if], data = [(o]
}
final int c = skipWhitespaceRead();
if (c == ']')
{
break;
}
else if (c != ',')
{
error("Expected ',' or ']' inside array"); // depends on control dependency: [if], data = [none]
}
}
return array.toArray();
} } |
public class class_name {
private void appendPropertyChanges(DiffBuilder diff, NodePair pair, final Optional<CommitMetadata> commitMetadata) {
List<JaversProperty> nodeProperties = pair.getProperties();
for (JaversProperty property : nodeProperties) {
//optimization, skip all appenders if null on both sides
if (pair.isNullOnBothSides(property)) {
continue;
}
JaversType javersType = property.getType();
appendChanges(diff, pair, property, javersType, commitMetadata);
}
} } | public class class_name {
private void appendPropertyChanges(DiffBuilder diff, NodePair pair, final Optional<CommitMetadata> commitMetadata) {
List<JaversProperty> nodeProperties = pair.getProperties();
for (JaversProperty property : nodeProperties) {
//optimization, skip all appenders if null on both sides
if (pair.isNullOnBothSides(property)) {
continue;
}
JaversType javersType = property.getType();
appendChanges(diff, pair, property, javersType, commitMetadata); // depends on control dependency: [for], data = [property]
}
} } |
public class class_name {
protected Object retriveValue(Class<?> type, RowData row, Column col) {
if (StringUtils.isNotEmpty(col.getPattern())) {
if (ClassUtils.isAssignable(type, Map.class)) {
return row.getCellValuesAsMap(col.getPattern(), 1, col.getReplace());
} else {
return row.getCellValues(col.getPattern(), col.getReplace(),
col.isExcludeEmptyValue());
}
} else {
if (ClassUtils.isAssignable(type, Integer.class)) {
return row.getInt(col.getName(), col.getReplace());
} else if (ClassUtils.isAssignable(type, Boolean.class)) {
return row.getBoolean(col.getName(), col.getTrueStr(), col.getReplace());
} else {
return row.getCellValue(col.getName(), col.getReplace());
}
}
} } | public class class_name {
protected Object retriveValue(Class<?> type, RowData row, Column col) {
if (StringUtils.isNotEmpty(col.getPattern())) {
if (ClassUtils.isAssignable(type, Map.class)) {
return row.getCellValuesAsMap(col.getPattern(), 1, col.getReplace());
// depends on control dependency: [if], data = [none]
} else {
return row.getCellValues(col.getPattern(), col.getReplace(),
col.isExcludeEmptyValue());
// depends on control dependency: [if], data = [none]
}
} else {
if (ClassUtils.isAssignable(type, Integer.class)) {
return row.getInt(col.getName(), col.getReplace());
// depends on control dependency: [if], data = [none]
} else if (ClassUtils.isAssignable(type, Boolean.class)) {
return row.getBoolean(col.getName(), col.getTrueStr(), col.getReplace());
// depends on control dependency: [if], data = [none]
} else {
return row.getCellValue(col.getName(), col.getReplace());
// depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static void equalizeSizes(JComponent[] components) {
Dimension targetSize = new Dimension(0, 0);
for (int i = 0; i < components.length; i++) {
JComponent comp = components[i];
Dimension compSize = comp.getPreferredSize();
double width = Math.max(targetSize.getWidth(), compSize.getWidth());
double height = Math.max(targetSize.getHeight(), compSize.getHeight());
targetSize.setSize(width, height);
}
setSizes(components, targetSize);
} } | public class class_name {
public static void equalizeSizes(JComponent[] components) {
Dimension targetSize = new Dimension(0, 0);
for (int i = 0; i < components.length; i++) {
JComponent comp = components[i];
Dimension compSize = comp.getPreferredSize();
double width = Math.max(targetSize.getWidth(), compSize.getWidth());
double height = Math.max(targetSize.getHeight(), compSize.getHeight());
targetSize.setSize(width, height); // depends on control dependency: [for], data = [none]
}
setSizes(components, targetSize);
} } |
public class class_name {
public void setData(byte[] data) {
if (immutable) {
throw new IllegalStateException(ERR_MSG_IMMUTABLE);
}
if (data == null) {
this.data = null;
} else {
setData(data, 0, data.length);
}
} } | public class class_name {
public void setData(byte[] data) {
if (immutable) {
throw new IllegalStateException(ERR_MSG_IMMUTABLE);
}
if (data == null) {
this.data = null; // depends on control dependency: [if], data = [none]
} else {
setData(data, 0, data.length); // depends on control dependency: [if], data = [(data]
}
} } |
public class class_name {
private void adaptMessageTextSize() {
if (getRootView() != null) {
View messageView = getRootView().findViewById(android.R.id.message);
if (messageView instanceof TextView) {
TextView messageTextView = (TextView) messageView;
if (TextUtils.isEmpty(getDialog().getTitle())) {
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getContext().getResources()
.getDimensionPixelSize(R.dimen.dialog_message_text_size_large));
} else {
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getContext().getResources().getDimensionPixelSize(
R.dimen.dialog_message_text_size_normal));
}
}
}
} } | public class class_name {
private void adaptMessageTextSize() {
if (getRootView() != null) {
View messageView = getRootView().findViewById(android.R.id.message);
if (messageView instanceof TextView) {
TextView messageTextView = (TextView) messageView;
if (TextUtils.isEmpty(getDialog().getTitle())) {
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getContext().getResources()
.getDimensionPixelSize(R.dimen.dialog_message_text_size_large)); // depends on control dependency: [if], data = [none]
} else {
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getContext().getResources().getDimensionPixelSize(
R.dimen.dialog_message_text_size_normal)); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
private void applySettings() {
linkContainer.reset();
WLink exampleLink = new WLink();
exampleLink.setText(tfLinkLabel.getText());
final String url = tfUrlField.getValue();
if ("".equals(url) || !isValidUrl(url)) {
tfUrlField.setText(URL);
exampleLink.setUrl(URL);
} else {
exampleLink.setUrl(url);
}
exampleLink.setRenderAsButton(cbRenderAsButton.isSelected());
exampleLink.setText(tfLinkLabel.getText());
if (cbSetImage.isSelected()) {
WImage linkImage = new WImage("/image/attachment.png", "Add attachment");
exampleLink.setImage(linkImage.getImage());
exampleLink.setImagePosition((ImagePosition) ddImagePosition.getSelected());
}
exampleLink.setDisabled(cbDisabled.isSelected());
if (tfAccesskey.getText() != null && tfAccesskey.getText().length() > 0) {
exampleLink.setAccessKey(tfAccesskey.getText().toCharArray()[0]);
}
if (cbOpenNew.isSelected()) {
exampleLink.setOpenNewWindow(true);
exampleLink.setTargetWindowName("_blank");
} else {
exampleLink.setOpenNewWindow(false);
}
linkContainer.add(exampleLink);
} } | public class class_name {
private void applySettings() {
linkContainer.reset();
WLink exampleLink = new WLink();
exampleLink.setText(tfLinkLabel.getText());
final String url = tfUrlField.getValue();
if ("".equals(url) || !isValidUrl(url)) {
tfUrlField.setText(URL); // depends on control dependency: [if], data = [none]
exampleLink.setUrl(URL); // depends on control dependency: [if], data = [none]
} else {
exampleLink.setUrl(url); // depends on control dependency: [if], data = [none]
}
exampleLink.setRenderAsButton(cbRenderAsButton.isSelected());
exampleLink.setText(tfLinkLabel.getText());
if (cbSetImage.isSelected()) {
WImage linkImage = new WImage("/image/attachment.png", "Add attachment");
exampleLink.setImage(linkImage.getImage()); // depends on control dependency: [if], data = [none]
exampleLink.setImagePosition((ImagePosition) ddImagePosition.getSelected()); // depends on control dependency: [if], data = [none]
}
exampleLink.setDisabled(cbDisabled.isSelected());
if (tfAccesskey.getText() != null && tfAccesskey.getText().length() > 0) {
exampleLink.setAccessKey(tfAccesskey.getText().toCharArray()[0]); // depends on control dependency: [if], data = [(tfAccesskey.getText()]
}
if (cbOpenNew.isSelected()) {
exampleLink.setOpenNewWindow(true); // depends on control dependency: [if], data = [none]
exampleLink.setTargetWindowName("_blank"); // depends on control dependency: [if], data = [none]
} else {
exampleLink.setOpenNewWindow(false); // depends on control dependency: [if], data = [none]
}
linkContainer.add(exampleLink);
} } |
public class class_name {
public static DualInputSemanticProperties readDualConstantAnnotations(UserCodeWrapper<?> udf) {
ImplicitlyForwardingTwoInputSemanticProperties semanticProperties = new ImplicitlyForwardingTwoInputSemanticProperties();
// get readSet annotation from stub
ConstantFieldsFirst constantSet1Annotation = udf.getUserCodeAnnotation(ConstantFieldsFirst.class);
ConstantFieldsSecond constantSet2Annotation = udf.getUserCodeAnnotation(ConstantFieldsSecond.class);
// get readSet annotation from stub
ConstantFieldsFirstExcept notConstantSet1Annotation = udf.getUserCodeAnnotation(ConstantFieldsFirstExcept.class);
ConstantFieldsSecondExcept notConstantSet2Annotation = udf.getUserCodeAnnotation(ConstantFieldsSecondExcept.class);
if (notConstantSet1Annotation != null && constantSet1Annotation != null) {
throw new RuntimeException("Either ConstantFieldsFirst or ConstantFieldsFirstExcept can be specified, not both.");
}
if (constantSet2Annotation != null && notConstantSet2Annotation != null) {
throw new RuntimeException("Either ConstantFieldsSecond or ConstantFieldsSecondExcept can be specified, not both.");
}
// extract readSets from annotations
if(notConstantSet1Annotation != null) {
semanticProperties.setImplicitlyForwardingFirstExcept(new FieldSet(notConstantSet1Annotation.value()));
}
if(notConstantSet2Annotation != null) {
semanticProperties.setImplicitlyForwardingSecondExcept(new FieldSet(notConstantSet2Annotation.value()));
}
// extract readSets from annotations
if (constantSet1Annotation != null) {
for(int value: constantSet1Annotation.value()) {
semanticProperties.addForwardedField1(value, value);
}
}
if (constantSet2Annotation != null) {
for(int value: constantSet2Annotation.value()) {
semanticProperties.addForwardedField2(value, value);
}
}
return semanticProperties;
} } | public class class_name {
public static DualInputSemanticProperties readDualConstantAnnotations(UserCodeWrapper<?> udf) {
ImplicitlyForwardingTwoInputSemanticProperties semanticProperties = new ImplicitlyForwardingTwoInputSemanticProperties();
// get readSet annotation from stub
ConstantFieldsFirst constantSet1Annotation = udf.getUserCodeAnnotation(ConstantFieldsFirst.class);
ConstantFieldsSecond constantSet2Annotation = udf.getUserCodeAnnotation(ConstantFieldsSecond.class);
// get readSet annotation from stub
ConstantFieldsFirstExcept notConstantSet1Annotation = udf.getUserCodeAnnotation(ConstantFieldsFirstExcept.class);
ConstantFieldsSecondExcept notConstantSet2Annotation = udf.getUserCodeAnnotation(ConstantFieldsSecondExcept.class);
if (notConstantSet1Annotation != null && constantSet1Annotation != null) {
throw new RuntimeException("Either ConstantFieldsFirst or ConstantFieldsFirstExcept can be specified, not both.");
}
if (constantSet2Annotation != null && notConstantSet2Annotation != null) {
throw new RuntimeException("Either ConstantFieldsSecond or ConstantFieldsSecondExcept can be specified, not both.");
}
// extract readSets from annotations
if(notConstantSet1Annotation != null) {
semanticProperties.setImplicitlyForwardingFirstExcept(new FieldSet(notConstantSet1Annotation.value())); // depends on control dependency: [if], data = [(notConstantSet1Annotation]
}
if(notConstantSet2Annotation != null) {
semanticProperties.setImplicitlyForwardingSecondExcept(new FieldSet(notConstantSet2Annotation.value())); // depends on control dependency: [if], data = [(notConstantSet2Annotation]
}
// extract readSets from annotations
if (constantSet1Annotation != null) {
for(int value: constantSet1Annotation.value()) {
semanticProperties.addForwardedField1(value, value); // depends on control dependency: [for], data = [value]
}
}
if (constantSet2Annotation != null) {
for(int value: constantSet2Annotation.value()) {
semanticProperties.addForwardedField2(value, value); // depends on control dependency: [for], data = [value]
}
}
return semanticProperties;
} } |
public class class_name {
static boolean shouldSkipOp(long currentTransactionId, FSEditLogOp op) {
if (currentTransactionId == -1
|| op.getTransactionId() > currentTransactionId) {
return false;
}
return true;
} } | public class class_name {
static boolean shouldSkipOp(long currentTransactionId, FSEditLogOp op) {
if (currentTransactionId == -1
|| op.getTransactionId() > currentTransactionId) {
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
@Override
public Constructor<T> getConstructor() {
if (this.constructor == null) {
try {
this.constructor = this.managedClass.getConstructor((Class<?>[]) null);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
}
}
return this.constructor;
} } | public class class_name {
@Override
public Constructor<T> getConstructor() {
if (this.constructor == null) {
try {
this.constructor = this.managedClass.getConstructor((Class<?>[]) null); // depends on control dependency: [try], data = [none]
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
} // depends on control dependency: [catch], data = [none]
}
return this.constructor;
} } |
public class class_name {
public static String extractBeanArchiveId(String beanArchiveRef, String base, String separator) {
beanArchiveRef = beanArchiveRef.replace('\\', '/');
StringBuilder id = new StringBuilder();
id.append(base);
id.append(BeanArchives.BEAN_ARCHIVE_ID_BASE_DELIMITER);
if (beanArchiveRef.contains(separator)) {
id.append(beanArchiveRef.substring(beanArchiveRef.indexOf(separator), beanArchiveRef.length()));
} else {
id.append(beanArchiveRef);
}
return id.toString();
} } | public class class_name {
public static String extractBeanArchiveId(String beanArchiveRef, String base, String separator) {
beanArchiveRef = beanArchiveRef.replace('\\', '/');
StringBuilder id = new StringBuilder();
id.append(base);
id.append(BeanArchives.BEAN_ARCHIVE_ID_BASE_DELIMITER);
if (beanArchiveRef.contains(separator)) {
id.append(beanArchiveRef.substring(beanArchiveRef.indexOf(separator), beanArchiveRef.length())); // depends on control dependency: [if], data = [none]
} else {
id.append(beanArchiveRef); // depends on control dependency: [if], data = [none]
}
return id.toString();
} } |
public class class_name {
public Field createFieldTable(
Field formFieldParam,
Form formDefinitionParam,
boolean sumDecimalsParam)
{
if(formFieldParam != null && this.serviceTicket != null)
{
formFieldParam.setServiceTicket(this.serviceTicket);
}
if(formFieldParam != null)
{
formFieldParam.setTypeAsEnum(Field.Type.Table);
formFieldParam.setTypeMetaData(
this.getMetaDataForTableField(
formDefinitionParam, sumDecimalsParam));
}
return new Field(this.putJson(
formFieldParam, WS.Path.FormField.Version1.formFieldCreate()));
} } | public class class_name {
public Field createFieldTable(
Field formFieldParam,
Form formDefinitionParam,
boolean sumDecimalsParam)
{
if(formFieldParam != null && this.serviceTicket != null)
{
formFieldParam.setServiceTicket(this.serviceTicket); // depends on control dependency: [if], data = [none]
}
if(formFieldParam != null)
{
formFieldParam.setTypeAsEnum(Field.Type.Table); // depends on control dependency: [if], data = [none]
formFieldParam.setTypeMetaData(
this.getMetaDataForTableField(
formDefinitionParam, sumDecimalsParam)); // depends on control dependency: [if], data = [none]
}
return new Field(this.putJson(
formFieldParam, WS.Path.FormField.Version1.formFieldCreate()));
} } |
public class class_name {
public static Identifier fromCompoundString(String identifier) {
String[] parts = identifier.split("/");
if (parts.length != 2) {
String[] rhs = identifier.split(":");
if (rhs.length != 2) {
return new Identifier(new Repository(identifier), null);
} else {
return new Identifier(new Repository(rhs[0]), rhs[1]);
}
}
String[] rhs = parts[1].split(":");
if (rhs.length != 2) {
return new Identifier(new Repository(identifier), null);
}
return new Identifier(new Repository(parts[0] + "/" + rhs[0]), rhs[1]);
} } | public class class_name {
public static Identifier fromCompoundString(String identifier) {
String[] parts = identifier.split("/");
if (parts.length != 2) {
String[] rhs = identifier.split(":");
if (rhs.length != 2) {
return new Identifier(new Repository(identifier), null); // depends on control dependency: [if], data = [none]
} else {
return new Identifier(new Repository(rhs[0]), rhs[1]); // depends on control dependency: [if], data = [none]
}
}
String[] rhs = parts[1].split(":");
if (rhs.length != 2) {
return new Identifier(new Repository(identifier), null); // depends on control dependency: [if], data = [none]
}
return new Identifier(new Repository(parts[0] + "/" + rhs[0]), rhs[1]);
} } |
public class class_name {
public LoginConfigType<WebAppType<T>> getOrCreateLoginConfig()
{
List<Node> nodeList = childNode.get("login-config");
if (nodeList != null && nodeList.size() > 0)
{
return new LoginConfigTypeImpl<WebAppType<T>>(this, "login-config", childNode, nodeList.get(0));
}
return createLoginConfig();
} } | public class class_name {
public LoginConfigType<WebAppType<T>> getOrCreateLoginConfig()
{
List<Node> nodeList = childNode.get("login-config");
if (nodeList != null && nodeList.size() > 0)
{
return new LoginConfigTypeImpl<WebAppType<T>>(this, "login-config", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createLoginConfig();
} } |
public class class_name {
public void removeAllBusStops() {
for (final BusStop busStop : this.validBusStops) {
busStop.setContainer(null);
busStop.setEventFirable(true);
}
for (final BusStop busStop : this.invalidBusStops) {
busStop.setContainer(null);
busStop.setEventFirable(true);
}
this.validBusStops.clear();
this.invalidBusStops.clear();
fireShapeChanged(new BusChangeEvent(this,
BusChangeEventType.ALL_STOPS_REMOVED,
null,
-1,
"shape", //$NON-NLS-1$
null,
null));
revalidate();
} } | public class class_name {
public void removeAllBusStops() {
for (final BusStop busStop : this.validBusStops) {
busStop.setContainer(null); // depends on control dependency: [for], data = [busStop]
busStop.setEventFirable(true); // depends on control dependency: [for], data = [busStop]
}
for (final BusStop busStop : this.invalidBusStops) {
busStop.setContainer(null); // depends on control dependency: [for], data = [busStop]
busStop.setEventFirable(true); // depends on control dependency: [for], data = [busStop]
}
this.validBusStops.clear();
this.invalidBusStops.clear();
fireShapeChanged(new BusChangeEvent(this,
BusChangeEventType.ALL_STOPS_REMOVED,
null,
-1,
"shape", //$NON-NLS-1$
null,
null));
revalidate();
} } |
public class class_name {
public void marshall(ListTypesRequest listTypesRequest, ProtocolMarshaller protocolMarshaller) {
if (listTypesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listTypesRequest.getApiId(), APIID_BINDING);
protocolMarshaller.marshall(listTypesRequest.getFormat(), FORMAT_BINDING);
protocolMarshaller.marshall(listTypesRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listTypesRequest.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(ListTypesRequest listTypesRequest, ProtocolMarshaller protocolMarshaller) {
if (listTypesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listTypesRequest.getApiId(), APIID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listTypesRequest.getFormat(), FORMAT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listTypesRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listTypesRequest.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 {
public String get(String key) {
try {
return bundle.getString(key);
}catch(MissingResourceException e) {
logger.warn("Missing resource.", e);
return key;
}
} } | public class class_name {
public String get(String key) {
try {
return bundle.getString(key); // depends on control dependency: [try], data = [none]
}catch(MissingResourceException e) {
logger.warn("Missing resource.", e);
return key;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public synchronized double variance()
{
long n = 0;
double mean = 0;
double s = 0.0;
for (double x : m_times.m_values)
{
n++;
double delta = x - mean;
mean += delta / n;
s += delta * (x - mean);
}
return (s / n);
} } | public class class_name {
public synchronized double variance()
{
long n = 0;
double mean = 0;
double s = 0.0;
for (double x : m_times.m_values)
{
n++; // depends on control dependency: [for], data = [none]
double delta = x - mean;
mean += delta / n; // depends on control dependency: [for], data = [none]
s += delta * (x - mean); // depends on control dependency: [for], data = [x]
}
return (s / n);
} } |
public class class_name {
@SuppressWarnings("WeakerAccess")
public int floorSum(long sum) {
int floor = IntAVLTree.NIL;
for (int node = tree.root(); node != IntAVLTree.NIL; ) {
final int left = tree.left(node);
final long leftCount = aggregatedCounts[left];
if (leftCount <= sum) {
floor = node;
sum -= leftCount + count(node);
node = tree.right(node);
} else {
node = tree.left(node);
}
}
return floor;
} } | public class class_name {
@SuppressWarnings("WeakerAccess")
public int floorSum(long sum) {
int floor = IntAVLTree.NIL;
for (int node = tree.root(); node != IntAVLTree.NIL; ) {
final int left = tree.left(node);
final long leftCount = aggregatedCounts[left];
if (leftCount <= sum) {
floor = node; // depends on control dependency: [if], data = [none]
sum -= leftCount + count(node); // depends on control dependency: [if], data = [none]
node = tree.right(node); // depends on control dependency: [if], data = [none]
} else {
node = tree.left(node); // depends on control dependency: [if], data = [none]
}
}
return floor;
} } |
public class class_name {
@Override
public void onError(SocializeException error) {
if(error instanceof SocializeApiError) {
SocializeApiError aError = (SocializeApiError) error;
if(aError.getResultCode() != 404) {
SocializeLogger.e(error.getMessage(), error);
}
}
else {
SocializeLogger.e(error.getMessage(), error);
}
onNotLiked();
} } | public class class_name {
@Override
public void onError(SocializeException error) {
if(error instanceof SocializeApiError) {
SocializeApiError aError = (SocializeApiError) error;
if(aError.getResultCode() != 404) {
SocializeLogger.e(error.getMessage(), error); // depends on control dependency: [if], data = [none]
}
}
else {
SocializeLogger.e(error.getMessage(), error); // depends on control dependency: [if], data = [none]
}
onNotLiked();
} } |
public class class_name {
public static List<String> convertPinyinList2TonePinyinList(List<Pinyin> pinyinList)
{
List<String> tonePinyinList = new ArrayList<String>(pinyinList.size());
for (Pinyin pinyin : pinyinList)
{
tonePinyinList.add(pinyin.getPinyinWithToneMark());
}
return tonePinyinList;
} } | public class class_name {
public static List<String> convertPinyinList2TonePinyinList(List<Pinyin> pinyinList)
{
List<String> tonePinyinList = new ArrayList<String>(pinyinList.size());
for (Pinyin pinyin : pinyinList)
{
tonePinyinList.add(pinyin.getPinyinWithToneMark()); // depends on control dependency: [for], data = [pinyin]
}
return tonePinyinList;
} } |
public class class_name {
protected void checkProducerMethod(EnhancedAnnotatedMethod<T, ? super X> method) {
if (method.getEnhancedParameters(Observes.class).size() > 0) {
throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@Observes", this.method,
Formats.formatAsStackTraceElement(method.getJavaMember()));
} else if (method.getEnhancedParameters(ObservesAsync.class).size() > 0) {
throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@ObservesAsync", this.method,
Formats.formatAsStackTraceElement(method.getJavaMember()));
} else if (method.getEnhancedParameters(Disposes.class).size() > 0) {
throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@Disposes", this.method,
Formats.formatAsStackTraceElement(method.getJavaMember()));
} else if (getDeclaringBean() instanceof SessionBean<?> && !Modifier.isStatic(method.slim().getJavaMember().getModifiers())) {
boolean methodDeclaredOnTypes = false;
for (Type type : getDeclaringBean().getTypes()) {
Class<?> clazz = Reflections.getRawType(type);
try {
AccessController.doPrivileged(new GetMethodAction(clazz, method.getName(), method.getParameterTypesAsArray()));
methodDeclaredOnTypes = true;
break;
} catch (PrivilegedActionException ignored) {
}
}
if (!methodDeclaredOnTypes) {
throw BeanLogger.LOG.methodNotBusinessMethod("Producer", this, getDeclaringBean(), Formats.formatAsStackTraceElement(method.getJavaMember()));
}
}
} } | public class class_name {
protected void checkProducerMethod(EnhancedAnnotatedMethod<T, ? super X> method) {
if (method.getEnhancedParameters(Observes.class).size() > 0) {
throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@Observes", this.method,
Formats.formatAsStackTraceElement(method.getJavaMember()));
} else if (method.getEnhancedParameters(ObservesAsync.class).size() > 0) {
throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@ObservesAsync", this.method,
Formats.formatAsStackTraceElement(method.getJavaMember()));
} else if (method.getEnhancedParameters(Disposes.class).size() > 0) {
throw BeanLogger.LOG.inconsistentAnnotationsOnMethod(PRODUCER_ANNOTATION, "@Disposes", this.method,
Formats.formatAsStackTraceElement(method.getJavaMember()));
} else if (getDeclaringBean() instanceof SessionBean<?> && !Modifier.isStatic(method.slim().getJavaMember().getModifiers())) {
boolean methodDeclaredOnTypes = false;
for (Type type : getDeclaringBean().getTypes()) {
Class<?> clazz = Reflections.getRawType(type);
try {
AccessController.doPrivileged(new GetMethodAction(clazz, method.getName(), method.getParameterTypesAsArray())); // depends on control dependency: [try], data = [none]
methodDeclaredOnTypes = true; // depends on control dependency: [try], data = [none]
break;
} catch (PrivilegedActionException ignored) {
} // depends on control dependency: [catch], data = [none]
}
if (!methodDeclaredOnTypes) {
throw BeanLogger.LOG.methodNotBusinessMethod("Producer", this, getDeclaringBean(), Formats.formatAsStackTraceElement(method.getJavaMember()));
}
}
} } |
public class class_name {
public double toDoubleValue(final Object value, final double defaultValue) {
final Double result = toDouble(value);
if (result == null) {
return defaultValue;
}
return result.doubleValue();
} } | public class class_name {
public double toDoubleValue(final Object value, final double defaultValue) {
final Double result = toDouble(value);
if (result == null) {
return defaultValue; // depends on control dependency: [if], data = [none]
}
return result.doubleValue();
} } |
public class class_name {
int numOpenSegments() {
int numOpen = 0;
for (PBDSegment segment : m_segments.values()) {
if (!segment.isClosed()) {
numOpen++;
}
}
return numOpen;
} } | public class class_name {
int numOpenSegments() {
int numOpen = 0;
for (PBDSegment segment : m_segments.values()) {
if (!segment.isClosed()) {
numOpen++; // depends on control dependency: [if], data = [none]
}
}
return numOpen;
} } |
public class class_name {
protected void handleAlert(Alert alert) {
if (LOGGEER.isDebugEnabled()) {
LOGGEER.debug("Accepting alert box with message: {}", alert.getText());
}
alert.accept();
} } | public class class_name {
protected void handleAlert(Alert alert) {
if (LOGGEER.isDebugEnabled()) {
LOGGEER.debug("Accepting alert box with message: {}", alert.getText()); // depends on control dependency: [if], data = [none]
}
alert.accept();
} } |
public class class_name {
private void putObject(String bucketName, String objectName, Long size, Object data,
Map<String, String> headerMap, ServerSideEncryption sse)
throws InvalidBucketNameException, NoSuchAlgorithmException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException,
InvalidArgumentException, InsufficientDataException {
boolean unknownSize = false;
// Add content type if not already set
if (headerMap.get("Content-Type") == null) {
headerMap.put("Content-Type", "application/octet-stream");
}
if (size == null) {
unknownSize = true;
size = MAX_OBJECT_SIZE;
}
if (size <= MIN_MULTIPART_SIZE) {
// Single put object.
if (sse != null) {
sse.marshal(headerMap);
}
putObject(bucketName, objectName, size.intValue(), data, null, 0, headerMap);
return;
}
/* Multipart upload */
int[] rv = calculateMultipartSize(size);
int partSize = rv[0];
int partCount = rv[1];
int lastPartSize = rv[2];
Part[] totalParts = new Part[partCount];
// if sse is requested set the necessary headers before we begin the multipart session.
if (sse != null) {
sse.marshal(headerMap);
}
// initiate new multipart upload.
String uploadId = initMultipartUpload(bucketName, objectName, headerMap);
try {
int expectedReadSize = partSize;
for (int partNumber = 1; partNumber <= partCount; partNumber++) {
if (partNumber == partCount) {
expectedReadSize = lastPartSize;
}
// For unknown sized stream, check available size.
int availableSize = 0;
if (unknownSize) {
// Check whether data is available one byte more than expectedReadSize.
availableSize = getAvailableSize(data, expectedReadSize + 1);
// If availableSize is less or equal to expectedReadSize, then we reached last part.
if (availableSize <= expectedReadSize) {
// If it is first part, do single put object.
if (partNumber == 1) {
putObject(bucketName, objectName, availableSize, data, null, 0, headerMap);
return;
}
expectedReadSize = availableSize;
partCount = partNumber;
}
}
// In multi-part uploads, Set encryption headers in the case of SSE-C.
Map<String, String> encryptionHeaders = new HashMap<>();
if (sse != null && sse.getType() == ServerSideEncryption.Type.SSE_C) {
sse.marshal(encryptionHeaders);
}
String etag = putObject(bucketName, objectName, expectedReadSize, data,
uploadId, partNumber, encryptionHeaders);
totalParts[partNumber - 1] = new Part(partNumber, etag);
}
// All parts have been uploaded, complete the multipart upload.
completeMultipart(bucketName, objectName, uploadId, totalParts);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
abortMultipartUpload(bucketName, objectName, uploadId);
throw e;
}
} } | public class class_name {
private void putObject(String bucketName, String objectName, Long size, Object data,
Map<String, String> headerMap, ServerSideEncryption sse)
throws InvalidBucketNameException, NoSuchAlgorithmException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException,
InvalidArgumentException, InsufficientDataException {
boolean unknownSize = false;
// Add content type if not already set
if (headerMap.get("Content-Type") == null) {
headerMap.put("Content-Type", "application/octet-stream");
}
if (size == null) {
unknownSize = true;
size = MAX_OBJECT_SIZE;
}
if (size <= MIN_MULTIPART_SIZE) {
// Single put object.
if (sse != null) {
sse.marshal(headerMap);
}
putObject(bucketName, objectName, size.intValue(), data, null, 0, headerMap);
return;
}
/* Multipart upload */
int[] rv = calculateMultipartSize(size);
int partSize = rv[0];
int partCount = rv[1];
int lastPartSize = rv[2];
Part[] totalParts = new Part[partCount];
// if sse is requested set the necessary headers before we begin the multipart session.
if (sse != null) {
sse.marshal(headerMap);
}
// initiate new multipart upload.
String uploadId = initMultipartUpload(bucketName, objectName, headerMap);
try {
int expectedReadSize = partSize;
for (int partNumber = 1; partNumber <= partCount; partNumber++) {
if (partNumber == partCount) {
expectedReadSize = lastPartSize; // depends on control dependency: [if], data = [none]
}
// For unknown sized stream, check available size.
int availableSize = 0;
if (unknownSize) {
// Check whether data is available one byte more than expectedReadSize.
availableSize = getAvailableSize(data, expectedReadSize + 1); // depends on control dependency: [if], data = [none]
// If availableSize is less or equal to expectedReadSize, then we reached last part.
if (availableSize <= expectedReadSize) {
// If it is first part, do single put object.
if (partNumber == 1) {
putObject(bucketName, objectName, availableSize, data, null, 0, headerMap); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
expectedReadSize = availableSize; // depends on control dependency: [if], data = [none]
partCount = partNumber; // depends on control dependency: [if], data = [none]
}
}
// In multi-part uploads, Set encryption headers in the case of SSE-C.
Map<String, String> encryptionHeaders = new HashMap<>();
if (sse != null && sse.getType() == ServerSideEncryption.Type.SSE_C) {
sse.marshal(encryptionHeaders); // depends on control dependency: [if], data = [none]
}
String etag = putObject(bucketName, objectName, expectedReadSize, data,
uploadId, partNumber, encryptionHeaders);
totalParts[partNumber - 1] = new Part(partNumber, etag); // depends on control dependency: [for], data = [partNumber]
}
// All parts have been uploaded, complete the multipart upload.
completeMultipart(bucketName, objectName, uploadId, totalParts);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
abortMultipartUpload(bucketName, objectName, uploadId);
throw e;
}
} } |
public class class_name {
public final AntlrDatatypeRuleToken ruleQualifiedName() throws RecognitionException {
AntlrDatatypeRuleToken current = new AntlrDatatypeRuleToken();
Token kw=null;
AntlrDatatypeRuleToken this_ValidID_0 = null;
AntlrDatatypeRuleToken this_ValidID_2 = null;
enterRule();
try {
// InternalSARL.g:15753:2: ( (this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )* ) )
// InternalSARL.g:15754:2: (this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )* )
{
// InternalSARL.g:15754:2: (this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )* )
// InternalSARL.g:15755:3: this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )*
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getQualifiedNameAccess().getValidIDParserRuleCall_0());
}
pushFollow(FOLLOW_93);
this_ValidID_0=ruleValidID();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current.merge(this_ValidID_0);
}
if ( state.backtracking==0 ) {
afterParserOrEnumRuleCall();
}
// InternalSARL.g:15765:3: ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )*
loop360:
do {
int alt360=2;
alt360 = dfa360.predict(input);
switch (alt360) {
case 1 :
// InternalSARL.g:15766:4: ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID
{
// InternalSARL.g:15766:4: ( ( '.' )=>kw= '.' )
// InternalSARL.g:15767:5: ( '.' )=>kw= '.'
{
kw=(Token)match(input,77,FOLLOW_3); if (state.failed) return current;
if ( state.backtracking==0 ) {
current.merge(kw);
newLeafNode(kw, grammarAccess.getQualifiedNameAccess().getFullStopKeyword_1_0());
}
}
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getQualifiedNameAccess().getValidIDParserRuleCall_1_1());
}
pushFollow(FOLLOW_93);
this_ValidID_2=ruleValidID();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current.merge(this_ValidID_2);
}
if ( state.backtracking==0 ) {
afterParserOrEnumRuleCall();
}
}
break;
default :
break loop360;
}
} while (true);
}
}
if ( state.backtracking==0 ) {
leaveRule();
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } | public class class_name {
public final AntlrDatatypeRuleToken ruleQualifiedName() throws RecognitionException {
AntlrDatatypeRuleToken current = new AntlrDatatypeRuleToken();
Token kw=null;
AntlrDatatypeRuleToken this_ValidID_0 = null;
AntlrDatatypeRuleToken this_ValidID_2 = null;
enterRule();
try {
// InternalSARL.g:15753:2: ( (this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )* ) )
// InternalSARL.g:15754:2: (this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )* )
{
// InternalSARL.g:15754:2: (this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )* )
// InternalSARL.g:15755:3: this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )*
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getQualifiedNameAccess().getValidIDParserRuleCall_0()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_93);
this_ValidID_0=ruleValidID();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current.merge(this_ValidID_0); // depends on control dependency: [if], data = [none]
}
if ( state.backtracking==0 ) {
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
// InternalSARL.g:15765:3: ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )*
loop360:
do {
int alt360=2;
alt360 = dfa360.predict(input);
switch (alt360) {
case 1 :
// InternalSARL.g:15766:4: ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID
{
// InternalSARL.g:15766:4: ( ( '.' )=>kw= '.' )
// InternalSARL.g:15767:5: ( '.' )=>kw= '.'
{
kw=(Token)match(input,77,FOLLOW_3); if (state.failed) return current;
if ( state.backtracking==0 ) {
current.merge(kw); // depends on control dependency: [if], data = [none]
newLeafNode(kw, grammarAccess.getQualifiedNameAccess().getFullStopKeyword_1_0()); // depends on control dependency: [if], data = [none]
}
}
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getQualifiedNameAccess().getValidIDParserRuleCall_1_1()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_93);
this_ValidID_2=ruleValidID();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current.merge(this_ValidID_2); // depends on control dependency: [if], data = [none]
}
if ( state.backtracking==0 ) {
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
}
break;
default :
break loop360;
}
} while (true);
}
}
if ( state.backtracking==0 ) {
leaveRule(); // depends on control dependency: [if], data = [none]
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } |
public class class_name {
private void updateLetsEncrypt() {
getReport().println(Messages.get().container(Messages.RPT_STARTING_LETSENCRYPT_UPDATE_0));
CmsLetsEncryptConfiguration config = OpenCms.getLetsEncryptConfig();
if ((config == null) || !config.isValidAndEnabled()) {
return;
}
CmsSiteConfigToLetsEncryptConfigConverter converter = new CmsSiteConfigToLetsEncryptConfigConverter(config);
boolean ok = converter.run(getReport(), OpenCms.getSiteManager());
if (ok) {
getReport().println(
org.opencms.ui.apps.Messages.get().container(org.opencms.ui.apps.Messages.RPT_LETSENCRYPT_FINISHED_0),
I_CmsReport.FORMAT_OK);
}
} } | public class class_name {
private void updateLetsEncrypt() {
getReport().println(Messages.get().container(Messages.RPT_STARTING_LETSENCRYPT_UPDATE_0));
CmsLetsEncryptConfiguration config = OpenCms.getLetsEncryptConfig();
if ((config == null) || !config.isValidAndEnabled()) {
return; // depends on control dependency: [if], data = [none]
}
CmsSiteConfigToLetsEncryptConfigConverter converter = new CmsSiteConfigToLetsEncryptConfigConverter(config);
boolean ok = converter.run(getReport(), OpenCms.getSiteManager());
if (ok) {
getReport().println(
org.opencms.ui.apps.Messages.get().container(org.opencms.ui.apps.Messages.RPT_LETSENCRYPT_FINISHED_0),
I_CmsReport.FORMAT_OK); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(ListCommandsRequest listCommandsRequest, ProtocolMarshaller protocolMarshaller) {
if (listCommandsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listCommandsRequest.getCommandId(), COMMANDID_BINDING);
protocolMarshaller.marshall(listCommandsRequest.getInstanceId(), INSTANCEID_BINDING);
protocolMarshaller.marshall(listCommandsRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(listCommandsRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(listCommandsRequest.getFilters(), FILTERS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ListCommandsRequest listCommandsRequest, ProtocolMarshaller protocolMarshaller) {
if (listCommandsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listCommandsRequest.getCommandId(), COMMANDID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listCommandsRequest.getInstanceId(), INSTANCEID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listCommandsRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listCommandsRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listCommandsRequest.getFilters(), FILTERS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public List<TriggerFiredResult> triggersFired(List<OperableTrigger> triggers, Jedis jedis) throws JobPersistenceException, ClassNotFoundException {
List<TriggerFiredResult> results = new ArrayList<>();
for (OperableTrigger trigger : triggers) {
final String triggerHashKey = redisSchema.triggerHashKey(trigger.getKey());
logger.debug(String.format("Trigger %s fired.", triggerHashKey));
Pipeline pipe = jedis.pipelined();
Response<Boolean> triggerExistsResponse = pipe.exists(triggerHashKey);
Response<Double> triggerAcquiredResponse = pipe.zscore(redisSchema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey);
pipe.sync();
if(!triggerExistsResponse.get() || triggerAcquiredResponse.get() == null){
// the trigger does not exist or the trigger is not acquired
if(!triggerExistsResponse.get()){
logger.debug(String.format("Trigger %s does not exist.", triggerHashKey));
}
else{
logger.debug(String.format("Trigger %s was not acquired.", triggerHashKey));
}
continue;
}
Calendar calendar = null;
final String calendarName = trigger.getCalendarName();
if(calendarName != null){
calendar = retrieveCalendar(calendarName, jedis);
if(calendar == null){
continue;
}
}
final Date previousFireTime = trigger.getPreviousFireTime();
trigger.triggered(calendar);
// set the trigger state to WAITING
final Date nextFireDate = trigger.getNextFireTime();
long nextFireTime = 0;
if (nextFireDate != null) {
nextFireTime = nextFireDate.getTime();
jedis.hset(triggerHashKey, TRIGGER_NEXT_FIRE_TIME, Long.toString(nextFireTime));
setTriggerState(RedisTriggerState.WAITING, (double) nextFireTime, triggerHashKey, jedis);
}
JobDetail job = retrieveJob(trigger.getJobKey(), jedis);
TriggerFiredBundle triggerFiredBundle = new TriggerFiredBundle(job, trigger, calendar, false, new Date(), previousFireTime, previousFireTime, nextFireDate);
// handling jobs for which concurrent execution is disallowed
if (isJobConcurrentExecutionDisallowed(job.getJobClass())){
if (logger.isTraceEnabled()) {
logger.trace("Firing trigger " + trigger.getKey() + " for job " + job.getKey() + " for which concurrent execution is disallowed. Adding job to blocked jobs set.");
}
final String jobHashKey = redisSchema.jobHashKey(trigger.getJobKey());
final String jobTriggerSetKey = redisSchema.jobTriggersSetKey(job.getKey());
for (String nonConcurrentTriggerHashKey : jedis.smembers(jobTriggerSetKey)) {
Double score = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.WAITING), nonConcurrentTriggerHashKey);
if(score != null){
if (logger.isTraceEnabled()) {
logger.trace("Setting state of trigger " + trigger.getKey() + " for non-concurrent job " + job.getKey() + " to BLOCKED.");
}
setTriggerState(RedisTriggerState.BLOCKED, score, nonConcurrentTriggerHashKey, jedis);
// setting trigger state removes trigger locks, so re-lock
lockTrigger(redisSchema.triggerKey(nonConcurrentTriggerHashKey), jedis);
}
else{
score = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.PAUSED), nonConcurrentTriggerHashKey);
if(score != null){
if (logger.isTraceEnabled()) {
logger.trace("Setting state of trigger " + trigger.getKey() + " for non-concurrent job " + job.getKey() + " to PAUSED_BLOCKED.");
}
setTriggerState(RedisTriggerState.PAUSED_BLOCKED, score, nonConcurrentTriggerHashKey, jedis);
// setting trigger state removes trigger locks, so re-lock
lockTrigger(redisSchema.triggerKey(nonConcurrentTriggerHashKey), jedis);
}
}
}
pipe = jedis.pipelined();
pipe.set(redisSchema.jobBlockedKey(job.getKey()), schedulerInstanceId);
pipe.sadd(redisSchema.blockedJobsSet(), jobHashKey);
pipe.sync();
} else if(nextFireDate != null){
jedis.hset(triggerHashKey, TRIGGER_NEXT_FIRE_TIME, Long.toString(nextFireTime));
logger.debug(String.format("Releasing trigger %s with next fire time %s. Setting state to WAITING.", triggerHashKey, nextFireTime));
setTriggerState(RedisTriggerState.WAITING, (double) nextFireTime, triggerHashKey, jedis);
} else {
jedis.hset(triggerHashKey, TRIGGER_NEXT_FIRE_TIME, "");
unsetTriggerState(triggerHashKey, jedis);
}
jedis.hset(triggerHashKey, TRIGGER_PREVIOUS_FIRE_TIME, Long.toString(System.currentTimeMillis()));
results.add(new TriggerFiredResult(triggerFiredBundle));
}
return results;
} } | public class class_name {
@Override
public List<TriggerFiredResult> triggersFired(List<OperableTrigger> triggers, Jedis jedis) throws JobPersistenceException, ClassNotFoundException {
List<TriggerFiredResult> results = new ArrayList<>();
for (OperableTrigger trigger : triggers) {
final String triggerHashKey = redisSchema.triggerHashKey(trigger.getKey());
logger.debug(String.format("Trigger %s fired.", triggerHashKey));
Pipeline pipe = jedis.pipelined();
Response<Boolean> triggerExistsResponse = pipe.exists(triggerHashKey);
Response<Double> triggerAcquiredResponse = pipe.zscore(redisSchema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey);
pipe.sync();
if(!triggerExistsResponse.get() || triggerAcquiredResponse.get() == null){
// the trigger does not exist or the trigger is not acquired
if(!triggerExistsResponse.get()){
logger.debug(String.format("Trigger %s does not exist.", triggerHashKey)); // depends on control dependency: [if], data = [none]
}
else{
logger.debug(String.format("Trigger %s was not acquired.", triggerHashKey)); // depends on control dependency: [if], data = [none]
}
continue;
}
Calendar calendar = null;
final String calendarName = trigger.getCalendarName();
if(calendarName != null){
calendar = retrieveCalendar(calendarName, jedis); // depends on control dependency: [if], data = [(calendarName]
if(calendar == null){
continue;
}
}
final Date previousFireTime = trigger.getPreviousFireTime();
trigger.triggered(calendar);
// set the trigger state to WAITING
final Date nextFireDate = trigger.getNextFireTime();
long nextFireTime = 0;
if (nextFireDate != null) {
nextFireTime = nextFireDate.getTime(); // depends on control dependency: [if], data = [none]
jedis.hset(triggerHashKey, TRIGGER_NEXT_FIRE_TIME, Long.toString(nextFireTime)); // depends on control dependency: [if], data = [none]
setTriggerState(RedisTriggerState.WAITING, (double) nextFireTime, triggerHashKey, jedis); // depends on control dependency: [if], data = [none]
}
JobDetail job = retrieveJob(trigger.getJobKey(), jedis);
TriggerFiredBundle triggerFiredBundle = new TriggerFiredBundle(job, trigger, calendar, false, new Date(), previousFireTime, previousFireTime, nextFireDate);
// handling jobs for which concurrent execution is disallowed
if (isJobConcurrentExecutionDisallowed(job.getJobClass())){
if (logger.isTraceEnabled()) {
logger.trace("Firing trigger " + trigger.getKey() + " for job " + job.getKey() + " for which concurrent execution is disallowed. Adding job to blocked jobs set."); // depends on control dependency: [if], data = [none]
}
final String jobHashKey = redisSchema.jobHashKey(trigger.getJobKey());
final String jobTriggerSetKey = redisSchema.jobTriggersSetKey(job.getKey());
for (String nonConcurrentTriggerHashKey : jedis.smembers(jobTriggerSetKey)) {
Double score = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.WAITING), nonConcurrentTriggerHashKey);
if(score != null){
if (logger.isTraceEnabled()) {
logger.trace("Setting state of trigger " + trigger.getKey() + " for non-concurrent job " + job.getKey() + " to BLOCKED."); // depends on control dependency: [if], data = [none]
}
setTriggerState(RedisTriggerState.BLOCKED, score, nonConcurrentTriggerHashKey, jedis); // depends on control dependency: [if], data = [none]
// setting trigger state removes trigger locks, so re-lock
lockTrigger(redisSchema.triggerKey(nonConcurrentTriggerHashKey), jedis); // depends on control dependency: [if], data = [none]
}
else{
score = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.PAUSED), nonConcurrentTriggerHashKey); // depends on control dependency: [if], data = [none]
if(score != null){
if (logger.isTraceEnabled()) {
logger.trace("Setting state of trigger " + trigger.getKey() + " for non-concurrent job " + job.getKey() + " to PAUSED_BLOCKED."); // depends on control dependency: [if], data = [none]
}
setTriggerState(RedisTriggerState.PAUSED_BLOCKED, score, nonConcurrentTriggerHashKey, jedis); // depends on control dependency: [if], data = [none]
// setting trigger state removes trigger locks, so re-lock
lockTrigger(redisSchema.triggerKey(nonConcurrentTriggerHashKey), jedis); // depends on control dependency: [if], data = [none]
}
}
}
pipe = jedis.pipelined(); // depends on control dependency: [if], data = [none]
pipe.set(redisSchema.jobBlockedKey(job.getKey()), schedulerInstanceId); // depends on control dependency: [if], data = [none]
pipe.sadd(redisSchema.blockedJobsSet(), jobHashKey); // depends on control dependency: [if], data = [none]
pipe.sync(); // depends on control dependency: [if], data = [none]
} else if(nextFireDate != null){
jedis.hset(triggerHashKey, TRIGGER_NEXT_FIRE_TIME, Long.toString(nextFireTime)); // depends on control dependency: [if], data = [none]
logger.debug(String.format("Releasing trigger %s with next fire time %s. Setting state to WAITING.", triggerHashKey, nextFireTime)); // depends on control dependency: [if], data = [none]
setTriggerState(RedisTriggerState.WAITING, (double) nextFireTime, triggerHashKey, jedis); // depends on control dependency: [if], data = [none]
} else {
jedis.hset(triggerHashKey, TRIGGER_NEXT_FIRE_TIME, ""); // depends on control dependency: [if], data = [none]
unsetTriggerState(triggerHashKey, jedis); // depends on control dependency: [if], data = [none]
}
jedis.hset(triggerHashKey, TRIGGER_PREVIOUS_FIRE_TIME, Long.toString(System.currentTimeMillis()));
results.add(new TriggerFiredResult(triggerFiredBundle));
}
return results;
} } |
public class class_name {
public void warn(String format, Object arg1, Object arg2) {
if (!logger.isWarnEnabled())
return;
if (instanceofLAL) {
String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
} else {
logger.warn(format, arg1, arg2);
}
} } | public class class_name {
public void warn(String format, Object arg1, Object arg2) {
if (!logger.isWarnEnabled())
return;
if (instanceofLAL) {
String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null); // depends on control dependency: [if], data = [none]
} else {
logger.warn(format, arg1, arg2); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@FFDCIgnore({IllegalCharsetNameException.class, UnsupportedCharsetException.class})
public static String mapCharset(String enc, String deflt) {
if (enc == null) {
return deflt;
}
//older versions of tomcat don't properly parse ContentType headers with stuff
//after charset=StandardCharsets.UTF_8
int idx = enc.indexOf(";");
if (idx != -1) {
enc = enc.substring(0, idx);
}
// Charsets can be quoted. But it's quite certain that they can't have escaped quoted or
// anything like that.
enc = charsetPattern.matcher(enc).replaceAll("").trim();
if ("".equals(enc)) {
return deflt;
}
String newenc = encodings.get(enc);
if (newenc == null) {
try {
newenc = Charset.forName(enc).name();
} catch (IllegalCharsetNameException icne) {
return null;
} catch (UnsupportedCharsetException uce) {
return null;
}
String tmpenc = encodings.putIfAbsent(enc, newenc);
if (tmpenc != null) {
newenc = tmpenc;
}
}
return newenc;
} } | public class class_name {
@FFDCIgnore({IllegalCharsetNameException.class, UnsupportedCharsetException.class})
public static String mapCharset(String enc, String deflt) {
if (enc == null) {
return deflt; // depends on control dependency: [if], data = [none]
}
//older versions of tomcat don't properly parse ContentType headers with stuff
//after charset=StandardCharsets.UTF_8
int idx = enc.indexOf(";");
if (idx != -1) {
enc = enc.substring(0, idx); // depends on control dependency: [if], data = [none]
}
// Charsets can be quoted. But it's quite certain that they can't have escaped quoted or
// anything like that.
enc = charsetPattern.matcher(enc).replaceAll("").trim();
if ("".equals(enc)) {
return deflt; // depends on control dependency: [if], data = [none]
}
String newenc = encodings.get(enc);
if (newenc == null) {
try {
newenc = Charset.forName(enc).name(); // depends on control dependency: [try], data = [none]
} catch (IllegalCharsetNameException icne) {
return null;
} catch (UnsupportedCharsetException uce) { // depends on control dependency: [catch], data = [none]
return null;
} // depends on control dependency: [catch], data = [none]
String tmpenc = encodings.putIfAbsent(enc, newenc);
if (tmpenc != null) {
newenc = tmpenc; // depends on control dependency: [if], data = [none]
}
}
return newenc;
} } |
public class class_name {
private ITag createFileMeta() {
log.debug("createFileMeta");
// create tag for onMetaData event
IoBuffer in = IoBuffer.allocate(1024);
in.setAutoExpand(true);
Output out = new Output(in);
out.writeString("onMetaData");
Map<Object, Object> props = new HashMap<Object, Object>();
props.put("audiocodecid", IoConstants.FLAG_FORMAT_MP3);
props.put("canSeekToEnd", true);
// set id3 meta data if it exists
if (metaData != null) {
if (metaData.artist != null) {
props.put("artist", metaData.artist);
}
if (metaData.album != null) {
props.put("album", metaData.album);
}
if (metaData.songName != null) {
props.put("songName", metaData.songName);
}
if (metaData.genre != null) {
props.put("genre", metaData.genre);
}
if (metaData.year != null) {
props.put("year", metaData.year);
}
if (metaData.track != null) {
props.put("track", metaData.track);
}
if (metaData.comment != null) {
props.put("comment", metaData.comment);
}
if (metaData.duration != null) {
props.put("duration", metaData.duration);
}
if (metaData.channels != null) {
props.put("channels", metaData.channels);
}
if (metaData.sampleRate != null) {
props.put("samplerate", metaData.sampleRate);
}
if (metaData.hasCoverImage()) {
Map<Object, Object> covr = new HashMap<>(1);
covr.put("covr", new Object[] { metaData.getCovr() });
props.put("tags", covr);
}
//clear meta for gc
metaData = null;
}
log.debug("Metadata properties map: {}", props);
// check for duration
if (!props.containsKey("duration")) {
// generate it from framemeta
if (frameMeta != null) {
props.put("duration", frameMeta.timestamps[frameMeta.timestamps.length - 1] / 1000.0);
} else {
log.debug("Frame meta was null");
}
}
// set datarate
if (dataRate > 0) {
props.put("audiodatarate", dataRate);
}
out.writeMap(props);
in.flip();
// meta-data
ITag result = new Tag(IoConstants.TYPE_METADATA, 0, in.limit(), null, prevSize);
result.setBody(in);
return result;
} } | public class class_name {
private ITag createFileMeta() {
log.debug("createFileMeta");
// create tag for onMetaData event
IoBuffer in = IoBuffer.allocate(1024);
in.setAutoExpand(true);
Output out = new Output(in);
out.writeString("onMetaData");
Map<Object, Object> props = new HashMap<Object, Object>();
props.put("audiocodecid", IoConstants.FLAG_FORMAT_MP3);
props.put("canSeekToEnd", true);
// set id3 meta data if it exists
if (metaData != null) {
if (metaData.artist != null) {
props.put("artist", metaData.artist);
// depends on control dependency: [if], data = [none]
}
if (metaData.album != null) {
props.put("album", metaData.album);
// depends on control dependency: [if], data = [none]
}
if (metaData.songName != null) {
props.put("songName", metaData.songName);
// depends on control dependency: [if], data = [none]
}
if (metaData.genre != null) {
props.put("genre", metaData.genre);
// depends on control dependency: [if], data = [none]
}
if (metaData.year != null) {
props.put("year", metaData.year);
// depends on control dependency: [if], data = [none]
}
if (metaData.track != null) {
props.put("track", metaData.track);
// depends on control dependency: [if], data = [none]
}
if (metaData.comment != null) {
props.put("comment", metaData.comment);
// depends on control dependency: [if], data = [none]
}
if (metaData.duration != null) {
props.put("duration", metaData.duration);
// depends on control dependency: [if], data = [none]
}
if (metaData.channels != null) {
props.put("channels", metaData.channels);
// depends on control dependency: [if], data = [none]
}
if (metaData.sampleRate != null) {
props.put("samplerate", metaData.sampleRate);
// depends on control dependency: [if], data = [none]
}
if (metaData.hasCoverImage()) {
Map<Object, Object> covr = new HashMap<>(1);
covr.put("covr", new Object[] { metaData.getCovr() });
// depends on control dependency: [if], data = [none]
props.put("tags", covr);
// depends on control dependency: [if], data = [none]
}
//clear meta for gc
metaData = null;
// depends on control dependency: [if], data = [none]
}
log.debug("Metadata properties map: {}", props);
// check for duration
if (!props.containsKey("duration")) {
// generate it from framemeta
if (frameMeta != null) {
props.put("duration", frameMeta.timestamps[frameMeta.timestamps.length - 1] / 1000.0);
// depends on control dependency: [if], data = [none]
} else {
log.debug("Frame meta was null");
// depends on control dependency: [if], data = [none]
}
}
// set datarate
if (dataRate > 0) {
props.put("audiodatarate", dataRate);
// depends on control dependency: [if], data = [none]
}
out.writeMap(props);
in.flip();
// meta-data
ITag result = new Tag(IoConstants.TYPE_METADATA, 0, in.limit(), null, prevSize);
result.setBody(in);
return result;
} } |
public class class_name {
@Override
public int compareTo(Object object)
{
if(!(object instanceof User))
{
return -1;
}
User user = (User)object;
return getLastName().compareTo(user.getLastName());
} } | public class class_name {
@Override
public int compareTo(Object object)
{
if(!(object instanceof User))
{
return -1;
// depends on control dependency: [if], data = [none]
}
User user = (User)object;
return getLastName().compareTo(user.getLastName());
} } |
public class class_name {
private String getAuthTokenFromRequest(HttpServletRequest httpRequest) {
String authToken = httpRequest.getHeader(AUTH_TOKEN_HEADER_KEY);
if (authToken == null) {
// token can also exist as request parameter
authToken = httpRequest.getParameter(AUTH_TOKEN_PARAMETER_KEY);
}
return authToken;
} } | public class class_name {
private String getAuthTokenFromRequest(HttpServletRequest httpRequest) {
String authToken = httpRequest.getHeader(AUTH_TOKEN_HEADER_KEY);
if (authToken == null) {
// token can also exist as request parameter
authToken = httpRequest.getParameter(AUTH_TOKEN_PARAMETER_KEY); // depends on control dependency: [if], data = [none]
}
return authToken;
} } |
public class class_name {
private synchronized void setAllMapping() {
//int count_final_sol = 1;
//System.out.println("Output of the final FinalMappings: ");
try {
List<Map<Integer, Integer>> sol = FinalMappings.getInstance().getFinalMapping();
int counter = 0;
for (Map<Integer, Integer> finalSolution : sol) {
TreeMap<Integer, Integer> atomMappings = new TreeMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> solutions : finalSolution.entrySet()) {
int iIndex = solutions.getKey().intValue();
int jIndex = solutions.getValue().intValue();
if (rOnPFlag) {
atomMappings.put(iIndex, jIndex);
} else {
atomMappings.put(jIndex, iIndex);
}
}
if (!allMCS.contains(atomMappings)) {
allMCS.add(counter++, atomMappings);
}
}
} catch (Exception ex) {
ex.getCause();
}
} } | public class class_name {
private synchronized void setAllMapping() {
//int count_final_sol = 1;
//System.out.println("Output of the final FinalMappings: ");
try {
List<Map<Integer, Integer>> sol = FinalMappings.getInstance().getFinalMapping();
int counter = 0;
for (Map<Integer, Integer> finalSolution : sol) {
TreeMap<Integer, Integer> atomMappings = new TreeMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> solutions : finalSolution.entrySet()) {
int iIndex = solutions.getKey().intValue();
int jIndex = solutions.getValue().intValue();
if (rOnPFlag) {
atomMappings.put(iIndex, jIndex); // depends on control dependency: [if], data = [none]
} else {
atomMappings.put(jIndex, iIndex); // depends on control dependency: [if], data = [none]
}
}
if (!allMCS.contains(atomMappings)) {
allMCS.add(counter++, atomMappings); // depends on control dependency: [if], data = [none]
}
}
} catch (Exception ex) {
ex.getCause();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected static void buildGetMethod(final Class< ? > originalClass,
final String className,
final Class< ? > superClass,
final Method getterMethod,
final ClassWriter cw) {
final Class< ? > fieldType = getterMethod.getReturnType();
Method overridingMethod;
try {
overridingMethod = superClass.getMethod( getOverridingGetMethodName( fieldType ),
InternalWorkingMemory.class, Object.class );
} catch ( final Exception e ) {
throw new RuntimeException( "This is a bug. Please report back to JBoss Rules team.",
e );
}
final MethodVisitor mv = cw.visitMethod( Opcodes.ACC_PUBLIC,
overridingMethod.getName(),
Type.getMethodDescriptor( overridingMethod ),
null,
null );
mv.visitCode();
final Label l0 = new Label();
mv.visitLabel( l0 );
mv.visitVarInsn( Opcodes.ALOAD,
2 );
mv.visitTypeInsn( Opcodes.CHECKCAST,
Type.getInternalName( originalClass ) );
if ( originalClass.isInterface() ) {
mv.visitMethodInsn( Opcodes.INVOKEINTERFACE,
Type.getInternalName( originalClass ),
getterMethod.getName(),
Type.getMethodDescriptor( getterMethod ) );
} else {
mv.visitMethodInsn( Opcodes.INVOKEVIRTUAL,
Type.getInternalName( originalClass ),
getterMethod.getName(),
Type.getMethodDescriptor( getterMethod ) );
}
mv.visitInsn( Type.getType( fieldType ).getOpcode( Opcodes.IRETURN ) );
final Label l1 = new Label();
mv.visitLabel( l1 );
mv.visitLocalVariable( "this",
"L" + className + ";",
null,
l0,
l1,
0 );
mv.visitLocalVariable( "workingMemory",
Type.getDescriptor( InternalWorkingMemory.class ),
null,
l0,
l1,
1 );
mv.visitLocalVariable( "object",
Type.getDescriptor( Object.class ),
null,
l0,
l1,
2 );
mv.visitMaxs( 0,
0 );
mv.visitEnd();
} } | public class class_name {
protected static void buildGetMethod(final Class< ? > originalClass,
final String className,
final Class< ? > superClass,
final Method getterMethod,
final ClassWriter cw) {
final Class< ? > fieldType = getterMethod.getReturnType();
Method overridingMethod;
try {
overridingMethod = superClass.getMethod( getOverridingGetMethodName( fieldType ),
InternalWorkingMemory.class, Object.class );
} catch ( final Exception e ) {
throw new RuntimeException( "This is a bug. Please report back to JBoss Rules team.",
e );
}
final MethodVisitor mv = cw.visitMethod( Opcodes.ACC_PUBLIC,
overridingMethod.getName(),
Type.getMethodDescriptor( overridingMethod ),
null,
null );
mv.visitCode();
final Label l0 = new Label();
mv.visitLabel( l0 );
mv.visitVarInsn( Opcodes.ALOAD,
2 );
mv.visitTypeInsn( Opcodes.CHECKCAST,
Type.getInternalName( originalClass ) );
if ( originalClass.isInterface() ) {
mv.visitMethodInsn( Opcodes.INVOKEINTERFACE,
Type.getInternalName( originalClass ),
getterMethod.getName(),
Type.getMethodDescriptor( getterMethod ) ); // depends on control dependency: [if], data = [none]
} else {
mv.visitMethodInsn( Opcodes.INVOKEVIRTUAL,
Type.getInternalName( originalClass ),
getterMethod.getName(),
Type.getMethodDescriptor( getterMethod ) ); // depends on control dependency: [if], data = [none]
}
mv.visitInsn( Type.getType( fieldType ).getOpcode( Opcodes.IRETURN ) );
final Label l1 = new Label();
mv.visitLabel( l1 );
mv.visitLocalVariable( "this",
"L" + className + ";",
null,
l0,
l1,
0 );
mv.visitLocalVariable( "workingMemory",
Type.getDescriptor( InternalWorkingMemory.class ),
null,
l0,
l1,
1 );
mv.visitLocalVariable( "object",
Type.getDescriptor( Object.class ),
null,
l0,
l1,
2 );
mv.visitMaxs( 0,
0 );
mv.visitEnd();
} } |
public class class_name {
public static IJavaSearchScope createSearchScope(IJavaProject project, Class<?> type, boolean onlySubTypes) {
try {
final IType superType = project.findType(type.getName());
return SearchEngine.createStrictHierarchyScope(
project,
superType,
// only sub types
onlySubTypes,
// include the type
true,
null);
} catch (JavaModelException e) {
SARLEclipsePlugin.getDefault().log(e);
}
return SearchEngine.createJavaSearchScope(new IJavaElement[] {project});
} } | public class class_name {
public static IJavaSearchScope createSearchScope(IJavaProject project, Class<?> type, boolean onlySubTypes) {
try {
final IType superType = project.findType(type.getName());
return SearchEngine.createStrictHierarchyScope(
project,
superType,
// only sub types
onlySubTypes,
// include the type
true,
null); // depends on control dependency: [try], data = [none]
} catch (JavaModelException e) {
SARLEclipsePlugin.getDefault().log(e);
} // depends on control dependency: [catch], data = [none]
return SearchEngine.createJavaSearchScope(new IJavaElement[] {project});
} } |
public class class_name {
@Nonnull
public ELoginResult loginUser (@Nullable final IUser aUser,
@Nullable final String sPlainTextPassword,
@Nullable final Iterable <String> aRequiredRoleIDs)
{
if (aUser == null)
return ELoginResult.USER_NOT_EXISTING;
final String sUserID = aUser.getID ();
// Deleted user?
if (aUser.isDeleted ())
{
AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-deleted");
return _onLoginError (sUserID, ELoginResult.USER_IS_DELETED);
}
// Disabled user?
if (aUser.isDisabled ())
{
AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-disabled");
return _onLoginError (sUserID, ELoginResult.USER_IS_DISABLED);
}
// Check the password
final UserManager aUserMgr = PhotonSecurityManager.getUserMgr ();
if (!aUserMgr.areUserIDAndPasswordValid (sUserID, sPlainTextPassword))
{
AuditHelper.onAuditExecuteFailure ("login", sUserID, "invalid-password");
return _onLoginError (sUserID, ELoginResult.INVALID_PASSWORD);
}
// Are all roles present?
if (!SecurityHelper.hasUserAllRoles (sUserID, aRequiredRoleIDs))
{
AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-missing-required-roles", aRequiredRoleIDs);
return _onLoginError (sUserID, ELoginResult.USER_IS_MISSING_ROLE);
}
// Check if the password hash needs to be updated
final String sExistingPasswordHashAlgorithmName = aUser.getPasswordHash ().getAlgorithmName ();
final String sDefaultPasswordHashAlgorithmName = GlobalPasswordSettings.getPasswordHashCreatorManager ()
.getDefaultPasswordHashCreatorAlgorithmName ();
if (!sExistingPasswordHashAlgorithmName.equals (sDefaultPasswordHashAlgorithmName))
{
// This implicitly implies using the default hash creator algorithm
// This automatically saves the file
aUserMgr.setUserPassword (sUserID, sPlainTextPassword);
if (LOGGER.isInfoEnabled ())
LOGGER.info ("Updated password hash of " +
_getUserIDLogText (sUserID) +
" from algorithm '" +
sExistingPasswordHashAlgorithmName +
"' to '" +
sDefaultPasswordHashAlgorithmName +
"'");
}
boolean bLoggedOutUser = false;
LoginInfo aInfo;
m_aRWLock.writeLock ().lock ();
try
{
if (m_aLoggedInUsers.containsKey (sUserID))
{
// The user is already logged in
if (isLogoutAlreadyLoggedInUser ())
{
// Explicitly log out
logoutUser (sUserID);
// Just a short check
if (m_aLoggedInUsers.containsKey (sUserID))
throw new IllegalStateException ("Failed to logout '" + sUserID + "'");
AuditHelper.onAuditExecuteSuccess ("logout-in-login", sUserID);
bLoggedOutUser = true;
}
else
{
// Error: user already logged in
AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-already-logged-in");
return _onLoginError (sUserID, ELoginResult.USER_ALREADY_LOGGED_IN);
}
}
// Update user in session
final InternalSessionUserHolder aSUH = InternalSessionUserHolder._getInstance ();
if (aSUH._hasUser ())
{
// This session already has a user
if (LOGGER.isWarnEnabled ())
LOGGER.warn ("The session user holder already has the user ID '" +
aSUH._getUserID () +
"' so the new ID '" +
sUserID +
"' will not be set!");
AuditHelper.onAuditExecuteFailure ("login", sUserID, "session-already-has-user");
return _onLoginError (sUserID, ELoginResult.SESSION_ALREADY_HAS_USER);
}
aInfo = new LoginInfo (aUser, ScopeManager.getSessionScope ());
m_aLoggedInUsers.put (sUserID, aInfo);
aSUH._setUser (this, aUser);
}
finally
{
m_aRWLock.writeLock ().unlock ();
}
if (LOGGER.isInfoEnabled ())
LOGGER.info ("Logged in " +
_getUserIDLogText (sUserID) +
(isAnonymousLogging () ? "" : " with login name '" + aUser.getLoginName () + "'"));
AuditHelper.onAuditExecuteSuccess ("login-user", sUserID, aUser.getLoginName ());
// Execute callback as the very last action
m_aUserLoginCallbacks.forEach (aCB -> aCB.onUserLogin (aInfo));
return bLoggedOutUser ? ELoginResult.SUCCESS_WITH_LOGOUT : ELoginResult.SUCCESS;
} } | public class class_name {
@Nonnull
public ELoginResult loginUser (@Nullable final IUser aUser,
@Nullable final String sPlainTextPassword,
@Nullable final Iterable <String> aRequiredRoleIDs)
{
if (aUser == null)
return ELoginResult.USER_NOT_EXISTING;
final String sUserID = aUser.getID ();
// Deleted user?
if (aUser.isDeleted ())
{
AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-deleted"); // depends on control dependency: [if], data = [none]
return _onLoginError (sUserID, ELoginResult.USER_IS_DELETED); // depends on control dependency: [if], data = [none]
}
// Disabled user?
if (aUser.isDisabled ())
{
AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-disabled"); // depends on control dependency: [if], data = [none]
return _onLoginError (sUserID, ELoginResult.USER_IS_DISABLED); // depends on control dependency: [if], data = [none]
}
// Check the password
final UserManager aUserMgr = PhotonSecurityManager.getUserMgr ();
if (!aUserMgr.areUserIDAndPasswordValid (sUserID, sPlainTextPassword))
{
AuditHelper.onAuditExecuteFailure ("login", sUserID, "invalid-password"); // depends on control dependency: [if], data = [none]
return _onLoginError (sUserID, ELoginResult.INVALID_PASSWORD); // depends on control dependency: [if], data = [none]
}
// Are all roles present?
if (!SecurityHelper.hasUserAllRoles (sUserID, aRequiredRoleIDs))
{
AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-is-missing-required-roles", aRequiredRoleIDs); // depends on control dependency: [if], data = [none]
return _onLoginError (sUserID, ELoginResult.USER_IS_MISSING_ROLE); // depends on control dependency: [if], data = [none]
}
// Check if the password hash needs to be updated
final String sExistingPasswordHashAlgorithmName = aUser.getPasswordHash ().getAlgorithmName ();
final String sDefaultPasswordHashAlgorithmName = GlobalPasswordSettings.getPasswordHashCreatorManager ()
.getDefaultPasswordHashCreatorAlgorithmName ();
if (!sExistingPasswordHashAlgorithmName.equals (sDefaultPasswordHashAlgorithmName))
{
// This implicitly implies using the default hash creator algorithm
// This automatically saves the file
aUserMgr.setUserPassword (sUserID, sPlainTextPassword); // depends on control dependency: [if], data = [none]
if (LOGGER.isInfoEnabled ())
LOGGER.info ("Updated password hash of " +
_getUserIDLogText (sUserID) +
" from algorithm '" +
sExistingPasswordHashAlgorithmName +
"' to '" +
sDefaultPasswordHashAlgorithmName +
"'");
}
boolean bLoggedOutUser = false;
LoginInfo aInfo;
m_aRWLock.writeLock ().lock ();
try
{
if (m_aLoggedInUsers.containsKey (sUserID))
{
// The user is already logged in
if (isLogoutAlreadyLoggedInUser ())
{
// Explicitly log out
logoutUser (sUserID); // depends on control dependency: [if], data = [none]
// Just a short check
if (m_aLoggedInUsers.containsKey (sUserID))
throw new IllegalStateException ("Failed to logout '" + sUserID + "'");
AuditHelper.onAuditExecuteSuccess ("logout-in-login", sUserID); // depends on control dependency: [if], data = [none]
bLoggedOutUser = true; // depends on control dependency: [if], data = [none]
}
else
{
// Error: user already logged in
AuditHelper.onAuditExecuteFailure ("login", sUserID, "user-already-logged-in"); // depends on control dependency: [if], data = [none]
return _onLoginError (sUserID, ELoginResult.USER_ALREADY_LOGGED_IN); // depends on control dependency: [if], data = [none]
}
}
// Update user in session
final InternalSessionUserHolder aSUH = InternalSessionUserHolder._getInstance ();
if (aSUH._hasUser ())
{
// This session already has a user
if (LOGGER.isWarnEnabled ())
LOGGER.warn ("The session user holder already has the user ID '" +
aSUH._getUserID () +
"' so the new ID '" +
sUserID +
"' will not be set!");
AuditHelper.onAuditExecuteFailure ("login", sUserID, "session-already-has-user");
return _onLoginError (sUserID, ELoginResult.SESSION_ALREADY_HAS_USER); // depends on control dependency: [if], data = [none]
}
aInfo = new LoginInfo (aUser, ScopeManager.getSessionScope ()); // depends on control dependency: [try], data = [none]
m_aLoggedInUsers.put (sUserID, aInfo); // depends on control dependency: [try], data = [none]
aSUH._setUser (this, aUser); // depends on control dependency: [try], data = [none]
}
finally
{
m_aRWLock.writeLock ().unlock ();
}
if (LOGGER.isInfoEnabled ())
LOGGER.info ("Logged in " +
_getUserIDLogText (sUserID) +
(isAnonymousLogging () ? "" : " with login name '" + aUser.getLoginName () + "'"));
AuditHelper.onAuditExecuteSuccess ("login-user", sUserID, aUser.getLoginName ());
// Execute callback as the very last action
m_aUserLoginCallbacks.forEach (aCB -> aCB.onUserLogin (aInfo));
return bLoggedOutUser ? ELoginResult.SUCCESS_WITH_LOGOUT : ELoginResult.SUCCESS;
} } |
public class class_name {
@Override
public void scan(String handlerLocations) {
if (StringHelper.isBlank(handlerLocations)) {
return;
}
// 对配置的xml路径按逗号分割的规则来解析,如果是XML文件则直接将该xml文件存放到xmlPaths的Set集合中,
// 否则就代表是xml资源目录,并解析目录下所有的xml文件,将这些xml文件存放到xmlPaths的Set集合中,
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String[] locationArr = handlerLocations.split(ZealotConst.COMMA);
for (String location: locationArr) {
if (StringHelper.isBlank(location)) {
continue;
}
// 判断文件如果是具体的Java文件和class文件,则将文件解析成Class对象.
// 如果都不是,则视其为包,然后解析该包及子包下面的所有class文件.
String cleanLocation = location.trim();
if (StringHelper.isJavaFile(cleanLocation) || StringHelper.isClassFile(cleanLocation)) {
this.addClassByName(classLoader, cleanLocation.substring(0, cleanLocation.lastIndexOf('.')));
} else {
this.addClassByPackage(classLoader, cleanLocation);
}
}
this.addTagHanderInMap();
} } | public class class_name {
@Override
public void scan(String handlerLocations) {
if (StringHelper.isBlank(handlerLocations)) {
return; // depends on control dependency: [if], data = [none]
}
// 对配置的xml路径按逗号分割的规则来解析,如果是XML文件则直接将该xml文件存放到xmlPaths的Set集合中,
// 否则就代表是xml资源目录,并解析目录下所有的xml文件,将这些xml文件存放到xmlPaths的Set集合中,
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String[] locationArr = handlerLocations.split(ZealotConst.COMMA);
for (String location: locationArr) {
if (StringHelper.isBlank(location)) {
continue;
}
// 判断文件如果是具体的Java文件和class文件,则将文件解析成Class对象.
// 如果都不是,则视其为包,然后解析该包及子包下面的所有class文件.
String cleanLocation = location.trim();
if (StringHelper.isJavaFile(cleanLocation) || StringHelper.isClassFile(cleanLocation)) {
this.addClassByName(classLoader, cleanLocation.substring(0, cleanLocation.lastIndexOf('.'))); // depends on control dependency: [if], data = [none]
} else {
this.addClassByPackage(classLoader, cleanLocation); // depends on control dependency: [if], data = [none]
}
}
this.addTagHanderInMap();
} } |
public class class_name {
public static boolean changePassword(String userName, String newPassword) {
LOGGER.entering(userName, newPassword.replaceAll(".", "*"));
boolean changeSucceeded = false;
File authFile = new File(AUTH_FILE_LOCATION);
try {
authFile.delete();
authFile.createNewFile();
createAuthFile(authFile, userName, newPassword);
changeSucceeded = true;
} catch (Exception e) {
changeSucceeded = false;
}
LOGGER.exiting(changeSucceeded);
return changeSucceeded;
} } | public class class_name {
public static boolean changePassword(String userName, String newPassword) {
LOGGER.entering(userName, newPassword.replaceAll(".", "*"));
boolean changeSucceeded = false;
File authFile = new File(AUTH_FILE_LOCATION);
try {
authFile.delete(); // depends on control dependency: [try], data = [none]
authFile.createNewFile(); // depends on control dependency: [try], data = [none]
createAuthFile(authFile, userName, newPassword); // depends on control dependency: [try], data = [none]
changeSucceeded = true; // depends on control dependency: [try], data = [none]
} catch (Exception e) {
changeSucceeded = false;
} // depends on control dependency: [catch], data = [none]
LOGGER.exiting(changeSucceeded);
return changeSucceeded;
} } |
public class class_name {
public static String printCommentTree(List<CommentTreeElement> cs) {
StringBuilder builder = new StringBuilder();
for (CommentTreeElement c : cs) {
builder.append(printCommentTree(c, 0));
}
return builder.toString();
} } | public class class_name {
public static String printCommentTree(List<CommentTreeElement> cs) {
StringBuilder builder = new StringBuilder();
for (CommentTreeElement c : cs) {
builder.append(printCommentTree(c, 0)); // depends on control dependency: [for], data = [c]
}
return builder.toString();
} } |
public class class_name {
public FacesConfigProtectedViewsType<FacesConfigType<T>> getOrCreateProtectedViews()
{
List<Node> nodeList = childNode.get("protected-views");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigProtectedViewsTypeImpl<FacesConfigType<T>>(this, "protected-views", childNode, nodeList.get(0));
}
return createProtectedViews();
} } | public class class_name {
public FacesConfigProtectedViewsType<FacesConfigType<T>> getOrCreateProtectedViews()
{
List<Node> nodeList = childNode.get("protected-views");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigProtectedViewsTypeImpl<FacesConfigType<T>>(this, "protected-views", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createProtectedViews();
} } |
public class class_name {
public void updateSlots () {
// Find the anchor point
Location<T> anchor = getAnchorPoint();
positionOffset.set(anchor.getPosition());
float orientationOffset = anchor.getOrientation();
if (motionModerator != null) {
positionOffset.sub(driftOffset.getPosition());
orientationOffset -= driftOffset.getOrientation();
}
// Get the orientation of the anchor point as a matrix
orientationMatrix.idt().rotateRad(anchor.getOrientation());
// Go through each member in turn
for (int i = 0; i < slotAssignments.size; i++) {
SlotAssignment<T> slotAssignment = slotAssignments.get(i);
// Retrieve the location reference of the formation member to calculate the new value
Location<T> relativeLoc = slotAssignment.member.getTargetLocation();
// Ask for the location of the slot relative to the anchor point
pattern.calculateSlotLocation(relativeLoc, slotAssignment.slotNumber);
T relativeLocPosition = relativeLoc.getPosition();
// System.out.println("relativeLoc.position = " + relativeLocPosition);
// [17:31] <@Xoppa> davebaol, interface Transform<T extends Vector<T>> { T getTranslation(); T getScale(); float getRotation();
// void transform(T val); }
// [17:31] <@Xoppa>
// https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g3d/utils/BaseAnimationController.java#L40
// [17:34] * ThreadL0ck (~ThreadL0c@197.220.114.182) Quit (Remote host closed the connection)
// [17:35] <davebaol> thanks Xoppa, sounds interesting
// TODO Consider the possibility of declaring mul(orientationMatrix) in Vector
// Transform it by the anchor point's position and orientation
// relativeLocPosition.mul(orientationMatrix).add(anchor.position);
if (relativeLocPosition instanceof Vector2)
((Vector2)relativeLocPosition).mul(orientationMatrix);
else if (relativeLocPosition instanceof Vector3) ((Vector3)relativeLocPosition).mul(orientationMatrix);
// Add the anchor and drift components
relativeLocPosition.add(positionOffset);
relativeLoc.setOrientation(relativeLoc.getOrientation() + orientationOffset);
}
// Possibly reset the anchor point if a moderator is set
if (motionModerator != null) {
motionModerator.updateAnchorPoint(anchor);
}
} } | public class class_name {
public void updateSlots () {
// Find the anchor point
Location<T> anchor = getAnchorPoint();
positionOffset.set(anchor.getPosition());
float orientationOffset = anchor.getOrientation();
if (motionModerator != null) {
positionOffset.sub(driftOffset.getPosition()); // depends on control dependency: [if], data = [none]
orientationOffset -= driftOffset.getOrientation(); // depends on control dependency: [if], data = [none]
}
// Get the orientation of the anchor point as a matrix
orientationMatrix.idt().rotateRad(anchor.getOrientation());
// Go through each member in turn
for (int i = 0; i < slotAssignments.size; i++) {
SlotAssignment<T> slotAssignment = slotAssignments.get(i);
// Retrieve the location reference of the formation member to calculate the new value
Location<T> relativeLoc = slotAssignment.member.getTargetLocation();
// Ask for the location of the slot relative to the anchor point
pattern.calculateSlotLocation(relativeLoc, slotAssignment.slotNumber); // depends on control dependency: [for], data = [none]
T relativeLocPosition = relativeLoc.getPosition();
// System.out.println("relativeLoc.position = " + relativeLocPosition);
// [17:31] <@Xoppa> davebaol, interface Transform<T extends Vector<T>> { T getTranslation(); T getScale(); float getRotation();
// void transform(T val); }
// [17:31] <@Xoppa>
// https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g3d/utils/BaseAnimationController.java#L40
// [17:34] * ThreadL0ck (~ThreadL0c@197.220.114.182) Quit (Remote host closed the connection)
// [17:35] <davebaol> thanks Xoppa, sounds interesting
// TODO Consider the possibility of declaring mul(orientationMatrix) in Vector
// Transform it by the anchor point's position and orientation
// relativeLocPosition.mul(orientationMatrix).add(anchor.position);
if (relativeLocPosition instanceof Vector2)
((Vector2)relativeLocPosition).mul(orientationMatrix);
else if (relativeLocPosition instanceof Vector3) ((Vector3)relativeLocPosition).mul(orientationMatrix);
// Add the anchor and drift components
relativeLocPosition.add(positionOffset); // depends on control dependency: [for], data = [none]
relativeLoc.setOrientation(relativeLoc.getOrientation() + orientationOffset); // depends on control dependency: [for], data = [none]
}
// Possibly reset the anchor point if a moderator is set
if (motionModerator != null) {
motionModerator.updateAnchorPoint(anchor); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Group getGroupByUUID(final UUID UUID) {
List<Group> allGroups = getGroups();
List<Group> groups = ListFilter.filter(allGroups, new Filter<Group>() {
@Override
public boolean matches(Group item) {
if (item.getUuid() != null && item.getUuid().compareTo(UUID) == 0) {
return true;
} else {
return false;
}
}
});
if (groups.size() == 1) {
return groups.get(0);
} else {
return null;
}
} } | public class class_name {
public Group getGroupByUUID(final UUID UUID) {
List<Group> allGroups = getGroups();
List<Group> groups = ListFilter.filter(allGroups, new Filter<Group>() {
@Override
public boolean matches(Group item) {
if (item.getUuid() != null && item.getUuid().compareTo(UUID) == 0) {
return true;
// depends on control dependency: [if], data = [none]
} else {
return false;
// depends on control dependency: [if], data = [none]
}
}
});
if (groups.size() == 1) {
return groups.get(0);
// depends on control dependency: [if], data = [none]
} else {
return null;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public SimpleOrderedMap<Object> create(ComponentList list, Boolean encode) {
SimpleOrderedMap<Object> mtasListResponse = new SimpleOrderedMap<>();
mtasListResponse.add("key", list.key);
if (list.number == 0) {
mtasListResponse.add("total", list.total);
}
if (list.output != null) {
ArrayList<NamedList<Object>> mtasListItemResponses = new ArrayList<>();
if (list.output.equals(ComponentList.LIST_OUTPUT_HIT)) {
mtasListResponse.add("number", list.hits.size());
for (ListHit hit : list.hits) {
NamedList<Object> mtasListItemResponse = new SimpleOrderedMap<>();
mtasListItemResponse.add("documentKey",
list.uniqueKey.get(hit.docId));
mtasListItemResponse.add("documentHitPosition", hit.docPosition);
mtasListItemResponse.add("documentHitTotal",
list.subTotal.get(hit.docId));
mtasListItemResponse.add("documentMinPosition",
list.minPosition.get(hit.docId));
mtasListItemResponse.add("documentMaxPosition",
list.maxPosition.get(hit.docId));
mtasListItemResponse.add("startPosition", hit.startPosition);
mtasListItemResponse.add("endPosition", hit.endPosition);
SortedMap<Integer, List<List<String>>> hitData = new TreeMap<>();
SortedMap<Integer, List<List<String>>> leftData = null;
SortedMap<Integer, List<List<String>>> rightData = null;
if (list.left > 0) {
leftData = new TreeMap<>();
}
if (list.right > 0) {
rightData = new TreeMap<>();
}
for (int position = Math.max(0,
hit.startPosition - list.left); position <= (hit.endPosition
+ list.right); position++) {
List<List<String>> hitDataItem = new ArrayList<>();
if (hit.hits.containsKey(position)) {
for (String term : hit.hits.get(position)) {
List<String> hitDataSubItem = new ArrayList<>();
hitDataSubItem.add(CodecUtil.termPrefix(term));
hitDataSubItem.add(CodecUtil.termValue(term));
hitDataItem.add(hitDataSubItem);
}
}
if (position < hit.startPosition) {
if (leftData != null) {
leftData.put(position, hitDataItem);
}
} else if (position > hit.endPosition) {
if (rightData != null) {
rightData.put(position, hitDataItem);
}
} else {
hitData.put(position, hitDataItem);
}
}
if (list.left > 0) {
mtasListItemResponse.add("left", leftData);
}
mtasListItemResponse.add("hit", hitData);
if (list.right > 0) {
mtasListItemResponse.add("right", rightData);
}
mtasListItemResponses.add(mtasListItemResponse);
}
} else if (list.output.equals(ComponentList.LIST_OUTPUT_TOKEN)) {
mtasListResponse.add("number", list.tokens.size());
for (ListToken tokenHit : list.tokens) {
NamedList<Object> mtasListItemResponse = new SimpleOrderedMap<>();
mtasListItemResponse.add("documentKey",
list.uniqueKey.get(tokenHit.docId));
mtasListItemResponse.add("documentHitPosition", tokenHit.docPosition);
mtasListItemResponse.add("documentHitTotal",
list.subTotal.get(tokenHit.docId));
mtasListItemResponse.add("documentMinPosition",
list.minPosition.get(tokenHit.docId));
mtasListItemResponse.add("documentMaxPosition",
list.maxPosition.get(tokenHit.docId));
mtasListItemResponse.add("startPosition", tokenHit.startPosition);
mtasListItemResponse.add("endPosition", tokenHit.endPosition);
ArrayList<NamedList<Object>> mtasListItemResponseItemTokens = new ArrayList<>();
for (MtasToken token : tokenHit.tokens) {
NamedList<Object> mtasListItemResponseItemToken = new SimpleOrderedMap<>();
if (token.getId() != null) {
mtasListItemResponseItemToken.add("mtasId", token.getId());
}
mtasListItemResponseItemToken.add("prefix", token.getPrefix());
mtasListItemResponseItemToken.add("value", token.getPostfix());
if (token.getPositionStart() != null) {
mtasListItemResponseItemToken.add("positionStart",
token.getPositionStart());
mtasListItemResponseItemToken.add("positionEnd",
token.getPositionEnd());
}
if (token.getPositions() != null) {
mtasListItemResponseItemToken.add("positions",
Arrays.toString(token.getPositions()));
}
if (token.getParentId() != null) {
mtasListItemResponseItemToken.add("parentMtasId",
token.getParentId());
}
if (token.getPayload() != null) {
mtasListItemResponseItemToken.add("payload", token.getPayload());
}
if (token.getOffsetStart() != null) {
mtasListItemResponseItemToken.add("offsetStart",
token.getOffsetStart());
mtasListItemResponseItemToken.add("offsetEnd",
token.getOffsetEnd());
}
if (token.getRealOffsetStart() != null) {
mtasListItemResponseItemToken.add("realOffsetStart",
token.getRealOffsetStart());
mtasListItemResponseItemToken.add("realOffsetEnd",
token.getRealOffsetEnd());
}
mtasListItemResponseItemTokens.add(mtasListItemResponseItemToken);
}
mtasListItemResponse.add("tokens", mtasListItemResponseItemTokens);
mtasListItemResponses.add(mtasListItemResponse);
}
}
mtasListResponse.add(NAME, mtasListItemResponses);
}
return mtasListResponse;
} } | public class class_name {
public SimpleOrderedMap<Object> create(ComponentList list, Boolean encode) {
SimpleOrderedMap<Object> mtasListResponse = new SimpleOrderedMap<>();
mtasListResponse.add("key", list.key);
if (list.number == 0) {
mtasListResponse.add("total", list.total); // depends on control dependency: [if], data = [none]
}
if (list.output != null) {
ArrayList<NamedList<Object>> mtasListItemResponses = new ArrayList<>();
if (list.output.equals(ComponentList.LIST_OUTPUT_HIT)) {
mtasListResponse.add("number", list.hits.size()); // depends on control dependency: [if], data = [none]
for (ListHit hit : list.hits) {
NamedList<Object> mtasListItemResponse = new SimpleOrderedMap<>();
mtasListItemResponse.add("documentKey",
list.uniqueKey.get(hit.docId)); // depends on control dependency: [for], data = [none]
mtasListItemResponse.add("documentHitPosition", hit.docPosition); // depends on control dependency: [for], data = [hit]
mtasListItemResponse.add("documentHitTotal",
list.subTotal.get(hit.docId)); // depends on control dependency: [for], data = [none]
mtasListItemResponse.add("documentMinPosition",
list.minPosition.get(hit.docId)); // depends on control dependency: [for], data = [none]
mtasListItemResponse.add("documentMaxPosition",
list.maxPosition.get(hit.docId)); // depends on control dependency: [for], data = [none]
mtasListItemResponse.add("startPosition", hit.startPosition); // depends on control dependency: [for], data = [hit]
mtasListItemResponse.add("endPosition", hit.endPosition); // depends on control dependency: [for], data = [hit]
SortedMap<Integer, List<List<String>>> hitData = new TreeMap<>();
SortedMap<Integer, List<List<String>>> leftData = null;
SortedMap<Integer, List<List<String>>> rightData = null;
if (list.left > 0) {
leftData = new TreeMap<>(); // depends on control dependency: [if], data = [none]
}
if (list.right > 0) {
rightData = new TreeMap<>(); // depends on control dependency: [if], data = [none]
}
for (int position = Math.max(0,
hit.startPosition - list.left); position <= (hit.endPosition
+ list.right); position++) {
List<List<String>> hitDataItem = new ArrayList<>();
if (hit.hits.containsKey(position)) {
for (String term : hit.hits.get(position)) {
List<String> hitDataSubItem = new ArrayList<>();
hitDataSubItem.add(CodecUtil.termPrefix(term)); // depends on control dependency: [for], data = [term]
hitDataSubItem.add(CodecUtil.termValue(term)); // depends on control dependency: [for], data = [term]
hitDataItem.add(hitDataSubItem); // depends on control dependency: [for], data = [none]
}
}
if (position < hit.startPosition) {
if (leftData != null) {
leftData.put(position, hitDataItem); // depends on control dependency: [if], data = [none]
}
} else if (position > hit.endPosition) {
if (rightData != null) {
rightData.put(position, hitDataItem); // depends on control dependency: [if], data = [none]
}
} else {
hitData.put(position, hitDataItem); // depends on control dependency: [if], data = [(position]
}
}
if (list.left > 0) {
mtasListItemResponse.add("left", leftData); // depends on control dependency: [if], data = [none]
}
mtasListItemResponse.add("hit", hitData); // depends on control dependency: [for], data = [hit]
if (list.right > 0) {
mtasListItemResponse.add("right", rightData); // depends on control dependency: [if], data = [none]
}
mtasListItemResponses.add(mtasListItemResponse); // depends on control dependency: [for], data = [none]
}
} else if (list.output.equals(ComponentList.LIST_OUTPUT_TOKEN)) {
mtasListResponse.add("number", list.tokens.size()); // depends on control dependency: [if], data = [none]
for (ListToken tokenHit : list.tokens) {
NamedList<Object> mtasListItemResponse = new SimpleOrderedMap<>();
mtasListItemResponse.add("documentKey",
list.uniqueKey.get(tokenHit.docId)); // depends on control dependency: [for], data = [none]
mtasListItemResponse.add("documentHitPosition", tokenHit.docPosition); // depends on control dependency: [for], data = [tokenHit]
mtasListItemResponse.add("documentHitTotal",
list.subTotal.get(tokenHit.docId)); // depends on control dependency: [for], data = [none]
mtasListItemResponse.add("documentMinPosition",
list.minPosition.get(tokenHit.docId)); // depends on control dependency: [for], data = [none]
mtasListItemResponse.add("documentMaxPosition",
list.maxPosition.get(tokenHit.docId)); // depends on control dependency: [for], data = [none]
mtasListItemResponse.add("startPosition", tokenHit.startPosition); // depends on control dependency: [for], data = [tokenHit]
mtasListItemResponse.add("endPosition", tokenHit.endPosition); // depends on control dependency: [for], data = [tokenHit]
ArrayList<NamedList<Object>> mtasListItemResponseItemTokens = new ArrayList<>();
for (MtasToken token : tokenHit.tokens) {
NamedList<Object> mtasListItemResponseItemToken = new SimpleOrderedMap<>();
if (token.getId() != null) {
mtasListItemResponseItemToken.add("mtasId", token.getId()); // depends on control dependency: [if], data = [none]
}
mtasListItemResponseItemToken.add("prefix", token.getPrefix()); // depends on control dependency: [for], data = [token]
mtasListItemResponseItemToken.add("value", token.getPostfix()); // depends on control dependency: [for], data = [token]
if (token.getPositionStart() != null) {
mtasListItemResponseItemToken.add("positionStart",
token.getPositionStart()); // depends on control dependency: [if], data = [none]
mtasListItemResponseItemToken.add("positionEnd",
token.getPositionEnd()); // depends on control dependency: [if], data = [none]
}
if (token.getPositions() != null) {
mtasListItemResponseItemToken.add("positions",
Arrays.toString(token.getPositions())); // depends on control dependency: [if], data = [none]
}
if (token.getParentId() != null) {
mtasListItemResponseItemToken.add("parentMtasId",
token.getParentId()); // depends on control dependency: [if], data = [none]
}
if (token.getPayload() != null) {
mtasListItemResponseItemToken.add("payload", token.getPayload()); // depends on control dependency: [if], data = [none]
}
if (token.getOffsetStart() != null) {
mtasListItemResponseItemToken.add("offsetStart",
token.getOffsetStart()); // depends on control dependency: [if], data = [none]
mtasListItemResponseItemToken.add("offsetEnd",
token.getOffsetEnd()); // depends on control dependency: [if], data = [none]
}
if (token.getRealOffsetStart() != null) {
mtasListItemResponseItemToken.add("realOffsetStart",
token.getRealOffsetStart()); // depends on control dependency: [if], data = [none]
mtasListItemResponseItemToken.add("realOffsetEnd",
token.getRealOffsetEnd()); // depends on control dependency: [if], data = [none]
}
mtasListItemResponseItemTokens.add(mtasListItemResponseItemToken); // depends on control dependency: [for], data = [none]
}
mtasListItemResponse.add("tokens", mtasListItemResponseItemTokens); // depends on control dependency: [for], data = [none]
mtasListItemResponses.add(mtasListItemResponse); // depends on control dependency: [for], data = [none]
}
}
mtasListResponse.add(NAME, mtasListItemResponses); // depends on control dependency: [if], data = [none]
}
return mtasListResponse;
} } |
public class class_name {
public void start(Consumer<UpdateRackHeartbeat> consumer,
Result<Integer> result)
{
if (_selfServer.port() < 0) {
result.ok(0);
return;
}
// boolean isPendingStart = false;
ArrayList<ClusterHeartbeat> clusterList = new ArrayList<>();
for (ClusterHeartbeat cluster : _root.getClusters()) {
clusterList.add(cluster);
}
if (clusterList.size() == 0) {
result.ok(0);
return;
}
/*
Result<Integer>[]resultFork = result.fork(clusterList.size(),
(x,r)->addInt(x,null,r),
(x,y,r)->addInt(x,y,r));
*/
Fork<Integer,Integer> fork = result.fork();
for (int i = 0; i < clusterList.size(); i++) {
ClusterHeartbeat cluster = clusterList.get(i);
startCluster(cluster, consumer, fork.branch()); // resultFork[i]);
}
fork.fail((v,f,r)->addInt(v,f,r));
fork.join((v,r)->addInt(v,null,r));
/*
for (ClusterHeartbeat cluster : _root.getClusters()) {
if (! _selfServer.getClusterId().equals(cluster.getId())) {
startCluster(cluster, cont);
}
}
*/
} } | public class class_name {
public void start(Consumer<UpdateRackHeartbeat> consumer,
Result<Integer> result)
{
if (_selfServer.port() < 0) {
result.ok(0); // depends on control dependency: [if], data = [0)]
return; // depends on control dependency: [if], data = [none]
}
// boolean isPendingStart = false;
ArrayList<ClusterHeartbeat> clusterList = new ArrayList<>();
for (ClusterHeartbeat cluster : _root.getClusters()) {
clusterList.add(cluster); // depends on control dependency: [for], data = [cluster]
}
if (clusterList.size() == 0) {
result.ok(0); // depends on control dependency: [if], data = [0)]
return; // depends on control dependency: [if], data = [none]
}
/*
Result<Integer>[]resultFork = result.fork(clusterList.size(),
(x,r)->addInt(x,null,r),
(x,y,r)->addInt(x,y,r));
*/
Fork<Integer,Integer> fork = result.fork();
for (int i = 0; i < clusterList.size(); i++) {
ClusterHeartbeat cluster = clusterList.get(i);
startCluster(cluster, consumer, fork.branch()); // resultFork[i]); // depends on control dependency: [for], data = [none]
}
fork.fail((v,f,r)->addInt(v,f,r));
fork.join((v,r)->addInt(v,null,r));
/*
for (ClusterHeartbeat cluster : _root.getClusters()) {
if (! _selfServer.getClusterId().equals(cluster.getId())) {
startCluster(cluster, cont);
}
}
*/
} } |
public class class_name {
private List<HistogramScene> computeHistograms(FeatureToWordHistogram_F64 featuresToHistogram ) {
List<String> scenes = getScenes();
List<HistogramScene> memory;// Processed results which will be passed into the k-NN algorithm
memory = new ArrayList<>();
for( int sceneIndex = 0; sceneIndex < scenes.size(); sceneIndex++ ) {
String scene = scenes.get(sceneIndex);
System.out.println(" " + scene);
List<String> imagePaths = train.get(scene);
for (String path : imagePaths) {
GrayU8 image = UtilImageIO.loadImage(path, GrayU8.class);
// reset before processing a new image
featuresToHistogram.reset();
describeImage.process(image);
for ( TupleDesc_F64 d : describeImage.getDescriptions() ) {
featuresToHistogram.addFeature(d);
}
featuresToHistogram.process();
// The histogram is already normalized so that it sums up to 1. This provides invariance
// against the overall number of features changing.
double[] histogram = featuresToHistogram.getHistogram();
// Create the data structure used by the KNN classifier
HistogramScene imageHist = new HistogramScene(NUMBER_OF_WORDS);
imageHist.setHistogram(histogram);
imageHist.type = sceneIndex;
memory.add(imageHist);
}
}
return memory;
} } | public class class_name {
private List<HistogramScene> computeHistograms(FeatureToWordHistogram_F64 featuresToHistogram ) {
List<String> scenes = getScenes();
List<HistogramScene> memory;// Processed results which will be passed into the k-NN algorithm
memory = new ArrayList<>();
for( int sceneIndex = 0; sceneIndex < scenes.size(); sceneIndex++ ) {
String scene = scenes.get(sceneIndex);
System.out.println(" " + scene); // depends on control dependency: [for], data = [none]
List<String> imagePaths = train.get(scene);
for (String path : imagePaths) {
GrayU8 image = UtilImageIO.loadImage(path, GrayU8.class);
// reset before processing a new image
featuresToHistogram.reset(); // depends on control dependency: [for], data = [none]
describeImage.process(image); // depends on control dependency: [for], data = [none]
for ( TupleDesc_F64 d : describeImage.getDescriptions() ) {
featuresToHistogram.addFeature(d); // depends on control dependency: [for], data = [d]
}
featuresToHistogram.process(); // depends on control dependency: [for], data = [none]
// The histogram is already normalized so that it sums up to 1. This provides invariance
// against the overall number of features changing.
double[] histogram = featuresToHistogram.getHistogram();
// Create the data structure used by the KNN classifier
HistogramScene imageHist = new HistogramScene(NUMBER_OF_WORDS);
imageHist.setHistogram(histogram); // depends on control dependency: [for], data = [none]
imageHist.type = sceneIndex; // depends on control dependency: [for], data = [none]
memory.add(imageHist); // depends on control dependency: [for], data = [none]
}
}
return memory;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.