code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
@Override
public int countMissing() {
int count = 0;
for (int i = 0; i < size(); i++) {
if (getIntInternal(i) == TimeColumnType.missingValueIndicator()) {
count++;
}
}
return count;
} } | public class class_name {
@Override
public int countMissing() {
int count = 0;
for (int i = 0; i < size(); i++) {
if (getIntInternal(i) == TimeColumnType.missingValueIndicator()) {
count++; // depends on control dependency: [if], data = [none]
}
}
return count;
} } |
public class class_name {
public DecimalStyle withZeroDigit(char zeroDigit) {
if (zeroDigit == this.zeroDigit) {
return this;
}
return new DecimalStyle(zeroDigit, positiveSign, negativeSign, decimalSeparator);
} } | public class class_name {
public DecimalStyle withZeroDigit(char zeroDigit) {
if (zeroDigit == this.zeroDigit) {
return this; // depends on control dependency: [if], data = [none]
}
return new DecimalStyle(zeroDigit, positiveSign, negativeSign, decimalSeparator);
} } |
public class class_name {
protected void getSAXRules() {
arrRuleRecords.clear();
Vector<SAXRule> rules = new Vector<SAXRule>(numRules.intValue());
rules.addElement(this);
SAXRule currentRule;
int processedRules = 0;
StringBuilder sbCurrentRule = new StringBuilder();
while (processedRules < rules.size()) {
currentRule = rules.elementAt(processedRules);
for (SAXSymbol sym = currentRule.first(); (!sym.isGuard()); sym = sym.n) {
if (sym.isNonTerminal()) {
SAXRule referedTo = ((SAXNonTerminal) sym).r;
if ((rules.size() > referedTo.index) && (rules.elementAt(referedTo.index) == referedTo)) {
index = referedTo.index;
}
else {
index = rules.size();
referedTo.index = index;
rules.addElement(referedTo);
}
sbCurrentRule.append('R');
sbCurrentRule.append(index);
}
else {
sbCurrentRule.append(sym.value);
}
sbCurrentRule.append(' ');
}
GrammarRuleRecord ruleConteiner = new GrammarRuleRecord();
ruleConteiner.setRuleNumber(processedRules);
ruleConteiner.setRuleString(sbCurrentRule.toString());
ruleConteiner.setRuleLevel(currentRule.getLevel());
ruleConteiner.setRuleUseFrequency(currentRule.count);
ruleConteiner.setOccurrences(currentRule.getIndexes());
arrRuleRecords.add(ruleConteiner);
sbCurrentRule = new StringBuilder();
processedRules++;
}
} } | public class class_name {
protected void getSAXRules() {
arrRuleRecords.clear();
Vector<SAXRule> rules = new Vector<SAXRule>(numRules.intValue());
rules.addElement(this);
SAXRule currentRule;
int processedRules = 0;
StringBuilder sbCurrentRule = new StringBuilder();
while (processedRules < rules.size()) {
currentRule = rules.elementAt(processedRules);
// depends on control dependency: [while], data = [(processedRules]
for (SAXSymbol sym = currentRule.first(); (!sym.isGuard()); sym = sym.n) {
if (sym.isNonTerminal()) {
SAXRule referedTo = ((SAXNonTerminal) sym).r;
if ((rules.size() > referedTo.index) && (rules.elementAt(referedTo.index) == referedTo)) {
index = referedTo.index;
// depends on control dependency: [if], data = [none]
}
else {
index = rules.size();
// depends on control dependency: [if], data = [none]
referedTo.index = index;
// depends on control dependency: [if], data = [none]
rules.addElement(referedTo);
// depends on control dependency: [if], data = [none]
}
sbCurrentRule.append('R');
// depends on control dependency: [if], data = [none]
sbCurrentRule.append(index);
// depends on control dependency: [if], data = [none]
}
else {
sbCurrentRule.append(sym.value);
// depends on control dependency: [if], data = [none]
}
sbCurrentRule.append(' ');
// depends on control dependency: [for], data = [none]
}
GrammarRuleRecord ruleConteiner = new GrammarRuleRecord();
ruleConteiner.setRuleNumber(processedRules);
// depends on control dependency: [while], data = [(processedRules]
ruleConteiner.setRuleString(sbCurrentRule.toString());
// depends on control dependency: [while], data = [none]
ruleConteiner.setRuleLevel(currentRule.getLevel());
// depends on control dependency: [while], data = [none]
ruleConteiner.setRuleUseFrequency(currentRule.count);
// depends on control dependency: [while], data = [none]
ruleConteiner.setOccurrences(currentRule.getIndexes());
// depends on control dependency: [while], data = [none]
arrRuleRecords.add(ruleConteiner);
// depends on control dependency: [while], data = [none]
sbCurrentRule = new StringBuilder();
// depends on control dependency: [while], data = [none]
processedRules++;
// depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
@Override
public long getModTime()
{
HTTPSeekableLineReader reader = null;
SimpleDateFormat lastModFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
try {
reader = get();
String result = reader.getHeaderValue(HTTPSeekableLineReader.LAST_MODIFIED);
Date date = lastModFormat.parse(result);
return date.getTime();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return 0;
} } | public class class_name {
@Override
public long getModTime()
{
HTTPSeekableLineReader reader = null;
SimpleDateFormat lastModFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
try {
reader = get(); // depends on control dependency: [try], data = [none]
String result = reader.getHeaderValue(HTTPSeekableLineReader.LAST_MODIFIED);
Date date = lastModFormat.parse(result);
return date.getTime(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
} finally { // depends on control dependency: [catch], data = [none]
if (reader != null) {
try {
reader.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
} // depends on control dependency: [catch], data = [none]
}
}
return 0;
} } |
public class class_name {
public void marshall(ListBuildsForProjectRequest listBuildsForProjectRequest, ProtocolMarshaller protocolMarshaller) {
if (listBuildsForProjectRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listBuildsForProjectRequest.getProjectName(), PROJECTNAME_BINDING);
protocolMarshaller.marshall(listBuildsForProjectRequest.getSortOrder(), SORTORDER_BINDING);
protocolMarshaller.marshall(listBuildsForProjectRequest.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ListBuildsForProjectRequest listBuildsForProjectRequest, ProtocolMarshaller protocolMarshaller) {
if (listBuildsForProjectRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listBuildsForProjectRequest.getProjectName(), PROJECTNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listBuildsForProjectRequest.getSortOrder(), SORTORDER_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(listBuildsForProjectRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
static private void checkErrorAndThrowExceptionSub(
JsonNode rootNode, boolean raiseReauthenticateError)
throws SnowflakeSQLException
{
// no need to throw exception if success
if (rootNode.path("success").asBoolean())
{
return;
}
String errorMessage;
String sqlState;
int errorCode;
String queryId = "unknown";
// if we have sqlstate in data, it's a sql error
if (!rootNode.path("data").path("sqlState").isMissingNode())
{
sqlState = rootNode.path("data").path("sqlState").asText();
errorCode = rootNode.path("data").path("errorCode").asInt();
queryId = rootNode.path("data").path("queryId").asText();
errorMessage = rootNode.path("message").asText();
}
else
{
sqlState = SqlState.INTERNAL_ERROR; // use internal error sql state
// check if there is an error code in the envelope
if (!rootNode.path("code").isMissingNode())
{
errorCode = rootNode.path("code").asInt();
errorMessage = rootNode.path("message").asText();
}
else
{
errorCode = ErrorCode.INTERNAL_ERROR.getMessageCode();
errorMessage = "no_error_code_from_server";
try
{
PrintWriter writer = new PrintWriter("output.json", "UTF-8");
writer.print(rootNode.toString());
}
catch (Exception ex)
{
logger.debug("{}", ex);
}
}
}
if (raiseReauthenticateError)
{
switch (errorCode)
{
case ID_TOKEN_EXPIRED_GS_CODE:
case SESSION_NOT_EXIST_GS_CODE:
case MASTER_TOKEN_NOTFOUND:
case MASTER_EXPIRED_GS_CODE:
case MASTER_TOKEN_INVALID_GS_CODE:
throw new SnowflakeReauthenticationRequest(
queryId, errorMessage, sqlState, errorCode);
}
}
throw new SnowflakeSQLException(queryId, errorMessage, sqlState,
errorCode);
} } | public class class_name {
static private void checkErrorAndThrowExceptionSub(
JsonNode rootNode, boolean raiseReauthenticateError)
throws SnowflakeSQLException
{
// no need to throw exception if success
if (rootNode.path("success").asBoolean())
{
return;
}
String errorMessage;
String sqlState;
int errorCode;
String queryId = "unknown";
// if we have sqlstate in data, it's a sql error
if (!rootNode.path("data").path("sqlState").isMissingNode())
{
sqlState = rootNode.path("data").path("sqlState").asText();
errorCode = rootNode.path("data").path("errorCode").asInt();
queryId = rootNode.path("data").path("queryId").asText();
errorMessage = rootNode.path("message").asText();
}
else
{
sqlState = SqlState.INTERNAL_ERROR; // use internal error sql state
// check if there is an error code in the envelope
if (!rootNode.path("code").isMissingNode())
{
errorCode = rootNode.path("code").asInt(); // depends on control dependency: [if], data = [none]
errorMessage = rootNode.path("message").asText(); // depends on control dependency: [if], data = [none]
}
else
{
errorCode = ErrorCode.INTERNAL_ERROR.getMessageCode(); // depends on control dependency: [if], data = [none]
errorMessage = "no_error_code_from_server"; // depends on control dependency: [if], data = [none]
try
{
PrintWriter writer = new PrintWriter("output.json", "UTF-8");
writer.print(rootNode.toString()); // depends on control dependency: [try], data = [none]
}
catch (Exception ex)
{
logger.debug("{}", ex);
} // depends on control dependency: [catch], data = [none]
}
}
if (raiseReauthenticateError)
{
switch (errorCode)
{
case ID_TOKEN_EXPIRED_GS_CODE:
case SESSION_NOT_EXIST_GS_CODE:
case MASTER_TOKEN_NOTFOUND:
case MASTER_EXPIRED_GS_CODE:
case MASTER_TOKEN_INVALID_GS_CODE:
throw new SnowflakeReauthenticationRequest(
queryId, errorMessage, sqlState, errorCode);
}
}
throw new SnowflakeSQLException(queryId, errorMessage, sqlState,
errorCode);
} } |
public class class_name {
public static String getPathFromURL(URL url) {
URI uri;
try {
uri = url.toURI();
} catch (URISyntaxException e) {
// this will probably not happen since the url was created
// from a filename beforehand
throw new InvalidCodeLocation(e.toString());
}
if(uri.toString().startsWith("file:") || uri.toString().startsWith("jar:")) {
return removeStart(uri.getSchemeSpecificPart(),"file:");
} else {
// this is wrong, but should at least give a
// helpful error when trying to open the file later
return uri.toString();
}
} } | public class class_name {
public static String getPathFromURL(URL url) {
URI uri;
try {
uri = url.toURI(); // depends on control dependency: [try], data = [none]
} catch (URISyntaxException e) {
// this will probably not happen since the url was created
// from a filename beforehand
throw new InvalidCodeLocation(e.toString());
} // depends on control dependency: [catch], data = [none]
if(uri.toString().startsWith("file:") || uri.toString().startsWith("jar:")) {
return removeStart(uri.getSchemeSpecificPart(),"file:"); // depends on control dependency: [if], data = [none]
} else {
// this is wrong, but should at least give a
// helpful error when trying to open the file later
return uri.toString(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected Map<String, Object> prepareEntityResultMap(Entity entity) {
final Map<String, Object> resultMap;
final DBMeta dbmeta = entity.asDBMeta();
if (dbmeta.hasPrimaryKey() && entity.hasPrimaryKeyValue()) { // mainly here
resultMap = dbmeta.extractPrimaryKeyMap(entity);
} else { // no PK table
resultMap = prepareHashResultMap(entity.instanceHash());
}
return resultMap;
} } | public class class_name {
protected Map<String, Object> prepareEntityResultMap(Entity entity) {
final Map<String, Object> resultMap;
final DBMeta dbmeta = entity.asDBMeta();
if (dbmeta.hasPrimaryKey() && entity.hasPrimaryKeyValue()) { // mainly here
resultMap = dbmeta.extractPrimaryKeyMap(entity); // depends on control dependency: [if], data = [none]
} else { // no PK table
resultMap = prepareHashResultMap(entity.instanceHash()); // depends on control dependency: [if], data = [none]
}
return resultMap;
} } |
public class class_name {
public SqlBuilder select(final String what) {
if (null == what) {
this.select = null;
} else {
if (Strings.contains(what.toLowerCase(), "select")) {
this.select = what;
} else {
this.select = "select " + what;
}
}
return this;
} } | public class class_name {
public SqlBuilder select(final String what) {
if (null == what) {
this.select = null; // depends on control dependency: [if], data = [none]
} else {
if (Strings.contains(what.toLowerCase(), "select")) {
this.select = what; // depends on control dependency: [if], data = [none]
} else {
this.select = "select " + what; // depends on control dependency: [if], data = [none]
}
}
return this;
} } |
public class class_name {
public void marshall(DescribePortfolioRequest describePortfolioRequest, ProtocolMarshaller protocolMarshaller) {
if (describePortfolioRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describePortfolioRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING);
protocolMarshaller.marshall(describePortfolioRequest.getId(), ID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DescribePortfolioRequest describePortfolioRequest, ProtocolMarshaller protocolMarshaller) {
if (describePortfolioRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describePortfolioRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(describePortfolioRequest.getId(), ID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected final void parseQuoted(String name, char quoteChar, TextBuffer tbuf)
throws XMLStreamException
{
if (quoteChar != '"' && quoteChar != '\'') {
throwUnexpectedChar(quoteChar, " in xml declaration; waited ' or \" to start a value for pseudo-attribute '"+name+"'");
}
char[] outBuf = tbuf.getCurrentSegment();
int outPtr = 0;
while (true) {
char c = (mInputPtr < mInputEnd) ? mInputBuffer[mInputPtr++]
: getNextChar(SUFFIX_IN_XML_DECL);
if (c == quoteChar) {
break;
}
if (c < CHAR_SPACE || c == '<') {
throwUnexpectedChar(c, SUFFIX_IN_XML_DECL);
} else if (c == CHAR_NULL) {
throwNullChar();
}
if (outPtr >= outBuf.length) {
outBuf = tbuf.finishCurrentSegment();
outPtr = 0;
}
outBuf[outPtr++] = c;
}
tbuf.setCurrentLength(outPtr);
} } | public class class_name {
protected final void parseQuoted(String name, char quoteChar, TextBuffer tbuf)
throws XMLStreamException
{
if (quoteChar != '"' && quoteChar != '\'') {
throwUnexpectedChar(quoteChar, " in xml declaration; waited ' or \" to start a value for pseudo-attribute '"+name+"'");
}
char[] outBuf = tbuf.getCurrentSegment();
int outPtr = 0;
while (true) {
char c = (mInputPtr < mInputEnd) ? mInputBuffer[mInputPtr++]
: getNextChar(SUFFIX_IN_XML_DECL);
if (c == quoteChar) {
break;
}
if (c < CHAR_SPACE || c == '<') {
throwUnexpectedChar(c, SUFFIX_IN_XML_DECL); // depends on control dependency: [if], data = [none]
} else if (c == CHAR_NULL) {
throwNullChar(); // depends on control dependency: [if], data = [none]
}
if (outPtr >= outBuf.length) {
outBuf = tbuf.finishCurrentSegment(); // depends on control dependency: [if], data = [none]
outPtr = 0; // depends on control dependency: [if], data = [none]
}
outBuf[outPtr++] = c;
}
tbuf.setCurrentLength(outPtr);
} } |
public class class_name {
public boolean markODOObjectInChildren(final String odoObjectCobolName,
final String stopChildCobolName) {
boolean found = false;
for (XsdDataItem child : getChildren()) {
if (child.getCobolName().equals(stopChildCobolName)) {
break;
}
if (child.getCobolName().equals(odoObjectCobolName)) {
child.setIsODOObject(true);
found = true;
break;
}
found = child.markODOObjectInChildren(odoObjectCobolName,
stopChildCobolName);
if (found) {
break;
}
}
return found;
} } | public class class_name {
public boolean markODOObjectInChildren(final String odoObjectCobolName,
final String stopChildCobolName) {
boolean found = false;
for (XsdDataItem child : getChildren()) {
if (child.getCobolName().equals(stopChildCobolName)) {
break;
}
if (child.getCobolName().equals(odoObjectCobolName)) {
child.setIsODOObject(true); // depends on control dependency: [if], data = [none]
found = true; // depends on control dependency: [if], data = [none]
break;
}
found = child.markODOObjectInChildren(odoObjectCobolName,
stopChildCobolName); // depends on control dependency: [for], data = [child]
if (found) {
break;
}
}
return found;
} } |
public class class_name {
public ListSnapshotsResponse listSnapshots(ListSnapshotsRequest request) {
checkNotNull(request, "request should not be null.");
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, SNAPSHOT_PREFIX);
if (!Strings.isNullOrEmpty(request.getMarker())) {
internalRequest.addParameter("marker", request.getMarker());
}
if (request.getMaxKeys() > 0) {
internalRequest.addParameter("maxKeys", String.valueOf(request.getMaxKeys()));
}
if (!Strings.isNullOrEmpty(request.getVolumeId())) {
internalRequest.addParameter("volumeId", request.getVolumeId());
}
return invokeHttpClient(internalRequest, ListSnapshotsResponse.class);
} } | public class class_name {
public ListSnapshotsResponse listSnapshots(ListSnapshotsRequest request) {
checkNotNull(request, "request should not be null.");
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, SNAPSHOT_PREFIX);
if (!Strings.isNullOrEmpty(request.getMarker())) {
internalRequest.addParameter("marker", request.getMarker()); // depends on control dependency: [if], data = [none]
}
if (request.getMaxKeys() > 0) {
internalRequest.addParameter("maxKeys", String.valueOf(request.getMaxKeys())); // depends on control dependency: [if], data = [(request.getMaxKeys()]
}
if (!Strings.isNullOrEmpty(request.getVolumeId())) {
internalRequest.addParameter("volumeId", request.getVolumeId()); // depends on control dependency: [if], data = [none]
}
return invokeHttpClient(internalRequest, ListSnapshotsResponse.class);
} } |
public class class_name {
public void process(Trace trace, Node node, Direction direction,
Map<String, ?> headers, Object... values) {
if (log.isLoggable(Level.FINEST)) {
log.finest("ProcessManager: process trace=" + trace + " node=" + node
+ " direction=" + direction + " headers=" + headers + " values=" + values
+ " : available processors=" + processors);
}
if (trace.getTransaction() != null) {
List<ProcessorWrapper> procs = null;
synchronized (processors) {
procs = processors.get(trace.getTransaction());
}
if (log.isLoggable(Level.FINEST)) {
log.finest("ProcessManager: trace name=" + trace.getTransaction() + " processors=" + procs);
}
if (procs != null) {
for (int i = 0; i < procs.size(); i++) {
procs.get(i).process(trace, node, direction, headers, values);
}
}
}
} } | public class class_name {
public void process(Trace trace, Node node, Direction direction,
Map<String, ?> headers, Object... values) {
if (log.isLoggable(Level.FINEST)) {
log.finest("ProcessManager: process trace=" + trace + " node=" + node
+ " direction=" + direction + " headers=" + headers + " values=" + values
+ " : available processors=" + processors);
}
if (trace.getTransaction() != null) {
List<ProcessorWrapper> procs = null;
synchronized (processors) {
procs = processors.get(trace.getTransaction());
}
if (log.isLoggable(Level.FINEST)) {
log.finest("ProcessManager: trace name=" + trace.getTransaction() + " processors=" + procs); // depends on control dependency: [if], data = [none]
}
if (procs != null) {
for (int i = 0; i < procs.size(); i++) {
procs.get(i).process(trace, node, direction, headers, values); // depends on control dependency: [for], data = [i]
}
}
}
} } |
public class class_name {
static void offerFirstTemporaryDirectBuffer(ByteBuffer buf) {
assert buf != null;
BufferCache cache = bufferCache.get();
if (!cache.offerFirst(buf)) {
// cache is full
free(buf);
}
} } | public class class_name {
static void offerFirstTemporaryDirectBuffer(ByteBuffer buf) {
assert buf != null;
BufferCache cache = bufferCache.get();
if (!cache.offerFirst(buf)) {
// cache is full
free(buf); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private MatchedPair doMatch(
SessionSchedulable schedulable, long now, long nodeWait, long rackWait) {
schedulable.adjustLocalityRequirement(now, nodeWait, rackWait);
for (LocalityLevel level : neededLocalityLevels) {
if (level.isBetterThan(schedulable.getLastLocality())) {
/**
* This means that the last time we tried to schedule this session
* we could not achieve the current LocalityLevel level.
* Since this is the same iteration of the scheduler we do not need to
* try this locality level.
* The last locality level of the shcedulable is getting reset on every
* iteration of the scheduler, so we will retry the better localities
* in the next run of the scheduler.
*/
continue;
}
if (needLocalityCheck(level, nodeWait, rackWait) &&
!schedulable.isLocalityGoodEnough(level)) {
break;
}
Session session = schedulable.getSession();
synchronized (session) {
if (session.isDeleted()) {
return null;
}
int pendingRequestCount = session.getPendingRequestCountForType(type);
MatchedPair matchedPair = null;
if (nodeSnapshot == null ||
pendingRequestCount < nodeSnapshot.getRunnableHostCount()) {
matchedPair = matchNodeForSession(session, level);
} else {
matchedPair = matchSessionForNode(session, level);
}
if (matchedPair != null) {
schedulable.setLocalityLevel(level);
return matchedPair;
}
}
}
schedulable.startLocalityWait(now);
if (LOG.isDebugEnabled()) {
LOG.debug("Could not find a node for " +
schedulable.getSession().getHandle());
}
return null;
} } | public class class_name {
private MatchedPair doMatch(
SessionSchedulable schedulable, long now, long nodeWait, long rackWait) {
schedulable.adjustLocalityRequirement(now, nodeWait, rackWait);
for (LocalityLevel level : neededLocalityLevels) {
if (level.isBetterThan(schedulable.getLastLocality())) {
/**
* This means that the last time we tried to schedule this session
* we could not achieve the current LocalityLevel level.
* Since this is the same iteration of the scheduler we do not need to
* try this locality level.
* The last locality level of the shcedulable is getting reset on every
* iteration of the scheduler, so we will retry the better localities
* in the next run of the scheduler.
*/
continue;
}
if (needLocalityCheck(level, nodeWait, rackWait) &&
!schedulable.isLocalityGoodEnough(level)) {
break;
}
Session session = schedulable.getSession();
synchronized (session) { // depends on control dependency: [for], data = [none]
if (session.isDeleted()) {
return null; // depends on control dependency: [if], data = [none]
}
int pendingRequestCount = session.getPendingRequestCountForType(type);
MatchedPair matchedPair = null;
if (nodeSnapshot == null ||
pendingRequestCount < nodeSnapshot.getRunnableHostCount()) {
matchedPair = matchNodeForSession(session, level); // depends on control dependency: [if], data = [none]
} else {
matchedPair = matchSessionForNode(session, level); // depends on control dependency: [if], data = [none]
}
if (matchedPair != null) {
schedulable.setLocalityLevel(level); // depends on control dependency: [if], data = [none]
return matchedPair; // depends on control dependency: [if], data = [none]
}
}
}
schedulable.startLocalityWait(now);
if (LOG.isDebugEnabled()) {
LOG.debug("Could not find a node for " +
schedulable.getSession().getHandle()); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
static boolean setAccessibleWorkaround(final AccessibleObject o) {
if (o == null || o.isAccessible()) {
return false;
}
final Member m = (Member) o;
if (!o.isAccessible()
&& Modifier.isPublic(m.getModifiers())
&& isPackageAccess(m.getDeclaringClass().getModifiers())) {
try {
o.setAccessible(true);
return true;
} catch (final SecurityException e) { // NOPMD
// ignore in favor of subsequent IllegalAccessException
}
}
return false;
} } | public class class_name {
static boolean setAccessibleWorkaround(final AccessibleObject o) {
if (o == null || o.isAccessible()) {
return false; // depends on control dependency: [if], data = [none]
}
final Member m = (Member) o;
if (!o.isAccessible()
&& Modifier.isPublic(m.getModifiers())
&& isPackageAccess(m.getDeclaringClass().getModifiers())) {
try {
o.setAccessible(true); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
} catch (final SecurityException e) { // NOPMD
// ignore in favor of subsequent IllegalAccessException
} // depends on control dependency: [catch], data = [none]
}
return false;
} } |
public class class_name {
public final EObject ruleXLiteral() throws RecognitionException {
EObject current = null;
EObject this_XCollectionLiteral_0 = null;
EObject this_XClosure_1 = null;
EObject this_XBooleanLiteral_2 = null;
EObject this_XNumberLiteral_3 = null;
EObject this_XNullLiteral_4 = null;
EObject this_XStringLiteral_5 = null;
EObject this_XTypeLiteral_6 = null;
enterRule();
try {
// InternalPureXbase.g:2872:2: ( (this_XCollectionLiteral_0= ruleXCollectionLiteral | ( ( ( () '[' ) )=>this_XClosure_1= ruleXClosure ) | this_XBooleanLiteral_2= ruleXBooleanLiteral | this_XNumberLiteral_3= ruleXNumberLiteral | this_XNullLiteral_4= ruleXNullLiteral | this_XStringLiteral_5= ruleXStringLiteral | this_XTypeLiteral_6= ruleXTypeLiteral ) )
// InternalPureXbase.g:2873:2: (this_XCollectionLiteral_0= ruleXCollectionLiteral | ( ( ( () '[' ) )=>this_XClosure_1= ruleXClosure ) | this_XBooleanLiteral_2= ruleXBooleanLiteral | this_XNumberLiteral_3= ruleXNumberLiteral | this_XNullLiteral_4= ruleXNullLiteral | this_XStringLiteral_5= ruleXStringLiteral | this_XTypeLiteral_6= ruleXTypeLiteral )
{
// InternalPureXbase.g:2873:2: (this_XCollectionLiteral_0= ruleXCollectionLiteral | ( ( ( () '[' ) )=>this_XClosure_1= ruleXClosure ) | this_XBooleanLiteral_2= ruleXBooleanLiteral | this_XNumberLiteral_3= ruleXNumberLiteral | this_XNullLiteral_4= ruleXNullLiteral | this_XStringLiteral_5= ruleXStringLiteral | this_XTypeLiteral_6= ruleXTypeLiteral )
int alt51=7;
int LA51_0 = input.LA(1);
if ( (LA51_0==58) ) {
alt51=1;
}
else if ( (LA51_0==61) && (synpred29_InternalPureXbase())) {
alt51=2;
}
else if ( ((LA51_0>=74 && LA51_0<=75)) ) {
alt51=3;
}
else if ( ((LA51_0>=RULE_HEX && LA51_0<=RULE_DECIMAL)) ) {
alt51=4;
}
else if ( (LA51_0==76) ) {
alt51=5;
}
else if ( (LA51_0==RULE_STRING) ) {
alt51=6;
}
else if ( (LA51_0==77) ) {
alt51=7;
}
else {
if (state.backtracking>0) {state.failed=true; return current;}
NoViableAltException nvae =
new NoViableAltException("", 51, 0, input);
throw nvae;
}
switch (alt51) {
case 1 :
// InternalPureXbase.g:2874:3: this_XCollectionLiteral_0= ruleXCollectionLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXCollectionLiteralParserRuleCall_0());
}
pushFollow(FOLLOW_2);
this_XCollectionLiteral_0=ruleXCollectionLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XCollectionLiteral_0;
afterParserOrEnumRuleCall();
}
}
break;
case 2 :
// InternalPureXbase.g:2883:3: ( ( ( () '[' ) )=>this_XClosure_1= ruleXClosure )
{
// InternalPureXbase.g:2883:3: ( ( ( () '[' ) )=>this_XClosure_1= ruleXClosure )
// InternalPureXbase.g:2884:4: ( ( () '[' ) )=>this_XClosure_1= ruleXClosure
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXClosureParserRuleCall_1());
}
pushFollow(FOLLOW_2);
this_XClosure_1=ruleXClosure();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XClosure_1;
afterParserOrEnumRuleCall();
}
}
}
break;
case 3 :
// InternalPureXbase.g:2900:3: this_XBooleanLiteral_2= ruleXBooleanLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXBooleanLiteralParserRuleCall_2());
}
pushFollow(FOLLOW_2);
this_XBooleanLiteral_2=ruleXBooleanLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XBooleanLiteral_2;
afterParserOrEnumRuleCall();
}
}
break;
case 4 :
// InternalPureXbase.g:2909:3: this_XNumberLiteral_3= ruleXNumberLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXNumberLiteralParserRuleCall_3());
}
pushFollow(FOLLOW_2);
this_XNumberLiteral_3=ruleXNumberLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XNumberLiteral_3;
afterParserOrEnumRuleCall();
}
}
break;
case 5 :
// InternalPureXbase.g:2918:3: this_XNullLiteral_4= ruleXNullLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXNullLiteralParserRuleCall_4());
}
pushFollow(FOLLOW_2);
this_XNullLiteral_4=ruleXNullLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XNullLiteral_4;
afterParserOrEnumRuleCall();
}
}
break;
case 6 :
// InternalPureXbase.g:2927:3: this_XStringLiteral_5= ruleXStringLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXStringLiteralParserRuleCall_5());
}
pushFollow(FOLLOW_2);
this_XStringLiteral_5=ruleXStringLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XStringLiteral_5;
afterParserOrEnumRuleCall();
}
}
break;
case 7 :
// InternalPureXbase.g:2936:3: this_XTypeLiteral_6= ruleXTypeLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXTypeLiteralParserRuleCall_6());
}
pushFollow(FOLLOW_2);
this_XTypeLiteral_6=ruleXTypeLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XTypeLiteral_6;
afterParserOrEnumRuleCall();
}
}
break;
}
}
if ( state.backtracking==0 ) {
leaveRule();
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } | public class class_name {
public final EObject ruleXLiteral() throws RecognitionException {
EObject current = null;
EObject this_XCollectionLiteral_0 = null;
EObject this_XClosure_1 = null;
EObject this_XBooleanLiteral_2 = null;
EObject this_XNumberLiteral_3 = null;
EObject this_XNullLiteral_4 = null;
EObject this_XStringLiteral_5 = null;
EObject this_XTypeLiteral_6 = null;
enterRule();
try {
// InternalPureXbase.g:2872:2: ( (this_XCollectionLiteral_0= ruleXCollectionLiteral | ( ( ( () '[' ) )=>this_XClosure_1= ruleXClosure ) | this_XBooleanLiteral_2= ruleXBooleanLiteral | this_XNumberLiteral_3= ruleXNumberLiteral | this_XNullLiteral_4= ruleXNullLiteral | this_XStringLiteral_5= ruleXStringLiteral | this_XTypeLiteral_6= ruleXTypeLiteral ) )
// InternalPureXbase.g:2873:2: (this_XCollectionLiteral_0= ruleXCollectionLiteral | ( ( ( () '[' ) )=>this_XClosure_1= ruleXClosure ) | this_XBooleanLiteral_2= ruleXBooleanLiteral | this_XNumberLiteral_3= ruleXNumberLiteral | this_XNullLiteral_4= ruleXNullLiteral | this_XStringLiteral_5= ruleXStringLiteral | this_XTypeLiteral_6= ruleXTypeLiteral )
{
// InternalPureXbase.g:2873:2: (this_XCollectionLiteral_0= ruleXCollectionLiteral | ( ( ( () '[' ) )=>this_XClosure_1= ruleXClosure ) | this_XBooleanLiteral_2= ruleXBooleanLiteral | this_XNumberLiteral_3= ruleXNumberLiteral | this_XNullLiteral_4= ruleXNullLiteral | this_XStringLiteral_5= ruleXStringLiteral | this_XTypeLiteral_6= ruleXTypeLiteral )
int alt51=7;
int LA51_0 = input.LA(1);
if ( (LA51_0==58) ) {
alt51=1; // depends on control dependency: [if], data = [none]
}
else if ( (LA51_0==61) && (synpred29_InternalPureXbase())) {
alt51=2; // depends on control dependency: [if], data = [none]
}
else if ( ((LA51_0>=74 && LA51_0<=75)) ) {
alt51=3; // depends on control dependency: [if], data = [none]
}
else if ( ((LA51_0>=RULE_HEX && LA51_0<=RULE_DECIMAL)) ) {
alt51=4; // depends on control dependency: [if], data = [none]
}
else if ( (LA51_0==76) ) {
alt51=5; // depends on control dependency: [if], data = [none]
}
else if ( (LA51_0==RULE_STRING) ) {
alt51=6; // depends on control dependency: [if], data = [none]
}
else if ( (LA51_0==77) ) {
alt51=7; // depends on control dependency: [if], data = [none]
}
else {
if (state.backtracking>0) {state.failed=true; return current;} // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
NoViableAltException nvae =
new NoViableAltException("", 51, 0, input);
throw nvae;
}
switch (alt51) {
case 1 :
// InternalPureXbase.g:2874:3: this_XCollectionLiteral_0= ruleXCollectionLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXCollectionLiteralParserRuleCall_0()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_2);
this_XCollectionLiteral_0=ruleXCollectionLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XCollectionLiteral_0; // depends on control dependency: [if], data = [none]
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
}
break;
case 2 :
// InternalPureXbase.g:2883:3: ( ( ( () '[' ) )=>this_XClosure_1= ruleXClosure )
{
// InternalPureXbase.g:2883:3: ( ( ( () '[' ) )=>this_XClosure_1= ruleXClosure )
// InternalPureXbase.g:2884:4: ( ( () '[' ) )=>this_XClosure_1= ruleXClosure
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXClosureParserRuleCall_1()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_2);
this_XClosure_1=ruleXClosure();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XClosure_1; // depends on control dependency: [if], data = [none]
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
}
}
break;
case 3 :
// InternalPureXbase.g:2900:3: this_XBooleanLiteral_2= ruleXBooleanLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXBooleanLiteralParserRuleCall_2()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_2);
this_XBooleanLiteral_2=ruleXBooleanLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XBooleanLiteral_2; // depends on control dependency: [if], data = [none]
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
}
break;
case 4 :
// InternalPureXbase.g:2909:3: this_XNumberLiteral_3= ruleXNumberLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXNumberLiteralParserRuleCall_3()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_2);
this_XNumberLiteral_3=ruleXNumberLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XNumberLiteral_3; // depends on control dependency: [if], data = [none]
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
}
break;
case 5 :
// InternalPureXbase.g:2918:3: this_XNullLiteral_4= ruleXNullLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXNullLiteralParserRuleCall_4()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_2);
this_XNullLiteral_4=ruleXNullLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XNullLiteral_4; // depends on control dependency: [if], data = [none]
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
}
break;
case 6 :
// InternalPureXbase.g:2927:3: this_XStringLiteral_5= ruleXStringLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXStringLiteralParserRuleCall_5()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_2);
this_XStringLiteral_5=ruleXStringLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XStringLiteral_5; // depends on control dependency: [if], data = [none]
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
}
break;
case 7 :
// InternalPureXbase.g:2936:3: this_XTypeLiteral_6= ruleXTypeLiteral
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXLiteralAccess().getXTypeLiteralParserRuleCall_6()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_2);
this_XTypeLiteral_6=ruleXTypeLiteral();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current = this_XTypeLiteral_6; // depends on control dependency: [if], data = [none]
afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none]
}
}
break;
}
}
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 {
@Nonnull
public static File canonize(@Nonnull final File pFile)
{
String resultPath = null;
try {
resultPath = pFile.getCanonicalPath();
}
catch (IOException e) {
resultPath = pFile.getAbsolutePath();
}
return new File(standardizeSlashes(resultPath));
} } | public class class_name {
@Nonnull
public static File canonize(@Nonnull final File pFile)
{
String resultPath = null;
try {
resultPath = pFile.getCanonicalPath(); // depends on control dependency: [try], data = [none]
}
catch (IOException e) {
resultPath = pFile.getAbsolutePath();
} // depends on control dependency: [catch], data = [none]
return new File(standardizeSlashes(resultPath));
} } |
public class class_name {
public static final SymbolReference<ResolvedValueDeclaration> solveWith(SymbolDeclarator symbolDeclarator, String name) {
for (ResolvedValueDeclaration decl : symbolDeclarator.getSymbolDeclarations()) {
if (decl.getName().equals(name)) {
return SymbolReference.solved(decl);
}
}
return SymbolReference.unsolved(ResolvedValueDeclaration.class);
} } | public class class_name {
public static final SymbolReference<ResolvedValueDeclaration> solveWith(SymbolDeclarator symbolDeclarator, String name) {
for (ResolvedValueDeclaration decl : symbolDeclarator.getSymbolDeclarations()) {
if (decl.getName().equals(name)) {
return SymbolReference.solved(decl); // depends on control dependency: [if], data = [none]
}
}
return SymbolReference.unsolved(ResolvedValueDeclaration.class);
} } |
public class class_name {
boolean ignoreInterface(String interfaceName) {
for (String regex : this.properties.getIgnoredInterfaces()) {
if (interfaceName.matches(regex)) {
this.log.trace("Ignoring interface: " + interfaceName);
return true;
}
}
return false;
} } | public class class_name {
boolean ignoreInterface(String interfaceName) {
for (String regex : this.properties.getIgnoredInterfaces()) {
if (interfaceName.matches(regex)) {
this.log.trace("Ignoring interface: " + interfaceName); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public Object getBean(String className) {
try {
Class<?> clazz = Class.forName(className);
if (A_CmsJspCustomContextBean.class.isAssignableFrom(clazz)) {
Constructor<?> constructor = clazz.getConstructor();
Object instance = constructor.newInstance();
Method setContextMethod = clazz.getMethod("setContext", CmsJspStandardContextBean.class);
setContextMethod.invoke(instance, this);
return instance;
} else {
throw new Exception();
}
} catch (Exception e) {
LOG.error(Messages.get().container(Messages.ERR_NO_CUSTOM_BEAN_1, className));
}
return null;
} } | public class class_name {
public Object getBean(String className) {
try {
Class<?> clazz = Class.forName(className);
if (A_CmsJspCustomContextBean.class.isAssignableFrom(clazz)) {
Constructor<?> constructor = clazz.getConstructor();
Object instance = constructor.newInstance();
Method setContextMethod = clazz.getMethod("setContext", CmsJspStandardContextBean.class);
setContextMethod.invoke(instance, this); // depends on control dependency: [if], data = [none]
return instance; // depends on control dependency: [if], data = [none]
} else {
throw new Exception();
}
} catch (Exception e) {
LOG.error(Messages.get().container(Messages.ERR_NO_CUSTOM_BEAN_1, className));
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
public void setValues(java.util.Collection<Double> values) {
if (values == null) {
this.values = null;
return;
}
this.values = new com.amazonaws.internal.SdkInternalList<Double>(values);
} } | public class class_name {
public void setValues(java.util.Collection<Double> values) {
if (values == null) {
this.values = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.values = new com.amazonaws.internal.SdkInternalList<Double>(values);
} } |
public class class_name {
@Override
public ExecArgList removeArgsForOsFamily(String filepath, String osFamily) {
if ("windows".equalsIgnoreCase(osFamily)) {
return ExecArgList.fromStrings(false, "del", filepath);
} else {
return ExecArgList.fromStrings(false, "rm", "-f", filepath);
}
} } | public class class_name {
@Override
public ExecArgList removeArgsForOsFamily(String filepath, String osFamily) {
if ("windows".equalsIgnoreCase(osFamily)) {
return ExecArgList.fromStrings(false, "del", filepath); // depends on control dependency: [if], data = [none]
} else {
return ExecArgList.fromStrings(false, "rm", "-f", filepath); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String calcMoisture1500Kpa(String slsnd, String slcly, String omPct) {
if ((slsnd = checkPctVal(slsnd)) == null
|| (slcly = checkPctVal(slcly)) == null
|| (omPct = checkPctVal(omPct)) == null) {
LOG.error("Invalid input parameters for calculating 1500 kPa moisture, %v");
return null;
}
String ret = sum(product("-0.02736", slsnd), product("0.55518", slcly), product("0.684", omPct),
product("0.0057", slsnd, omPct), product("-0.01482", slcly, omPct), product("0.0007752", slsnd, slcly), "1.534");
LOG.debug("Calculate result for 1500 kPa moisture, %v is {}", ret);
return ret;
} } | public class class_name {
public static String calcMoisture1500Kpa(String slsnd, String slcly, String omPct) {
if ((slsnd = checkPctVal(slsnd)) == null
|| (slcly = checkPctVal(slcly)) == null
|| (omPct = checkPctVal(omPct)) == null) {
LOG.error("Invalid input parameters for calculating 1500 kPa moisture, %v"); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [null]
}
String ret = sum(product("-0.02736", slsnd), product("0.55518", slcly), product("0.684", omPct),
product("0.0057", slsnd, omPct), product("-0.01482", slcly, omPct), product("0.0007752", slsnd, slcly), "1.534");
LOG.debug("Calculate result for 1500 kPa moisture, %v is {}", ret);
return ret;
} } |
public class class_name {
@Override
public Map<String, Object> createUploadToken(UploadTokenParam param) {
Map<String, Object> result = new HashMap<>();
PolicyConditions policyConds = new PolicyConditions();
if(param.getFsizeMin() != null && param.getFsizeMax() != null){
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, param.getFsizeMin(), param.getFsizeMax());
}else{
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
}
if(param.getUploadDir() != null){
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, param.getUploadDir());
}
if(StringUtils.isBlank(param.getCallbackHost())){
param.setCallbackHost(host);
}
if(StringUtils.isBlank(param.getCallbackBody())){
param.setCallbackBody(DEFAULT_CALLBACK_BODY);
}
Date expire = DateUtils.addSeconds(new Date(), (int)param.getExpires());
String policy = ossClient.generatePostPolicy(expire, policyConds);
String policyBase64 = null;
String callbackBase64 = null;
try {
policyBase64 = BinaryUtil.toBase64String(policy.getBytes(StandardCharsets.UTF_8.name()));
String callbackJson = param.getCallbackRuleAsJson();
if(callbackJson != null){
callbackBase64 = BinaryUtil.toBase64String(callbackJson.getBytes(StandardCharsets.UTF_8.name()));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
String signature = ossClient.calculatePostSignature(policy);
result.put("OSSAccessKeyId", accessKeyId);
result.put("policy", policyBase64);
result.put("signature", signature);
result.put("host", this.urlprefix);
result.put("dir", param.getUploadDir());
result.put("expire", String.valueOf(expire.getTime()));
if(callbackBase64 != null){
result.put("callback", callbackBase64);
}
return result;
} } | public class class_name {
@Override
public Map<String, Object> createUploadToken(UploadTokenParam param) {
Map<String, Object> result = new HashMap<>();
PolicyConditions policyConds = new PolicyConditions();
if(param.getFsizeMin() != null && param.getFsizeMax() != null){
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, param.getFsizeMin(), param.getFsizeMax()); // depends on control dependency: [if], data = [none]
}else{
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000); // depends on control dependency: [if], data = [none]
}
if(param.getUploadDir() != null){
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, param.getUploadDir()); // depends on control dependency: [if], data = [none]
}
if(StringUtils.isBlank(param.getCallbackHost())){
param.setCallbackHost(host); // depends on control dependency: [if], data = [none]
}
if(StringUtils.isBlank(param.getCallbackBody())){
param.setCallbackBody(DEFAULT_CALLBACK_BODY); // depends on control dependency: [if], data = [none]
}
Date expire = DateUtils.addSeconds(new Date(), (int)param.getExpires());
String policy = ossClient.generatePostPolicy(expire, policyConds);
String policyBase64 = null;
String callbackBase64 = null;
try {
policyBase64 = BinaryUtil.toBase64String(policy.getBytes(StandardCharsets.UTF_8.name())); // depends on control dependency: [try], data = [none]
String callbackJson = param.getCallbackRuleAsJson();
if(callbackJson != null){
callbackBase64 = BinaryUtil.toBase64String(callbackJson.getBytes(StandardCharsets.UTF_8.name())); // depends on control dependency: [if], data = [(callbackJson]
}
} catch (Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
String signature = ossClient.calculatePostSignature(policy);
result.put("OSSAccessKeyId", accessKeyId);
result.put("policy", policyBase64);
result.put("signature", signature);
result.put("host", this.urlprefix);
result.put("dir", param.getUploadDir());
result.put("expire", String.valueOf(expire.getTime()));
if(callbackBase64 != null){
result.put("callback", callbackBase64); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public void dfsSpanningTree(Vertex<T> v, DFSVisitor<T> visitor)
{
v.visit();
if( visitor != null )
visitor.visit(this, v);
for (int i = 0; i < v.getOutgoingEdgeCount(); i++)
{
Edge<T> e = v.getOutgoingEdge(i);
if (!e.getTo().visited())
{
if( visitor != null )
visitor.visit(this, v, e);
e.mark();
dfsSpanningTree(e.getTo(), visitor);
}
}
} } | public class class_name {
public void dfsSpanningTree(Vertex<T> v, DFSVisitor<T> visitor)
{
v.visit();
if( visitor != null )
visitor.visit(this, v);
for (int i = 0; i < v.getOutgoingEdgeCount(); i++)
{
Edge<T> e = v.getOutgoingEdge(i);
if (!e.getTo().visited())
{
if( visitor != null )
visitor.visit(this, v, e);
e.mark(); // depends on control dependency: [if], data = [none]
dfsSpanningTree(e.getTo(), visitor); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
protected void initMaxCellWidth() {
m_maxCellWidth = m_opener.getOffsetWidth() - 2 /*border*/;
for (Widget widget : m_selector) {
if (widget instanceof A_CmsSelectCell) {
int cellWidth = ((A_CmsSelectCell)widget).getRequiredWidth();
if (cellWidth > m_maxCellWidth) {
m_maxCellWidth = cellWidth;
}
}
}
} } | public class class_name {
protected void initMaxCellWidth() {
m_maxCellWidth = m_opener.getOffsetWidth() - 2 /*border*/;
for (Widget widget : m_selector) {
if (widget instanceof A_CmsSelectCell) {
int cellWidth = ((A_CmsSelectCell)widget).getRequiredWidth();
if (cellWidth > m_maxCellWidth) {
m_maxCellWidth = cellWidth; // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
private static FileSystem getJarFs(Path jarFile) throws IOException {
Path key = jarFile.toAbsolutePath();
synchronized (ZIP_FILESYSTEMS) {
FsWrapper fs = ZIP_FILESYSTEMS.get(key);
if (fs == null) {
fs = new FsWrapper(FileSystems.newFileSystem(key, null), key);
fs.incrRefCount();
ZIP_FILESYSTEMS.put(key, fs);
} else {
fs.incrRefCount();
}
return fs;
}
} } | public class class_name {
private static FileSystem getJarFs(Path jarFile) throws IOException {
Path key = jarFile.toAbsolutePath();
synchronized (ZIP_FILESYSTEMS) {
FsWrapper fs = ZIP_FILESYSTEMS.get(key);
if (fs == null) {
fs = new FsWrapper(FileSystems.newFileSystem(key, null), key); // depends on control dependency: [if], data = [null)]
fs.incrRefCount(); // depends on control dependency: [if], data = [none]
ZIP_FILESYSTEMS.put(key, fs); // depends on control dependency: [if], data = [none]
} else {
fs.incrRefCount(); // depends on control dependency: [if], data = [none]
}
return fs;
}
} } |
public class class_name {
private void divide(int[] idx, double[] data, ArrayList<int[]> ret, int start, int end, int depth) {
if(depth == 0) {
int[] a = Arrays.copyOfRange(idx, start, end);
Arrays.sort(a);
ret.add(a);
return;
}
final int count = end - start;
if(count == 0) {
// Corner case, that should barely happen. But for ties, we currently
// Do not yet assure that it doesn't happen!
for(int j = 1 << depth; j > 0; --j) {
ret.add(new int[0]);
}
return;
}
double m = 0.;
for(int i = start; i < end; i++) {
m += data[i];
}
m /= count;
int pos = Arrays.binarySearch(data, start, end, m);
if(pos >= 0) {
// Ties: try to choose the most central element.
final int opt = (start + end) >> 1;
while(data[pos] == m) {
if(pos < opt) {
pos++;
}
else if(pos > opt) {
pos--;
}
else {
break;
}
}
}
else {
pos = (-pos - 1);
}
divide(idx, data, ret, start, pos, depth - 1);
divide(idx, data, ret, pos, end, depth - 1);
} } | public class class_name {
private void divide(int[] idx, double[] data, ArrayList<int[]> ret, int start, int end, int depth) {
if(depth == 0) {
int[] a = Arrays.copyOfRange(idx, start, end);
Arrays.sort(a); // depends on control dependency: [if], data = [none]
ret.add(a); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
final int count = end - start;
if(count == 0) {
// Corner case, that should barely happen. But for ties, we currently
// Do not yet assure that it doesn't happen!
for(int j = 1 << depth; j > 0; --j) {
ret.add(new int[0]); // depends on control dependency: [for], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
double m = 0.;
for(int i = start; i < end; i++) {
m += data[i]; // depends on control dependency: [for], data = [i]
}
m /= count;
int pos = Arrays.binarySearch(data, start, end, m);
if(pos >= 0) {
// Ties: try to choose the most central element.
final int opt = (start + end) >> 1;
while(data[pos] == m) {
if(pos < opt) {
pos++; // depends on control dependency: [if], data = [none]
}
else if(pos > opt) {
pos--; // depends on control dependency: [if], data = [none]
}
else {
break;
}
}
}
else {
pos = (-pos - 1); // depends on control dependency: [if], data = [none]
}
divide(idx, data, ret, start, pos, depth - 1);
divide(idx, data, ret, pos, end, depth - 1);
} } |
public class class_name {
protected void unregister(IConnection conn, boolean deleteIfNoConns) {
log.debug("Unregister connection ({}:{}) client id: {}", conn.getRemoteAddress(), conn.getRemotePort(), id);
// remove connection from connected scopes list
connections.remove(conn);
// If client is not connected to any scope any longer then remove
if (deleteIfNoConns && connections.isEmpty()) {
// TODO DW dangerous the way this is called from BaseConnection.initialize(). Could we unexpectedly pop a Client out of the registry?
removeInstance();
}
} } | public class class_name {
protected void unregister(IConnection conn, boolean deleteIfNoConns) {
log.debug("Unregister connection ({}:{}) client id: {}", conn.getRemoteAddress(), conn.getRemotePort(), id);
// remove connection from connected scopes list
connections.remove(conn);
// If client is not connected to any scope any longer then remove
if (deleteIfNoConns && connections.isEmpty()) {
// TODO DW dangerous the way this is called from BaseConnection.initialize(). Could we unexpectedly pop a Client out of the registry?
removeInstance();
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected void bumpLit(final int lit) {
final double maxPriority = 1e300;
final int idx = Math.abs(lit);
double oldPriority;
if (this.scoreIncrement > maxPriority || (oldPriority = this.decisions.priority(idx)) > maxPriority) {
rescore();
oldPriority = this.decisions.priority(idx);
}
final double newPriority = oldPriority + this.scoreIncrement;
this.decisions.update(idx, newPriority);
} } | public class class_name {
protected void bumpLit(final int lit) {
final double maxPriority = 1e300;
final int idx = Math.abs(lit);
double oldPriority;
if (this.scoreIncrement > maxPriority || (oldPriority = this.decisions.priority(idx)) > maxPriority) {
rescore(); // depends on control dependency: [if], data = [none]
oldPriority = this.decisions.priority(idx); // depends on control dependency: [if], data = [none]
}
final double newPriority = oldPriority + this.scoreIncrement;
this.decisions.update(idx, newPriority);
} } |
public class class_name {
public Object getTag() {
Object result = null;
if (view != null) {
result = view.getTag();
}
return result;
} } | public class class_name {
public Object getTag() {
Object result = null;
if (view != null) {
result = view.getTag(); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public void addPreferredLanguages(String preferredLanguages) {
if (preferredLanguages != null && !preferredLanguages.trim().isEmpty()) {
setPreferredLanguages(Arrays.asList(preferredLanguages.split(",")));
}
} } | public class class_name {
public void addPreferredLanguages(String preferredLanguages) {
if (preferredLanguages != null && !preferredLanguages.trim().isEmpty()) {
setPreferredLanguages(Arrays.asList(preferredLanguages.split(","))); // depends on control dependency: [if], data = [(preferredLanguages]
}
} } |
public class class_name {
@Override
public String getNameFor(Cluster<?> cluster) {
String nam = names.get(cluster);
if(nam == null) {
updateNames();
nam = names.get(cluster);
}
if(nam.endsWith(NULLPOSTFIX)) {
String basename = nam.substring(0, nam.length() - NULLPOSTFIX.length());
if(namefreq.getInt(basename) == 1) {
nam = basename;
}
}
return nam;
} } | public class class_name {
@Override
public String getNameFor(Cluster<?> cluster) {
String nam = names.get(cluster);
if(nam == null) {
updateNames(); // depends on control dependency: [if], data = [none]
nam = names.get(cluster); // depends on control dependency: [if], data = [none]
}
if(nam.endsWith(NULLPOSTFIX)) {
String basename = nam.substring(0, nam.length() - NULLPOSTFIX.length());
if(namefreq.getInt(basename) == 1) {
nam = basename; // depends on control dependency: [if], data = [none]
}
}
return nam;
} } |
public class class_name {
@Override
protected void afterPaint(final RenderContext renderContext) {
super.afterPaint(renderContext);
// UIC serialization stats
UicStats stats = new UicStats(UIContextHolder.getCurrent());
stats.analyseWC(this);
if (renderContext instanceof WebXmlRenderContext) {
PrintWriter writer = ((WebXmlRenderContext) renderContext).getWriter();
writer.println("<h2>Serialization Profile of UIC</h2>");
UicStatsAsHtml.write(writer, stats);
// ObjectProfiler
writer.println("<h2>ObjectProfiler - " + getClass().getName() + "</h2>");
writer.println("<pre>");
try {
writer.println(ObjectGraphDump.dump(this).toFlatSummary());
} catch (Exception e) {
LOG.error("Failed to dump component", e);
}
writer.println("</pre>");
}
} } | public class class_name {
@Override
protected void afterPaint(final RenderContext renderContext) {
super.afterPaint(renderContext);
// UIC serialization stats
UicStats stats = new UicStats(UIContextHolder.getCurrent());
stats.analyseWC(this);
if (renderContext instanceof WebXmlRenderContext) {
PrintWriter writer = ((WebXmlRenderContext) renderContext).getWriter();
writer.println("<h2>Serialization Profile of UIC</h2>"); // depends on control dependency: [if], data = [none]
UicStatsAsHtml.write(writer, stats); // depends on control dependency: [if], data = [none]
// ObjectProfiler
writer.println("<h2>ObjectProfiler - " + getClass().getName() + "</h2>"); // depends on control dependency: [if], data = [none]
writer.println("<pre>"); // depends on control dependency: [if], data = [none]
try {
writer.println(ObjectGraphDump.dump(this).toFlatSummary()); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
LOG.error("Failed to dump component", e);
} // depends on control dependency: [catch], data = [none]
writer.println("</pre>"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public final int strNCmp(byte[]bytes, int p, int end, byte[]ascii, int asciiP, int n) {
while (n-- > 0) {
if (p >= end) return ascii[asciiP];
int c = mbcToCode(bytes, p, end);
int x = ascii[asciiP] - c;
if (x != 0) return x;
asciiP++;
p += length(bytes, p, end);
}
return 0;
} } | public class class_name {
public final int strNCmp(byte[]bytes, int p, int end, byte[]ascii, int asciiP, int n) {
while (n-- > 0) {
if (p >= end) return ascii[asciiP];
int c = mbcToCode(bytes, p, end);
int x = ascii[asciiP] - c;
if (x != 0) return x;
asciiP++; // depends on control dependency: [while], data = [none]
p += length(bytes, p, end); // depends on control dependency: [while], data = [none]
}
return 0;
} } |
public class class_name {
private void generateRuleDependencyGraph(List<CQIE> program) {
for (CQIE rule : program) {
ruleDependencyGraph.addVertex(rule);
Predicate headPred = rule.getHead().getFunctionSymbol();
Set<DefaultEdge> ontgoingEdges = predicateDependencyGraph
.outgoingEdgesOf(headPred);
for (DefaultEdge e : ontgoingEdges) {
Predicate edgeTarget = predicateDependencyGraph
.getEdgeTarget(e);
Collection<CQIE> rules = ruleIndex.get(edgeTarget);
if (rules != null) {
for (CQIE dependentRule : rules) {
ruleDependencyGraph.addVertex(dependentRule);
ruleDependencyGraph.addEdge(rule, dependentRule);
}
}
}
}
} } | public class class_name {
private void generateRuleDependencyGraph(List<CQIE> program) {
for (CQIE rule : program) {
ruleDependencyGraph.addVertex(rule); // depends on control dependency: [for], data = [rule]
Predicate headPred = rule.getHead().getFunctionSymbol();
Set<DefaultEdge> ontgoingEdges = predicateDependencyGraph
.outgoingEdgesOf(headPred);
for (DefaultEdge e : ontgoingEdges) {
Predicate edgeTarget = predicateDependencyGraph
.getEdgeTarget(e);
Collection<CQIE> rules = ruleIndex.get(edgeTarget);
if (rules != null) {
for (CQIE dependentRule : rules) {
ruleDependencyGraph.addVertex(dependentRule); // depends on control dependency: [for], data = [dependentRule]
ruleDependencyGraph.addEdge(rule, dependentRule); // depends on control dependency: [for], data = [dependentRule]
}
}
}
}
} } |
public class class_name {
public void marshall(UpdateGcmChannelRequest updateGcmChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (updateGcmChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateGcmChannelRequest.getApplicationId(), APPLICATIONID_BINDING);
protocolMarshaller.marshall(updateGcmChannelRequest.getGCMChannelRequest(), GCMCHANNELREQUEST_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UpdateGcmChannelRequest updateGcmChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (updateGcmChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateGcmChannelRequest.getApplicationId(), APPLICATIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateGcmChannelRequest.getGCMChannelRequest(), GCMCHANNELREQUEST_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 IComplexNDArray put(int i, INDArray element) {
if (element == null)
throw new IllegalArgumentException("Unable to insert null element");
assert element.isScalar() : "Unable to insert non scalar element";
if (element instanceof IComplexNDArray) {
IComplexNDArray n1 = (IComplexNDArray) element;
IComplexNumber n = n1.getComplex(0);
put(i, n);
} else
putScalar(i, Nd4j.createDouble(element.getDouble(0), 0.0));
return this;
} } | public class class_name {
@Override
public IComplexNDArray put(int i, INDArray element) {
if (element == null)
throw new IllegalArgumentException("Unable to insert null element");
assert element.isScalar() : "Unable to insert non scalar element";
if (element instanceof IComplexNDArray) {
IComplexNDArray n1 = (IComplexNDArray) element;
IComplexNumber n = n1.getComplex(0);
put(i, n); // depends on control dependency: [if], data = [none]
} else
putScalar(i, Nd4j.createDouble(element.getDouble(0), 0.0));
return this;
} } |
public class class_name {
static String pad(final String data, final char doPadWithThis, final int totalWidth, final Alignment orientation) {
final String pad = repeat(new String(new char[]{doPadWithThis}), Math.max(0, totalWidth - data.length()));
String returnVal = "";
if (orientation == null) {
returnVal = data + pad;
} else {
switch (orientation) {
case Center:
returnVal = pad.substring(0, pad.length() / 2) + data + pad.substring(pad.length() / 2, pad.length());
break;
case Right:
returnVal = pad + data;
break;
default:
returnVal = data + pad;
}
}
return returnVal;
} } | public class class_name {
static String pad(final String data, final char doPadWithThis, final int totalWidth, final Alignment orientation) {
final String pad = repeat(new String(new char[]{doPadWithThis}), Math.max(0, totalWidth - data.length()));
String returnVal = "";
if (orientation == null) {
returnVal = data + pad; // depends on control dependency: [if], data = [none]
} else {
switch (orientation) {
case Center:
returnVal = pad.substring(0, pad.length() / 2) + data + pad.substring(pad.length() / 2, pad.length());
break;
case Right:
returnVal = pad + data;
break;
default:
returnVal = data + pad;
}
}
return returnVal;
} } |
public class class_name {
@SneakyThrows
public Event terminate(final RequestContext context) {
val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context);
val tgtId = getTicketGrantingTicket(context);
if (StringUtils.isNotBlank(tgtId)) {
LOGGER.trace("Destroying SSO session linked to ticket-granting ticket [{}]", tgtId);
val logoutRequests = this.centralAuthenticationService.destroyTicketGrantingTicket(tgtId);
WebUtils.putLogoutRequests(context, logoutRequests);
}
LOGGER.trace("Removing CAS cookies");
this.ticketGrantingTicketCookieGenerator.removeCookie(response);
this.warnCookieGenerator.removeCookie(response);
destroyApplicationSession(request, response);
LOGGER.debug("Terminated all CAS sessions successfully.");
if (StringUtils.isNotBlank(logoutProperties.getRedirectUrl())) {
WebUtils.putLogoutRedirectUrl(context, logoutProperties.getRedirectUrl());
return this.eventFactorySupport.event(this, CasWebflowConstants.STATE_ID_REDIRECT);
}
return this.eventFactorySupport.success(this);
} } | public class class_name {
@SneakyThrows
public Event terminate(final RequestContext context) {
val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context);
val tgtId = getTicketGrantingTicket(context);
if (StringUtils.isNotBlank(tgtId)) {
LOGGER.trace("Destroying SSO session linked to ticket-granting ticket [{}]", tgtId);
val logoutRequests = this.centralAuthenticationService.destroyTicketGrantingTicket(tgtId);
WebUtils.putLogoutRequests(context, logoutRequests); // depends on control dependency: [if], data = [none]
}
LOGGER.trace("Removing CAS cookies");
this.ticketGrantingTicketCookieGenerator.removeCookie(response);
this.warnCookieGenerator.removeCookie(response);
destroyApplicationSession(request, response);
LOGGER.debug("Terminated all CAS sessions successfully.");
if (StringUtils.isNotBlank(logoutProperties.getRedirectUrl())) {
WebUtils.putLogoutRedirectUrl(context, logoutProperties.getRedirectUrl()); // depends on control dependency: [if], data = [none]
return this.eventFactorySupport.event(this, CasWebflowConstants.STATE_ID_REDIRECT); // depends on control dependency: [if], data = [none]
}
return this.eventFactorySupport.success(this);
} } |
public class class_name {
public void setAttribute(String key, Object attribute) {
if(!isValid()) {
throw new IllegalStateException("Can not bind object to session that has been invalidated!!");
}
if(key == null) {
throw new NullPointerException("Name of attribute to bind cant be null!!!");
}
if(attribute == null) {
throw new NullPointerException("Attribute that is to be bound cant be null!!!");
}
// Construct an event with the new value
SipSessionBindingEvent event = null;
// Call the valueBound() method if necessary
if (attribute instanceof SipSessionBindingListener) {
// Don't call any notification if replacing with the same value
Object oldValue = getAttributeMap().get(key);
if (attribute != oldValue) {
event = new SipSessionBindingEvent(this, key);
try {
((SipSessionBindingListener) attribute).valueBound(event);
} catch (Throwable t){
logger.error("SipSessionBindingListener threw exception", t);
}
}
}
Object previousValue = this.getAttributeMap().put(key, attribute);
if (previousValue != null && previousValue != attribute &&
previousValue instanceof SipSessionBindingListener) {
try {
((SipSessionBindingListener) previousValue).valueUnbound
(new SipSessionBindingEvent(this, key));
} catch (Throwable t) {
logger.error("SipSessionBindingListener threw exception", t);
}
}
// Notifying Listeners of attribute addition or modification
SipListeners sipListenersHolder = this.getSipApplicationSession().getSipContext().getListeners();
List<SipSessionAttributeListener> listenersList = sipListenersHolder.getSipSessionAttributeListeners();
if(listenersList.size() > 0) {
if(event == null) {
event = new SipSessionBindingEvent(this, key);
}
if (previousValue == null) {
// This is initial, we need to send value bound event
for (SipSessionAttributeListener listener : listenersList) {
if(logger.isDebugEnabled()) {
logger.debug("notifying SipSessionAttributeListener " + listener.getClass().getCanonicalName() + " of attribute added on key "+ key);
}
try {
listener.attributeAdded(event);
} catch (Throwable t) {
logger.error("SipSessionAttributeListener threw exception", t);
}
}
} else {
for (SipSessionAttributeListener listener : listenersList) {
if(logger.isDebugEnabled()) {
logger.debug("notifying SipSessionAttributeListener " + listener.getClass().getCanonicalName() + " of attribute replaced on key "+ key);
}
try {
listener.attributeReplaced(event);
} catch (Throwable t) {
logger.error("SipSessionAttributeListener threw exception", t);
}
}
}
}
} } | public class class_name {
public void setAttribute(String key, Object attribute) {
if(!isValid()) {
throw new IllegalStateException("Can not bind object to session that has been invalidated!!");
}
if(key == null) {
throw new NullPointerException("Name of attribute to bind cant be null!!!");
}
if(attribute == null) {
throw new NullPointerException("Attribute that is to be bound cant be null!!!");
}
// Construct an event with the new value
SipSessionBindingEvent event = null;
// Call the valueBound() method if necessary
if (attribute instanceof SipSessionBindingListener) {
// Don't call any notification if replacing with the same value
Object oldValue = getAttributeMap().get(key);
if (attribute != oldValue) {
event = new SipSessionBindingEvent(this, key); // depends on control dependency: [if], data = [none]
try {
((SipSessionBindingListener) attribute).valueBound(event); // depends on control dependency: [try], data = [none]
} catch (Throwable t){
logger.error("SipSessionBindingListener threw exception", t);
} // depends on control dependency: [catch], data = [none]
}
}
Object previousValue = this.getAttributeMap().put(key, attribute);
if (previousValue != null && previousValue != attribute &&
previousValue instanceof SipSessionBindingListener) {
try {
((SipSessionBindingListener) previousValue).valueUnbound
(new SipSessionBindingEvent(this, key)); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
logger.error("SipSessionBindingListener threw exception", t);
} // depends on control dependency: [catch], data = [none]
}
// Notifying Listeners of attribute addition or modification
SipListeners sipListenersHolder = this.getSipApplicationSession().getSipContext().getListeners();
List<SipSessionAttributeListener> listenersList = sipListenersHolder.getSipSessionAttributeListeners();
if(listenersList.size() > 0) {
if(event == null) {
event = new SipSessionBindingEvent(this, key); // depends on control dependency: [if], data = [none]
}
if (previousValue == null) {
// This is initial, we need to send value bound event
for (SipSessionAttributeListener listener : listenersList) {
if(logger.isDebugEnabled()) {
logger.debug("notifying SipSessionAttributeListener " + listener.getClass().getCanonicalName() + " of attribute added on key "+ key); // depends on control dependency: [if], data = [none]
}
try {
listener.attributeAdded(event); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
logger.error("SipSessionAttributeListener threw exception", t);
} // depends on control dependency: [catch], data = [none]
}
} else {
for (SipSessionAttributeListener listener : listenersList) {
if(logger.isDebugEnabled()) {
logger.debug("notifying SipSessionAttributeListener " + listener.getClass().getCanonicalName() + " of attribute replaced on key "+ key); // depends on control dependency: [if], data = [none]
}
try {
listener.attributeReplaced(event); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
logger.error("SipSessionAttributeListener threw exception", t);
} // depends on control dependency: [catch], data = [none]
}
}
}
} } |
public class class_name {
public void setWeight(int i, double w)
{
if(i >= size() || i < 0)
throw new IndexOutOfBoundsException("Dataset has only " + size() + " members, can't access index " + i );
else if(Double.isNaN(w) || Double.isInfinite(w) || w < 0)
throw new ArithmeticException("Invalid weight assignment of " + w);
if(w == 1 && weights == null)
return;//nothing to do, already handled implicitly
if(weights == null)//need to init?
{
weights = new double[size()];
Arrays.fill(weights, 1.0);
}
//make sure we have enouh space
if (weights.length <= i)
weights = Arrays.copyOfRange(weights, 0, Math.max(weights.length*2, i+1));
weights[i] = w;
} } | public class class_name {
public void setWeight(int i, double w)
{
if(i >= size() || i < 0)
throw new IndexOutOfBoundsException("Dataset has only " + size() + " members, can't access index " + i );
else if(Double.isNaN(w) || Double.isInfinite(w) || w < 0)
throw new ArithmeticException("Invalid weight assignment of " + w);
if(w == 1 && weights == null)
return;//nothing to do, already handled implicitly
if(weights == null)//need to init?
{
weights = new double[size()];
// depends on control dependency: [if], data = [none]
Arrays.fill(weights, 1.0);
// depends on control dependency: [if], data = [(weights]
}
//make sure we have enouh space
if (weights.length <= i)
weights = Arrays.copyOfRange(weights, 0, Math.max(weights.length*2, i+1));
weights[i] = w;
} } |
public class class_name {
public void convertTo(Type toType, boolean preferCast) {
Type fromType = getType();
Type actual = Type.preserveType(fromType, toType);
if (actual.equals(fromType)) {
return;
}
boolean legal = false;
if (!preferCast && fromType == Type.NULL_TYPE) {
preferCast = true;
}
if (fromType == null) {
legal = true;
}
else if (fromType.isPrimitive()) {
if (actual.isPrimitive()) {
if (actual.getNaturalClass() != void.class) {
legal = true;
}
}
else {
Class<?> fromObj = fromType.getObjectClass();
Class<?> toObj = actual.getObjectClass();
if (toObj.isAssignableFrom(fromObj)) {
legal = true;
if (fromObj != toObj) {
actual = fromType.toNonPrimitive();
}
}
else if (Number.class.isAssignableFrom(fromObj) &&
actual.hasPrimitivePeer()) {
if (Number.class.isAssignableFrom(toObj)) {
legal = true;
convertTo(actual.toPrimitive());
}
else if (Character.class.isAssignableFrom(toObj)) {
legal = true;
convertTo(new Type(char.class));
}
}
}
}
else {
// From non-primitive...
if (actual.isPrimitive()) {
if (fromType.hasPrimitivePeer()) {
legal = true;
if (fromType.isNullable()) {
// NullPointerException is possible.
mExceptionPossible = true;
}
Type fromPrim = fromType.toPrimitive();
if (fromPrim.getNaturalClass() !=
actual.getNaturalClass()) {
convertTo(fromPrim);
}
}
else {
Class<?> fromObj = fromType.getObjectClass();
Class<?> toObj = actual.getObjectClass();
if (Number.class.isAssignableFrom(fromObj) &&
Number.class.isAssignableFrom(toObj)) {
legal = true;
if (fromType.isNullable()) {
// NullPointerException is possible.
mExceptionPossible = true;
}
}
else if (preferCast) {
legal = true;
convertTo(actual.toNonPrimitive(), true);
}
}
}
else {
Class<?> fromObj = fromType.getObjectClass();
Class<?> toObj = actual.getObjectClass();
if (fromObj.equals(toObj)) {
legal = true;
if (fromType.isNonNull() || !actual.isNonNull()) {
// No useful conversion applied, bail out.
return;
}
}
else if (fromObj.isAssignableFrom(toObj)) {
// Downcast.
if (preferCast) {
legal = true;
}
}
else if (toObj.isAssignableFrom(fromObj)) {
// Upcast.
legal = true;
if (fromType.isNonNull() || !actual.isNonNull()) {
// No useful conversion applied, bail out.
return;
}
}
else if (Number.class.isAssignableFrom(fromObj) &&
Number.class.isAssignableFrom(toObj) &&
actual.hasPrimitivePeer()) {
// Conversion like Integer -> Double.
legal = true;
if (fromType.isNonNull()) {
convertTo(actual.toPrimitive(), true);
}
}
// This test only captures array conversions.
else if (fromObj.getComponentType() != null &&
toObj.getComponentType() != null &&
actual.convertableFrom(fromType) >= 0) {
legal = true;
if (fromType.isNullable()) {
// NullPointerException is possible.
mExceptionPossible = true;
}
}
}
}
if (!legal) {
// Try String conversion.
if (actual.getNaturalClass().isAssignableFrom(String.class)) {
legal = true;
if (actual.isNonNull()) {
addConversion(Type.NON_NULL_STRING_TYPE, false);
}
else {
addConversion(Type.STRING_TYPE, false);
}
}
}
if (!legal && !preferCast &&
!fromType.isPrimitive() && !actual.isPrimitive()) {
// Even though a cast isn't preferred, its the last available
// option.
Class<?> fromObj = fromType.getObjectClass();
Class<?> toObj = actual.getObjectClass();
if (fromObj.isAssignableFrom(toObj)) {
// Downcast.
legal = true;
}
else if (toObj.isAssignableFrom(fromObj)) {
// Upcast.
legal = true;
}
}
if (legal) {
addConversion(actual, preferCast);
}
else {
throw new IllegalArgumentException("Can't convert " + fromType +
" to " + toType);
}
} } | public class class_name {
public void convertTo(Type toType, boolean preferCast) {
Type fromType = getType();
Type actual = Type.preserveType(fromType, toType);
if (actual.equals(fromType)) {
return; // depends on control dependency: [if], data = [none]
}
boolean legal = false;
if (!preferCast && fromType == Type.NULL_TYPE) {
preferCast = true; // depends on control dependency: [if], data = [none]
}
if (fromType == null) {
legal = true; // depends on control dependency: [if], data = [none]
}
else if (fromType.isPrimitive()) {
if (actual.isPrimitive()) {
if (actual.getNaturalClass() != void.class) {
legal = true; // depends on control dependency: [if], data = [none]
}
}
else {
Class<?> fromObj = fromType.getObjectClass();
Class<?> toObj = actual.getObjectClass();
if (toObj.isAssignableFrom(fromObj)) {
legal = true; // depends on control dependency: [if], data = [none]
if (fromObj != toObj) {
actual = fromType.toNonPrimitive(); // depends on control dependency: [if], data = [none]
}
}
else if (Number.class.isAssignableFrom(fromObj) &&
actual.hasPrimitivePeer()) {
if (Number.class.isAssignableFrom(toObj)) {
legal = true; // depends on control dependency: [if], data = [none]
convertTo(actual.toPrimitive()); // depends on control dependency: [if], data = [none]
}
else if (Character.class.isAssignableFrom(toObj)) {
legal = true; // depends on control dependency: [if], data = [none]
convertTo(new Type(char.class)); // depends on control dependency: [if], data = [none]
}
}
}
}
else {
// From non-primitive...
if (actual.isPrimitive()) {
if (fromType.hasPrimitivePeer()) {
legal = true; // depends on control dependency: [if], data = [none]
if (fromType.isNullable()) {
// NullPointerException is possible.
mExceptionPossible = true; // depends on control dependency: [if], data = [none]
}
Type fromPrim = fromType.toPrimitive();
if (fromPrim.getNaturalClass() !=
actual.getNaturalClass()) {
convertTo(fromPrim); // depends on control dependency: [if], data = [none]
}
}
else {
Class<?> fromObj = fromType.getObjectClass();
Class<?> toObj = actual.getObjectClass();
if (Number.class.isAssignableFrom(fromObj) &&
Number.class.isAssignableFrom(toObj)) {
legal = true; // depends on control dependency: [if], data = [none]
if (fromType.isNullable()) {
// NullPointerException is possible.
mExceptionPossible = true; // depends on control dependency: [if], data = [none]
}
}
else if (preferCast) {
legal = true; // depends on control dependency: [if], data = [none]
convertTo(actual.toNonPrimitive(), true); // depends on control dependency: [if], data = [none]
}
}
}
else {
Class<?> fromObj = fromType.getObjectClass();
Class<?> toObj = actual.getObjectClass();
if (fromObj.equals(toObj)) {
legal = true; // depends on control dependency: [if], data = [none]
if (fromType.isNonNull() || !actual.isNonNull()) {
// No useful conversion applied, bail out.
return; // depends on control dependency: [if], data = [none]
}
}
else if (fromObj.isAssignableFrom(toObj)) {
// Downcast.
if (preferCast) {
legal = true; // depends on control dependency: [if], data = [none]
}
}
else if (toObj.isAssignableFrom(fromObj)) {
// Upcast.
legal = true; // depends on control dependency: [if], data = [none]
if (fromType.isNonNull() || !actual.isNonNull()) {
// No useful conversion applied, bail out.
return; // depends on control dependency: [if], data = [none]
}
}
else if (Number.class.isAssignableFrom(fromObj) &&
Number.class.isAssignableFrom(toObj) &&
actual.hasPrimitivePeer()) {
// Conversion like Integer -> Double.
legal = true; // depends on control dependency: [if], data = [none]
if (fromType.isNonNull()) {
convertTo(actual.toPrimitive(), true); // depends on control dependency: [if], data = [none]
}
}
// This test only captures array conversions.
else if (fromObj.getComponentType() != null &&
toObj.getComponentType() != null &&
actual.convertableFrom(fromType) >= 0) {
legal = true; // depends on control dependency: [if], data = [none]
if (fromType.isNullable()) {
// NullPointerException is possible.
mExceptionPossible = true; // depends on control dependency: [if], data = [none]
}
}
}
}
if (!legal) {
// Try String conversion.
if (actual.getNaturalClass().isAssignableFrom(String.class)) {
legal = true; // depends on control dependency: [if], data = [none]
if (actual.isNonNull()) {
addConversion(Type.NON_NULL_STRING_TYPE, false); // depends on control dependency: [if], data = [none]
}
else {
addConversion(Type.STRING_TYPE, false); // depends on control dependency: [if], data = [none]
}
}
}
if (!legal && !preferCast &&
!fromType.isPrimitive() && !actual.isPrimitive()) {
// Even though a cast isn't preferred, its the last available
// option.
Class<?> fromObj = fromType.getObjectClass();
Class<?> toObj = actual.getObjectClass();
if (fromObj.isAssignableFrom(toObj)) {
// Downcast.
legal = true; // depends on control dependency: [if], data = [none]
}
else if (toObj.isAssignableFrom(fromObj)) {
// Upcast.
legal = true; // depends on control dependency: [if], data = [none]
}
}
if (legal) {
addConversion(actual, preferCast); // depends on control dependency: [if], data = [none]
}
else {
throw new IllegalArgumentException("Can't convert " + fromType +
" to " + toType);
}
} } |
public class class_name {
public void postProcess() {
if (!this.isEmptySlot()) {
switch (savedItem.getExpressionItemType()) {
case OPERATOR: {
if (savedItem == OPERATOR_SUB) {
if (!childElements[0].isEmptySlot() && childElements[1].isEmptySlot()) {
final ExpressionTreeElement left = childElements[0];
final ExpressionItem item = left.getItem();
if (item.getExpressionItemType() == ExpressionItemType.VALUE) {
final Value val = (Value) item;
switch (val.getType()) {
case INT: {
childElements = EMPTY;
savedItem = Value.valueOf(0 - val.asLong());
makeMaxPriority();
}
break;
case FLOAT: {
childElements = EMPTY;
savedItem = Value.valueOf(0.0f - val.asFloat());
makeMaxPriority();
}
break;
default: {
if (!left.isEmptySlot()) {
left.postProcess();
}
}
break;
}
}
} else {
for (final ExpressionTreeElement element : childElements) {
if (!element.isEmptySlot()) {
element.postProcess();
}
}
}
} else {
for (final ExpressionTreeElement element : childElements) {
if (!element.isEmptySlot()) {
element.postProcess();
}
}
}
}
break;
case FUNCTION: {
for (final ExpressionTreeElement element : childElements) {
if (!element.isEmptySlot()) {
element.postProcess();
}
}
}
break;
}
}
} } | public class class_name {
public void postProcess() {
if (!this.isEmptySlot()) {
switch (savedItem.getExpressionItemType()) {
case OPERATOR: {
if (savedItem == OPERATOR_SUB) {
if (!childElements[0].isEmptySlot() && childElements[1].isEmptySlot()) {
final ExpressionTreeElement left = childElements[0];
final ExpressionItem item = left.getItem();
if (item.getExpressionItemType() == ExpressionItemType.VALUE) {
final Value val = (Value) item;
switch (val.getType()) {
case INT: {
childElements = EMPTY;
savedItem = Value.valueOf(0 - val.asLong()); // depends on control dependency: [if], data = [none]
makeMaxPriority(); // depends on control dependency: [if], data = [none]
}
break;
case FLOAT: {
childElements = EMPTY;
savedItem = Value.valueOf(0.0f - val.asFloat()); // depends on control dependency: [if], data = [none]
makeMaxPriority(); // depends on control dependency: [if], data = [none]
}
break;
default: {
if (!left.isEmptySlot()) {
left.postProcess(); // depends on control dependency: [if], data = [none]
}
}
break;
}
}
} else {
for (final ExpressionTreeElement element : childElements) {
if (!element.isEmptySlot()) {
element.postProcess(); // depends on control dependency: [if], data = [none]
}
}
}
} else {
for (final ExpressionTreeElement element : childElements) {
if (!element.isEmptySlot()) {
element.postProcess(); // depends on control dependency: [if], data = [none]
}
}
}
}
break;
case FUNCTION: {
for (final ExpressionTreeElement element : childElements) {
if (!element.isEmptySlot()) {
element.postProcess();
}
}
}
break;
}
}
} } |
public class class_name {
public UnixPath removeTrailingSeparator() {
if (!isRoot() && hasTrailingSeparator()) {
return new UnixPath(permitEmptyComponents, path.substring(0, path.length() - 1));
} else {
return this;
}
} } | public class class_name {
public UnixPath removeTrailingSeparator() {
if (!isRoot() && hasTrailingSeparator()) {
return new UnixPath(permitEmptyComponents, path.substring(0, path.length() - 1)); // depends on control dependency: [if], data = [none]
} else {
return this; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String post(String url, String bodyString, byte[] bodyByteArray, Map<String, String>... head) {
BufferedReader in = null;
StringBuilder sb = new StringBuilder();
try {
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
if (head != null && head.length != 0) {
Map<String, String> header = head[0];
for (Map.Entry<String, String> h : header.entrySet()) {
connection.setRequestProperty(h.getKey(), h.getValue());
}
}
connection.setDoOutput(true);
connection.setDoInput(true);
if (bodyString != null) {
OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());
outputStream.write(bodyString);
outputStream.flush();
outputStream.close();
}
if (bodyByteArray != null) {
OutputStream outputStream = connection.getOutputStream();
outputStream.write(bodyByteArray);
outputStream.flush();
outputStream.close();
}
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return sb.toString();
} } | public class class_name {
public static String post(String url, String bodyString, byte[] bodyByteArray, Map<String, String>... head) {
BufferedReader in = null;
StringBuilder sb = new StringBuilder();
try {
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
if (head != null && head.length != 0) {
Map<String, String> header = head[0];
for (Map.Entry<String, String> h : header.entrySet()) {
connection.setRequestProperty(h.getKey(), h.getValue()); // depends on control dependency: [for], data = [h]
}
}
connection.setDoOutput(true); // depends on control dependency: [try], data = [none]
connection.setDoInput(true); // depends on control dependency: [try], data = [none]
if (bodyString != null) {
OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());
outputStream.write(bodyString); // depends on control dependency: [if], data = [(bodyString]
outputStream.flush(); // depends on control dependency: [if], data = [none]
outputStream.close(); // depends on control dependency: [if], data = [none]
}
if (bodyByteArray != null) {
OutputStream outputStream = connection.getOutputStream();
outputStream.write(bodyByteArray); // depends on control dependency: [if], data = [(bodyByteArray]
outputStream.flush(); // depends on control dependency: [if], data = [none]
outputStream.close(); // depends on control dependency: [if], data = [none]
}
connection.connect(); // depends on control dependency: [try], data = [none]
in = new BufferedReader(new InputStreamReader(connection.getInputStream())); // depends on control dependency: [try], data = [none]
String line;
while ((line = in.readLine()) != null) {
sb.append(line); // depends on control dependency: [while], data = [none]
}
} catch (Exception e) {
e.printStackTrace();
} finally { // depends on control dependency: [catch], data = [none]
try {
if (in != null) {
in.close(); // depends on control dependency: [if], data = [none]
}
} catch (IOException ex) {
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
return sb.toString();
} } |
public class class_name {
private void initialize(){
if(config.commandLogging){
Log.d(config.commandLoggingTag, "initialize()");
}
Timeout.setLargeTimeout(initializeTimeout("solo_large_timeout", config.timeout_large));
Timeout.setSmallTimeout(initializeTimeout("solo_small_timeout", config.timeout_small));
} } | public class class_name {
private void initialize(){
if(config.commandLogging){
Log.d(config.commandLoggingTag, "initialize()"); // depends on control dependency: [if], data = [none]
}
Timeout.setLargeTimeout(initializeTimeout("solo_large_timeout", config.timeout_large));
Timeout.setSmallTimeout(initializeTimeout("solo_small_timeout", config.timeout_small));
} } |
public class class_name {
public void setPreviewResults(java.util.Collection<LifecyclePolicyPreviewResult> previewResults) {
if (previewResults == null) {
this.previewResults = null;
return;
}
this.previewResults = new java.util.ArrayList<LifecyclePolicyPreviewResult>(previewResults);
} } | public class class_name {
public void setPreviewResults(java.util.Collection<LifecyclePolicyPreviewResult> previewResults) {
if (previewResults == null) {
this.previewResults = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.previewResults = new java.util.ArrayList<LifecyclePolicyPreviewResult>(previewResults);
} } |
public class class_name {
public LocalDate letzterTag(DayOfWeek wochentag) {
LocalDate tag = ersterTag();
while (tag.getDayOfWeek() != wochentag) {
tag = tag.minusDays(1);
}
return tag;
} } | public class class_name {
public LocalDate letzterTag(DayOfWeek wochentag) {
LocalDate tag = ersterTag();
while (tag.getDayOfWeek() != wochentag) {
tag = tag.minusDays(1); // depends on control dependency: [while], data = [none]
}
return tag;
} } |
public class class_name {
private static float getObjectTransformationCost(Class<?> srcClass, Class<?> destClass) {
float cost = 0.0f;
while (srcClass != null && !destClass.equals(srcClass)) {
if (destClass.isPrimitive()) {
Class<?> destClassWrapperClazz = getPrimitiveWrapper(destClass);
if (destClassWrapperClazz != null && destClassWrapperClazz.equals(srcClass)) {
cost += 0.25f;
break;
}
}
if (destClass.isInterface() && isAssignmentCompatible(destClass,srcClass)) {
// slight penalty for interface match.
// we still want an exact match to override an interface match, but
// an interface match should override anything where we have to get a
// superclass.
cost += 0.25f;
break;
}
cost++;
srcClass = srcClass.getSuperclass();
}
/*
* If the destination class is null, we've travelled all the way up to
* an Object match. We'll penalize this by adding 1.5 to the cost.
*/
if (srcClass == null) {
cost += 1.5f;
}
return cost;
} } | public class class_name {
private static float getObjectTransformationCost(Class<?> srcClass, Class<?> destClass) {
float cost = 0.0f;
while (srcClass != null && !destClass.equals(srcClass)) {
if (destClass.isPrimitive()) {
Class<?> destClassWrapperClazz = getPrimitiveWrapper(destClass);
if (destClassWrapperClazz != null && destClassWrapperClazz.equals(srcClass)) {
cost += 0.25f;
// depends on control dependency: [if], data = [none]
break;
}
}
if (destClass.isInterface() && isAssignmentCompatible(destClass,srcClass)) {
// slight penalty for interface match.
// we still want an exact match to override an interface match, but
// an interface match should override anything where we have to get a
// superclass.
cost += 0.25f;
// depends on control dependency: [if], data = [none]
break;
}
cost++;
// depends on control dependency: [while], data = [none]
srcClass = srcClass.getSuperclass();
// depends on control dependency: [while], data = [none]
}
/*
* If the destination class is null, we've travelled all the way up to
* an Object match. We'll penalize this by adding 1.5 to the cost.
*/
if (srcClass == null) {
cost += 1.5f;
// depends on control dependency: [if], data = [none]
}
return cost;
} } |
public class class_name {
@EventHandler("drop")
private void onDrop(DropEvent event) {
BaseComponent dragged = event.getRelatedTarget();
if (dragged instanceof DropContainer) {
getParent().addChild(dragged, this);
}
} } | public class class_name {
@EventHandler("drop")
private void onDrop(DropEvent event) {
BaseComponent dragged = event.getRelatedTarget();
if (dragged instanceof DropContainer) {
getParent().addChild(dragged, this); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public ZipFileBuilder asZip() {
final ZipFileBuilder zfb = new ZipFileBuilder(folder, filename);
if(this.content != null) {
zfb.addResource(getContenFileName(), this.content);
}
return zfb;
} } | public class class_name {
public ZipFileBuilder asZip() {
final ZipFileBuilder zfb = new ZipFileBuilder(folder, filename);
if(this.content != null) {
zfb.addResource(getContenFileName(), this.content); // depends on control dependency: [if], data = [none]
}
return zfb;
} } |
public class class_name {
public List<byte[]> getDbiNames() {
final List<byte[]> result = new ArrayList<>();
final Dbi<T> names = openDbi((byte[]) null);
try (Txn<T> txn = txnRead();
Cursor<T> cursor = names.openCursor(txn)) {
if (!cursor.first()) {
return Collections.emptyList();
}
do {
final byte[] name = proxy.getBytes(cursor.key());
result.add(name);
} while (cursor.next());
}
return result;
} } | public class class_name {
public List<byte[]> getDbiNames() {
final List<byte[]> result = new ArrayList<>();
final Dbi<T> names = openDbi((byte[]) null);
try (Txn<T> txn = txnRead();
Cursor<T> cursor = names.openCursor(txn)) {
if (!cursor.first()) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
do {
final byte[] name = proxy.getBytes(cursor.key());
result.add(name);
} while (cursor.next());
}
return result;
} } |
public class class_name {
public LuceneIndex current() {
// Reopen index searcher if necessary.
IndexSearcher oldSearcher = index.searcher.get();
try {
// Guarded lock, to prevent us from unnecessarily synchronizing every time.
if (oldSearcher == null) {
synchronized (this) {
if ((oldSearcher = index.searcher.get()) == null) {
IndexSearcher newSearcher = new IndexSearcher(index.directory);
index.searcher.compareAndSet(null, newSearcher);
}
}
// Yes it's open, but is it stale?
} else {
DirectoryReader directoryReader = DirectoryReader.openIfChanged(index.directory);
if (null != directoryReader) {
index.directory = directoryReader;
synchronized (this) {
IndexSearcher newSearcher;
try {
newSearcher = new IndexSearcher(directoryReader);
} catch (AlreadyClosedException e) {
log.warning("Old index reader could not be reopened. Opening a new one...");
newSearcher = new IndexSearcher(DirectoryReader.open(index.writer, true));
}
if (!index.searcher.compareAndSet(oldSearcher, newSearcher)) {
// Someone beat us to it. No worries.
log.finest("Another searcher was already open for this index. Nothing to do.");
}
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return index;
} } | public class class_name {
public LuceneIndex current() {
// Reopen index searcher if necessary.
IndexSearcher oldSearcher = index.searcher.get();
try {
// Guarded lock, to prevent us from unnecessarily synchronizing every time.
if (oldSearcher == null) {
synchronized (this) { // depends on control dependency: [if], data = [none]
if ((oldSearcher = index.searcher.get()) == null) {
IndexSearcher newSearcher = new IndexSearcher(index.directory);
index.searcher.compareAndSet(null, newSearcher); // depends on control dependency: [if], data = [none]
}
}
// Yes it's open, but is it stale?
} else {
DirectoryReader directoryReader = DirectoryReader.openIfChanged(index.directory);
if (null != directoryReader) {
index.directory = directoryReader; // depends on control dependency: [if], data = [none]
synchronized (this) { // depends on control dependency: [if], data = [none]
IndexSearcher newSearcher;
try {
newSearcher = new IndexSearcher(directoryReader); // depends on control dependency: [try], data = [none]
} catch (AlreadyClosedException e) {
log.warning("Old index reader could not be reopened. Opening a new one...");
newSearcher = new IndexSearcher(DirectoryReader.open(index.writer, true));
} // depends on control dependency: [catch], data = [none]
if (!index.searcher.compareAndSet(oldSearcher, newSearcher)) {
// Someone beat us to it. No worries.
log.finest("Another searcher was already open for this index. Nothing to do."); // depends on control dependency: [if], data = [none]
}
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
return index;
} } |
public class class_name {
protected List<Container> callRemoteKieServerOperation(ServerTemplate serverTemplate,
ContainerSpec containerSpec,
RemoteKieServerOperation operation) {
List<Container> containers = new ArrayList<org.kie.server.controller.api.model.runtime.Container>();
if (serverTemplate.getServerInstanceKeys() == null || serverTemplate.getServerInstanceKeys().isEmpty() || containerSpec == null) {
return containers;
}
for (ServerInstanceKey instanceUrl : serverTemplate.getServerInstanceKeys()) {
Container container = new Container();
container.setContainerSpecId(containerSpec.getId());
container.setServerTemplateId(serverTemplate.getId());
container.setServerInstanceId(instanceUrl.getServerInstanceId());
container.setUrl(instanceUrl.getUrl() + "/containers/" + containerSpec.getId());
container.setStatus(containerSpec.getStatus());
try {
final KieServicesClient client = getClient(instanceUrl.getUrl());
operation.doOperation(client, container);
containers.add(container);
} catch (Exception e) {
logger.debug("Unable to connect to {}",
instanceUrl);
}
}
return containers;
} } | public class class_name {
protected List<Container> callRemoteKieServerOperation(ServerTemplate serverTemplate,
ContainerSpec containerSpec,
RemoteKieServerOperation operation) {
List<Container> containers = new ArrayList<org.kie.server.controller.api.model.runtime.Container>();
if (serverTemplate.getServerInstanceKeys() == null || serverTemplate.getServerInstanceKeys().isEmpty() || containerSpec == null) {
return containers; // depends on control dependency: [if], data = [none]
}
for (ServerInstanceKey instanceUrl : serverTemplate.getServerInstanceKeys()) {
Container container = new Container();
container.setContainerSpecId(containerSpec.getId()); // depends on control dependency: [for], data = [none]
container.setServerTemplateId(serverTemplate.getId()); // depends on control dependency: [for], data = [none]
container.setServerInstanceId(instanceUrl.getServerInstanceId()); // depends on control dependency: [for], data = [instanceUrl]
container.setUrl(instanceUrl.getUrl() + "/containers/" + containerSpec.getId()); // depends on control dependency: [for], data = [instanceUrl]
container.setStatus(containerSpec.getStatus()); // depends on control dependency: [for], data = [none]
try {
final KieServicesClient client = getClient(instanceUrl.getUrl());
operation.doOperation(client, container); // depends on control dependency: [try], data = [none]
containers.add(container); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.debug("Unable to connect to {}",
instanceUrl);
} // depends on control dependency: [catch], data = [none]
}
return containers;
} } |
public class class_name {
static Interval gridSearch(UnivariateFunction fn, double start,
double end, double step) {
double lowMax = start; // lower bound on interval surrounding alphaMax
double alphaMax = start - step;
double likMax = 0.0;
double lastAlpha = start;
double alpha = start;
while (alpha < end) {
double likelihood = fn.value(alpha);
if (alphaMax < start || likelihood > likMax) {
lowMax = lastAlpha;
alphaMax = alpha;
likMax = likelihood;
}
lastAlpha = alpha;
alpha += step;
}
// make sure we've checked the rightmost endpoint (won't happen if
// end - start is not an integer multiple of step, because of roundoff
// errors, etc)
double likelihood = fn.value(end);
if (likelihood > likMax) {
lowMax = lastAlpha;
alphaMax = end;
likMax = likelihood;
}
return new Interval(lowMax, Math.min(end, alphaMax + step));
} } | public class class_name {
static Interval gridSearch(UnivariateFunction fn, double start,
double end, double step) {
double lowMax = start; // lower bound on interval surrounding alphaMax
double alphaMax = start - step;
double likMax = 0.0;
double lastAlpha = start;
double alpha = start;
while (alpha < end) {
double likelihood = fn.value(alpha);
if (alphaMax < start || likelihood > likMax) {
lowMax = lastAlpha; // depends on control dependency: [if], data = [none]
alphaMax = alpha; // depends on control dependency: [if], data = [none]
likMax = likelihood; // depends on control dependency: [if], data = [none]
}
lastAlpha = alpha; // depends on control dependency: [while], data = [none]
alpha += step; // depends on control dependency: [while], data = [none]
}
// make sure we've checked the rightmost endpoint (won't happen if
// end - start is not an integer multiple of step, because of roundoff
// errors, etc)
double likelihood = fn.value(end);
if (likelihood > likMax) {
lowMax = lastAlpha; // depends on control dependency: [if], data = [none]
alphaMax = end; // depends on control dependency: [if], data = [none]
likMax = likelihood; // depends on control dependency: [if], data = [none]
}
return new Interval(lowMax, Math.min(end, alphaMax + step));
} } |
public class class_name {
public String getNameSpace() {
if (nameSpace == null) {
nameSpace = new StringBuilder().append(catalog).append(".").append(table).toString();
}
return nameSpace;
} } | public class class_name {
public String getNameSpace() {
if (nameSpace == null) {
nameSpace = new StringBuilder().append(catalog).append(".").append(table).toString(); // depends on control dependency: [if], data = [none]
}
return nameSpace;
} } |
public class class_name {
public String delete(MappedStatement ms) {
Class<?> entityClass = getEntityClass(ms);
StringBuilder sql = new StringBuilder();
//如果设置了安全删除,就不允许执行不带查询条件的 delete 方法
if (getConfig().isSafeDelete()) {
sql.append(SqlHelper.notAllNullParameterCheck("_parameter", EntityHelper.getColumns(entityClass)));
}
// 如果是逻辑删除,则修改为更新表,修改逻辑删除字段的值
if (SqlHelper.hasLogicDeleteColumn(entityClass)) {
sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass)));
sql.append("<set>");
sql.append(SqlHelper.logicDeleteColumnEqualsValue(entityClass, true));
sql.append("</set>");
MetaObjectUtil.forObject(ms).setValue("sqlCommandType", SqlCommandType.UPDATE);
} else {
sql.append(SqlHelper.deleteFromTable(entityClass, tableName(entityClass)));
}
sql.append(SqlHelper.whereAllIfColumns(entityClass, isNotEmpty()));
return sql.toString();
} } | public class class_name {
public String delete(MappedStatement ms) {
Class<?> entityClass = getEntityClass(ms);
StringBuilder sql = new StringBuilder();
//如果设置了安全删除,就不允许执行不带查询条件的 delete 方法
if (getConfig().isSafeDelete()) {
sql.append(SqlHelper.notAllNullParameterCheck("_parameter", EntityHelper.getColumns(entityClass))); // depends on control dependency: [if], data = [none]
}
// 如果是逻辑删除,则修改为更新表,修改逻辑删除字段的值
if (SqlHelper.hasLogicDeleteColumn(entityClass)) {
sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass))); // depends on control dependency: [if], data = [none]
sql.append("<set>");
sql.append(SqlHelper.logicDeleteColumnEqualsValue(entityClass, true)); // depends on control dependency: [if], data = [none]
sql.append("</set>");
MetaObjectUtil.forObject(ms).setValue("sqlCommandType", SqlCommandType.UPDATE); // depends on control dependency: [if], data = [none]
} else {
sql.append(SqlHelper.deleteFromTable(entityClass, tableName(entityClass))); // depends on control dependency: [if], data = [none]
}
sql.append(SqlHelper.whereAllIfColumns(entityClass, isNotEmpty()));
return sql.toString();
} } |
public class class_name {
public void addComponentResource(FacesContext context, UIComponent componentResource, String target) {
final Map<String,Object> attributes = componentResource.getAttributes();
// look for a target in the component attribute set if arg is not set.
if (target == null) {
target = (String) attributes.get("target");
}
if (target == null) {
target = "head";
}
List<UIComponent> facetChildren = getComponentResources(context,
target,
true);
String id = componentResource.getId();
if (id != null) {
for (UIComponent c : facetChildren) {
if (id.equals(c.getId())) {
facetChildren.remove(c);
}
}
}
// add the resource to the facet
facetChildren.add(componentResource);
} } | public class class_name {
public void addComponentResource(FacesContext context, UIComponent componentResource, String target) {
final Map<String,Object> attributes = componentResource.getAttributes();
// look for a target in the component attribute set if arg is not set.
if (target == null) {
target = (String) attributes.get("target"); // depends on control dependency: [if], data = [none]
}
if (target == null) {
target = "head"; // depends on control dependency: [if], data = [none]
}
List<UIComponent> facetChildren = getComponentResources(context,
target,
true);
String id = componentResource.getId();
if (id != null) {
for (UIComponent c : facetChildren) {
if (id.equals(c.getId())) {
facetChildren.remove(c); // depends on control dependency: [if], data = [none]
}
}
}
// add the resource to the facet
facetChildren.add(componentResource);
} } |
public class class_name {
@Override
public void clear() {
try {
warnUnusedOptions();
if (clean == null || clean.getValue() == Boolean.TRUE) {
for (ExamSystem sys : subsystems) {
sys.clear();
}
FileUtils.delete(cache.getCanonicalFile());
}
}
catch (IOException e) {
// LOG.info("Clearing " + this.toString() + " failed." ,e);
}
} } | public class class_name {
@Override
public void clear() {
try {
warnUnusedOptions(); // depends on control dependency: [try], data = [none]
if (clean == null || clean.getValue() == Boolean.TRUE) {
for (ExamSystem sys : subsystems) {
sys.clear(); // depends on control dependency: [for], data = [sys]
}
FileUtils.delete(cache.getCanonicalFile()); // depends on control dependency: [if], data = [none]
}
}
catch (IOException e) {
// LOG.info("Clearing " + this.toString() + " failed." ,e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public boolean isSystemModule() {
if (name == null || name.isEmpty()) {
return false;
}
return name.startsWith("java.") || name.startsWith("jdk.") || name.startsWith("javafx.")
|| name.startsWith("oracle.");
} } | public class class_name {
public boolean isSystemModule() {
if (name == null || name.isEmpty()) {
return false; // depends on control dependency: [if], data = [none]
}
return name.startsWith("java.") || name.startsWith("jdk.") || name.startsWith("javafx.")
|| name.startsWith("oracle.");
} } |
public class class_name {
private void initialise(final UUID _uuid,
final String _instanceKey,
final UUID _selectCmdUUID)
throws EFapsException
{
final WebMarkupContainer borderPanel = new WebMarkupContainer("borderPanel");
this.add(borderPanel);
borderPanel.add(new BorderContainerBehavior(Design.SIDEBAR, true));
this.borderPanelId = borderPanel.getMarkupId(true);
final AbstractCommand cmd = getCommand(_uuid);
UUID tmpUUID = _uuid;
this.webForm = cmd.getTargetForm() != null;
if (cmd instanceof Menu) {
for (final AbstractCommand childcmd : ((Menu) cmd).getCommands()) {
if (_selectCmdUUID == null && childcmd.isDefaultSelected()) {
tmpUUID = childcmd.getUUID();
this.webForm = childcmd.getTargetForm() != null;
break;
} else if (childcmd.getUUID().equals(_selectCmdUUID)) {
tmpUUID = childcmd.getUUID();
this.webForm = childcmd.getTargetForm() != null;
break;
}
}
}
final UUID uuid4NewPage = tmpUUID;
final LazyIframe centerPanel = new LazyIframe("centerPanel", new IFrameProvider()
{
private static final long serialVersionUID = 1L;
@Override
public Page getPage(final Component _component)
{
Page error = null;
WebPage page = null;
try {
if (ContentContainerPage.this.webForm) {
final UIForm uiForm = new UIForm(uuid4NewPage, _instanceKey).setPagePosition(PagePosition.TREE);
page = new FormPage(Model.of(uiForm), getPageReference());
} else {
if (getCommand(uuid4NewPage).getTargetStructurBrowserField() == null) {
if ("GridX".equals(Configuration.getAttribute(ConfigAttribute.TABLE_DEFAULTTYPETREE))) {
page = new GridPage(Model.of(UIGrid.get(uuid4NewPage, PagePosition.TREE)
.setCallInstance(Instance.get(_instanceKey))));
} else {
final UITable uiTable = new UITable(uuid4NewPage, _instanceKey)
.setPagePosition(PagePosition.TREE);
page = new TablePage(Model.of(uiTable));
}
} else {
if ("GridX".equals(Configuration.getAttribute(
ConfigAttribute.STRUCBRWSR_DEFAULTTYPETREE))) {
page = new GridPage(Model.of(UIGrid.get(uuid4NewPage, PagePosition.TREE)
.setCallInstance(Instance.get(_instanceKey))));
} else {
page = new StructurBrowserPage(uuid4NewPage, _instanceKey, getPageReference());
}
}
}
} catch (final EFapsException e) {
error = new ErrorPage(e);
}
return error == null ? page : error;
}
}, null);
borderPanel.add(centerPanel);
centerPanel.add(new ContentPaneBehavior(Region.CENTER, false));
this.centerPanelId = centerPanel.getMarkupId(true);
borderPanel.add(new SidePanel("leftPanel", _uuid, _instanceKey, _selectCmdUUID,
this.structurbrowser));
} } | public class class_name {
private void initialise(final UUID _uuid,
final String _instanceKey,
final UUID _selectCmdUUID)
throws EFapsException
{
final WebMarkupContainer borderPanel = new WebMarkupContainer("borderPanel");
this.add(borderPanel);
borderPanel.add(new BorderContainerBehavior(Design.SIDEBAR, true));
this.borderPanelId = borderPanel.getMarkupId(true);
final AbstractCommand cmd = getCommand(_uuid);
UUID tmpUUID = _uuid;
this.webForm = cmd.getTargetForm() != null;
if (cmd instanceof Menu) {
for (final AbstractCommand childcmd : ((Menu) cmd).getCommands()) {
if (_selectCmdUUID == null && childcmd.isDefaultSelected()) {
tmpUUID = childcmd.getUUID(); // depends on control dependency: [if], data = [none]
this.webForm = childcmd.getTargetForm() != null; // depends on control dependency: [if], data = [none]
break;
} else if (childcmd.getUUID().equals(_selectCmdUUID)) {
tmpUUID = childcmd.getUUID(); // depends on control dependency: [if], data = [none]
this.webForm = childcmd.getTargetForm() != null; // depends on control dependency: [if], data = [none]
break;
}
}
}
final UUID uuid4NewPage = tmpUUID;
final LazyIframe centerPanel = new LazyIframe("centerPanel", new IFrameProvider()
{
private static final long serialVersionUID = 1L;
@Override
public Page getPage(final Component _component)
{
Page error = null;
WebPage page = null;
try {
if (ContentContainerPage.this.webForm) {
final UIForm uiForm = new UIForm(uuid4NewPage, _instanceKey).setPagePosition(PagePosition.TREE);
page = new FormPage(Model.of(uiForm), getPageReference()); // depends on control dependency: [if], data = [none]
} else {
if (getCommand(uuid4NewPage).getTargetStructurBrowserField() == null) {
if ("GridX".equals(Configuration.getAttribute(ConfigAttribute.TABLE_DEFAULTTYPETREE))) {
page = new GridPage(Model.of(UIGrid.get(uuid4NewPage, PagePosition.TREE)
.setCallInstance(Instance.get(_instanceKey)))); // depends on control dependency: [if], data = [none]
} else {
final UITable uiTable = new UITable(uuid4NewPage, _instanceKey)
.setPagePosition(PagePosition.TREE);
page = new TablePage(Model.of(uiTable)); // depends on control dependency: [if], data = [none]
}
} else {
if ("GridX".equals(Configuration.getAttribute(
ConfigAttribute.STRUCBRWSR_DEFAULTTYPETREE))) {
page = new GridPage(Model.of(UIGrid.get(uuid4NewPage, PagePosition.TREE)
.setCallInstance(Instance.get(_instanceKey)))); // depends on control dependency: [if], data = [none]
} else {
page = new StructurBrowserPage(uuid4NewPage, _instanceKey, getPageReference()); // depends on control dependency: [if], data = [none]
}
}
}
} catch (final EFapsException e) {
error = new ErrorPage(e);
} // depends on control dependency: [catch], data = [none]
return error == null ? page : error;
}
}, null);
borderPanel.add(centerPanel);
centerPanel.add(new ContentPaneBehavior(Region.CENTER, false));
this.centerPanelId = centerPanel.getMarkupId(true);
borderPanel.add(new SidePanel("leftPanel", _uuid, _instanceKey, _selectCmdUUID,
this.structurbrowser));
} } |
public class class_name {
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
super.startElement(handler, uri, localName, rawName, attributes);
try
{
int stylesheetType = handler.getStylesheetType();
Stylesheet stylesheet;
if (stylesheetType == StylesheetHandler.STYPE_ROOT)
{
try
{
stylesheet = getStylesheetRoot(handler);
}
catch(TransformerConfigurationException tfe)
{
throw new TransformerException(tfe);
}
}
else
{
Stylesheet parent = handler.getStylesheet();
if (stylesheetType == StylesheetHandler.STYPE_IMPORT)
{
StylesheetComposed sc = new StylesheetComposed(parent);
parent.setImport(sc);
stylesheet = sc;
}
else
{
stylesheet = new Stylesheet(parent);
parent.setInclude(stylesheet);
}
}
stylesheet.setDOMBackPointer(handler.getOriginatingNode());
stylesheet.setLocaterInfo(handler.getLocator());
stylesheet.setPrefixes(handler.getNamespaceSupport());
handler.pushStylesheet(stylesheet);
setPropertiesFromAttributes(handler, rawName, attributes,
handler.getStylesheet());
handler.pushElemTemplateElement(handler.getStylesheet());
}
catch(TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
} } | public class class_name {
public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
super.startElement(handler, uri, localName, rawName, attributes);
try
{
int stylesheetType = handler.getStylesheetType();
Stylesheet stylesheet;
if (stylesheetType == StylesheetHandler.STYPE_ROOT)
{
try
{
stylesheet = getStylesheetRoot(handler); // depends on control dependency: [try], data = [none]
}
catch(TransformerConfigurationException tfe)
{
throw new TransformerException(tfe);
} // depends on control dependency: [catch], data = [none]
}
else
{
Stylesheet parent = handler.getStylesheet();
if (stylesheetType == StylesheetHandler.STYPE_IMPORT)
{
StylesheetComposed sc = new StylesheetComposed(parent);
parent.setImport(sc); // depends on control dependency: [if], data = [none]
stylesheet = sc; // depends on control dependency: [if], data = [none]
}
else
{
stylesheet = new Stylesheet(parent); // depends on control dependency: [if], data = [none]
parent.setInclude(stylesheet); // depends on control dependency: [if], data = [none]
}
}
stylesheet.setDOMBackPointer(handler.getOriginatingNode());
stylesheet.setLocaterInfo(handler.getLocator());
stylesheet.setPrefixes(handler.getNamespaceSupport());
handler.pushStylesheet(stylesheet);
setPropertiesFromAttributes(handler, rawName, attributes,
handler.getStylesheet());
handler.pushElemTemplateElement(handler.getStylesheet());
}
catch(TransformerException te)
{
throw new org.xml.sax.SAXException(te);
}
} } |
public class class_name {
@Trivial
Collection<String> getContextualMethods() {
lock.readLock().lock();
try {
@SuppressWarnings("unchecked")
Collection<String> contextualMethods = (Collection<String>) properties.get(CONTEXTUAL_METHODS);
return contextualMethods;
} finally {
lock.readLock().unlock();
}
} } | public class class_name {
@Trivial
Collection<String> getContextualMethods() {
lock.readLock().lock();
try {
@SuppressWarnings("unchecked")
Collection<String> contextualMethods = (Collection<String>) properties.get(CONTEXTUAL_METHODS);
return contextualMethods; // depends on control dependency: [try], data = [none]
} finally {
lock.readLock().unlock();
}
} } |
public class class_name {
public void highlight() {
final JTabbedPane parent = (JTabbedPane) this.getUiComponent().getParent();
//search through tabs until we find this one
for (int i = 0; i < parent.getTabCount(); i++) {
String title = parent.getTitleAt(i);
if (getTabCaption().equals(title)) { //found this tab
//create new colored label and set it into the tab
final JLabel label = new JLabel(getTabCaption());
label.setForeground(new Color(0xff6633));
parent.setTabComponentAt(i, label);
//schedule a task to change back to original color
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
label.setForeground(Color.black);
}
};
timer.schedule(task, 3000);
break;
}
}
} } | public class class_name {
public void highlight() {
final JTabbedPane parent = (JTabbedPane) this.getUiComponent().getParent();
//search through tabs until we find this one
for (int i = 0; i < parent.getTabCount(); i++) {
String title = parent.getTitleAt(i);
if (getTabCaption().equals(title)) { //found this tab
//create new colored label and set it into the tab
final JLabel label = new JLabel(getTabCaption());
label.setForeground(new Color(0xff6633)); // depends on control dependency: [if], data = [none]
parent.setTabComponentAt(i, label); // depends on control dependency: [if], data = [none]
//schedule a task to change back to original color
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
label.setForeground(Color.black);
}
};
timer.schedule(task, 3000); // depends on control dependency: [if], data = [none]
break;
}
}
} } |
public class class_name {
private void extractVariableNames() {
if (expression == null) {
throw new IllegalArgumentException("The expression was null");
}
for (final List<String> exp_list : JEXL_ENGINE.getVariables(expression)) {
for (final String variable : exp_list) {
names.add(variable);
}
}
} } | public class class_name {
private void extractVariableNames() {
if (expression == null) {
throw new IllegalArgumentException("The expression was null");
}
for (final List<String> exp_list : JEXL_ENGINE.getVariables(expression)) {
for (final String variable : exp_list) {
names.add(variable); // depends on control dependency: [for], data = [variable]
}
}
} } |
public class class_name {
private void createRelationshipforCollectionOfComponents(AssociationKey associationKey, String collectionRole, String[] embeddedColumnNames, Object[] embeddedColumnValues, StringBuilder queryBuilder) {
int offset = associationKey.getEntityKey().getColumnNames().length;
EmbeddedNodesTree tree = createEmbeddedTree( collectionRole, embeddedColumnNames, embeddedColumnValues, offset );
if ( isPartOfEmbedded( collectionRole ) ) {
String[] pathToEmbedded = appendEmbeddedNodes( collectionRole, queryBuilder );
queryBuilder.append( " CREATE (e) -[r:" );
appendRelationshipType( queryBuilder, pathToEmbedded[ pathToEmbedded.length - 1] );
}
else {
queryBuilder.append( " CREATE (owner) -[r:" );
appendRelationshipType( queryBuilder, collectionRole );
}
queryBuilder.append( "]-> " );
queryBuilder.append( "(target:" );
queryBuilder.append( EMBEDDED );
queryBuilder.append( ":" );
escapeIdentifier( queryBuilder, associationKey.getMetadata().getAssociatedEntityKeyMetadata().getEntityKeyMetadata().getTable() );
int index = 0;
int embeddedNumber = 0;
// Append primitive properties
if ( !tree.getProperties().isEmpty() ) {
queryBuilder.append( " {" );
for ( EmbeddedNodeProperty property : tree.getProperties() ) {
escapeIdentifier( queryBuilder, property.getColumn() );
queryBuilder.append( ": {" );
queryBuilder.append( property.getParam() );
queryBuilder.append( "}" );
if ( index++ < tree.getProperties().size() - 1 ) {
queryBuilder.append( ", " );
}
}
queryBuilder.append( "}" );
}
queryBuilder.append( ")" );
// Append relationships representing embedded properties
Map<String, EmbeddedNodesTree> children = tree.getChildren();
boolean first = true;
for ( Entry<String, EmbeddedNodesTree> entry : children.entrySet() ) {
index = 0;
String relationshipType = entry.getKey();
EmbeddedNodesTree child = entry.getValue();
if ( first ) {
first = false;
}
else {
queryBuilder.append( ", (target)" );
}
queryBuilder.append( " - [:" );
appendRelationshipType( queryBuilder, relationshipType );
queryBuilder.append( "] -> " );
queryBuilder.append( "(a" );
queryBuilder.append( embeddedNumber++ );
queryBuilder.append( ":" );
queryBuilder.append( EMBEDDED );
if ( !child.getProperties().isEmpty() ) {
queryBuilder.append( " {" );
for ( EmbeddedNodeProperty property : child.getProperties() ) {
escapeIdentifier( queryBuilder, property.getColumn() );
queryBuilder.append( ": {" );
queryBuilder.append( property.getParam() );
queryBuilder.append( "}" );
if ( index++ < child.getProperties().size() - 1 ) {
queryBuilder.append( ", " );
}
}
queryBuilder.append( "}" );
}
queryBuilder.append( ")" );
}
queryBuilder.append( " RETURN r" );
} } | public class class_name {
private void createRelationshipforCollectionOfComponents(AssociationKey associationKey, String collectionRole, String[] embeddedColumnNames, Object[] embeddedColumnValues, StringBuilder queryBuilder) {
int offset = associationKey.getEntityKey().getColumnNames().length;
EmbeddedNodesTree tree = createEmbeddedTree( collectionRole, embeddedColumnNames, embeddedColumnValues, offset );
if ( isPartOfEmbedded( collectionRole ) ) {
String[] pathToEmbedded = appendEmbeddedNodes( collectionRole, queryBuilder );
queryBuilder.append( " CREATE (e) -[r:" ); // depends on control dependency: [if], data = [none]
appendRelationshipType( queryBuilder, pathToEmbedded[ pathToEmbedded.length - 1] ); // depends on control dependency: [if], data = [none]
}
else {
queryBuilder.append( " CREATE (owner) -[r:" ); // depends on control dependency: [if], data = [none]
appendRelationshipType( queryBuilder, collectionRole ); // depends on control dependency: [if], data = [none]
}
queryBuilder.append( "]-> " );
queryBuilder.append( "(target:" );
queryBuilder.append( EMBEDDED );
queryBuilder.append( ":" );
escapeIdentifier( queryBuilder, associationKey.getMetadata().getAssociatedEntityKeyMetadata().getEntityKeyMetadata().getTable() );
int index = 0;
int embeddedNumber = 0;
// Append primitive properties
if ( !tree.getProperties().isEmpty() ) {
queryBuilder.append( " {" ); // depends on control dependency: [if], data = [none]
for ( EmbeddedNodeProperty property : tree.getProperties() ) {
escapeIdentifier( queryBuilder, property.getColumn() ); // depends on control dependency: [for], data = [property]
queryBuilder.append( ": {" ); // depends on control dependency: [for], data = [none]
queryBuilder.append( property.getParam() ); // depends on control dependency: [for], data = [property]
queryBuilder.append( "}" ); // depends on control dependency: [for], data = [none]
if ( index++ < tree.getProperties().size() - 1 ) {
queryBuilder.append( ", " ); // depends on control dependency: [if], data = [none]
}
}
queryBuilder.append( "}" ); // depends on control dependency: [if], data = [none]
}
queryBuilder.append( ")" );
// Append relationships representing embedded properties
Map<String, EmbeddedNodesTree> children = tree.getChildren();
boolean first = true;
for ( Entry<String, EmbeddedNodesTree> entry : children.entrySet() ) {
index = 0; // depends on control dependency: [for], data = [none]
String relationshipType = entry.getKey();
EmbeddedNodesTree child = entry.getValue();
if ( first ) {
first = false; // depends on control dependency: [if], data = [none]
}
else {
queryBuilder.append( ", (target)" );
}
queryBuilder.append( " - [:" );
appendRelationshipType( queryBuilder, relationshipType );
queryBuilder.append( "] -> " );
queryBuilder.append( "(a" );
queryBuilder.append( embeddedNumber++ );
queryBuilder.append( ":" );
queryBuilder.append( EMBEDDED );
if ( !child.getProperties().isEmpty() ) {
queryBuilder.append( " {" );
for ( EmbeddedNodeProperty property : child.getProperties() ) {
escapeIdentifier( queryBuilder, property.getColumn() );
queryBuilder.append( ": {" );
queryBuilder.append( property.getParam() );
queryBuilder.append( "}" );
if ( index++ < child.getProperties().size() - 1 ) {
queryBuilder.append( ", " );
}
}
queryBuilder.append( "}" );
}
queryBuilder.append( ")" ); // depends on control dependency: [if], data = [none]
}
queryBuilder.append( " RETURN r" ); // depends on control dependency: [for], data = [none]
} } |
public class class_name {
public void auditRetrieveDocumentSetEvent(
RFC3881EventOutcomeCodes eventOutcome,
String consumerUserId, String consumerUserName, String consumerIpAddress,
String repositoryEndpointUri,
String[] documentUniqueIds, String repositoryUniqueId, String homeCommunityId,
List<CodedValueType> purposesOfUse, List<CodedValueType> userRoles)
{
if (!isAuditorEnabled()) {
return;
}
String[] repositoryUniqueIds = null;
if (!EventUtils.isEmptyOrNull(documentUniqueIds)) {
repositoryUniqueIds = new String[documentUniqueIds.length];
Arrays.fill(repositoryUniqueIds, repositoryUniqueId);
}
auditRetrieveDocumentSetEvent(eventOutcome, consumerUserId, consumerUserName, consumerIpAddress,
repositoryEndpointUri, documentUniqueIds, repositoryUniqueIds, homeCommunityId, purposesOfUse, userRoles);
} } | public class class_name {
public void auditRetrieveDocumentSetEvent(
RFC3881EventOutcomeCodes eventOutcome,
String consumerUserId, String consumerUserName, String consumerIpAddress,
String repositoryEndpointUri,
String[] documentUniqueIds, String repositoryUniqueId, String homeCommunityId,
List<CodedValueType> purposesOfUse, List<CodedValueType> userRoles)
{
if (!isAuditorEnabled()) {
return; // depends on control dependency: [if], data = [none]
}
String[] repositoryUniqueIds = null;
if (!EventUtils.isEmptyOrNull(documentUniqueIds)) {
repositoryUniqueIds = new String[documentUniqueIds.length]; // depends on control dependency: [if], data = [none]
Arrays.fill(repositoryUniqueIds, repositoryUniqueId); // depends on control dependency: [if], data = [none]
}
auditRetrieveDocumentSetEvent(eventOutcome, consumerUserId, consumerUserName, consumerIpAddress,
repositoryEndpointUri, documentUniqueIds, repositoryUniqueIds, homeCommunityId, purposesOfUse, userRoles);
} } |
public class class_name {
@Override
public Map<String, Object> getChildren(Boolean includeInheritedFields)
{
Map<String, Object> fields = new HashMap<String, Object>();
if (includeInheritedFields)
{
fields.putAll(super.getChildren(includeInheritedFields));
}
fields.put("name", this.name);
fields.put("old", this.old);
return fields;
} } | public class class_name {
@Override
public Map<String, Object> getChildren(Boolean includeInheritedFields)
{
Map<String, Object> fields = new HashMap<String, Object>();
if (includeInheritedFields)
{
fields.putAll(super.getChildren(includeInheritedFields)); // depends on control dependency: [if], data = [(includeInheritedFields)]
}
fields.put("name", this.name);
fields.put("old", this.old);
return fields;
} } |
public class class_name {
public static ArrayList<ClassLabel> allClassLabels(MultipleObjectsBundle bundle, int col) {
HashSet<ClassLabel> labels = new HashSet<ClassLabel>();
for(int i = 0, l = bundle.dataLength(); i < l; ++i) {
Object o = bundle.data(i, col);
if(o == null || !(o instanceof ClassLabel)) {
continue;
}
labels.add((ClassLabel) o);
}
ArrayList<ClassLabel> ret = new ArrayList<>(labels);
Collections.sort(ret);
return ret;
} } | public class class_name {
public static ArrayList<ClassLabel> allClassLabels(MultipleObjectsBundle bundle, int col) {
HashSet<ClassLabel> labels = new HashSet<ClassLabel>();
for(int i = 0, l = bundle.dataLength(); i < l; ++i) {
Object o = bundle.data(i, col);
if(o == null || !(o instanceof ClassLabel)) {
continue;
}
labels.add((ClassLabel) o); // depends on control dependency: [for], data = [none]
}
ArrayList<ClassLabel> ret = new ArrayList<>(labels);
Collections.sort(ret);
return ret;
} } |
public class class_name {
public void execute( EnforcerRuleHelper helper )
throws EnforcerRuleException
{
boolean callSuper;
MavenProject project = null;
if ( onlyWhenRelease )
{
// get the project
project = getProject( helper );
// only call super if this project is a release
callSuper = !project.getArtifact().isSnapshot();
}
else
{
callSuper = true;
}
if ( callSuper )
{
super.execute( helper );
if ( failWhenParentIsSnapshot )
{
if ( project == null )
{
project = getProject( helper );
}
Artifact parentArtifact = project.getParentArtifact();
if ( parentArtifact != null && parentArtifact.isSnapshot() )
{
throw new EnforcerRuleException( "Parent Cannot be a snapshot: " + parentArtifact.getId() );
}
}
}
} } | public class class_name {
public void execute( EnforcerRuleHelper helper )
throws EnforcerRuleException
{
boolean callSuper;
MavenProject project = null;
if ( onlyWhenRelease )
{
// get the project
project = getProject( helper );
// only call super if this project is a release
callSuper = !project.getArtifact().isSnapshot();
}
else
{
callSuper = true;
}
if ( callSuper )
{
super.execute( helper );
if ( failWhenParentIsSnapshot )
{
if ( project == null )
{
project = getProject( helper ); // depends on control dependency: [if], data = [none]
}
Artifact parentArtifact = project.getParentArtifact();
if ( parentArtifact != null && parentArtifact.isSnapshot() )
{
throw new EnforcerRuleException( "Parent Cannot be a snapshot: " + parentArtifact.getId() );
}
}
}
} } |
public class class_name {
public void replace(BaseCell oldOne, BaseCell newOne) {
VirtualLayoutManager layoutManager = getLayoutManager();
if (oldOne != null && newOne != null && mGroupBasicAdapter != null && layoutManager != null) {
int replacePosition = mGroupBasicAdapter.getPositionByItem(oldOne);
if (replacePosition >= 0) {
int cardIdx = mGroupBasicAdapter.findCardIdxFor(replacePosition);
Card card = mGroupBasicAdapter.getCardRange(cardIdx).second;
card.replaceCell(oldOne, newOne);
mGroupBasicAdapter.replaceComponent(Arrays.asList(oldOne), Arrays.asList(newOne));
}
}
} } | public class class_name {
public void replace(BaseCell oldOne, BaseCell newOne) {
VirtualLayoutManager layoutManager = getLayoutManager();
if (oldOne != null && newOne != null && mGroupBasicAdapter != null && layoutManager != null) {
int replacePosition = mGroupBasicAdapter.getPositionByItem(oldOne);
if (replacePosition >= 0) {
int cardIdx = mGroupBasicAdapter.findCardIdxFor(replacePosition);
Card card = mGroupBasicAdapter.getCardRange(cardIdx).second;
card.replaceCell(oldOne, newOne); // depends on control dependency: [if], data = [none]
mGroupBasicAdapter.replaceComponent(Arrays.asList(oldOne), Arrays.asList(newOne)); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public T argMax() {
double maxCount = -Double.MAX_VALUE;
T maxKey = null;
for (Map.Entry<T, AtomicDouble> entry : map.entrySet()) {
if (entry.getValue().get() > maxCount || maxKey == null) {
maxKey = entry.getKey();
maxCount = entry.getValue().get();
}
}
return maxKey;
} } | public class class_name {
public T argMax() {
double maxCount = -Double.MAX_VALUE;
T maxKey = null;
for (Map.Entry<T, AtomicDouble> entry : map.entrySet()) {
if (entry.getValue().get() > maxCount || maxKey == null) {
maxKey = entry.getKey(); // depends on control dependency: [if], data = [none]
maxCount = entry.getValue().get(); // depends on control dependency: [if], data = [none]
}
}
return maxKey;
} } |
public class class_name {
public void unregister() {
context.unregisterReceiver(networkConnectionChangeReceiver);
context.unregisterReceiver(internetConnectionChangeReceiver);
if (wifiAccessPointsScanEnabled) {
context.unregisterReceiver(wifiSignalStrengthChangeReceiver);
}
} } | public class class_name {
public void unregister() {
context.unregisterReceiver(networkConnectionChangeReceiver);
context.unregisterReceiver(internetConnectionChangeReceiver);
if (wifiAccessPointsScanEnabled) {
context.unregisterReceiver(wifiSignalStrengthChangeReceiver); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Dependency asDependency(MavenDependencySPI dependency, ArtifactTypeRegistry registry) {
/*
* Allow for undeclared scopes
*/
String scope = dependency.getScope().toString();
if (dependency.isUndeclaredScope()) {
scope = EMPTY;
}
return new Dependency(asArtifact(dependency, registry), scope, dependency.isOptional(),
asExclusions(dependency.getExclusions()));
} } | public class class_name {
public static Dependency asDependency(MavenDependencySPI dependency, ArtifactTypeRegistry registry) {
/*
* Allow for undeclared scopes
*/
String scope = dependency.getScope().toString();
if (dependency.isUndeclaredScope()) {
scope = EMPTY; // depends on control dependency: [if], data = [none]
}
return new Dependency(asArtifact(dependency, registry), scope, dependency.isOptional(),
asExclusions(dependency.getExclusions()));
} } |
public class class_name {
public boolean isActive() {
final Project project = getProject();
if (!CUtil.isActive(project, this.ifProp, this.unlessProp)) {
return false;
}
return true;
} } | public class class_name {
public boolean isActive() {
final Project project = getProject();
if (!CUtil.isActive(project, this.ifProp, this.unlessProp)) {
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public ClassNameMatchStatus addPattern(String classNamePattern) {
boolean matchFound = false;
if (m_classList == null) {
m_classList = getClasspathClassFileNames();
}
String preppedName = classNamePattern.trim();
// include only full classes
// for nested classes, include the parent pattern
int indexOfDollarSign = classNamePattern.indexOf('$');
if (indexOfDollarSign >= 0) {
classNamePattern = classNamePattern.substring(0, indexOfDollarSign);
}
// Substitution order is critical.
// Keep track of whether or not this is a wildcard expression.
// '.' is specifically not a wildcard.
String regExPreppedName = preppedName.replace(".", "[.]");
boolean isWildcard = regExPreppedName.contains("*");
if (isWildcard) {
regExPreppedName = regExPreppedName.replace("**", "[\\w.\\$]+");
regExPreppedName = regExPreppedName.replace("*", "[\\w\\$]*");
}
String regex = "^" + // (line start)
regExPreppedName +
"$"; // (line end)
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(m_classList);
while (matcher.find()) {
String match = matcher.group();
// skip nested classes; the base class will include them
if (match.contains("$")) {
continue;
}
matchFound = true;
m_classNameMatches.add(match);
}
if (matchFound) {
return ClassNameMatchStatus.MATCH_FOUND;
}
else {
if (isWildcard) {
return ClassNameMatchStatus.NO_WILDCARD_MATCH;
}
else {
return ClassNameMatchStatus.NO_EXACT_MATCH;
}
}
} } | public class class_name {
public ClassNameMatchStatus addPattern(String classNamePattern) {
boolean matchFound = false;
if (m_classList == null) {
m_classList = getClasspathClassFileNames(); // depends on control dependency: [if], data = [none]
}
String preppedName = classNamePattern.trim();
// include only full classes
// for nested classes, include the parent pattern
int indexOfDollarSign = classNamePattern.indexOf('$');
if (indexOfDollarSign >= 0) {
classNamePattern = classNamePattern.substring(0, indexOfDollarSign); // depends on control dependency: [if], data = [none]
}
// Substitution order is critical.
// Keep track of whether or not this is a wildcard expression.
// '.' is specifically not a wildcard.
String regExPreppedName = preppedName.replace(".", "[.]");
boolean isWildcard = regExPreppedName.contains("*");
if (isWildcard) {
regExPreppedName = regExPreppedName.replace("**", "[\\w.\\$]+"); // depends on control dependency: [if], data = [none]
regExPreppedName = regExPreppedName.replace("*", "[\\w\\$]*"); // depends on control dependency: [if], data = [none]
}
String regex = "^" + // (line start)
regExPreppedName +
"$"; // (line end)
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(m_classList);
while (matcher.find()) {
String match = matcher.group();
// skip nested classes; the base class will include them
if (match.contains("$")) {
continue;
}
matchFound = true; // depends on control dependency: [while], data = [none]
m_classNameMatches.add(match); // depends on control dependency: [while], data = [none]
}
if (matchFound) {
return ClassNameMatchStatus.MATCH_FOUND; // depends on control dependency: [if], data = [none]
}
else {
if (isWildcard) {
return ClassNameMatchStatus.NO_WILDCARD_MATCH; // depends on control dependency: [if], data = [none]
}
else {
return ClassNameMatchStatus.NO_EXACT_MATCH; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static Shape generatePolygon(int sides, int outsideRadius, int insideRadius,
boolean normalize) {
Shape shape = generatePolygon(sides, outsideRadius, insideRadius);
if (normalize) {
Rectangle2D bounds = shape.getBounds2D();
GeneralPath path = new GeneralPath(shape);
shape = path.createTransformedShape(AffineTransform.getTranslateInstance(
-bounds.getX(), -bounds.getY()));
}
return shape;
} } | public class class_name {
public static Shape generatePolygon(int sides, int outsideRadius, int insideRadius,
boolean normalize) {
Shape shape = generatePolygon(sides, outsideRadius, insideRadius);
if (normalize) {
Rectangle2D bounds = shape.getBounds2D();
GeneralPath path = new GeneralPath(shape);
shape = path.createTransformedShape(AffineTransform.getTranslateInstance(
-bounds.getX(), -bounds.getY())); // depends on control dependency: [if], data = [none]
}
return shape;
} } |
public class class_name {
private void closeConnection(WsOutbound outbound, int guacamoleStatusCode,
int webSocketCode) {
try {
byte[] message = Integer.toString(guacamoleStatusCode).getBytes("UTF-8");
outbound.close(webSocketCode, ByteBuffer.wrap(message));
}
catch (IOException e) {
logger.debug("Unable to close WebSocket tunnel.", e);
}
} } | public class class_name {
private void closeConnection(WsOutbound outbound, int guacamoleStatusCode,
int webSocketCode) {
try {
byte[] message = Integer.toString(guacamoleStatusCode).getBytes("UTF-8");
outbound.close(webSocketCode, ByteBuffer.wrap(message)); // depends on control dependency: [try], data = [none]
}
catch (IOException e) {
logger.debug("Unable to close WebSocket tunnel.", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void mutateMany(Map<String, Map<StaticBuffer, KCVMutation>> mutations, StoreTransaction txh) throws BackendException {
Preconditions.checkNotNull(mutations);
final MaskedTimestamp commitTime = new MaskedTimestamp(txh);
int size = 0;
for (Map<StaticBuffer, KCVMutation> mutation : mutations.values()) size += mutation.size();
Map<StaticBuffer, org.apache.cassandra.db.Mutation> rowMutations = new HashMap<>(size);
for (Map.Entry<String, Map<StaticBuffer, KCVMutation>> mutEntry : mutations.entrySet()) {
String columnFamily = mutEntry.getKey();
for (Map.Entry<StaticBuffer, KCVMutation> titanMutation : mutEntry.getValue().entrySet()) {
StaticBuffer key = titanMutation.getKey();
KCVMutation mut = titanMutation.getValue();
org.apache.cassandra.db.Mutation rm = rowMutations.get(key);
if (rm == null) {
rm = new org.apache.cassandra.db.Mutation(keySpaceName, key.asByteBuffer());
rowMutations.put(key, rm);
}
if (mut.hasAdditions()) {
for (Entry e : mut.getAdditions()) {
Integer ttl = (Integer) e.getMetaData().get(EntryMetaData.TTL);
if (null != ttl && ttl > 0) {
rm.add(columnFamily, CellNames.simpleDense(e.getColumnAs(StaticBuffer.BB_FACTORY)),
e.getValueAs(StaticBuffer.BB_FACTORY), commitTime.getAdditionTime(times), ttl);
} else {
rm.add(columnFamily, CellNames.simpleDense(e.getColumnAs(StaticBuffer.BB_FACTORY)),
e.getValueAs(StaticBuffer.BB_FACTORY), commitTime.getAdditionTime(times));
}
}
}
if (mut.hasDeletions()) {
for (StaticBuffer col : mut.getDeletions()) {
rm.delete(columnFamily, CellNames.simpleDense(col.as(StaticBuffer.BB_FACTORY)),
commitTime.getDeletionTime(times));
}
}
}
}
mutate(new ArrayList<org.apache.cassandra.db.Mutation>(rowMutations.values()), getTx(txh).getWriteConsistencyLevel().getDB());
sleepAfterWrite(txh, commitTime);
} } | public class class_name {
@Override
public void mutateMany(Map<String, Map<StaticBuffer, KCVMutation>> mutations, StoreTransaction txh) throws BackendException {
Preconditions.checkNotNull(mutations);
final MaskedTimestamp commitTime = new MaskedTimestamp(txh);
int size = 0;
for (Map<StaticBuffer, KCVMutation> mutation : mutations.values()) size += mutation.size();
Map<StaticBuffer, org.apache.cassandra.db.Mutation> rowMutations = new HashMap<>(size);
for (Map.Entry<String, Map<StaticBuffer, KCVMutation>> mutEntry : mutations.entrySet()) {
String columnFamily = mutEntry.getKey();
for (Map.Entry<StaticBuffer, KCVMutation> titanMutation : mutEntry.getValue().entrySet()) {
StaticBuffer key = titanMutation.getKey();
KCVMutation mut = titanMutation.getValue();
org.apache.cassandra.db.Mutation rm = rowMutations.get(key);
if (rm == null) {
rm = new org.apache.cassandra.db.Mutation(keySpaceName, key.asByteBuffer());
rowMutations.put(key, rm);
}
if (mut.hasAdditions()) {
for (Entry e : mut.getAdditions()) {
Integer ttl = (Integer) e.getMetaData().get(EntryMetaData.TTL);
if (null != ttl && ttl > 0) {
rm.add(columnFamily, CellNames.simpleDense(e.getColumnAs(StaticBuffer.BB_FACTORY)),
e.getValueAs(StaticBuffer.BB_FACTORY), commitTime.getAdditionTime(times), ttl); // depends on control dependency: [if], data = [none]
} else {
rm.add(columnFamily, CellNames.simpleDense(e.getColumnAs(StaticBuffer.BB_FACTORY)),
e.getValueAs(StaticBuffer.BB_FACTORY), commitTime.getAdditionTime(times)); // depends on control dependency: [if], data = [none]
}
}
}
if (mut.hasDeletions()) {
for (StaticBuffer col : mut.getDeletions()) {
rm.delete(columnFamily, CellNames.simpleDense(col.as(StaticBuffer.BB_FACTORY)),
commitTime.getDeletionTime(times));
}
}
}
}
mutate(new ArrayList<org.apache.cassandra.db.Mutation>(rowMutations.values()), getTx(txh).getWriteConsistencyLevel().getDB());
sleepAfterWrite(txh, commitTime);
} } |
public class class_name {
void defineFields(ClassVisitor writer) {
for (Variable var : allVariables) {
var.maybeDefineField(writer);
}
if (currentCalleeField != null) {
currentCalleeField.defineField(writer);
}
if (currentRendereeField != null) {
currentRendereeField.defineField(writer);
}
if (currentAppendable != null) {
currentAppendable.defineField(writer);
}
} } | public class class_name {
void defineFields(ClassVisitor writer) {
for (Variable var : allVariables) {
var.maybeDefineField(writer); // depends on control dependency: [for], data = [var]
}
if (currentCalleeField != null) {
currentCalleeField.defineField(writer); // depends on control dependency: [if], data = [none]
}
if (currentRendereeField != null) {
currentRendereeField.defineField(writer); // depends on control dependency: [if], data = [none]
}
if (currentAppendable != null) {
currentAppendable.defineField(writer); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Node addChildNode(Document doc, Node parentNode, String childName, String childValue){
if(doc == null || parentNode == null || childName == null){
return null;
}
Node childNode = doc.createElement(childName);
if(childValue != null){
childNode.setTextContent(childValue);
}
parentNode.appendChild(childNode);
return childNode;
} } | public class class_name {
public static Node addChildNode(Document doc, Node parentNode, String childName, String childValue){
if(doc == null || parentNode == null || childName == null){
return null; // depends on control dependency: [if], data = [none]
}
Node childNode = doc.createElement(childName);
if(childValue != null){
childNode.setTextContent(childValue); // depends on control dependency: [if], data = [(childValue]
}
parentNode.appendChild(childNode);
return childNode;
} } |
public class class_name {
public void jumpahead(int count) {
if (count < 0) {
throw new IllegalArgumentException();
}
if (buf != null) {
bufPos += count;
if (bufPos > buf.length) {
throw new IllegalArgumentException();
}
if (bufPos == buf.length) {
buf = null;
}
} else {
int i = pos.getIndex() + count;
pos.setIndex(i);
if (i > text.length()) {
throw new IllegalArgumentException();
}
}
} } | public class class_name {
public void jumpahead(int count) {
if (count < 0) {
throw new IllegalArgumentException();
}
if (buf != null) {
bufPos += count; // depends on control dependency: [if], data = [none]
if (bufPos > buf.length) {
throw new IllegalArgumentException();
}
if (bufPos == buf.length) {
buf = null; // depends on control dependency: [if], data = [none]
}
} else {
int i = pos.getIndex() + count;
pos.setIndex(i); // depends on control dependency: [if], data = [none]
if (i > text.length()) {
throw new IllegalArgumentException();
}
}
} } |
public class class_name {
private Object processNestedObject(Class targetClass, Method method, Class parameterType, String keyPrefix,
Map<Class, Class> processedClassRelations, int arrayIndex, boolean
watchAllFields) throws Exception {
Object nestedTarget = parameterType.getConstructor().newInstance();
Class nestedTargetClass = nestedTarget.getClass();
// check for cycles
if (processedClassRelations.containsKey(nestedTargetClass) && processedClassRelations.get(nestedTargetClass)
.equals(targetClass)) {
log.warning("There is a cycle in the configuration class tree. ConfigBundle class may not " +
"be populated as expected.");
} else {
String key = getKeyName(targetClass, method.getName(), keyPrefix);
if (arrayIndex >= 0) {
key += "[" + arrayIndex + "]";
}
boolean isEmpty = processConfigBundleBeanSetters(nestedTarget, nestedTargetClass, key,
processedClassRelations, watchAllFields);
if (isEmpty) {
return null;
}
}
return nestedTarget;
} } | public class class_name {
private Object processNestedObject(Class targetClass, Method method, Class parameterType, String keyPrefix,
Map<Class, Class> processedClassRelations, int arrayIndex, boolean
watchAllFields) throws Exception {
Object nestedTarget = parameterType.getConstructor().newInstance();
Class nestedTargetClass = nestedTarget.getClass();
// check for cycles
if (processedClassRelations.containsKey(nestedTargetClass) && processedClassRelations.get(nestedTargetClass)
.equals(targetClass)) {
log.warning("There is a cycle in the configuration class tree. ConfigBundle class may not " +
"be populated as expected.");
} else {
String key = getKeyName(targetClass, method.getName(), keyPrefix);
if (arrayIndex >= 0) {
key += "[" + arrayIndex + "]"; // depends on control dependency: [if], data = [none]
}
boolean isEmpty = processConfigBundleBeanSetters(nestedTarget, nestedTargetClass, key,
processedClassRelations, watchAllFields);
if (isEmpty) {
return null; // depends on control dependency: [if], data = [none]
}
}
return nestedTarget;
} } |
public class class_name {
public static <ResType> Iterable<ResType> filterAuthorizedResources(
final HttpServletRequest request,
final Iterable<ResType> resources,
final Function<? super ResType, Iterable<ResourceAction>> resourceActionGenerator,
final AuthorizerMapper authorizerMapper
)
{
if (request.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH) != null) {
return resources;
}
if (request.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED) != null) {
throw new ISE("Request already had authorization check.");
}
final AuthenticationResult authenticationResult = authenticationResultFromRequest(request);
final Iterable<ResType> filteredResources = filterAuthorizedResources(
authenticationResult,
resources,
resourceActionGenerator,
authorizerMapper
);
// We're filtering, so having access to none of the objects isn't an authorization failure (in terms of whether
// to send an error response or not.)
request.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
return filteredResources;
} } | public class class_name {
public static <ResType> Iterable<ResType> filterAuthorizedResources(
final HttpServletRequest request,
final Iterable<ResType> resources,
final Function<? super ResType, Iterable<ResourceAction>> resourceActionGenerator,
final AuthorizerMapper authorizerMapper
)
{
if (request.getAttribute(AuthConfig.DRUID_ALLOW_UNSECURED_PATH) != null) {
return resources; // depends on control dependency: [if], data = [none]
}
if (request.getAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED) != null) {
throw new ISE("Request already had authorization check.");
}
final AuthenticationResult authenticationResult = authenticationResultFromRequest(request);
final Iterable<ResType> filteredResources = filterAuthorizedResources(
authenticationResult,
resources,
resourceActionGenerator,
authorizerMapper
);
// We're filtering, so having access to none of the objects isn't an authorization failure (in terms of whether
// to send an error response or not.)
request.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true);
return filteredResources;
} } |
public class class_name {
public void reserve (@Nonnegative final int nExpectedLength)
{
ValueEnforcer.isGE0 (nExpectedLength, "ExpectedLength");
if (m_aBuffer.position () != 0)
throw new IllegalStateException ("cannot be called except after finish()");
if (nExpectedLength > m_aBuffer.capacity ())
{
// Allocate a temporary buffer large enough for this string rounded up
int nDesiredLength = nExpectedLength;
if ((nDesiredLength & SIZE_ALIGNMENT_MASK) != 0)
{
// round up
nDesiredLength = (nExpectedLength + SIZE_ALIGNMENT) & ~SIZE_ALIGNMENT_MASK;
}
assert nDesiredLength % SIZE_ALIGNMENT == 0;
m_aBuffer = CharBuffer.allocate (nDesiredLength);
}
if (m_aBuffer.position () != 0)
throw new IllegalStateException ("Buffer position weird!");
if (nExpectedLength > m_aBuffer.capacity ())
throw new IllegalStateException ();
} } | public class class_name {
public void reserve (@Nonnegative final int nExpectedLength)
{
ValueEnforcer.isGE0 (nExpectedLength, "ExpectedLength");
if (m_aBuffer.position () != 0)
throw new IllegalStateException ("cannot be called except after finish()");
if (nExpectedLength > m_aBuffer.capacity ())
{
// Allocate a temporary buffer large enough for this string rounded up
int nDesiredLength = nExpectedLength;
if ((nDesiredLength & SIZE_ALIGNMENT_MASK) != 0)
{
// round up
nDesiredLength = (nExpectedLength + SIZE_ALIGNMENT) & ~SIZE_ALIGNMENT_MASK; // depends on control dependency: [if], data = [none]
}
assert nDesiredLength % SIZE_ALIGNMENT == 0;
m_aBuffer = CharBuffer.allocate (nDesiredLength); // depends on control dependency: [if], data = [none]
}
if (m_aBuffer.position () != 0)
throw new IllegalStateException ("Buffer position weird!");
if (nExpectedLength > m_aBuffer.capacity ())
throw new IllegalStateException ();
} } |
public class class_name {
public static <T> int findIndexOf(Iterator<T> self, int startIndex, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
int result = -1;
int i = 0;
BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
while (self.hasNext()) {
Object value = self.next();
if (i++ < startIndex) {
continue;
}
if (bcw.call(value)) {
result = i - 1;
break;
}
}
return result;
} } | public class class_name {
public static <T> int findIndexOf(Iterator<T> self, int startIndex, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
int result = -1;
int i = 0;
BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
while (self.hasNext()) {
Object value = self.next();
if (i++ < startIndex) {
continue;
}
if (bcw.call(value)) {
result = i - 1; // depends on control dependency: [if], data = [none]
break;
}
}
return result;
} } |
public class class_name {
private InputStream toBufferedInputStream() {
int remaining = count;
if (remaining == 0) {
return new ClosedInputStream();
}
List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
for (byte[] buf : buffers) {
int c = Math.min(buf.length, remaining);
list.add(new ByteArrayInputStream(buf, 0, c));
remaining -= c;
if (remaining == 0) {
break;
}
}
return new SequenceInputStream(Collections.enumeration(list));
} } | public class class_name {
private InputStream toBufferedInputStream() {
int remaining = count;
if (remaining == 0) {
return new ClosedInputStream(); // depends on control dependency: [if], data = [none]
}
List<ByteArrayInputStream> list = new ArrayList<ByteArrayInputStream>(buffers.size());
for (byte[] buf : buffers) {
int c = Math.min(buf.length, remaining);
list.add(new ByteArrayInputStream(buf, 0, c)); // depends on control dependency: [for], data = [buf]
remaining -= c; // depends on control dependency: [for], data = [none]
if (remaining == 0) {
break;
}
}
return new SequenceInputStream(Collections.enumeration(list));
} } |
public class class_name {
protected final synchronized GenerationContext getContext(JvmIdentifiableElement type) {
for (final GenerationContext candidate : this.bufferedContexes) {
if (Objects.equal(candidate.getTypeIdentifier(), type.getIdentifier())) {
return candidate;
}
}
throw new GenerationContextNotFoundInternalError(type);
} } | public class class_name {
protected final synchronized GenerationContext getContext(JvmIdentifiableElement type) {
for (final GenerationContext candidate : this.bufferedContexes) {
if (Objects.equal(candidate.getTypeIdentifier(), type.getIdentifier())) {
return candidate; // depends on control dependency: [if], data = [none]
}
}
throw new GenerationContextNotFoundInternalError(type);
} } |
public class class_name {
private final int strcmpMax(String s, int unfoldOffset, int max) {
int i1, length, c1, c2;
length=s.length();
max-=length; /* we require length<=max, so no need to decrement max in the loop */
i1=0;
do {
c1=s.charAt(i1++);
c2=unfold[unfoldOffset++];
if(c2==0) {
return 1; /* reached the end of t but not of s */
}
c1-=c2;
if(c1!=0) {
return c1; /* return difference result */
}
} while(--length>0);
/* ends with length==0 */
if(max==0 || unfold[unfoldOffset]==0) {
return 0; /* equal to length of both strings */
} else {
return -max; /* return lengh difference */
}
} } | public class class_name {
private final int strcmpMax(String s, int unfoldOffset, int max) {
int i1, length, c1, c2;
length=s.length();
max-=length; /* we require length<=max, so no need to decrement max in the loop */
i1=0;
do {
c1=s.charAt(i1++);
c2=unfold[unfoldOffset++];
if(c2==0) {
return 1; /* reached the end of t but not of s */ // depends on control dependency: [if], data = [none]
}
c1-=c2;
if(c1!=0) {
return c1; /* return difference result */ // depends on control dependency: [if], data = [none]
}
} while(--length>0);
/* ends with length==0 */
if(max==0 || unfold[unfoldOffset]==0) {
return 0; /* equal to length of both strings */ // depends on control dependency: [if], data = [none]
} else {
return -max; /* return lengh difference */ // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected boolean doRejectedAttributesRefusePrincipalAccess(final Map<String, Object> principalAttributes) {
LOGGER.debug("These rejected attributes [{}] are examined against [{}] before service can proceed.", rejectedAttributes, principalAttributes);
if (rejectedAttributes.isEmpty()) {
return false;
}
return requiredAttributesFoundInMap(principalAttributes, rejectedAttributes);
} } | public class class_name {
protected boolean doRejectedAttributesRefusePrincipalAccess(final Map<String, Object> principalAttributes) {
LOGGER.debug("These rejected attributes [{}] are examined against [{}] before service can proceed.", rejectedAttributes, principalAttributes);
if (rejectedAttributes.isEmpty()) {
return false; // depends on control dependency: [if], data = [none]
}
return requiredAttributesFoundInMap(principalAttributes, rejectedAttributes);
} } |
public class class_name {
@Override
public List<String> getEurekaServerServiceUrls(String myZone) {
String serviceUrls = configInstance.getStringProperty(
namespace + CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX + "." + myZone, null).get();
if (serviceUrls == null || serviceUrls.isEmpty()) {
serviceUrls = configInstance.getStringProperty(
namespace + CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX + ".default", null).get();
}
if (serviceUrls != null) {
return Arrays.asList(serviceUrls.split(URL_SEPARATOR));
}
return new ArrayList<String>();
} } | public class class_name {
@Override
public List<String> getEurekaServerServiceUrls(String myZone) {
String serviceUrls = configInstance.getStringProperty(
namespace + CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX + "." + myZone, null).get();
if (serviceUrls == null || serviceUrls.isEmpty()) {
serviceUrls = configInstance.getStringProperty(
namespace + CONFIG_EUREKA_SERVER_SERVICE_URL_PREFIX + ".default", null).get(); // depends on control dependency: [if], data = [none]
}
if (serviceUrls != null) {
return Arrays.asList(serviceUrls.split(URL_SEPARATOR)); // depends on control dependency: [if], data = [(serviceUrls]
}
return new ArrayList<String>();
} } |
public class class_name {
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public static CharSequence optCharSequence(@Nullable Bundle bundle, @Nullable String key, @Nullable CharSequence fallback) {
if (bundle == null) {
return fallback;
}
return bundle.getCharSequence(key, fallback);
} } | public class class_name {
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public static CharSequence optCharSequence(@Nullable Bundle bundle, @Nullable String key, @Nullable CharSequence fallback) {
if (bundle == null) {
return fallback; // depends on control dependency: [if], data = [none]
}
return bundle.getCharSequence(key, fallback);
} } |
public class class_name {
public void verifyNet( Pipe[] networkPipes, IHMProgressMonitor pm ) {
/*
* serve per verificare che ci sia almeno un'uscita. True= esiste
* un'uscita
*/
boolean isOut = false;
if (networkPipes != null) {
/* VERIFICA DATI GEOMETRICI DELLA RETE */
// Per ogni stato
int length = networkPipes.length;
int kj;
for( int i = 0; i < length; i++ )
{
// verifica che la rete abbia almeno un-uscita.
if (networkPipes[i].getIdPipeWhereDrain() == 0) {
isOut = true;
}
/*
* Controlla che non ci siano errori nei dati geometrici della
* rete, numero ID pipe in cui drena i >del numero consentito
* (la numerazione va da 1 a length
*/
if (networkPipes[i].getIndexPipeWhereDrain() > length) {
pm.errorMessage(msg.message("trentoP.error.pipe"));
throw new IllegalArgumentException(msg.message("trentoP.error.pipe"));
}
/*
* Da quanto si puo leggere nel file di input fossolo.geo in
* Fluide Turtle, ogni stato o sottobacino e contraddistinto da
* un numero crescente che va da 1 a n=numero di stati; n e
* anche pari a data->nrh. Inoltre si apprende che la prima
* colonna della matrice in fossolo.geo riporta l'elenco degli
* stati, mentre la seconda colonna ci dice dove ciascun stato
* va a drenare.(NON E AMMESSO CHE LO STESSO STATO DRENI SU PIU
* DI UNO!!) Questa if serve per verificare che non siano
* presenti condotte non dichiarate, ovvero piu realisticamente
* che non ci sia un'errore di numerazione o battitura. In altri
* termini lo stato analizzato non puo drenare in uno stato al
* di fuori di quelli esplicitamente dichiarati o dell'uscita,
* contradistinta con ID 0
*/
kj = i;
/*
* Terra conto degli stati attraversati dall'acqua che inizia a
* scorrere a partire dallo stato analizzato
*/
int count = 0;
/*
* Seguo il percorso dell'acqua a partire dallo stato corrente
*/
while( networkPipes[kj].getIdPipeWhereDrain() != 0 ) {
kj = networkPipes[kj].getIndexPipeWhereDrain();
/*
* L'acqua non puo finire in uno stato che con sia tra
* quelli esplicitamente definiti, in altre parole il
* percorso dell'acqua non puo essere al di fuori
* dell'inseme dei dercorsi possibili
*/
if (kj > length) {
pm.errorMessage(msg.message("trentoP.error.drainPipe") + kj);
throw new IllegalArgumentException(msg.message("trentoP.error.drainPipe") + kj);
}
count++;
if (count > length) {
pm.errorMessage(msg.message("trentoP.error.pipe"));
throw new IllegalArgumentException(msg.message("trentoP.error.pipe"));
}
/*
* La variabile count mi consente di uscire dal ciclo while,
* nel caso non ci fosse [kj][2]=0, ossia un'uscita. Infatti
* partendo da uno stato qualsiasi il numero degli stati
* attraversati prima di raggiungere l'uscita non puo essere
* superiore al numero degli stati effettivamente presenti.
* Quando questo accade vuol dire che l'acqua e in un loop
* chiuso
*/
}
}
/*
* Non si e trovato neanche un uscita, quindi Trento_p da errore di
* esecuzione, perchè almeno una colonna deve essere l'uscita
*/
if (isOut == false) {
pm.errorMessage(msg.message("trentoP.error.noout"));
throw new IllegalArgumentException(msg.message("trentoP.error.noout"));
}
} else {
throw new IllegalArgumentException(msg.message("trentoP.error.incorrectmatrix"));
}
} } | public class class_name {
public void verifyNet( Pipe[] networkPipes, IHMProgressMonitor pm ) {
/*
* serve per verificare che ci sia almeno un'uscita. True= esiste
* un'uscita
*/
boolean isOut = false;
if (networkPipes != null) {
/* VERIFICA DATI GEOMETRICI DELLA RETE */
// Per ogni stato
int length = networkPipes.length;
int kj;
for( int i = 0; i < length; i++ )
{
// verifica che la rete abbia almeno un-uscita.
if (networkPipes[i].getIdPipeWhereDrain() == 0) {
isOut = true; // depends on control dependency: [if], data = [none]
}
/*
* Controlla che non ci siano errori nei dati geometrici della
* rete, numero ID pipe in cui drena i >del numero consentito
* (la numerazione va da 1 a length
*/
if (networkPipes[i].getIndexPipeWhereDrain() > length) {
pm.errorMessage(msg.message("trentoP.error.pipe"));
throw new IllegalArgumentException(msg.message("trentoP.error.pipe"));
}
/*
* Da quanto si puo leggere nel file di input fossolo.geo in
* Fluide Turtle, ogni stato o sottobacino e contraddistinto da
* un numero crescente che va da 1 a n=numero di stati; n e
* anche pari a data->nrh. Inoltre si apprende che la prima
* colonna della matrice in fossolo.geo riporta l'elenco degli
* stati, mentre la seconda colonna ci dice dove ciascun stato
* va a drenare.(NON E AMMESSO CHE LO STESSO STATO DRENI SU PIU
* DI UNO!!) Questa if serve per verificare che non siano
* presenti condotte non dichiarate, ovvero piu realisticamente
* che non ci sia un'errore di numerazione o battitura. In altri
* termini lo stato analizzato non puo drenare in uno stato al
* di fuori di quelli esplicitamente dichiarati o dell'uscita,
* contradistinta con ID 0
*/
kj = i;
/*
* Terra conto degli stati attraversati dall'acqua che inizia a
* scorrere a partire dallo stato analizzato
*/
int count = 0;
/*
* Seguo il percorso dell'acqua a partire dallo stato corrente
*/
while( networkPipes[kj].getIdPipeWhereDrain() != 0 ) {
kj = networkPipes[kj].getIndexPipeWhereDrain();
/*
* L'acqua non puo finire in uno stato che con sia tra
* quelli esplicitamente definiti, in altre parole il
* percorso dell'acqua non puo essere al di fuori
* dell'inseme dei dercorsi possibili
*/
if (kj > length) {
pm.errorMessage(msg.message("trentoP.error.drainPipe") + kj);
throw new IllegalArgumentException(msg.message("trentoP.error.drainPipe") + kj);
}
count++;
if (count > length) {
pm.errorMessage(msg.message("trentoP.error.pipe"));
throw new IllegalArgumentException(msg.message("trentoP.error.pipe"));
}
/*
* La variabile count mi consente di uscire dal ciclo while,
* nel caso non ci fosse [kj][2]=0, ossia un'uscita. Infatti
* partendo da uno stato qualsiasi il numero degli stati
* attraversati prima di raggiungere l'uscita non puo essere
* superiore al numero degli stati effettivamente presenti.
* Quando questo accade vuol dire che l'acqua e in un loop
* chiuso
*/
}
}
/*
* Non si e trovato neanche un uscita, quindi Trento_p da errore di
* esecuzione, perchè almeno una colonna deve essere l'uscita
*/
if (isOut == false) {
pm.errorMessage(msg.message("trentoP.error.noout"));
throw new IllegalArgumentException(msg.message("trentoP.error.noout")); // depends on control dependency: [if], data = [none]
}
} else {
throw new IllegalArgumentException(msg.message("trentoP.error.incorrectmatrix"));
}
} } |
public class class_name {
void gatherProtocol(int maxPos) throws IOException {
// protocol buffer has max capacity, shouldn't need resizing
try {
while(this.bufferPosition < maxPos) {
byte b = this.buffer[this.bufferPosition];
this.bufferPosition++;
if (gotCR) {
if (b == NatsConnection.LF) {
this.protocolBuffer.flip();
this.mode = Mode.PARSE_PROTO;
this.gotCR = false;
break;
} else {
throw new IllegalStateException("Bad socket data, no LF after CR");
}
} else if (b == NatsConnection.CR) {
this.gotCR = true;
} else {
if (!protocolBuffer.hasRemaining()) {
this.protocolBuffer = this.connection.enlargeBuffer(this.protocolBuffer, 0); // just double it
}
this.protocolBuffer.put(b);
}
}
} catch (IllegalStateException | NumberFormatException | NullPointerException ex) {
this.encounteredProtocolError(ex);
}
} } | public class class_name {
void gatherProtocol(int maxPos) throws IOException {
// protocol buffer has max capacity, shouldn't need resizing
try {
while(this.bufferPosition < maxPos) {
byte b = this.buffer[this.bufferPosition];
this.bufferPosition++;
if (gotCR) {
if (b == NatsConnection.LF) {
this.protocolBuffer.flip();
// depends on control dependency: [if], data = [none]
this.mode = Mode.PARSE_PROTO;
// depends on control dependency: [if], data = [none]
this.gotCR = false;
// depends on control dependency: [if], data = [none]
break;
} else {
throw new IllegalStateException("Bad socket data, no LF after CR");
}
} else if (b == NatsConnection.CR) {
this.gotCR = true;
} else {
if (!protocolBuffer.hasRemaining()) {
this.protocolBuffer = this.connection.enlargeBuffer(this.protocolBuffer, 0); // just double it
}
this.protocolBuffer.put(b);
}
}
} catch (IllegalStateException | NumberFormatException | NullPointerException ex) {
this.encounteredProtocolError(ex);
}
} } |
public class class_name {
public static <T> Set<T> wrapSet(final T source) {
val list = new LinkedHashSet<T>();
if (source != null) {
list.add(source);
}
return list;
} } | public class class_name {
public static <T> Set<T> wrapSet(final T source) {
val list = new LinkedHashSet<T>();
if (source != null) {
list.add(source); // depends on control dependency: [if], data = [(source]
}
return list;
} } |
public class class_name {
public static final ParseResult parseParams(Object[] params) {
Tree data = null;
CallOptions.Options opts = null;
Groups groups = null;
PacketStream stream = null;
if (params != null) {
if (params.length == 1) {
if (params[0] instanceof Tree) {
data = (Tree) params[0];
} else if (params[0] instanceof CallOptions.Options) {
opts = (CallOptions.Options) params[0];
} else if (params[0] instanceof Groups) {
groups = (Groups) params[0];
} else if (params[0] instanceof PacketStream) {
data = new Tree();
stream = (PacketStream) params[0];
} else {
data = new CheckedTree(params[0]);
}
} else {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
String prev = null;
Object value;
for (int i = 0; i < params.length; i++) {
value = params[i];
if (prev == null) {
if (!(value instanceof String)) {
if (value instanceof CallOptions.Options) {
opts = (CallOptions.Options) value;
continue;
}
if (value instanceof Groups) {
groups = (Groups) value;
continue;
}
if (value instanceof PacketStream) {
stream = (PacketStream) value;
continue;
}
i++;
throw new IllegalArgumentException("Parameter #" + i + " (\"" + value
+ "\") must be String, Context, Groups, PacketStream or CallOptions!");
}
prev = (String) value;
continue;
}
map.put(prev, value);
prev = null;
}
data = new Tree(map);
}
}
return new ParseResult(data, opts, groups, stream);
} } | public class class_name {
public static final ParseResult parseParams(Object[] params) {
Tree data = null;
CallOptions.Options opts = null;
Groups groups = null;
PacketStream stream = null;
if (params != null) {
if (params.length == 1) {
if (params[0] instanceof Tree) {
data = (Tree) params[0];
// depends on control dependency: [if], data = [none]
} else if (params[0] instanceof CallOptions.Options) {
opts = (CallOptions.Options) params[0];
// depends on control dependency: [if], data = [none]
} else if (params[0] instanceof Groups) {
groups = (Groups) params[0];
// depends on control dependency: [if], data = [none]
} else if (params[0] instanceof PacketStream) {
data = new Tree();
// depends on control dependency: [if], data = [none]
stream = (PacketStream) params[0];
// depends on control dependency: [if], data = [none]
} else {
data = new CheckedTree(params[0]);
// depends on control dependency: [if], data = [none]
}
} else {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
String prev = null;
Object value;
for (int i = 0; i < params.length; i++) {
value = params[i];
// depends on control dependency: [for], data = [i]
if (prev == null) {
if (!(value instanceof String)) {
if (value instanceof CallOptions.Options) {
opts = (CallOptions.Options) value;
// depends on control dependency: [if], data = [none]
continue;
}
if (value instanceof Groups) {
groups = (Groups) value;
// depends on control dependency: [if], data = [none]
continue;
}
if (value instanceof PacketStream) {
stream = (PacketStream) value;
// depends on control dependency: [if], data = [none]
continue;
}
i++;
// depends on control dependency: [if], data = [none]
throw new IllegalArgumentException("Parameter #" + i + " (\"" + value
+ "\") must be String, Context, Groups, PacketStream or CallOptions!");
}
prev = (String) value;
// depends on control dependency: [if], data = [none]
continue;
}
map.put(prev, value);
// depends on control dependency: [for], data = [none]
prev = null;
// depends on control dependency: [for], data = [none]
}
data = new Tree(map);
// depends on control dependency: [if], data = [none]
}
}
return new ParseResult(data, opts, groups, stream);
} } |
public class class_name {
public double evaluateCoverage(Collection<Tree> trees, Set<String> missingWords,
Set<String> missingTags, Set<IntTaggedWord> missingTW) {
List<IntTaggedWord> iTW1 = new ArrayList<IntTaggedWord>();
for (Tree t : trees) {
iTW1.addAll(treeToEvents(t));
}
int total = 0;
int unseen = 0;
for (IntTaggedWord itw : iTW1) {
total++;
if (!words.contains(new IntTaggedWord(itw.word(), nullTag))) {
missingWords.add(wordIndex.get(itw.word()));
}
if (!tags.contains(new IntTaggedWord(nullWord, itw.tag()))) {
missingTags.add(tagIndex.get(itw.tag()));
}
// if (!rules.contains(itw)) {
if (seenCounter.getCount(itw) == 0.0) {
unseen++;
missingTW.add(itw);
}
}
return (double) unseen / total;
} } | public class class_name {
public double evaluateCoverage(Collection<Tree> trees, Set<String> missingWords,
Set<String> missingTags, Set<IntTaggedWord> missingTW) {
List<IntTaggedWord> iTW1 = new ArrayList<IntTaggedWord>();
for (Tree t : trees) {
iTW1.addAll(treeToEvents(t));
// depends on control dependency: [for], data = [t]
}
int total = 0;
int unseen = 0;
for (IntTaggedWord itw : iTW1) {
total++;
// depends on control dependency: [for], data = [none]
if (!words.contains(new IntTaggedWord(itw.word(), nullTag))) {
missingWords.add(wordIndex.get(itw.word()));
// depends on control dependency: [if], data = [none]
}
if (!tags.contains(new IntTaggedWord(nullWord, itw.tag()))) {
missingTags.add(tagIndex.get(itw.tag()));
// depends on control dependency: [if], data = [none]
}
// if (!rules.contains(itw)) {
if (seenCounter.getCount(itw) == 0.0) {
unseen++;
// depends on control dependency: [if], data = [none]
missingTW.add(itw);
// depends on control dependency: [if], data = [none]
}
}
return (double) unseen / total;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.