code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private static LocalizationContext findMatch(PageContext pageContext,
String basename) {
LocalizationContext locCtxt = null;
// Determine locale from client's browser settings.
for (Enumeration enum_ = Util
.getRequestLocales((HttpServletRequest) pageContext
.getRequest()); enum_.hasMoreElements();) {
Locale pref = (Locale) enum_.nextElement();
ResourceBundle match = findMatch(basename, pref);
if (match != null) {
locCtxt = new LocalizationContext(match, pref);
break;
}
}
return locCtxt;
} } | public class class_name {
private static LocalizationContext findMatch(PageContext pageContext,
String basename) {
LocalizationContext locCtxt = null;
// Determine locale from client's browser settings.
for (Enumeration enum_ = Util
.getRequestLocales((HttpServletRequest) pageContext
.getRequest()); enum_.hasMoreElements();) {
Locale pref = (Locale) enum_.nextElement();
ResourceBundle match = findMatch(basename, pref);
if (match != null) {
locCtxt = new LocalizationContext(match, pref); // depends on control dependency: [if], data = [(match]
break;
}
}
return locCtxt;
} } |
public class class_name {
public final void recover(final Sheet sheet) {
this.getAttrs().recover(sheet);
if (this.commandList != null) {
for (ConfigCommand command : this.commandList) {
command.recover(sheet);
}
}
} } | public class class_name {
public final void recover(final Sheet sheet) {
this.getAttrs().recover(sheet);
if (this.commandList != null) {
for (ConfigCommand command : this.commandList) {
command.recover(sheet);
// depends on control dependency: [for], data = [command]
}
}
} } |
public class class_name {
@Override
public void setSpan(Object what, int start, int end, int flags) {
if (mSpanCount + 1 >= mSpans.length) {
int newsize = mSpanCount + 10;
Object[] newtags = new Object[newsize];
int[] newdata = new int[newsize * 3];
System.arraycopy(mSpans, 0, newtags, 0, mSpanCount);
System.arraycopy(mSpanData, 0, newdata, 0, mSpanCount * 3);
mSpans = newtags;
mSpanData = newdata;
}
mSpans[mSpanCount] = what;
mSpanData[mSpanCount * COLUMNS + START] = start;
mSpanData[mSpanCount * COLUMNS + END] = end;
mSpanData[mSpanCount * COLUMNS + FLAGS] = flags;
mSpanCount++;
} } | public class class_name {
@Override
public void setSpan(Object what, int start, int end, int flags) {
if (mSpanCount + 1 >= mSpans.length) {
int newsize = mSpanCount + 10;
Object[] newtags = new Object[newsize];
int[] newdata = new int[newsize * 3];
System.arraycopy(mSpans, 0, newtags, 0, mSpanCount); // depends on control dependency: [if], data = [none]
System.arraycopy(mSpanData, 0, newdata, 0, mSpanCount * 3); // depends on control dependency: [if], data = [none]
mSpans = newtags; // depends on control dependency: [if], data = [none]
mSpanData = newdata; // depends on control dependency: [if], data = [none]
}
mSpans[mSpanCount] = what;
mSpanData[mSpanCount * COLUMNS + START] = start;
mSpanData[mSpanCount * COLUMNS + END] = end;
mSpanData[mSpanCount * COLUMNS + FLAGS] = flags;
mSpanCount++;
} } |
public class class_name {
@CheckReturnValue
protected Statement genParamTypeChecks(TemplateNode node, String alias) {
ImmutableList.Builder<Statement> declarations = ImmutableList.builder();
for (TemplateParam param : node.getAllParams()) {
String paramName = param.name();
SoyType paramType = param.type();
CodeChunk.Generator generator = templateTranslationContext.codeGenerator();
Expression paramChunk = genCodeForParamAccess(paramName, param);
JsType jsType = getJsTypeForParamTypeCheck(paramType);
// The opt_param.name value that will be type-tested.
String paramAlias = genParamAlias(paramName);
Expression coerced = jsType.getValueCoercion(paramChunk, generator);
if (coerced != null) {
// since we have coercion logic, dump into a temporary
paramChunk = generator.declarationBuilder().setRhs(coerced).build().ref();
}
if (param.hasDefault()) {
if (coerced == null) {
paramChunk = generator.declarationBuilder().setRhs(paramChunk).build().ref();
}
declarations.add(
genParamDefault(param, paramChunk, alias, jsType, /* declareStatic= */ true));
}
// The param value to assign
Expression value;
Optional<Expression> soyTypeAssertion =
jsType.getSoyTypeAssertion(paramChunk, paramName, generator);
// The type-cast expression.
if (soyTypeAssertion.isPresent()) {
value = soyTypeAssertion.get();
} else {
value = paramChunk;
}
VariableDeclaration.Builder declarationBuilder =
VariableDeclaration.builder(paramAlias)
.setRhs(value)
.setGoogRequires(jsType.getGoogRequires());
declarationBuilder.setJsDoc(
JsDoc.builder()
.addParameterizedAnnotation(
"type", getJsTypeForParamForDeclaration(paramType).typeExpr())
.build());
VariableDeclaration declaration = declarationBuilder.build();
declarations.add(declaration);
templateTranslationContext
.soyToJsVariableMappings()
// TODO(lukes): this should really be declartion.ref() but we cannot do that until
// everything is on the code chunk api.
.put(paramName, id(paramAlias));
}
return Statement.of(declarations.build());
} } | public class class_name {
@CheckReturnValue
protected Statement genParamTypeChecks(TemplateNode node, String alias) {
ImmutableList.Builder<Statement> declarations = ImmutableList.builder();
for (TemplateParam param : node.getAllParams()) {
String paramName = param.name();
SoyType paramType = param.type();
CodeChunk.Generator generator = templateTranslationContext.codeGenerator();
Expression paramChunk = genCodeForParamAccess(paramName, param);
JsType jsType = getJsTypeForParamTypeCheck(paramType);
// The opt_param.name value that will be type-tested.
String paramAlias = genParamAlias(paramName);
Expression coerced = jsType.getValueCoercion(paramChunk, generator);
if (coerced != null) {
// since we have coercion logic, dump into a temporary
paramChunk = generator.declarationBuilder().setRhs(coerced).build().ref(); // depends on control dependency: [if], data = [(coerced]
}
if (param.hasDefault()) {
if (coerced == null) {
paramChunk = generator.declarationBuilder().setRhs(paramChunk).build().ref(); // depends on control dependency: [if], data = [none]
}
declarations.add(
genParamDefault(param, paramChunk, alias, jsType, /* declareStatic= */ true)); // depends on control dependency: [if], data = [none]
}
// The param value to assign
Expression value;
Optional<Expression> soyTypeAssertion =
jsType.getSoyTypeAssertion(paramChunk, paramName, generator);
// The type-cast expression.
if (soyTypeAssertion.isPresent()) {
value = soyTypeAssertion.get(); // depends on control dependency: [if], data = [none]
} else {
value = paramChunk; // depends on control dependency: [if], data = [none]
}
VariableDeclaration.Builder declarationBuilder =
VariableDeclaration.builder(paramAlias)
.setRhs(value)
.setGoogRequires(jsType.getGoogRequires());
declarationBuilder.setJsDoc(
JsDoc.builder()
.addParameterizedAnnotation(
"type", getJsTypeForParamForDeclaration(paramType).typeExpr())
.build()); // depends on control dependency: [for], data = [none]
VariableDeclaration declaration = declarationBuilder.build();
declarations.add(declaration); // depends on control dependency: [for], data = [none]
templateTranslationContext
.soyToJsVariableMappings()
// TODO(lukes): this should really be declartion.ref() but we cannot do that until
// everything is on the code chunk api.
.put(paramName, id(paramAlias)); // depends on control dependency: [for], data = [none]
}
return Statement.of(declarations.build());
} } |
public class class_name {
public synchronized void shutdownImmediately() {
if (!this.isShutdown) {
final Thread runner = this.taskRunnerThread;
this.isShutdown = true;
if (runner != null && runner.isAlive()) {
runner.interrupt();
}
this.taskQueue.cancelAllTasks();
}
} } | public class class_name {
public synchronized void shutdownImmediately() {
if (!this.isShutdown) {
final Thread runner = this.taskRunnerThread;
this.isShutdown = true; // depends on control dependency: [if], data = [none]
if (runner != null && runner.isAlive()) {
runner.interrupt(); // depends on control dependency: [if], data = [none]
}
this.taskQueue.cancelAllTasks(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void set(String key, Object entry, long expireAfterWrite, long expireAfterAccess) {
if (!(entry instanceof CacheEntry)) {
CacheEntry ce = new CacheEntry(key, CacheUtils.tryClone(entry), expireAfterWrite,
expireAfterAccess);
entry = ce;
} else {
entry = CacheUtils.tryClone(entry);
}
cache.put(key, entry);
} } | public class class_name {
@Override
public void set(String key, Object entry, long expireAfterWrite, long expireAfterAccess) {
if (!(entry instanceof CacheEntry)) {
CacheEntry ce = new CacheEntry(key, CacheUtils.tryClone(entry), expireAfterWrite,
expireAfterAccess);
entry = ce; // depends on control dependency: [if], data = [none]
} else {
entry = CacheUtils.tryClone(entry); // depends on control dependency: [if], data = [none]
}
cache.put(key, entry);
} } |
public class class_name {
public static IStatus addNatures(IProject project, IProgressMonitor monitor, String... natureIdentifiers) {
if (project != null && natureIdentifiers != null && natureIdentifiers.length > 0) {
try {
final SubMonitor subMonitor = SubMonitor.convert(monitor, natureIdentifiers.length + 2);
final IProjectDescription description = project.getDescription();
final List<String> natures = new LinkedList<>(Arrays.asList(description.getNatureIds()));
for (final String natureIdentifier : natureIdentifiers) {
if (!Strings.isNullOrEmpty(natureIdentifier) && !natures.contains(natureIdentifier)) {
natures.add(0, natureIdentifier);
}
subMonitor.worked(1);
}
final String[] newNatures = natures.toArray(new String[natures.size()]);
final IStatus status = ResourcesPlugin.getWorkspace().validateNatureSet(newNatures);
subMonitor.worked(1);
// check the status and decide what to do
if (status.getCode() == IStatus.OK) {
description.setNatureIds(newNatures);
project.setDescription(description, subMonitor.newChild(1));
}
subMonitor.done();
return status;
} catch (CoreException exception) {
return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, exception);
}
}
return SARLEclipsePlugin.getDefault().createOkStatus();
} } | public class class_name {
public static IStatus addNatures(IProject project, IProgressMonitor monitor, String... natureIdentifiers) {
if (project != null && natureIdentifiers != null && natureIdentifiers.length > 0) {
try {
final SubMonitor subMonitor = SubMonitor.convert(monitor, natureIdentifiers.length + 2);
final IProjectDescription description = project.getDescription();
final List<String> natures = new LinkedList<>(Arrays.asList(description.getNatureIds()));
for (final String natureIdentifier : natureIdentifiers) {
if (!Strings.isNullOrEmpty(natureIdentifier) && !natures.contains(natureIdentifier)) {
natures.add(0, natureIdentifier); // depends on control dependency: [if], data = [none]
}
subMonitor.worked(1); // depends on control dependency: [for], data = [none]
}
final String[] newNatures = natures.toArray(new String[natures.size()]);
final IStatus status = ResourcesPlugin.getWorkspace().validateNatureSet(newNatures);
subMonitor.worked(1); // depends on control dependency: [try], data = [none]
// check the status and decide what to do
if (status.getCode() == IStatus.OK) {
description.setNatureIds(newNatures); // depends on control dependency: [if], data = [none]
project.setDescription(description, subMonitor.newChild(1)); // depends on control dependency: [if], data = [none]
}
subMonitor.done(); // depends on control dependency: [try], data = [none]
return status; // depends on control dependency: [try], data = [none]
} catch (CoreException exception) {
return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, exception);
} // depends on control dependency: [catch], data = [none]
}
return SARLEclipsePlugin.getDefault().createOkStatus();
} } |
public class class_name {
public static void safeEncodeValue(final StringBuilder encoder, @Nullable final Object value) {
if (value == null) {
encoder.append("null");
} else if (value instanceof Map) {
safeEncodeMap(encoder, (Map<?, ?>) value);
} else if (value instanceof List) {
safeEncodeList(encoder, (List<?>) value);
} else if (value.getClass().isArray()) {
safeEncodeArray(encoder, value);
} else if (value instanceof LogValueMapFactory.LogValueMap) {
safeEncodeLogValueMap(encoder, (LogValueMapFactory.LogValueMap) value);
} else if (value instanceof Throwable) {
safeEncodeThrowable(encoder, (Throwable) value);
} else if (StenoSerializationHelper.isSimpleType(value)) {
if (value instanceof Boolean) {
encoder.append(BooleanNode.valueOf((Boolean) value).toString());
} else if (value instanceof Double) {
encoder.append(DoubleNode.valueOf((Double) value).toString());
} else if (value instanceof Float) {
encoder.append(FloatNode.valueOf((Float) value).toString());
} else if (value instanceof Long) {
encoder.append(LongNode.valueOf((Long) value).toString());
} else if (value instanceof Integer) {
encoder.append(IntNode.valueOf((Integer) value).toString());
} else {
encoder.append(new TextNode(value.toString()).toString());
}
} else {
safeEncodeValue(encoder, LogReferenceOnly.of(value).toLogValue());
}
} } | public class class_name {
public static void safeEncodeValue(final StringBuilder encoder, @Nullable final Object value) {
if (value == null) {
encoder.append("null"); // depends on control dependency: [if], data = [none]
} else if (value instanceof Map) {
safeEncodeMap(encoder, (Map<?, ?>) value); // depends on control dependency: [if], data = [none]
} else if (value instanceof List) {
safeEncodeList(encoder, (List<?>) value); // depends on control dependency: [if], data = [none]
} else if (value.getClass().isArray()) {
safeEncodeArray(encoder, value); // depends on control dependency: [if], data = [none]
} else if (value instanceof LogValueMapFactory.LogValueMap) {
safeEncodeLogValueMap(encoder, (LogValueMapFactory.LogValueMap) value); // depends on control dependency: [if], data = [none]
} else if (value instanceof Throwable) {
safeEncodeThrowable(encoder, (Throwable) value); // depends on control dependency: [if], data = [none]
} else if (StenoSerializationHelper.isSimpleType(value)) {
if (value instanceof Boolean) {
encoder.append(BooleanNode.valueOf((Boolean) value).toString()); // depends on control dependency: [if], data = [none]
} else if (value instanceof Double) {
encoder.append(DoubleNode.valueOf((Double) value).toString()); // depends on control dependency: [if], data = [none]
} else if (value instanceof Float) {
encoder.append(FloatNode.valueOf((Float) value).toString()); // depends on control dependency: [if], data = [none]
} else if (value instanceof Long) {
encoder.append(LongNode.valueOf((Long) value).toString()); // depends on control dependency: [if], data = [none]
} else if (value instanceof Integer) {
encoder.append(IntNode.valueOf((Integer) value).toString()); // depends on control dependency: [if], data = [none]
} else {
encoder.append(new TextNode(value.toString()).toString()); // depends on control dependency: [if], data = [none]
}
} else {
safeEncodeValue(encoder, LogReferenceOnly.of(value).toLogValue()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public MarkupContainer add(final Component... _childs)
{
MarkupContainer ret = null;
for (final Component child : _childs) {
if (child instanceof HtmlHeaderContainer) {
ret = add2Page(child);
} else {
ret = body.add(_childs);
}
}
return ret;
} } | public class class_name {
@Override
public MarkupContainer add(final Component... _childs)
{
MarkupContainer ret = null;
for (final Component child : _childs) {
if (child instanceof HtmlHeaderContainer) {
ret = add2Page(child); // depends on control dependency: [if], data = [none]
} else {
ret = body.add(_childs); // depends on control dependency: [if], data = [none]
}
}
return ret;
} } |
public class class_name {
private void handleInit(ChaincodeMessage message) {
new Thread(() -> {
try {
// Get the function and args from Payload
final ChaincodeInput input = ChaincodeInput.parseFrom(message.getPayload());
// Mark as a transaction (allow put/del state)
markIsTransaction(message.getChannelId(), message.getTxid(), true);
// Create the ChaincodeStub which the chaincode can use to
// callback
final ChaincodeStub stub = new ChaincodeStubImpl(message.getChannelId(), message.getTxid(), this, input.getArgsList(), message.getProposal());
// Call chaincode's init
final Chaincode.Response result = chaincode.init(stub);
if (result.getStatus().getCode() >= Chaincode.Response.Status.INTERNAL_SERVER_ERROR.getCode()) {
// Send ERROR with entire result.Message as payload
logger.severe(format("[%-8.8s] Init failed. Sending %s", message.getTxid(), ERROR));
queueOutboundChaincodeMessage(newErrorEventMessage(message.getChannelId(), message.getTxid(), result.getMessage(), stub.getEvent()));
} else {
// Send COMPLETED with entire result as payload
if (logger.isLoggable(Level.FINE)) {
logger.fine(format(format("[%-8.8s] Init succeeded. Sending %s", message.getTxid(), COMPLETED)));
}
queueOutboundChaincodeMessage(newCompletedEventMessage(message.getChannelId(), message.getTxid(), result, stub.getEvent()));
}
} catch (InvalidProtocolBufferException | RuntimeException e) {
logger.severe(format("[%-8.8s] Init failed. Sending %s: %s", message.getTxid(), ERROR, e));
queueOutboundChaincodeMessage(newErrorEventMessage(message.getChannelId(), message.getTxid(), e));
} finally {
// delete isTransaction entry
deleteIsTransaction(message.getChannelId(), message.getTxid());
}
}).start();
} } | public class class_name {
private void handleInit(ChaincodeMessage message) {
new Thread(() -> {
try {
// Get the function and args from Payload
final ChaincodeInput input = ChaincodeInput.parseFrom(message.getPayload());
// Mark as a transaction (allow put/del state)
markIsTransaction(message.getChannelId(), message.getTxid(), true); // depends on control dependency: [try], data = [none]
// Create the ChaincodeStub which the chaincode can use to
// callback
final ChaincodeStub stub = new ChaincodeStubImpl(message.getChannelId(), message.getTxid(), this, input.getArgsList(), message.getProposal());
// Call chaincode's init
final Chaincode.Response result = chaincode.init(stub);
if (result.getStatus().getCode() >= Chaincode.Response.Status.INTERNAL_SERVER_ERROR.getCode()) {
// Send ERROR with entire result.Message as payload
logger.severe(format("[%-8.8s] Init failed. Sending %s", message.getTxid(), ERROR)); // depends on control dependency: [if], data = [none]
queueOutboundChaincodeMessage(newErrorEventMessage(message.getChannelId(), message.getTxid(), result.getMessage(), stub.getEvent())); // depends on control dependency: [if], data = [none]
} else {
// Send COMPLETED with entire result as payload
if (logger.isLoggable(Level.FINE)) {
logger.fine(format(format("[%-8.8s] Init succeeded. Sending %s", message.getTxid(), COMPLETED))); // depends on control dependency: [if], data = [none]
}
queueOutboundChaincodeMessage(newCompletedEventMessage(message.getChannelId(), message.getTxid(), result, stub.getEvent())); // depends on control dependency: [if], data = [none]
}
} catch (InvalidProtocolBufferException | RuntimeException e) {
logger.severe(format("[%-8.8s] Init failed. Sending %s: %s", message.getTxid(), ERROR, e));
queueOutboundChaincodeMessage(newErrorEventMessage(message.getChannelId(), message.getTxid(), e));
} finally { // depends on control dependency: [catch], data = [none]
// delete isTransaction entry
deleteIsTransaction(message.getChannelId(), message.getTxid());
}
}).start();
} } |
public class class_name {
public static Set<Node> getSeedInteractions(Collection<BioPAXElement> elements, Graph graph)
{
Set<Node> nodes = new HashSet<Node>();
for (BioPAXElement ele : elements)
{
if (ele instanceof Conversion || ele instanceof TemplateReaction ||
ele instanceof Control)
{
GraphObject go = graph.getGraphObject(ele);
if (go instanceof Node)
{
nodes.add((Node) go);
}
}
}
return nodes;
} } | public class class_name {
public static Set<Node> getSeedInteractions(Collection<BioPAXElement> elements, Graph graph)
{
Set<Node> nodes = new HashSet<Node>();
for (BioPAXElement ele : elements)
{
if (ele instanceof Conversion || ele instanceof TemplateReaction ||
ele instanceof Control)
{
GraphObject go = graph.getGraphObject(ele);
if (go instanceof Node)
{
nodes.add((Node) go); // depends on control dependency: [if], data = [none]
}
}
}
return nodes;
} } |
public class class_name {
public JType getGenericType()
{
SignatureAttribute sigAttr = (SignatureAttribute) getAttribute("Signature");
if (sigAttr != null) {
return getClassLoader().parseParameterizedType(sigAttr.getSignature());
}
return getType();
} } | public class class_name {
public JType getGenericType()
{
SignatureAttribute sigAttr = (SignatureAttribute) getAttribute("Signature");
if (sigAttr != null) {
return getClassLoader().parseParameterizedType(sigAttr.getSignature()); // depends on control dependency: [if], data = [(sigAttr]
}
return getType();
} } |
public class class_name {
public static void initializeClass(Class clazz) {
try {
Class.forName(clazz.getName(), true, Thread.currentThread().getContextClassLoader());
}
catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static void initializeClass(Class clazz) {
try {
Class.forName(clazz.getName(), true, Thread.currentThread().getContextClassLoader());
}
catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
Set<Dependency<?>> getInternalDependencies() {
ImmutableSet.Builder<InjectionPoint> builder = ImmutableSet.builder();
if (factory.constructorInjector == null) {
builder.add(constructorInjectionPoint);
// If the below throws, it's OK -- we just ignore those dependencies, because no one
// could have used them anyway.
try {
builder.addAll(
InjectionPoint.forInstanceMethodsAndFields(
constructorInjectionPoint.getDeclaringType()));
} catch (ConfigurationException ignored) {
}
} else {
builder.add(getConstructor()).addAll(getInjectableMembers());
}
return Dependency.forInjectionPoints(builder.build());
} } | public class class_name {
Set<Dependency<?>> getInternalDependencies() {
ImmutableSet.Builder<InjectionPoint> builder = ImmutableSet.builder();
if (factory.constructorInjector == null) {
builder.add(constructorInjectionPoint); // depends on control dependency: [if], data = [none]
// If the below throws, it's OK -- we just ignore those dependencies, because no one
// could have used them anyway.
try {
builder.addAll(
InjectionPoint.forInstanceMethodsAndFields(
constructorInjectionPoint.getDeclaringType())); // depends on control dependency: [try], data = [none]
} catch (ConfigurationException ignored) {
} // depends on control dependency: [catch], data = [none]
} else {
builder.add(getConstructor()).addAll(getInjectableMembers()); // depends on control dependency: [if], data = [none]
}
return Dependency.forInjectionPoints(builder.build());
} } |
public class class_name {
public static ContentSpec transform(final ContentSpecWrapper spec, final DataProviderFactory providerFactory,
final boolean includeChecksum) {
// local variables that are used to map transformed content
Map<Integer, Node> nodes = new HashMap<Integer, Node>();
Map<String, SpecTopic> topicTargets = new HashMap<String, SpecTopic>();
List<CSNodeWrapper> relationshipFromNodes = new ArrayList<CSNodeWrapper>();
List<Process> processes = new ArrayList<Process>();
// Start the transformation
final ContentSpec contentSpec = new ContentSpec();
contentSpec.setId(spec.getId());
transformGlobalOptions(spec, contentSpec);
// Add all the levels/topics
boolean localeFound = false;
if (spec.getChildren() != null) {
final List<CSNodeWrapper> childNodes = spec.getChildren().getItems();
final HashMap<CSNodeWrapper, Node> levelNodes = new HashMap<CSNodeWrapper, Node>();
for (final CSNodeWrapper childNode : childNodes) {
if (childNode.getNodeType() == CommonConstants.CS_NODE_TOPIC) {
final SpecTopic topic = transformSpecTopic(childNode, nodes, topicTargets, relationshipFromNodes);
levelNodes.put(childNode, topic);
} else if (childNode.getNodeType() == CommonConstants.CS_NODE_COMMENT) {
final Comment comment = transformComment(childNode);
levelNodes.put(childNode, comment);
} else if (childNode.getNodeType() == CommonConstants.CS_NODE_COMMON_CONTENT) {
final CommonContent commonContent = transformCommonContent(childNode);
levelNodes.put(childNode, commonContent);
} else if (childNode.getNodeType() == CommonConstants.CS_NODE_META_DATA || childNode.getNodeType() == CommonConstants
.CS_NODE_META_DATA_TOPIC) {
if (!IGNORE_META_DATA.contains(childNode.getTitle().toLowerCase())) {
final KeyValueNode<?> metaDataNode = transformMetaData(childNode, nodes, topicTargets, relationshipFromNodes);
levelNodes.put(childNode, metaDataNode);
}
if (CommonConstants.CS_LOCALE_TITLE.equalsIgnoreCase(childNode.getTitle())) {
localeFound = true;
}
} else {
final Level level = transformLevel(childNode, nodes, topicTargets, relationshipFromNodes, processes);
levelNodes.put(childNode, level);
}
}
// Sort the level nodes so that they are in the right order based on next/prev values.
final LinkedHashMap<CSNodeWrapper, Node> sortedMap = CSNodeSorter.sortMap(levelNodes);
// Add the child nodes to the content spec now that they are in the right order.
boolean addToBaseLevel = false;
final Iterator<Map.Entry<CSNodeWrapper, Node>> iter = sortedMap.entrySet().iterator();
while (iter.hasNext()) {
final Map.Entry<CSNodeWrapper, Node> entry = iter.next();
// If a level or spec topic is found then start adding to the base level instead of the content spec
if ((entry.getValue() instanceof Level || entry.getValue() instanceof SpecTopic) && !addToBaseLevel) {
addToBaseLevel = true;
// Add the locale if it wasn't specified
if (!localeFound) {
contentSpec.setLocale(spec.getLocale() == null ? null : spec.getLocale().getValue());
}
// Add a space between the base metadata and optional metadata
contentSpec.appendChild(new TextNode("\n"));
}
// Add the node to the right component.
if (addToBaseLevel) {
contentSpec.getBaseLevel().appendChild(entry.getValue());
// Add a new line to separate chapters/parts
if (isNodeASeparatorLevel(entry.getValue()) && iter.hasNext()) {
contentSpec.getBaseLevel().appendChild(new TextNode("\n"));
}
} else {
contentSpec.appendChild(entry.getValue());
}
}
}
// Apply the relationships to the nodes
applyRelationships(contentSpec, nodes, topicTargets, relationshipFromNodes, processes, providerFactory);
// Set the line numbers
setLineNumbers(contentSpec, includeChecksum ? 2 : 1);
return contentSpec;
} } | public class class_name {
public static ContentSpec transform(final ContentSpecWrapper spec, final DataProviderFactory providerFactory,
final boolean includeChecksum) {
// local variables that are used to map transformed content
Map<Integer, Node> nodes = new HashMap<Integer, Node>();
Map<String, SpecTopic> topicTargets = new HashMap<String, SpecTopic>();
List<CSNodeWrapper> relationshipFromNodes = new ArrayList<CSNodeWrapper>();
List<Process> processes = new ArrayList<Process>();
// Start the transformation
final ContentSpec contentSpec = new ContentSpec();
contentSpec.setId(spec.getId());
transformGlobalOptions(spec, contentSpec);
// Add all the levels/topics
boolean localeFound = false;
if (spec.getChildren() != null) {
final List<CSNodeWrapper> childNodes = spec.getChildren().getItems();
final HashMap<CSNodeWrapper, Node> levelNodes = new HashMap<CSNodeWrapper, Node>();
for (final CSNodeWrapper childNode : childNodes) {
if (childNode.getNodeType() == CommonConstants.CS_NODE_TOPIC) {
final SpecTopic topic = transformSpecTopic(childNode, nodes, topicTargets, relationshipFromNodes);
levelNodes.put(childNode, topic); // depends on control dependency: [if], data = [none]
} else if (childNode.getNodeType() == CommonConstants.CS_NODE_COMMENT) {
final Comment comment = transformComment(childNode);
levelNodes.put(childNode, comment); // depends on control dependency: [if], data = [none]
} else if (childNode.getNodeType() == CommonConstants.CS_NODE_COMMON_CONTENT) {
final CommonContent commonContent = transformCommonContent(childNode);
levelNodes.put(childNode, commonContent); // depends on control dependency: [if], data = [none]
} else if (childNode.getNodeType() == CommonConstants.CS_NODE_META_DATA || childNode.getNodeType() == CommonConstants
.CS_NODE_META_DATA_TOPIC) {
if (!IGNORE_META_DATA.contains(childNode.getTitle().toLowerCase())) {
final KeyValueNode<?> metaDataNode = transformMetaData(childNode, nodes, topicTargets, relationshipFromNodes);
levelNodes.put(childNode, metaDataNode); // depends on control dependency: [if], data = [none]
}
if (CommonConstants.CS_LOCALE_TITLE.equalsIgnoreCase(childNode.getTitle())) {
localeFound = true; // depends on control dependency: [if], data = [none]
}
} else {
final Level level = transformLevel(childNode, nodes, topicTargets, relationshipFromNodes, processes);
levelNodes.put(childNode, level); // depends on control dependency: [if], data = [none]
}
}
// Sort the level nodes so that they are in the right order based on next/prev values.
final LinkedHashMap<CSNodeWrapper, Node> sortedMap = CSNodeSorter.sortMap(levelNodes);
// Add the child nodes to the content spec now that they are in the right order.
boolean addToBaseLevel = false;
final Iterator<Map.Entry<CSNodeWrapper, Node>> iter = sortedMap.entrySet().iterator();
while (iter.hasNext()) {
final Map.Entry<CSNodeWrapper, Node> entry = iter.next();
// If a level or spec topic is found then start adding to the base level instead of the content spec
if ((entry.getValue() instanceof Level || entry.getValue() instanceof SpecTopic) && !addToBaseLevel) {
addToBaseLevel = true; // depends on control dependency: [if], data = [none]
// Add the locale if it wasn't specified
if (!localeFound) {
contentSpec.setLocale(spec.getLocale() == null ? null : spec.getLocale().getValue()); // depends on control dependency: [if], data = [none]
}
// Add a space between the base metadata and optional metadata
contentSpec.appendChild(new TextNode("\n")); // depends on control dependency: [if], data = [none]
}
// Add the node to the right component.
if (addToBaseLevel) {
contentSpec.getBaseLevel().appendChild(entry.getValue()); // depends on control dependency: [if], data = [none]
// Add a new line to separate chapters/parts
if (isNodeASeparatorLevel(entry.getValue()) && iter.hasNext()) {
contentSpec.getBaseLevel().appendChild(new TextNode("\n")); // depends on control dependency: [if], data = [none]
}
} else {
contentSpec.appendChild(entry.getValue()); // depends on control dependency: [if], data = [none]
}
}
}
// Apply the relationships to the nodes
applyRelationships(contentSpec, nodes, topicTargets, relationshipFromNodes, processes, providerFactory);
// Set the line numbers
setLineNumbers(contentSpec, includeChecksum ? 2 : 1);
return contentSpec;
} } |
public class class_name {
public static void randomize(
MutableDoubleTuple t, double min, double max, Random random)
{
double delta = max - min;
for (int i=0; i<t.getSize(); i++)
{
t.set(i, min + random.nextDouble() * delta);
}
} } | public class class_name {
public static void randomize(
MutableDoubleTuple t, double min, double max, Random random)
{
double delta = max - min;
for (int i=0; i<t.getSize(); i++)
{
t.set(i, min + random.nextDouble() * delta);
// depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
private Map<UUID, FieldType> populateCustomFieldMap()
{
byte[] data = m_taskProps.getByteArray(Props.CUSTOM_FIELDS);
int length = MPPUtility.getInt(data, 0);
int index = length + 36;
// 4 byte record count
int recordCount = MPPUtility.getInt(data, index);
index += 4;
// 8 bytes per record
index += (8 * recordCount);
Map<UUID, FieldType> map = new HashMap<UUID, FieldType>();
while (index < data.length)
{
int blockLength = MPPUtility.getInt(data, index);
if (blockLength <= 0 || index + blockLength > data.length)
{
break;
}
int fieldID = MPPUtility.getInt(data, index + 4);
FieldType field = FieldTypeHelper.getInstance(fieldID);
UUID guid = MPPUtility.getGUID(data, index + 160);
map.put(guid, field);
index += blockLength;
}
return map;
} } | public class class_name {
private Map<UUID, FieldType> populateCustomFieldMap()
{
byte[] data = m_taskProps.getByteArray(Props.CUSTOM_FIELDS);
int length = MPPUtility.getInt(data, 0);
int index = length + 36;
// 4 byte record count
int recordCount = MPPUtility.getInt(data, index);
index += 4;
// 8 bytes per record
index += (8 * recordCount);
Map<UUID, FieldType> map = new HashMap<UUID, FieldType>();
while (index < data.length)
{
int blockLength = MPPUtility.getInt(data, index);
if (blockLength <= 0 || index + blockLength > data.length)
{
break;
}
int fieldID = MPPUtility.getInt(data, index + 4);
FieldType field = FieldTypeHelper.getInstance(fieldID);
UUID guid = MPPUtility.getGUID(data, index + 160);
map.put(guid, field); // depends on control dependency: [while], data = [none]
index += blockLength; // depends on control dependency: [while], data = [none]
}
return map;
} } |
public class class_name {
public void marshall(DataTransfer dataTransfer, ProtocolMarshaller protocolMarshaller) {
if (dataTransfer == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(dataTransfer.getBytesTransferred(), BYTESTRANSFERRED_BINDING);
protocolMarshaller.marshall(dataTransfer.getObjectsTransferred(), OBJECTSTRANSFERRED_BINDING);
protocolMarshaller.marshall(dataTransfer.getTotalBytes(), TOTALBYTES_BINDING);
protocolMarshaller.marshall(dataTransfer.getTotalObjects(), TOTALOBJECTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DataTransfer dataTransfer, ProtocolMarshaller protocolMarshaller) {
if (dataTransfer == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(dataTransfer.getBytesTransferred(), BYTESTRANSFERRED_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(dataTransfer.getObjectsTransferred(), OBJECTSTRANSFERRED_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(dataTransfer.getTotalBytes(), TOTALBYTES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(dataTransfer.getTotalObjects(), TOTALOBJECTS_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 String getString(char c, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(c);
}
return sb.toString();
} } | public class class_name {
static String getString(char c, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(c); // depends on control dependency: [for], data = [none]
}
return sb.toString();
} } |
public class class_name {
public void mergeSubTransaction(SpiderTransaction subTran) {
// Column adds
for (String storeName : subTran.m_columnAdds.keySet()) {
Map<String, Map<String, byte[]>> rowMap = subTran.m_columnAdds.get(storeName);
for (String rowKey : rowMap.keySet()) {
Map<String, byte[]> colMap = rowMap.get(rowKey);
for (String colName : colMap.keySet()) {
this.addColumn(storeName, rowKey, colName, colMap.get(colName));
}
}
}
// Column deletes
for (String storeName : subTran.m_columnDeletes.keySet()) {
Map<String, List<String>> rowMap = subTran.m_columnDeletes.get(storeName);
for (String rowKey : rowMap.keySet()) {
this.deleteColumns(storeName, rowKey, rowMap.get(rowKey));
}
}
// Row deletes
for (String storeName : subTran.m_rowDeletes.keySet()) {
for (String rowKey : subTran.m_rowDeletes.get(storeName)) {
this.deleteRow(storeName, rowKey);
}
}
} } | public class class_name {
public void mergeSubTransaction(SpiderTransaction subTran) {
// Column adds
for (String storeName : subTran.m_columnAdds.keySet()) {
Map<String, Map<String, byte[]>> rowMap = subTran.m_columnAdds.get(storeName);
for (String rowKey : rowMap.keySet()) {
Map<String, byte[]> colMap = rowMap.get(rowKey);
for (String colName : colMap.keySet()) {
this.addColumn(storeName, rowKey, colName, colMap.get(colName));
// depends on control dependency: [for], data = [colName]
}
}
}
// Column deletes
for (String storeName : subTran.m_columnDeletes.keySet()) {
Map<String, List<String>> rowMap = subTran.m_columnDeletes.get(storeName);
for (String rowKey : rowMap.keySet()) {
this.deleteColumns(storeName, rowKey, rowMap.get(rowKey));
// depends on control dependency: [for], data = [rowKey]
}
}
// Row deletes
for (String storeName : subTran.m_rowDeletes.keySet()) {
for (String rowKey : subTran.m_rowDeletes.get(storeName)) {
this.deleteRow(storeName, rowKey);
// depends on control dependency: [for], data = [rowKey]
}
}
} } |
public class class_name {
static void extractPorts(final Map<String, Integer> input, final Map<ServiceType, Integer> ports,
final Map<ServiceType, Integer> sslPorts) {
for (Map.Entry<String, Integer> entry : input.entrySet()) {
String service = entry.getKey();
int port = entry.getValue();
if (service.equals("mgmt")) {
ports.put(ServiceType.CONFIG, port);
} else if (service.equals("capi")) {
ports.put(ServiceType.VIEW, port);
} else if (service.equals("kv")) {
ports.put(ServiceType.BINARY, port);
} else if (service.equals("kvSSL")) {
sslPorts.put(ServiceType.BINARY, port);
} else if (service.equals("capiSSL")) {
sslPorts.put(ServiceType.VIEW, port);
} else if (service.equals("mgmtSSL")) {
sslPorts.put(ServiceType.CONFIG, port);
} else if (service.equals("n1ql")) {
ports.put(ServiceType.QUERY, port);
} else if (service.equals("n1qlSSL")) {
sslPorts.put(ServiceType.QUERY, port);
} else if (service.equals("fts")) {
ports.put(ServiceType.SEARCH, port);
} else if (service.equals("ftsSSL")) {
sslPorts.put(ServiceType.SEARCH, port);
} else if (service.equals("cbas")) {
ports.put(ServiceType.ANALYTICS, port);
} else if (service.equals("cbasSSL")) {
sslPorts.put(ServiceType.ANALYTICS, port);
}
}
} } | public class class_name {
static void extractPorts(final Map<String, Integer> input, final Map<ServiceType, Integer> ports,
final Map<ServiceType, Integer> sslPorts) {
for (Map.Entry<String, Integer> entry : input.entrySet()) {
String service = entry.getKey();
int port = entry.getValue();
if (service.equals("mgmt")) {
ports.put(ServiceType.CONFIG, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("capi")) {
ports.put(ServiceType.VIEW, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("kv")) {
ports.put(ServiceType.BINARY, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("kvSSL")) {
sslPorts.put(ServiceType.BINARY, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("capiSSL")) {
sslPorts.put(ServiceType.VIEW, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("mgmtSSL")) {
sslPorts.put(ServiceType.CONFIG, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("n1ql")) {
ports.put(ServiceType.QUERY, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("n1qlSSL")) {
sslPorts.put(ServiceType.QUERY, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("fts")) {
ports.put(ServiceType.SEARCH, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("ftsSSL")) {
sslPorts.put(ServiceType.SEARCH, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("cbas")) {
ports.put(ServiceType.ANALYTICS, port); // depends on control dependency: [if], data = [none]
} else if (service.equals("cbasSSL")) {
sslPorts.put(ServiceType.ANALYTICS, port); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static AccessibilityNodeInfoCompat focusSearch(
AccessibilityNodeInfoCompat node, int direction) {
final AccessibilityNodeInfoRef ref = AccessibilityNodeInfoRef.unOwned(node);
switch (direction) {
case SEARCH_FORWARD: {
if (!ref.nextInOrder()) {
return null;
}
return ref.release();
}
case SEARCH_BACKWARD: {
if (!ref.previousInOrder()) {
return null;
}
return ref.release();
}
}
return null;
} } | public class class_name {
public static AccessibilityNodeInfoCompat focusSearch(
AccessibilityNodeInfoCompat node, int direction) {
final AccessibilityNodeInfoRef ref = AccessibilityNodeInfoRef.unOwned(node);
switch (direction) {
case SEARCH_FORWARD: {
if (!ref.nextInOrder()) {
return null; // depends on control dependency: [if], data = [none]
}
return ref.release();
}
case SEARCH_BACKWARD: {
if (!ref.previousInOrder()) {
return null; // depends on control dependency: [if], data = [none]
}
return ref.release();
}
}
return null;
} } |
public class class_name {
@Pure
public static Point3f computeLineLineIntersection(
double x1, double y1, double z1, double x2, double y2, double z2,
double x3, double y3, double z3, double x4, double y4, double z4) {
double s = computeLineLineIntersectionFactor(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
if (Double.isNaN(s)) {
return null;
}
return new Point3f(
x1 + s * (x2 - x1),
y1 + s * (y2 - y1),
z1 + s * (z2 - z1));
} } | public class class_name {
@Pure
public static Point3f computeLineLineIntersection(
double x1, double y1, double z1, double x2, double y2, double z2,
double x3, double y3, double z3, double x4, double y4, double z4) {
double s = computeLineLineIntersectionFactor(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
if (Double.isNaN(s)) {
return null; // depends on control dependency: [if], data = [none]
}
return new Point3f(
x1 + s * (x2 - x1),
y1 + s * (y2 - y1),
z1 + s * (z2 - z1));
} } |
public class class_name {
public void setStart(DateType start) {
this.start = start;
useStart = true;
if (useEnd) {
this.isMoving = this.start.isPresent() || this.end.isPresent();
useDuration = false;
recalcDuration();
} else {
this.isMoving = this.start.isPresent();
this.end = this.start.add(duration);
}
checkIfEmpty();
} } | public class class_name {
public void setStart(DateType start) {
this.start = start;
useStart = true;
if (useEnd) {
this.isMoving = this.start.isPresent() || this.end.isPresent(); // depends on control dependency: [if], data = [none]
useDuration = false; // depends on control dependency: [if], data = [none]
recalcDuration(); // depends on control dependency: [if], data = [none]
} else {
this.isMoving = this.start.isPresent(); // depends on control dependency: [if], data = [none]
this.end = this.start.add(duration); // depends on control dependency: [if], data = [none]
}
checkIfEmpty();
} } |
public class class_name {
public <T> boolean containsNodeNames(Class<T> T, String... nodeNames) {
for(NodeModel node : nodes) {
if(!T.isInstance(node)) {
continue;
}
for(String nodeName : nodeNames) {
if(node.getName().equals(nodeName)) {
return true;
}
}
}
return false;
} } | public class class_name {
public <T> boolean containsNodeNames(Class<T> T, String... nodeNames) {
for(NodeModel node : nodes) {
if(!T.isInstance(node)) {
continue;
}
for(String nodeName : nodeNames) {
if(node.getName().equals(nodeName)) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} } |
public class class_name {
@Override
protected final List<SuperColumn> loadSuperColumns(String keyspace, String columnFamily, String rowId,
String... superColumnNames)
{
// TODO::: super column abstract entity and discriminator column
if (!isOpen())
throw new PersistenceException("ThriftClient is closed.");
byte[] rowKey = rowId.getBytes();
SlicePredicate predicate = new SlicePredicate();
List<ByteBuffer> columnNames = new ArrayList<ByteBuffer>();
for (String superColumnName : superColumnNames)
{
KunderaCoreUtils.printQuery("Fetch superColumn:" + superColumnName, showQuery);
columnNames.add(ByteBuffer.wrap(superColumnName.getBytes()));
}
predicate.setColumn_names(columnNames);
ColumnParent parent = new ColumnParent(columnFamily);
List<ColumnOrSuperColumn> coscList;
Connection conn = null;
try
{
conn = getConnection();
coscList = conn.getClient().get_slice(ByteBuffer.wrap(rowKey), parent, predicate, getConsistencyLevel());
}
catch (InvalidRequestException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
catch (UnavailableException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
catch (TimedOutException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
catch (TException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
finally
{
releaseConnection(conn);
}
List<SuperColumn> superColumns = ThriftDataResultHelper.transformThriftResult(coscList,
ColumnFamilyType.SUPER_COLUMN, null);
return superColumns;
} } | public class class_name {
@Override
protected final List<SuperColumn> loadSuperColumns(String keyspace, String columnFamily, String rowId,
String... superColumnNames)
{
// TODO::: super column abstract entity and discriminator column
if (!isOpen())
throw new PersistenceException("ThriftClient is closed.");
byte[] rowKey = rowId.getBytes();
SlicePredicate predicate = new SlicePredicate();
List<ByteBuffer> columnNames = new ArrayList<ByteBuffer>();
for (String superColumnName : superColumnNames)
{
KunderaCoreUtils.printQuery("Fetch superColumn:" + superColumnName, showQuery); // depends on control dependency: [for], data = [superColumnName]
columnNames.add(ByteBuffer.wrap(superColumnName.getBytes())); // depends on control dependency: [for], data = [superColumnName]
}
predicate.setColumn_names(columnNames);
ColumnParent parent = new ColumnParent(columnFamily);
List<ColumnOrSuperColumn> coscList;
Connection conn = null;
try
{
conn = getConnection();
coscList = conn.getClient().get_slice(ByteBuffer.wrap(rowKey), parent, predicate, getConsistencyLevel());
}
catch (InvalidRequestException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
catch (UnavailableException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
catch (TimedOutException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
catch (TException e)
{
log.error("Error while getting super columns for row Key {} , Caused by: .", rowId, e);
throw new EntityReaderException(e);
}
finally
{
releaseConnection(conn);
}
List<SuperColumn> superColumns = ThriftDataResultHelper.transformThriftResult(coscList,
ColumnFamilyType.SUPER_COLUMN, null);
return superColumns;
} } |
public class class_name {
@SuppressWarnings("unchecked")
private InvalidSessionStrategy getInvalidSessionStrategy(H http) {
SessionManagementConfigurer<H> sessionManagement = http
.getConfigurer(SessionManagementConfigurer.class);
if (sessionManagement == null) {
return null;
}
return sessionManagement.getInvalidSessionStrategy();
} } | public class class_name {
@SuppressWarnings("unchecked")
private InvalidSessionStrategy getInvalidSessionStrategy(H http) {
SessionManagementConfigurer<H> sessionManagement = http
.getConfigurer(SessionManagementConfigurer.class);
if (sessionManagement == null) {
return null; // depends on control dependency: [if], data = [none]
}
return sessionManagement.getInvalidSessionStrategy();
} } |
public class class_name {
public void messageReceived(Object message) {
if (message instanceof Packet) {
try {
messageReceived(conn, (Packet) message);
} catch (Exception e) {
log.warn("Exception on packet receive", e);
}
} else {
// raw buffer handling
IoBuffer in = (IoBuffer) message;
// filter based on current connection state
RTMP rtmp = conn.getState();
final byte connectionState = conn.getStateCode();
log.trace("connectionState: {}", RTMP.states[connectionState]);
// get the handshake
OutboundHandshake handshake = (OutboundHandshake) conn.getAttribute(RTMPConnection.RTMP_HANDSHAKE);
switch (connectionState) {
case RTMP.STATE_CONNECT:
log.debug("Handshake - client phase 1 - size: {}", in.remaining());
in.get(); // 0x01
byte handshakeType = in.get(); // usually 0x03 (rtmp)
log.debug("Handshake - byte type: {}", handshakeType);
// copy out 1536 bytes
byte[] s1 = new byte[Constants.HANDSHAKE_SIZE];
in.get(s1);
// decode s1
IoBuffer out = handshake.decodeServerResponse1(IoBuffer.wrap(s1));
if (out != null) {
// set state to indicate we're waiting for S2
rtmp.setState(RTMP.STATE_HANDSHAKE);
conn.writeRaw(out);
// if we got S0S1+S2 continue processing
if (in.remaining() >= Constants.HANDSHAKE_SIZE) {
log.debug("Handshake - client phase 2 - size: {}", in.remaining());
if (handshake.decodeServerResponse2(in)) {
// conn.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
// conn.setStateCode(RTMP.STATE_CONNECTED);
// connectionOpened(conn);
} else {
log.warn("Handshake failed on S2 processing");
//conn.close();
}
// open regardless of server type
conn.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
conn.setStateCode(RTMP.STATE_CONNECTED);
connectionOpened(conn);
}
} else {
log.warn("Handshake failed on S0S1 processing");
conn.close();
}
break;
case RTMP.STATE_HANDSHAKE:
log.debug("Handshake - client phase 2 - size: {}", in.remaining());
if (handshake.decodeServerResponse2(in)) {
// conn.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
// conn.setStateCode(RTMP.STATE_CONNECTED);
// connectionOpened(conn);
} else {
log.warn("Handshake failed on S2 processing");
//conn.close();
}
// open regardless of server type
conn.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
conn.setStateCode(RTMP.STATE_CONNECTED);
connectionOpened(conn);
break;
default:
throw new IllegalStateException("Invalid RTMP state: " + connectionState);
}
}
} } | public class class_name {
public void messageReceived(Object message) {
if (message instanceof Packet) {
try {
messageReceived(conn, (Packet) message);
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
log.warn("Exception on packet receive", e);
}
// depends on control dependency: [catch], data = [none]
} else {
// raw buffer handling
IoBuffer in = (IoBuffer) message;
// filter based on current connection state
RTMP rtmp = conn.getState();
final byte connectionState = conn.getStateCode();
log.trace("connectionState: {}", RTMP.states[connectionState]);
// depends on control dependency: [if], data = [none]
// get the handshake
OutboundHandshake handshake = (OutboundHandshake) conn.getAttribute(RTMPConnection.RTMP_HANDSHAKE);
switch (connectionState) {
case RTMP.STATE_CONNECT:
log.debug("Handshake - client phase 1 - size: {}", in.remaining());
in.get(); // 0x01
byte handshakeType = in.get(); // usually 0x03 (rtmp)
log.debug("Handshake - byte type: {}", handshakeType);
// copy out 1536 bytes
byte[] s1 = new byte[Constants.HANDSHAKE_SIZE];
in.get(s1);
// decode s1
IoBuffer out = handshake.decodeServerResponse1(IoBuffer.wrap(s1));
if (out != null) {
// set state to indicate we're waiting for S2
rtmp.setState(RTMP.STATE_HANDSHAKE);
// depends on control dependency: [if], data = [none]
conn.writeRaw(out);
// depends on control dependency: [if], data = [(out]
// if we got S0S1+S2 continue processing
if (in.remaining() >= Constants.HANDSHAKE_SIZE) {
log.debug("Handshake - client phase 2 - size: {}", in.remaining());
// depends on control dependency: [if], data = [none]
if (handshake.decodeServerResponse2(in)) {
// conn.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
// conn.setStateCode(RTMP.STATE_CONNECTED);
// connectionOpened(conn);
} else {
log.warn("Handshake failed on S2 processing");
// depends on control dependency: [if], data = [none]
//conn.close();
}
// open regardless of server type
conn.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
// depends on control dependency: [if], data = [none]
conn.setStateCode(RTMP.STATE_CONNECTED);
// depends on control dependency: [if], data = [none]
connectionOpened(conn);
// depends on control dependency: [if], data = [none]
}
} else {
log.warn("Handshake failed on S0S1 processing");
// depends on control dependency: [if], data = [none]
conn.close();
// depends on control dependency: [if], data = [none]
}
break;
case RTMP.STATE_HANDSHAKE:
log.debug("Handshake - client phase 2 - size: {}", in.remaining());
if (handshake.decodeServerResponse2(in)) {
// conn.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
// conn.setStateCode(RTMP.STATE_CONNECTED);
// connectionOpened(conn);
} else {
log.warn("Handshake failed on S2 processing");
// depends on control dependency: [if], data = [none]
//conn.close();
}
// open regardless of server type
conn.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
conn.setStateCode(RTMP.STATE_CONNECTED);
connectionOpened(conn);
break;
default:
throw new IllegalStateException("Invalid RTMP state: " + connectionState);
}
}
} } |
public class class_name {
private static BigDecimal divide(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) {
int mcp = mc.precision;
if(xscale <= yscale && yscale < 18 && mcp<18) {
return divideSmallFastPath(xs, xscale, ys, yscale, preferredScale, mc);
}
if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
yscale -= 1; // [that is, divisor *= 10]
}
int roundingMode = mc.roundingMode.oldMode;
// In order to find out whether the divide generates the exact result,
// we avoid calling the above divide method. 'quotient' holds the
// return BigDecimal object whose scale will be set to 'scl'.
int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
BigDecimal quotient;
if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
int raise = checkScaleNonZero((long) mcp + yscale - xscale);
long scaledXs;
if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {
BigInteger rb = bigMultiplyPowerTen(xs,raise);
quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
} else {
quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
}
} else {
int newScale = checkScaleNonZero((long) xscale - mcp);
// assert newScale >= yscale
if (newScale == yscale) { // easy case
quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
} else {
int raise = checkScaleNonZero((long) newScale - yscale);
long scaledYs;
if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
BigInteger rb = bigMultiplyPowerTen(ys,raise);
quotient = divideAndRound(BigInteger.valueOf(xs),
rb, scl, roundingMode,checkScaleNonZero(preferredScale));
} else {
quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
}
}
}
// doRound, here, only affects 1000000000 case.
return doRound(quotient,mc);
} } | public class class_name {
private static BigDecimal divide(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) {
int mcp = mc.precision;
if(xscale <= yscale && yscale < 18 && mcp<18) {
return divideSmallFastPath(xs, xscale, ys, yscale, preferredScale, mc); // depends on control dependency: [if], data = [none]
}
if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
yscale -= 1; // [that is, divisor *= 10] // depends on control dependency: [if], data = [none]
}
int roundingMode = mc.roundingMode.oldMode;
// In order to find out whether the divide generates the exact result,
// we avoid calling the above divide method. 'quotient' holds the
// return BigDecimal object whose scale will be set to 'scl'.
int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
BigDecimal quotient;
if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {
int raise = checkScaleNonZero((long) mcp + yscale - xscale);
long scaledXs;
if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {
BigInteger rb = bigMultiplyPowerTen(xs,raise);
quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); // depends on control dependency: [if], data = [none]
} else {
quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); // depends on control dependency: [if], data = [none]
}
} else {
int newScale = checkScaleNonZero((long) xscale - mcp);
// assert newScale >= yscale
if (newScale == yscale) { // easy case
quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale)); // depends on control dependency: [if], data = [none]
} else {
int raise = checkScaleNonZero((long) newScale - yscale);
long scaledYs;
if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
BigInteger rb = bigMultiplyPowerTen(ys,raise);
quotient = divideAndRound(BigInteger.valueOf(xs),
rb, scl, roundingMode,checkScaleNonZero(preferredScale)); // depends on control dependency: [if], data = [none]
} else {
quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale)); // depends on control dependency: [if], data = [none]
}
}
}
// doRound, here, only affects 1000000000 case.
return doRound(quotient,mc);
} } |
public class class_name {
public static void setText(Activity context, int field, String text) {
View view = context.findViewById(field);
if (view instanceof TextView) {
((TextView) view).setText(text);
} else {
Log.e("Caffeine", "ViewUtils.setText() given a field that is not a TextView");
}
} } | public class class_name {
public static void setText(Activity context, int field, String text) {
View view = context.findViewById(field);
if (view instanceof TextView) {
((TextView) view).setText(text); // depends on control dependency: [if], data = [none]
} else {
Log.e("Caffeine", "ViewUtils.setText() given a field that is not a TextView"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private String transform(String expression) {
char[] arr = expression.toCharArray();
for (int i = 0; i < arr.length; i++) {
char cc=arr[i];
if (cc == '-') {
if (i == 0) {
arr[i] = '~';
} else {
char c = arr[i - 1];
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == 'E' || c == 'e') {
arr[i] = '~';
}
}
}
}
if(arr[0]=='~'||arr[1]=='('){
arr[0]='-';
return "0"+new String(arr);
}else{
return new String(arr);
}
} } | public class class_name {
private String transform(String expression) {
char[] arr = expression.toCharArray();
for (int i = 0; i < arr.length; i++) {
char cc=arr[i];
if (cc == '-') {
if (i == 0) {
arr[i] = '~'; // depends on control dependency: [if], data = [none]
} else {
char c = arr[i - 1];
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == 'E' || c == 'e') {
arr[i] = '~'; // depends on control dependency: [if], data = [none]
}
}
}
}
if(arr[0]=='~'||arr[1]=='('){
arr[0]='-'; // depends on control dependency: [if], data = [none]
return "0"+new String(arr); // depends on control dependency: [if], data = [none]
}else{
return new String(arr); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static FormatBundle<DatasetKeyInputFormat> inputBundle(Configuration conf) {
FormatBundle<DatasetKeyInputFormat> bundle = FormatBundle
.forInput(DatasetKeyInputFormat.class);
for (Map.Entry<String, String> entry : conf) {
bundle.set(entry.getKey(), entry.getValue());
}
return bundle;
} } | public class class_name {
private static FormatBundle<DatasetKeyInputFormat> inputBundle(Configuration conf) {
FormatBundle<DatasetKeyInputFormat> bundle = FormatBundle
.forInput(DatasetKeyInputFormat.class);
for (Map.Entry<String, String> entry : conf) {
bundle.set(entry.getKey(), entry.getValue()); // depends on control dependency: [for], data = [entry]
}
return bundle;
} } |
public class class_name {
public void marshall(APNSVoipChannelRequest aPNSVoipChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (aPNSVoipChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(aPNSVoipChannelRequest.getBundleId(), BUNDLEID_BINDING);
protocolMarshaller.marshall(aPNSVoipChannelRequest.getCertificate(), CERTIFICATE_BINDING);
protocolMarshaller.marshall(aPNSVoipChannelRequest.getDefaultAuthenticationMethod(), DEFAULTAUTHENTICATIONMETHOD_BINDING);
protocolMarshaller.marshall(aPNSVoipChannelRequest.getEnabled(), ENABLED_BINDING);
protocolMarshaller.marshall(aPNSVoipChannelRequest.getPrivateKey(), PRIVATEKEY_BINDING);
protocolMarshaller.marshall(aPNSVoipChannelRequest.getTeamId(), TEAMID_BINDING);
protocolMarshaller.marshall(aPNSVoipChannelRequest.getTokenKey(), TOKENKEY_BINDING);
protocolMarshaller.marshall(aPNSVoipChannelRequest.getTokenKeyId(), TOKENKEYID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(APNSVoipChannelRequest aPNSVoipChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (aPNSVoipChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(aPNSVoipChannelRequest.getBundleId(), BUNDLEID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(aPNSVoipChannelRequest.getCertificate(), CERTIFICATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(aPNSVoipChannelRequest.getDefaultAuthenticationMethod(), DEFAULTAUTHENTICATIONMETHOD_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(aPNSVoipChannelRequest.getEnabled(), ENABLED_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(aPNSVoipChannelRequest.getPrivateKey(), PRIVATEKEY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(aPNSVoipChannelRequest.getTeamId(), TEAMID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(aPNSVoipChannelRequest.getTokenKey(), TOKENKEY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(aPNSVoipChannelRequest.getTokenKeyId(), TOKENKEYID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static boolean isValidStartEndForLength(int start, int end, int length) {
if (start > length || end > length) {
return false;
}
return true;
} } | public class class_name {
private static boolean isValidStartEndForLength(int start, int end, int length) {
if (start > length || end > length) {
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public String[] listProviders() {
String[] providers = new String[container.size()];
int i = 0;
Iterator<String> ki = container.keySet().iterator();
while(ki.hasNext()) {
providers[i++] = (String) ki.next();
}
return providers;
} } | public class class_name {
public String[] listProviders() {
String[] providers = new String[container.size()];
int i = 0;
Iterator<String> ki = container.keySet().iterator();
while(ki.hasNext()) {
providers[i++] = (String) ki.next(); // depends on control dependency: [while], data = [none]
}
return providers;
} } |
public class class_name {
protected void configureWindowsLiveClient(final Collection<BaseClient> properties) {
val live = pac4jProperties.getWindowsLive();
if (StringUtils.isNotBlank(live.getId()) && StringUtils.isNotBlank(live.getSecret())) {
val client = new WindowsLiveClient(live.getId(), live.getSecret());
configureClient(client, live);
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
} } | public class class_name {
protected void configureWindowsLiveClient(final Collection<BaseClient> properties) {
val live = pac4jProperties.getWindowsLive();
if (StringUtils.isNotBlank(live.getId()) && StringUtils.isNotBlank(live.getSecret())) {
val client = new WindowsLiveClient(live.getId(), live.getSecret());
configureClient(client, live); // depends on control dependency: [if], data = [none]
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey()); // depends on control dependency: [if], data = [none]
properties.add(client); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected void addSocket(final S newSocket) {
if(isClosed()) throw new IllegalStateException("SocketContext is closed");
Future<?> future;
synchronized(sockets) {
Identifier id = newSocket.getId();
if(sockets.containsKey(id)) throw new IllegalStateException("Socket with the same ID has already been added");
sockets.put(id, newSocket);
future = listenerManager.enqueueEvent(
new ConcurrentListenerManager.Event<SocketContextListener>() {
@Override
public Runnable createCall(final SocketContextListener listener) {
return new Runnable() {
@Override
public void run() {
listener.onNewSocket(AbstractSocketContext.this, newSocket);
}
};
}
}
);
}
try {
future.get();
} catch(ExecutionException e) {
logger.log(Level.SEVERE, null, e);
} catch(InterruptedException e) {
logger.log(Level.SEVERE, null, e);
// Restore the interrupted status
Thread.currentThread().interrupt();
}
} } | public class class_name {
protected void addSocket(final S newSocket) {
if(isClosed()) throw new IllegalStateException("SocketContext is closed");
Future<?> future;
synchronized(sockets) {
Identifier id = newSocket.getId();
if(sockets.containsKey(id)) throw new IllegalStateException("Socket with the same ID has already been added");
sockets.put(id, newSocket);
future = listenerManager.enqueueEvent(
new ConcurrentListenerManager.Event<SocketContextListener>() {
@Override
public Runnable createCall(final SocketContextListener listener) {
return new Runnable() {
@Override
public void run() {
listener.onNewSocket(AbstractSocketContext.this, newSocket);
}
};
}
}
);
}
try {
future.get(); // depends on control dependency: [try], data = [none]
} catch(ExecutionException e) {
logger.log(Level.SEVERE, null, e);
} catch(InterruptedException e) { // depends on control dependency: [catch], data = [none]
logger.log(Level.SEVERE, null, e);
// Restore the interrupted status
Thread.currentThread().interrupt();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected String getTitle(boolean truncating) {
if (m_titleGenerator != null) {
return m_titleGenerator.getTitle(m_originalText);
}
if (truncating) {
return getText();
} else {
return super.getTitle();
}
} } | public class class_name {
protected String getTitle(boolean truncating) {
if (m_titleGenerator != null) {
return m_titleGenerator.getTitle(m_originalText); // depends on control dependency: [if], data = [none]
}
if (truncating) {
return getText(); // depends on control dependency: [if], data = [none]
} else {
return super.getTitle(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void readAssignments(Project plannerProject)
{
Allocations allocations = plannerProject.getAllocations();
List<Allocation> allocationList = allocations.getAllocation();
Set<Task> tasksWithAssignments = new HashSet<Task>();
for (Allocation allocation : allocationList)
{
Integer taskID = getInteger(allocation.getTaskId());
Integer resourceID = getInteger(allocation.getResourceId());
Integer units = getInteger(allocation.getUnits());
Task task = m_projectFile.getTaskByUniqueID(taskID);
Resource resource = m_projectFile.getResourceByUniqueID(resourceID);
if (task != null && resource != null)
{
Duration work = task.getWork();
int percentComplete = NumberHelper.getInt(task.getPercentageComplete());
ResourceAssignment assignment = task.addResourceAssignment(resource);
assignment.setUnits(units);
assignment.setWork(work);
if (percentComplete != 0)
{
Duration actualWork = Duration.getInstance((work.getDuration() * percentComplete) / 100, work.getUnits());
assignment.setActualWork(actualWork);
assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits()));
}
else
{
assignment.setRemainingWork(work);
}
assignment.setStart(task.getStart());
assignment.setFinish(task.getFinish());
tasksWithAssignments.add(task);
m_eventManager.fireAssignmentReadEvent(assignment);
}
}
//
// Adjust work per assignment for tasks with multiple assignments
//
for (Task task : tasksWithAssignments)
{
List<ResourceAssignment> assignments = task.getResourceAssignments();
if (assignments.size() > 1)
{
double maxUnits = 0;
for (ResourceAssignment assignment : assignments)
{
maxUnits += assignment.getUnits().doubleValue();
}
for (ResourceAssignment assignment : assignments)
{
Duration work = assignment.getWork();
double factor = assignment.getUnits().doubleValue() / maxUnits;
work = Duration.getInstance(work.getDuration() * factor, work.getUnits());
assignment.setWork(work);
Duration actualWork = assignment.getActualWork();
if (actualWork != null)
{
actualWork = Duration.getInstance(actualWork.getDuration() * factor, actualWork.getUnits());
assignment.setActualWork(actualWork);
}
Duration remainingWork = assignment.getRemainingWork();
if (remainingWork != null)
{
remainingWork = Duration.getInstance(remainingWork.getDuration() * factor, remainingWork.getUnits());
assignment.setRemainingWork(remainingWork);
}
}
}
}
} } | public class class_name {
private void readAssignments(Project plannerProject)
{
Allocations allocations = plannerProject.getAllocations();
List<Allocation> allocationList = allocations.getAllocation();
Set<Task> tasksWithAssignments = new HashSet<Task>();
for (Allocation allocation : allocationList)
{
Integer taskID = getInteger(allocation.getTaskId());
Integer resourceID = getInteger(allocation.getResourceId());
Integer units = getInteger(allocation.getUnits());
Task task = m_projectFile.getTaskByUniqueID(taskID);
Resource resource = m_projectFile.getResourceByUniqueID(resourceID);
if (task != null && resource != null)
{
Duration work = task.getWork();
int percentComplete = NumberHelper.getInt(task.getPercentageComplete());
ResourceAssignment assignment = task.addResourceAssignment(resource);
assignment.setUnits(units); // depends on control dependency: [if], data = [none]
assignment.setWork(work); // depends on control dependency: [if], data = [none]
if (percentComplete != 0)
{
Duration actualWork = Duration.getInstance((work.getDuration() * percentComplete) / 100, work.getUnits());
assignment.setActualWork(actualWork); // depends on control dependency: [if], data = [none]
assignment.setRemainingWork(Duration.getInstance(work.getDuration() - actualWork.getDuration(), work.getUnits())); // depends on control dependency: [if], data = [none]
}
else
{
assignment.setRemainingWork(work); // depends on control dependency: [if], data = [none]
}
assignment.setStart(task.getStart()); // depends on control dependency: [if], data = [(task]
assignment.setFinish(task.getFinish()); // depends on control dependency: [if], data = [(task]
tasksWithAssignments.add(task); // depends on control dependency: [if], data = [(task]
m_eventManager.fireAssignmentReadEvent(assignment); // depends on control dependency: [if], data = [none]
}
}
//
// Adjust work per assignment for tasks with multiple assignments
//
for (Task task : tasksWithAssignments)
{
List<ResourceAssignment> assignments = task.getResourceAssignments();
if (assignments.size() > 1)
{
double maxUnits = 0;
for (ResourceAssignment assignment : assignments)
{
maxUnits += assignment.getUnits().doubleValue(); // depends on control dependency: [for], data = [assignment]
}
for (ResourceAssignment assignment : assignments)
{
Duration work = assignment.getWork();
double factor = assignment.getUnits().doubleValue() / maxUnits;
work = Duration.getInstance(work.getDuration() * factor, work.getUnits()); // depends on control dependency: [for], data = [none]
assignment.setWork(work); // depends on control dependency: [for], data = [assignment]
Duration actualWork = assignment.getActualWork();
if (actualWork != null)
{
actualWork = Duration.getInstance(actualWork.getDuration() * factor, actualWork.getUnits()); // depends on control dependency: [if], data = [(actualWork]
assignment.setActualWork(actualWork); // depends on control dependency: [if], data = [(actualWork]
}
Duration remainingWork = assignment.getRemainingWork();
if (remainingWork != null)
{
remainingWork = Duration.getInstance(remainingWork.getDuration() * factor, remainingWork.getUnits()); // depends on control dependency: [if], data = [(remainingWork]
assignment.setRemainingWork(remainingWork); // depends on control dependency: [if], data = [(remainingWork]
}
}
}
}
} } |
public class class_name {
public ClassGraph whitelistJars(final String... jarLeafNames) {
for (final String jarLeafName : jarLeafNames) {
final String leafName = JarUtils.leafName(jarLeafName);
if (!leafName.equals(jarLeafName)) {
throw new IllegalArgumentException("Can only whitelist jars by leafname: " + jarLeafName);
}
scanSpec.jarWhiteBlackList.addToWhitelist(leafName);
}
return this;
} } | public class class_name {
public ClassGraph whitelistJars(final String... jarLeafNames) {
for (final String jarLeafName : jarLeafNames) {
final String leafName = JarUtils.leafName(jarLeafName);
if (!leafName.equals(jarLeafName)) {
throw new IllegalArgumentException("Can only whitelist jars by leafname: " + jarLeafName);
}
scanSpec.jarWhiteBlackList.addToWhitelist(leafName); // depends on control dependency: [for], data = [none]
}
return this;
} } |
public class class_name {
public static long getLong(MemorySegment[] segments, int offset) {
if (inFirstSegment(segments, offset, 8)) {
return segments[0].getLong(offset);
} else {
return getLongMultiSegments(segments, offset);
}
} } | public class class_name {
public static long getLong(MemorySegment[] segments, int offset) {
if (inFirstSegment(segments, offset, 8)) {
return segments[0].getLong(offset); // depends on control dependency: [if], data = [none]
} else {
return getLongMultiSegments(segments, offset); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String getId() {
if (id == null) {
synchronized (this) {
if (id == null) {
id = "rpc-cfg-" + ID_GENERATOR.getAndIncrement();
}
}
}
return id;
} } | public class class_name {
public String getId() {
if (id == null) {
synchronized (this) { // depends on control dependency: [if], data = [none]
if (id == null) {
id = "rpc-cfg-" + ID_GENERATOR.getAndIncrement(); // depends on control dependency: [if], data = [none]
}
}
}
return id;
} } |
public class class_name {
@Override
public int capacity() {
if (isFCEnabled()) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "FileChannel capacity: " + this.fcSize);
}
return this.fcSize;
}
return super.capacity();
} } | public class class_name {
@Override
public int capacity() {
if (isFCEnabled()) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "FileChannel capacity: " + this.fcSize); // depends on control dependency: [if], data = [none]
}
return this.fcSize; // depends on control dependency: [if], data = [none]
}
return super.capacity();
} } |
public class class_name {
public Content getAllClassesLinkScript(String id) {
HtmlTree script = HtmlTree.SCRIPT();
String scriptCode = "<!--\n" +
" allClassesLink = document.getElementById(\"" + id + "\");\n" +
" if(window==top) {\n" +
" allClassesLink.style.display = \"block\";\n" +
" }\n" +
" else {\n" +
" allClassesLink.style.display = \"none\";\n" +
" }\n" +
" //-->\n";
Content scriptContent = new RawHtml(scriptCode.replace("\n", DocletConstants.NL));
script.addContent(scriptContent);
Content div = HtmlTree.DIV(script);
Content div_noscript = HtmlTree.DIV(contents.noScriptMessage);
Content noScript = HtmlTree.NOSCRIPT(div_noscript);
div.addContent(noScript);
return div;
} } | public class class_name {
public Content getAllClassesLinkScript(String id) {
HtmlTree script = HtmlTree.SCRIPT();
String scriptCode = "<!--\n" +
" allClassesLink = document.getElementById(\"" + id + "\");\n" +
" if(window==top) {\n" +
" allClassesLink.style.display = \"block\";\n" + // depends on control dependency: [if], data = [none]
" }\n" +
" else {\n" +
" allClassesLink.style.display = \"none\";\n" +
" }\n" +
" //-->\n";
Content scriptContent = new RawHtml(scriptCode.replace("\n", DocletConstants.NL));
script.addContent(scriptContent);
Content div = HtmlTree.DIV(script);
Content div_noscript = HtmlTree.DIV(contents.noScriptMessage);
Content noScript = HtmlTree.NOSCRIPT(div_noscript);
div.addContent(noScript);
return div;
} } |
public class class_name {
static void logResult(Map<String, Object> result, DumpConfig config) {
Consumer<String> loggerFunc = getLoggerFuncBasedOnLevel(config.getLogLevel());
if(config.isUseJson()) {
logResultUsingJson(result, loggerFunc);
} else {
int startLevel = -1;
StringBuilder sb = new StringBuilder("Http request/response information:");
_logResult(result, startLevel, config.getIndentSize(), sb);
loggerFunc.accept(sb.toString());
}
} } | public class class_name {
static void logResult(Map<String, Object> result, DumpConfig config) {
Consumer<String> loggerFunc = getLoggerFuncBasedOnLevel(config.getLogLevel());
if(config.isUseJson()) {
logResultUsingJson(result, loggerFunc); // depends on control dependency: [if], data = [none]
} else {
int startLevel = -1;
StringBuilder sb = new StringBuilder("Http request/response information:");
_logResult(result, startLevel, config.getIndentSize(), sb); // depends on control dependency: [if], data = [none]
loggerFunc.accept(sb.toString()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setPara(AttributedCharacterIterator paragraph)
{
byte paraLvl;
Boolean runDirection = (Boolean) paragraph.getAttribute(TextAttribute.RUN_DIRECTION);
if (runDirection == null) {
paraLvl = LEVEL_DEFAULT_LTR;
} else {
paraLvl = (runDirection.equals(TextAttribute.RUN_DIRECTION_LTR)) ?
LTR : RTL;
}
byte[] lvls = null;
int len = paragraph.getEndIndex() - paragraph.getBeginIndex();
byte[] embeddingLevels = new byte[len];
char[] txt = new char[len];
int i = 0;
char ch = paragraph.first();
while (ch != AttributedCharacterIterator.DONE) {
txt[i] = ch;
Integer embedding = (Integer) paragraph.getAttribute(TextAttribute.BIDI_EMBEDDING);
if (embedding != null) {
byte level = embedding.byteValue();
if (level == 0) {
/* no-op */
} else if (level < 0) {
lvls = embeddingLevels;
embeddingLevels[i] = (byte)((0 - level) | LEVEL_OVERRIDE);
} else {
lvls = embeddingLevels;
embeddingLevels[i] = level;
}
}
ch = paragraph.next();
++i;
}
NumericShaper shaper = (NumericShaper) paragraph.getAttribute(TextAttribute.NUMERIC_SHAPING);
if (shaper != null) {
shaper.shape(txt, 0, len);
}
setPara(txt, paraLvl, lvls);
} } | public class class_name {
public void setPara(AttributedCharacterIterator paragraph)
{
byte paraLvl;
Boolean runDirection = (Boolean) paragraph.getAttribute(TextAttribute.RUN_DIRECTION);
if (runDirection == null) {
paraLvl = LEVEL_DEFAULT_LTR; // depends on control dependency: [if], data = [none]
} else {
paraLvl = (runDirection.equals(TextAttribute.RUN_DIRECTION_LTR)) ?
LTR : RTL; // depends on control dependency: [if], data = [none]
}
byte[] lvls = null;
int len = paragraph.getEndIndex() - paragraph.getBeginIndex();
byte[] embeddingLevels = new byte[len];
char[] txt = new char[len];
int i = 0;
char ch = paragraph.first();
while (ch != AttributedCharacterIterator.DONE) {
txt[i] = ch; // depends on control dependency: [while], data = [none]
Integer embedding = (Integer) paragraph.getAttribute(TextAttribute.BIDI_EMBEDDING);
if (embedding != null) {
byte level = embedding.byteValue();
if (level == 0) {
/* no-op */
} else if (level < 0) {
lvls = embeddingLevels; // depends on control dependency: [if], data = [none]
embeddingLevels[i] = (byte)((0 - level) | LEVEL_OVERRIDE); // depends on control dependency: [if], data = [none]
} else {
lvls = embeddingLevels; // depends on control dependency: [if], data = [none]
embeddingLevels[i] = level; // depends on control dependency: [if], data = [none]
}
}
ch = paragraph.next(); // depends on control dependency: [while], data = [none]
++i; // depends on control dependency: [while], data = [none]
}
NumericShaper shaper = (NumericShaper) paragraph.getAttribute(TextAttribute.NUMERIC_SHAPING);
if (shaper != null) {
shaper.shape(txt, 0, len); // depends on control dependency: [if], data = [none]
}
setPara(txt, paraLvl, lvls);
} } |
public class class_name {
public void marshall(ReplicationTaskStats replicationTaskStats, ProtocolMarshaller protocolMarshaller) {
if (replicationTaskStats == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(replicationTaskStats.getFullLoadProgressPercent(), FULLLOADPROGRESSPERCENT_BINDING);
protocolMarshaller.marshall(replicationTaskStats.getElapsedTimeMillis(), ELAPSEDTIMEMILLIS_BINDING);
protocolMarshaller.marshall(replicationTaskStats.getTablesLoaded(), TABLESLOADED_BINDING);
protocolMarshaller.marshall(replicationTaskStats.getTablesLoading(), TABLESLOADING_BINDING);
protocolMarshaller.marshall(replicationTaskStats.getTablesQueued(), TABLESQUEUED_BINDING);
protocolMarshaller.marshall(replicationTaskStats.getTablesErrored(), TABLESERRORED_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ReplicationTaskStats replicationTaskStats, ProtocolMarshaller protocolMarshaller) {
if (replicationTaskStats == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(replicationTaskStats.getFullLoadProgressPercent(), FULLLOADPROGRESSPERCENT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskStats.getElapsedTimeMillis(), ELAPSEDTIMEMILLIS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskStats.getTablesLoaded(), TABLESLOADED_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskStats.getTablesLoading(), TABLESLOADING_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskStats.getTablesQueued(), TABLESQUEUED_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(replicationTaskStats.getTablesErrored(), TABLESERRORED_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 boolean isInherited(ProgramElementDoc ped){
if(ped.isPrivate() || (ped.isPackagePrivate() &&
! ped.containingPackage().equals(classdoc.containingPackage()))){
return false;
}
return true;
} } | public class class_name {
protected boolean isInherited(ProgramElementDoc ped){
if(ped.isPrivate() || (ped.isPackagePrivate() &&
! ped.containingPackage().equals(classdoc.containingPackage()))){
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public static byte[] inputStreamToBytes(InputStream in) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
System.out.println("Error converting InputStream to byte[]: "
+ e.getMessage());
}
return out.toByteArray();
} } | public class class_name {
public static byte[] inputStreamToBytes(InputStream in) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
// depends on control dependency: [while], data = [none]
}
} catch (Exception e) {
System.out.println("Error converting InputStream to byte[]: "
+ e.getMessage());
}
// depends on control dependency: [catch], data = [none]
return out.toByteArray();
} } |
public class class_name {
private int externalInterruptibleAwaitDone() throws InterruptedException {
int s;
if (Thread.interrupted())
throw new InterruptedException();
while ((s = status) >= 0) {
if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
synchronized (this) {
if (status >= 0)
wait();
else
notifyAll();
}
}
}
return s;
} } | public class class_name {
private int externalInterruptibleAwaitDone() throws InterruptedException {
int s;
if (Thread.interrupted())
throw new InterruptedException();
while ((s = status) >= 0) {
if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
synchronized (this) { // depends on control dependency: [if], data = [none]
if (status >= 0)
wait();
else
notifyAll();
}
}
}
return s;
} } |
public class class_name {
public GlstringBuilder locus(final String glstring) {
if (tree.isEmpty()) {
locus = glstring;
}
else if (tree.root.isOperator() && tree.root.right == null) {
throw new IllegalStateException("must call allele(String) between successive calls to any operator (allelicAmbiguity, inPhase, plus, genotypicAmbiguity, locus)");
}
else {
Node root = new Node();
root.value = "^";
root.left = tree.root;
tree.root = root;
}
return this;
} } | public class class_name {
public GlstringBuilder locus(final String glstring) {
if (tree.isEmpty()) {
locus = glstring; // depends on control dependency: [if], data = [none]
}
else if (tree.root.isOperator() && tree.root.right == null) {
throw new IllegalStateException("must call allele(String) between successive calls to any operator (allelicAmbiguity, inPhase, plus, genotypicAmbiguity, locus)");
}
else {
Node root = new Node();
root.value = "^"; // depends on control dependency: [if], data = [none]
root.left = tree.root; // depends on control dependency: [if], data = [none]
tree.root = root; // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public void reverse() {
for (int i = 0, size = mTransitionControls.size(); i < size; i++) {
mTransitionControls.get(i).reverse();
}
} } | public class class_name {
public void reverse() {
for (int i = 0, size = mTransitionControls.size(); i < size; i++) {
mTransitionControls.get(i).reverse(); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
private List<AvailablePhoneNumber> toAvailablePhoneNumbers(List<PhoneNumber> phoneNumbers) {
final List<AvailablePhoneNumber> availablePhoneNumbers = new ArrayList<AvailablePhoneNumber>();
for (PhoneNumber phoneNumber : phoneNumbers) {
final AvailablePhoneNumber number = new AvailablePhoneNumber(phoneNumber.getFriendlyName(),
phoneNumber.getPhoneNumber(), phoneNumber.getLata(), phoneNumber.getRateCenter(),
phoneNumber.getLatitude(), phoneNumber.getLongitude(), phoneNumber.getRegion(),
phoneNumber.getPostalCode(), phoneNumber.getIsoCountry(), phoneNumber.getCost(), phoneNumber.isVoiceCapable(),
phoneNumber.isSmsCapable(), phoneNumber.isMmsCapable(), phoneNumber.isFaxCapable());
availablePhoneNumbers.add(number);
}
return availablePhoneNumbers;
} } | public class class_name {
private List<AvailablePhoneNumber> toAvailablePhoneNumbers(List<PhoneNumber> phoneNumbers) {
final List<AvailablePhoneNumber> availablePhoneNumbers = new ArrayList<AvailablePhoneNumber>();
for (PhoneNumber phoneNumber : phoneNumbers) {
final AvailablePhoneNumber number = new AvailablePhoneNumber(phoneNumber.getFriendlyName(),
phoneNumber.getPhoneNumber(), phoneNumber.getLata(), phoneNumber.getRateCenter(),
phoneNumber.getLatitude(), phoneNumber.getLongitude(), phoneNumber.getRegion(),
phoneNumber.getPostalCode(), phoneNumber.getIsoCountry(), phoneNumber.getCost(), phoneNumber.isVoiceCapable(),
phoneNumber.isSmsCapable(), phoneNumber.isMmsCapable(), phoneNumber.isFaxCapable());
availablePhoneNumbers.add(number); // depends on control dependency: [for], data = [none]
}
return availablePhoneNumbers;
} } |
public class class_name {
public void shutdown() {
lock.lock();
try {
isShutdown = true;
notEmpty.signalAll();
notFull.signalAll();
}
finally {
lock.unlock();
}
} } | public class class_name {
public void shutdown() {
lock.lock();
try {
isShutdown = true; // depends on control dependency: [try], data = [none]
notEmpty.signalAll(); // depends on control dependency: [try], data = [none]
notFull.signalAll(); // depends on control dependency: [try], data = [none]
}
finally {
lock.unlock();
}
} } |
public class class_name {
public void setPermissions(IConnection conn, Collection<String> permissions) {
if (permissions == null) {
conn.removeAttribute(PERMISSIONS);
} else {
conn.setAttribute(PERMISSIONS, permissions);
}
} } | public class class_name {
public void setPermissions(IConnection conn, Collection<String> permissions) {
if (permissions == null) {
conn.removeAttribute(PERMISSIONS);
// depends on control dependency: [if], data = [none]
} else {
conn.setAttribute(PERMISSIONS, permissions);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
boolean findRemainingCameraMatrices(LookupSimilarImages db, View seed, GrowQueue_I32 motions) {
points3D.reset(); // points in 3D
for (int i = 0; i < structure.points.length; i++) {
structure.points[i].get(points3D.grow());
}
// contains associated pairs of pixel observations
// save a call to db by using the previously loaded points
assocPixel.reset();
for (int i = 0; i < inlierToSeed.size; i++) {
// inliers from triple RANSAC
// each of these inliers was declared a feature in the world reference frame
assocPixel.grow().p1.set(matchesTriple.get(i).p1);
}
DMatrixRMaj cameraMatrix = new DMatrixRMaj(3,4);
for (int motionIdx = 0; motionIdx < motions.size; motionIdx++) {
// skip views already in the scene's structure
if( motionIdx == selectedTriple[0] || motionIdx == selectedTriple[1])
continue;
int connectionIdx = motions.get(motionIdx);
Motion edge = seed.connections.get(connectionIdx);
View viewI = edge.other(seed);
// Lookup pixel locations of features in the connected view
db.lookupPixelFeats(viewI.id,featsB);
if ( !computeCameraMatrix(seed, edge,featsB,cameraMatrix) ) {
if( verbose != null ) {
verbose.println("Pose estimator failed! motionIdx="+motionIdx);
}
return false;
}
db.lookupShape(edge.other(seed).id,shape);
structure.setView(motionIdx,false,cameraMatrix,shape.width,shape.height);
}
return true;
} } | public class class_name {
boolean findRemainingCameraMatrices(LookupSimilarImages db, View seed, GrowQueue_I32 motions) {
points3D.reset(); // points in 3D
for (int i = 0; i < structure.points.length; i++) {
structure.points[i].get(points3D.grow()); // depends on control dependency: [for], data = [i]
}
// contains associated pairs of pixel observations
// save a call to db by using the previously loaded points
assocPixel.reset();
for (int i = 0; i < inlierToSeed.size; i++) {
// inliers from triple RANSAC
// each of these inliers was declared a feature in the world reference frame
assocPixel.grow().p1.set(matchesTriple.get(i).p1); // depends on control dependency: [for], data = [i]
}
DMatrixRMaj cameraMatrix = new DMatrixRMaj(3,4);
for (int motionIdx = 0; motionIdx < motions.size; motionIdx++) {
// skip views already in the scene's structure
if( motionIdx == selectedTriple[0] || motionIdx == selectedTriple[1])
continue;
int connectionIdx = motions.get(motionIdx);
Motion edge = seed.connections.get(connectionIdx);
View viewI = edge.other(seed);
// Lookup pixel locations of features in the connected view
db.lookupPixelFeats(viewI.id,featsB); // depends on control dependency: [for], data = [none]
if ( !computeCameraMatrix(seed, edge,featsB,cameraMatrix) ) {
if( verbose != null ) {
verbose.println("Pose estimator failed! motionIdx="+motionIdx); // depends on control dependency: [if], data = [none]
}
return false; // depends on control dependency: [if], data = [none]
}
db.lookupShape(edge.other(seed).id,shape); // depends on control dependency: [for], data = [none]
structure.setView(motionIdx,false,cameraMatrix,shape.width,shape.height); // depends on control dependency: [for], data = [motionIdx]
}
return true;
} } |
public class class_name {
private void enrich(final Dependency dependency) {
log.debug("Enrich dependency: {}", dependency);
for (Identifier id : dependency.getSoftwareIdentifiers()) {
if (id instanceof PurlIdentifier) {
log.debug(" Package: {} -> {}", id, id.getConfidence());
PackageUrl purl = parsePackageUrl(id.getValue());
if (purl != null) {
try {
ComponentReport report = reports.get(purl);
if (report == null) {
throw new IllegalStateException("Missing component-report for: " + purl);
}
// expose the URL to the package details for report generation
id.setUrl(report.getReference().toString());
for (ComponentReportVulnerability vuln : report.getVulnerabilities()) {
Vulnerability v = transform(report, vuln);
Vulnerability existing = dependency.getVulnerabilities().stream().filter(e->e.getName().equals(v.getName())).findFirst().orElse(null);
if (existing!=null) {
//TODO - can we enhance anything other than the references?
existing.getReferences().addAll(v.getReferences());
} else {
dependency.addVulnerability(v);
}
}
} catch (Exception e) {
log.warn("Failed to fetch component-report for: {}", purl, e);
}
}
}
}
} } | public class class_name {
private void enrich(final Dependency dependency) {
log.debug("Enrich dependency: {}", dependency);
for (Identifier id : dependency.getSoftwareIdentifiers()) {
if (id instanceof PurlIdentifier) {
log.debug(" Package: {} -> {}", id, id.getConfidence()); // depends on control dependency: [if], data = [none]
PackageUrl purl = parsePackageUrl(id.getValue());
if (purl != null) {
try {
ComponentReport report = reports.get(purl);
if (report == null) {
throw new IllegalStateException("Missing component-report for: " + purl);
}
// expose the URL to the package details for report generation
id.setUrl(report.getReference().toString()); // depends on control dependency: [try], data = [none]
for (ComponentReportVulnerability vuln : report.getVulnerabilities()) {
Vulnerability v = transform(report, vuln);
Vulnerability existing = dependency.getVulnerabilities().stream().filter(e->e.getName().equals(v.getName())).findFirst().orElse(null);
if (existing!=null) {
//TODO - can we enhance anything other than the references?
existing.getReferences().addAll(v.getReferences()); // depends on control dependency: [if], data = [none]
} else {
dependency.addVulnerability(v); // depends on control dependency: [if], data = [none]
}
}
} catch (Exception e) {
log.warn("Failed to fetch component-report for: {}", purl, e);
} // depends on control dependency: [catch], data = [none]
}
}
}
} } |
public class class_name {
public List<WebElement> findExpectedElements(By by) {
waitForLoaders();
try {
return new WebDriverWait(getWebDriver(), getSeleniumManager().getTimeout())
.until(ExpectedConditions.presenceOfAllElementsLocatedBy(by));
} catch (WebDriverException wde) {
log.error("Expected elements not found: ", wde);
fail("Element: " + by.toString() + " not found after waiting for " + getSeleniumManager().getTimeout() + " seconds. Webdriver though exception: " + wde.getClass().getCanonicalName() + " with error message: " + wde.getMessage());
}
return null;
} } | public class class_name {
public List<WebElement> findExpectedElements(By by) {
waitForLoaders();
try {
return new WebDriverWait(getWebDriver(), getSeleniumManager().getTimeout())
.until(ExpectedConditions.presenceOfAllElementsLocatedBy(by)); // depends on control dependency: [try], data = [none]
} catch (WebDriverException wde) {
log.error("Expected elements not found: ", wde);
fail("Element: " + by.toString() + " not found after waiting for " + getSeleniumManager().getTimeout() + " seconds. Webdriver though exception: " + wde.getClass().getCanonicalName() + " with error message: " + wde.getMessage());
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
public static RedisConnectionException create(String remoteAddress, Throwable cause) {
if (remoteAddress == null) {
if (cause instanceof RedisConnectionException) {
return new RedisConnectionException(cause.getMessage(), cause.getCause());
}
return new RedisConnectionException(null, cause);
}
return new RedisConnectionException(String.format("Unable to connect to %s", remoteAddress), cause);
} } | public class class_name {
public static RedisConnectionException create(String remoteAddress, Throwable cause) {
if (remoteAddress == null) {
if (cause instanceof RedisConnectionException) {
return new RedisConnectionException(cause.getMessage(), cause.getCause()); // depends on control dependency: [if], data = [none]
}
return new RedisConnectionException(null, cause); // depends on control dependency: [if], data = [none]
}
return new RedisConnectionException(String.format("Unable to connect to %s", remoteAddress), cause);
} } |
public class class_name {
List<Job> getRemainingJobs() {
if (mThread.isAlive()) {
LOG.warn("Internal error: Polling running monitor for jobs");
}
synchronized (mJobs) {
return new ArrayList<Job>(mJobs);
}
} } | public class class_name {
List<Job> getRemainingJobs() {
if (mThread.isAlive()) {
LOG.warn("Internal error: Polling running monitor for jobs"); // depends on control dependency: [if], data = [none]
}
synchronized (mJobs) {
return new ArrayList<Job>(mJobs);
}
} } |
public class class_name {
public static int dimensionFromConstraint(String constraint, String columnName) {
Matcher matcher = Z_CONSTRAINT_PATTERN.matcher(constraint);
if(matcher.find()) {
String extractedColumnName = matcher.group(1).replace("\"","").replace("`", "");
if(extractedColumnName.equalsIgnoreCase(columnName)) {
int constraint_value = Integer.valueOf(matcher.group(8));
String sign = matcher.group(5);
if("<>".equals(sign) || "!=".equals(sign)) {
constraint_value = constraint_value == 3 ? 2 : 3;
}
if("<".equals(sign)) {
constraint_value = 2;
}
if(">".equals(sign)) {
constraint_value = constraint_value == 2 ? 3 : 2;
}
return constraint_value;
}
}
return 2;
} } | public class class_name {
public static int dimensionFromConstraint(String constraint, String columnName) {
Matcher matcher = Z_CONSTRAINT_PATTERN.matcher(constraint);
if(matcher.find()) {
String extractedColumnName = matcher.group(1).replace("\"","").replace("`", "");
if(extractedColumnName.equalsIgnoreCase(columnName)) {
int constraint_value = Integer.valueOf(matcher.group(8));
String sign = matcher.group(5);
if("<>".equals(sign) || "!=".equals(sign)) {
constraint_value = constraint_value == 3 ? 2 : 3; // depends on control dependency: [if], data = [none]
}
if("<".equals(sign)) {
constraint_value = 2; // depends on control dependency: [if], data = [none]
}
if(">".equals(sign)) {
constraint_value = constraint_value == 2 ? 3 : 2; // depends on control dependency: [if], data = [none]
}
return constraint_value; // depends on control dependency: [if], data = [none]
}
}
return 2;
} } |
public class class_name {
private static String initCreateRelationshipQuery(EntityKeyMetadata ownerEntityKeyMetadata, AssociationKeyMetadata associationKeyMetadata) {
EntityKeyMetadata targetEntityKeyMetadata = associationKeyMetadata.getAssociatedEntityKeyMetadata().getEntityKeyMetadata();
int offset = 0;
StringBuilder queryBuilder = new StringBuilder( "MATCH " );
appendEntityNode( "n", ownerEntityKeyMetadata, queryBuilder );
queryBuilder.append( ", " );
offset += ownerEntityKeyMetadata.getColumnNames().length;
appendEntityNode( "t", targetEntityKeyMetadata, queryBuilder, offset );
queryBuilder.append( " MERGE (n)" );
queryBuilder.append( " -[r" );
queryBuilder.append( ":" );
appendRelationshipType( queryBuilder, associationKeyMetadata );
offset = ownerEntityKeyMetadata.getColumnNames().length;
if ( associationKeyMetadata.getRowKeyIndexColumnNames().length > 0 ) {
offset += targetEntityKeyMetadata.getColumnNames().length;
appendProperties( queryBuilder, associationKeyMetadata.getRowKeyIndexColumnNames(), offset );
}
queryBuilder.append( "]-> (t)" );
queryBuilder.append( " RETURN r" );
return queryBuilder.toString();
} } | public class class_name {
private static String initCreateRelationshipQuery(EntityKeyMetadata ownerEntityKeyMetadata, AssociationKeyMetadata associationKeyMetadata) {
EntityKeyMetadata targetEntityKeyMetadata = associationKeyMetadata.getAssociatedEntityKeyMetadata().getEntityKeyMetadata();
int offset = 0;
StringBuilder queryBuilder = new StringBuilder( "MATCH " );
appendEntityNode( "n", ownerEntityKeyMetadata, queryBuilder );
queryBuilder.append( ", " );
offset += ownerEntityKeyMetadata.getColumnNames().length;
appendEntityNode( "t", targetEntityKeyMetadata, queryBuilder, offset );
queryBuilder.append( " MERGE (n)" );
queryBuilder.append( " -[r" );
queryBuilder.append( ":" );
appendRelationshipType( queryBuilder, associationKeyMetadata );
offset = ownerEntityKeyMetadata.getColumnNames().length;
if ( associationKeyMetadata.getRowKeyIndexColumnNames().length > 0 ) {
offset += targetEntityKeyMetadata.getColumnNames().length; // depends on control dependency: [if], data = [none]
appendProperties( queryBuilder, associationKeyMetadata.getRowKeyIndexColumnNames(), offset ); // depends on control dependency: [if], data = [none]
}
queryBuilder.append( "]-> (t)" );
queryBuilder.append( " RETURN r" );
return queryBuilder.toString();
} } |
public class class_name {
public static JSONArray getRepositoryNames() {
final JSONArray ret = new JSONArray();
if (null == repositoriesDescription) {
LOGGER.log(Level.INFO, "Not found repository description[repository.json] file under classpath");
return ret;
}
final JSONArray repositories = repositoriesDescription.optJSONArray("repositories");
for (int i = 0; i < repositories.length(); i++) {
final JSONObject repository = repositories.optJSONObject(i);
ret.put(repository.optString("name"));
}
return ret;
} } | public class class_name {
public static JSONArray getRepositoryNames() {
final JSONArray ret = new JSONArray();
if (null == repositoriesDescription) {
LOGGER.log(Level.INFO, "Not found repository description[repository.json] file under classpath"); // depends on control dependency: [if], data = [none]
return ret; // depends on control dependency: [if], data = [none]
}
final JSONArray repositories = repositoriesDescription.optJSONArray("repositories");
for (int i = 0; i < repositories.length(); i++) {
final JSONObject repository = repositories.optJSONObject(i);
ret.put(repository.optString("name")); // depends on control dependency: [for], data = [none]
}
return ret;
} } |
public class class_name {
public void printLine(String text) {
if (!DEBUG) {
return;
}
Element child = DOM.createElement("p");
child.setInnerHTML(text);
m_html.insertFirst(child);
} } | public class class_name {
public void printLine(String text) {
if (!DEBUG) {
return; // depends on control dependency: [if], data = [none]
}
Element child = DOM.createElement("p");
child.setInnerHTML(text);
m_html.insertFirst(child);
} } |
public class class_name {
public void marshall(CreateGroupCertificateAuthorityRequest createGroupCertificateAuthorityRequest, ProtocolMarshaller protocolMarshaller) {
if (createGroupCertificateAuthorityRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createGroupCertificateAuthorityRequest.getAmznClientToken(), AMZNCLIENTTOKEN_BINDING);
protocolMarshaller.marshall(createGroupCertificateAuthorityRequest.getGroupId(), GROUPID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateGroupCertificateAuthorityRequest createGroupCertificateAuthorityRequest, ProtocolMarshaller protocolMarshaller) {
if (createGroupCertificateAuthorityRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createGroupCertificateAuthorityRequest.getAmznClientToken(), AMZNCLIENTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(createGroupCertificateAuthorityRequest.getGroupId(), GROUPID_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected void displaySystem (String bundle, String message, byte attLevel, String localtype)
{
// nothing should be untranslated, so pass the default bundle if need be.
if (bundle == null) {
bundle = _bundle;
}
SystemMessage msg = new SystemMessage(message, bundle, attLevel);
dispatchMessage(msg, localtype);
} } | public class class_name {
protected void displaySystem (String bundle, String message, byte attLevel, String localtype)
{
// nothing should be untranslated, so pass the default bundle if need be.
if (bundle == null) {
bundle = _bundle; // depends on control dependency: [if], data = [none]
}
SystemMessage msg = new SystemMessage(message, bundle, attLevel);
dispatchMessage(msg, localtype);
} } |
public class class_name {
static public int byteIndexOf(byte[] bytes, byte target, int start_index) {
int rc = -1; // simulate String.indexOf rc
// stop when we are out of data or hit the target byte
for (int index = start_index; index < bytes.length; index++) {
if (target == bytes[index]) {
rc = index;
break;
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "byteIndexOf returning [" + rc + "]");
}
return rc;
} } | public class class_name {
static public int byteIndexOf(byte[] bytes, byte target, int start_index) {
int rc = -1; // simulate String.indexOf rc
// stop when we are out of data or hit the target byte
for (int index = start_index; index < bytes.length; index++) {
if (target == bytes[index]) {
rc = index; // depends on control dependency: [if], data = [none]
break;
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "byteIndexOf returning [" + rc + "]"); // depends on control dependency: [if], data = [none]
}
return rc;
} } |
public class class_name {
@Override
public void setInput(InputStream is, String charset) {
position = 0;
limit = 0;
boolean detectCharset = (charset == null);
if (is == null) {
throw new IllegalArgumentException();
}
try {
if (detectCharset) {
// read the four bytes looking for an indication of the encoding
// in use
int firstFourBytes = 0;
while (limit < 4) {
int i = is.read();
if (i == -1) {
break;
}
firstFourBytes = (firstFourBytes << 8) | i;
buffer[limit++] = (char) i;
}
if (limit == 4) {
switch (firstFourBytes) {
case 0x00000FEFF: // UTF-32BE BOM
charset = "UTF-32BE";
limit = 0;
break;
case 0x0FFFE0000: // UTF-32LE BOM
charset = "UTF-32LE";
limit = 0;
break;
case 0x0000003c: // '<' in UTF-32BE
charset = "UTF-32BE";
buffer[0] = '<';
limit = 1;
break;
case 0x03c000000: // '<' in UTF-32LE
charset = "UTF-32LE";
buffer[0] = '<';
limit = 1;
break;
case 0x0003c003f: // "<?" in UTF-16BE
charset = "UTF-16BE";
buffer[0] = '<';
buffer[1] = '?';
limit = 2;
break;
case 0x03c003f00: // "<?" in UTF-16LE
charset = "UTF-16LE";
buffer[0] = '<';
buffer[1] = '?';
limit = 2;
break;
case 0x03c3f786d: // "<?xm" in ASCII etc.
while (true) {
int i = is.read();
if (i == -1) {
break;
}
buffer[limit++] = (char) i;
if (i == '>') {
String s = new String(buffer, 0, limit);
int i0 = s.indexOf("encoding");
if (i0 != -1) {
while (s.charAt(i0) != '"' && s.charAt(i0) != '\'') {
i0++;
}
char deli = s.charAt(i0++);
int i1 = s.indexOf(deli, i0);
charset = s.substring(i0, i1);
}
break;
}
}
break;
default:
// handle a byte order mark followed by something other
// than <?
if ((firstFourBytes & 0x0ffff0000) == 0x0feff0000) {
charset = "UTF-16BE";
buffer[0] = (char) ((buffer[2] << 8) | buffer[3]);
limit = 1;
} else if ((firstFourBytes & 0x0ffff0000) == 0x0fffe0000) {
charset = "UTF-16LE";
buffer[0] = (char) ((buffer[3] << 8) | buffer[2]);
limit = 1;
} else if ((firstFourBytes & 0x0ffffff00) == 0x0efbbbf00) {
charset = "UTF-8";
buffer[0] = buffer[3];
limit = 1;
}
}
}
}
if (charset == null) {
charset = "UTF-8";
}
int savedLimit = limit;
setInput(new InputStreamReader(is, charset));
encoding = charset;
limit = savedLimit;
/*
* Skip the optional BOM if we didn't above. This decrements limit
* rather than incrementing position so that <?xml version='1.0'?>
* is still at character 0.
*/
if (!detectCharset && peekCharacter() == 0xfeff) {
limit--;
System.arraycopy(buffer, 1, buffer, 0, limit);
}
} catch (Exception e) {
throw new KriptonRuntimeException("Invalid stream or encoding: " + e, true, this.getLineNumber(), this.getColumnNumber(), getPositionDescription(), e);
}
} } | public class class_name {
@Override
public void setInput(InputStream is, String charset) {
position = 0;
limit = 0;
boolean detectCharset = (charset == null);
if (is == null) {
throw new IllegalArgumentException();
}
try {
if (detectCharset) {
// read the four bytes looking for an indication of the encoding
// in use
int firstFourBytes = 0;
while (limit < 4) {
int i = is.read();
if (i == -1) {
break;
}
firstFourBytes = (firstFourBytes << 8) | i; // depends on control dependency: [while], data = [none]
buffer[limit++] = (char) i; // depends on control dependency: [while], data = [none]
}
if (limit == 4) {
switch (firstFourBytes) {
case 0x00000FEFF: // UTF-32BE BOM
charset = "UTF-32BE";
limit = 0;
break;
case 0x0FFFE0000: // UTF-32LE BOM
charset = "UTF-32LE";
limit = 0;
break;
case 0x0000003c: // '<' in UTF-32BE
charset = "UTF-32BE";
buffer[0] = '<';
limit = 1;
break;
case 0x03c000000: // '<' in UTF-32LE
charset = "UTF-32LE";
buffer[0] = '<';
limit = 1;
break;
case 0x0003c003f: // "<?" in UTF-16BE
charset = "UTF-16BE";
buffer[0] = '<';
buffer[1] = '?';
limit = 2;
break;
case 0x03c003f00: // "<?" in UTF-16LE
charset = "UTF-16LE";
buffer[0] = '<';
buffer[1] = '?';
limit = 2;
break;
case 0x03c3f786d: // "<?xm" in ASCII etc.
while (true) {
int i = is.read();
if (i == -1) {
break;
}
buffer[limit++] = (char) i; // depends on control dependency: [while], data = [none]
if (i == '>') {
String s = new String(buffer, 0, limit);
int i0 = s.indexOf("encoding");
if (i0 != -1) {
while (s.charAt(i0) != '"' && s.charAt(i0) != '\'') {
i0++; // depends on control dependency: [while], data = [none]
}
char deli = s.charAt(i0++);
int i1 = s.indexOf(deli, i0);
charset = s.substring(i0, i1); // depends on control dependency: [if], data = [(i0]
}
break;
}
}
break;
default:
// handle a byte order mark followed by something other
// than <?
if ((firstFourBytes & 0x0ffff0000) == 0x0feff0000) {
charset = "UTF-16BE"; // depends on control dependency: [if], data = [none]
buffer[0] = (char) ((buffer[2] << 8) | buffer[3]); // depends on control dependency: [if], data = [none]
limit = 1; // depends on control dependency: [if], data = [none]
} else if ((firstFourBytes & 0x0ffff0000) == 0x0fffe0000) {
charset = "UTF-16LE"; // depends on control dependency: [if], data = [none]
buffer[0] = (char) ((buffer[3] << 8) | buffer[2]); // depends on control dependency: [if], data = [none]
limit = 1; // depends on control dependency: [if], data = [none]
} else if ((firstFourBytes & 0x0ffffff00) == 0x0efbbbf00) {
charset = "UTF-8"; // depends on control dependency: [if], data = [none]
buffer[0] = buffer[3]; // depends on control dependency: [if], data = [none]
limit = 1; // depends on control dependency: [if], data = [none]
}
}
}
}
if (charset == null) {
charset = "UTF-8"; // depends on control dependency: [if], data = [none]
}
int savedLimit = limit;
setInput(new InputStreamReader(is, charset)); // depends on control dependency: [try], data = [none]
encoding = charset; // depends on control dependency: [try], data = [none]
limit = savedLimit; // depends on control dependency: [try], data = [none]
/*
* Skip the optional BOM if we didn't above. This decrements limit
* rather than incrementing position so that <?xml version='1.0'?>
* is still at character 0.
*/
if (!detectCharset && peekCharacter() == 0xfeff) {
limit--; // depends on control dependency: [if], data = [none]
System.arraycopy(buffer, 1, buffer, 0, limit); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
throw new KriptonRuntimeException("Invalid stream or encoding: " + e, true, this.getLineNumber(), this.getColumnNumber(), getPositionDescription(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public final QueryParser.regex_match_return regex_match() throws RecognitionException {
QueryParser.regex_match_return retval = new QueryParser.regex_match_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token WS41=null;
Token REGEX_MATCH42=null;
Token WS43=null;
QueryParser.field_return field40 = null;
QueryParser.value_return value44 = null;
CommonTree WS41_tree=null;
CommonTree REGEX_MATCH42_tree=null;
CommonTree WS43_tree=null;
try {
// src/riemann/Query.g:56:2: ( field ( WS )* REGEX_MATCH ( WS )* value )
// src/riemann/Query.g:56:4: field ( WS )* REGEX_MATCH ( WS )* value
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_field_in_regex_match376);
field40=field();
state._fsp--;
adaptor.addChild(root_0, field40.getTree());
// src/riemann/Query.g:56:10: ( WS )*
loop15:
do {
int alt15=2;
int LA15_0 = input.LA(1);
if ( (LA15_0==WS) ) {
alt15=1;
}
switch (alt15) {
case 1 :
// src/riemann/Query.g:56:10: WS
{
WS41=(Token)match(input,WS,FOLLOW_WS_in_regex_match378);
WS41_tree = (CommonTree)adaptor.create(WS41);
adaptor.addChild(root_0, WS41_tree);
}
break;
default :
break loop15;
}
} while (true);
REGEX_MATCH42=(Token)match(input,REGEX_MATCH,FOLLOW_REGEX_MATCH_in_regex_match381);
REGEX_MATCH42_tree = (CommonTree)adaptor.create(REGEX_MATCH42);
root_0 = (CommonTree)adaptor.becomeRoot(REGEX_MATCH42_tree, root_0);
// src/riemann/Query.g:56:27: ( WS )*
loop16:
do {
int alt16=2;
int LA16_0 = input.LA(1);
if ( (LA16_0==WS) ) {
alt16=1;
}
switch (alt16) {
case 1 :
// src/riemann/Query.g:56:27: WS
{
WS43=(Token)match(input,WS,FOLLOW_WS_in_regex_match384);
WS43_tree = (CommonTree)adaptor.create(WS43);
adaptor.addChild(root_0, WS43_tree);
}
break;
default :
break loop16;
}
} while (true);
pushFollow(FOLLOW_value_in_regex_match387);
value44=value();
state._fsp--;
adaptor.addChild(root_0, value44.getTree());
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
}
return retval;
} } | public class class_name {
public final QueryParser.regex_match_return regex_match() throws RecognitionException {
QueryParser.regex_match_return retval = new QueryParser.regex_match_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token WS41=null;
Token REGEX_MATCH42=null;
Token WS43=null;
QueryParser.field_return field40 = null;
QueryParser.value_return value44 = null;
CommonTree WS41_tree=null;
CommonTree REGEX_MATCH42_tree=null;
CommonTree WS43_tree=null;
try {
// src/riemann/Query.g:56:2: ( field ( WS )* REGEX_MATCH ( WS )* value )
// src/riemann/Query.g:56:4: field ( WS )* REGEX_MATCH ( WS )* value
{
root_0 = (CommonTree)adaptor.nil();
pushFollow(FOLLOW_field_in_regex_match376);
field40=field();
state._fsp--;
adaptor.addChild(root_0, field40.getTree());
// src/riemann/Query.g:56:10: ( WS )*
loop15:
do {
int alt15=2;
int LA15_0 = input.LA(1);
if ( (LA15_0==WS) ) {
alt15=1; // depends on control dependency: [if], data = [none]
}
switch (alt15) {
case 1 :
// src/riemann/Query.g:56:10: WS
{
WS41=(Token)match(input,WS,FOLLOW_WS_in_regex_match378);
WS41_tree = (CommonTree)adaptor.create(WS41);
adaptor.addChild(root_0, WS41_tree);
}
break;
default :
break loop15;
}
} while (true);
REGEX_MATCH42=(Token)match(input,REGEX_MATCH,FOLLOW_REGEX_MATCH_in_regex_match381);
REGEX_MATCH42_tree = (CommonTree)adaptor.create(REGEX_MATCH42);
root_0 = (CommonTree)adaptor.becomeRoot(REGEX_MATCH42_tree, root_0);
// src/riemann/Query.g:56:27: ( WS )*
loop16:
do {
int alt16=2;
int LA16_0 = input.LA(1);
if ( (LA16_0==WS) ) {
alt16=1; // depends on control dependency: [if], data = [none]
}
switch (alt16) {
case 1 :
// src/riemann/Query.g:56:27: WS
{
WS43=(Token)match(input,WS,FOLLOW_WS_in_regex_match384);
WS43_tree = (CommonTree)adaptor.create(WS43);
adaptor.addChild(root_0, WS43_tree);
}
break;
default :
break loop16;
}
} while (true);
pushFollow(FOLLOW_value_in_regex_match387);
value44=value();
state._fsp--;
adaptor.addChild(root_0, value44.getTree());
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
}
return retval;
} } |
public class class_name {
public T next(int offset) {
if (offset < 0) {
throw new IllegalArgumentException("offset < 0");
}
while (itemBuffer.size() <= offset && !endReached) {
T item = fetch();
if (item != null) {
itemBuffer.add(item);
} else {
endReached = true;
}
}
if (offset >= itemBuffer.size()) {
if (endOfInputIndicator == null) {
endOfInputIndicator = endOfInput();
}
return endOfInputIndicator;
} else {
return itemBuffer.get(offset);
}
} } | public class class_name {
public T next(int offset) {
if (offset < 0) {
throw new IllegalArgumentException("offset < 0");
}
while (itemBuffer.size() <= offset && !endReached) {
T item = fetch();
if (item != null) {
itemBuffer.add(item); // depends on control dependency: [if], data = [(item]
} else {
endReached = true; // depends on control dependency: [if], data = [none]
}
}
if (offset >= itemBuffer.size()) {
if (endOfInputIndicator == null) {
endOfInputIndicator = endOfInput(); // depends on control dependency: [if], data = [none]
}
return endOfInputIndicator; // depends on control dependency: [if], data = [none]
} else {
return itemBuffer.get(offset); // depends on control dependency: [if], data = [(offset]
}
} } |
public class class_name {
private void setHelpEnabled(boolean enabled) {
if (getView() == null) {
return;
}
JRootPane rootPane = getView().getMainFrame().getRootPane();
if (enabled && findHelpSetUrl() != null) {
createHelpBroker();
loadAddOnHelpSets(ExtensionFactory.getAddOnLoader().getAddOnCollection().getInstalledAddOns());
getMenuHelpZapUserGuide().addActionListener(showHelpActionListener);
getMenuHelpZapUserGuide().setToolTipText(null);
getMenuHelpZapUserGuide().setEnabled(true);
// Enable the top level F1 help key
hb.enableHelpKey(rootPane, "zap.intro", hs, "javax.help.SecondaryWindow", null);
for (Entry<JComponent, String> entry : componentsWithHelp.entrySet()) {
hb.enableHelp(entry.getKey(), entry.getValue(), hs);
}
getHelpButton().setToolTipText(Constant.messages.getString("help.button.tooltip"));
getHelpButton().setEnabled(true);
} else {
String toolTipNoHelp = Constant.messages.getString("help.error.nohelp");
getMenuHelpZapUserGuide().setEnabled(false);
getMenuHelpZapUserGuide().setToolTipText(toolTipNoHelp);
getMenuHelpZapUserGuide().removeActionListener(showHelpActionListener);
rootPane.unregisterKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0));
rootPane.unregisterKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
removeHelpProperties(rootPane);
for (JComponent component : componentsWithHelp.keySet()) {
removeHelpProperties(component);
}
getHelpButton().setEnabled(false);
getHelpButton().setToolTipText(toolTipNoHelp);
hb = null;
hs = null;
showHelpActionListener = null;
}
} } | public class class_name {
private void setHelpEnabled(boolean enabled) {
if (getView() == null) {
return; // depends on control dependency: [if], data = [none]
}
JRootPane rootPane = getView().getMainFrame().getRootPane();
if (enabled && findHelpSetUrl() != null) {
createHelpBroker();
loadAddOnHelpSets(ExtensionFactory.getAddOnLoader().getAddOnCollection().getInstalledAddOns());
getMenuHelpZapUserGuide().addActionListener(showHelpActionListener);
getMenuHelpZapUserGuide().setToolTipText(null);
getMenuHelpZapUserGuide().setEnabled(true);
// Enable the top level F1 help key
hb.enableHelpKey(rootPane, "zap.intro", hs, "javax.help.SecondaryWindow", null);
for (Entry<JComponent, String> entry : componentsWithHelp.entrySet()) {
hb.enableHelp(entry.getKey(), entry.getValue(), hs); // depends on control dependency: [for], data = [entry]
}
getHelpButton().setToolTipText(Constant.messages.getString("help.button.tooltip"));
getHelpButton().setEnabled(true);
} else {
String toolTipNoHelp = Constant.messages.getString("help.error.nohelp");
getMenuHelpZapUserGuide().setEnabled(false);
getMenuHelpZapUserGuide().setToolTipText(toolTipNoHelp);
getMenuHelpZapUserGuide().removeActionListener(showHelpActionListener);
rootPane.unregisterKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0));
rootPane.unregisterKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
removeHelpProperties(rootPane);
for (JComponent component : componentsWithHelp.keySet()) {
removeHelpProperties(component);
}
getHelpButton().setEnabled(false);
getHelpButton().setToolTipText(toolTipNoHelp);
hb = null;
hs = null;
showHelpActionListener = null;
}
} } |
public class class_name {
public static Package getTaskTemplatePackage(Long taskId) {
try {
for (Package pkg : getPackageList()) {
if (pkg.containsTaskTemplate(taskId))
return pkg;
}
return Package.getDefaultPackage();
}
catch (CachingException ex) {
logger.severeException(ex.getMessage(), ex);
return null;
}
} } | public class class_name {
public static Package getTaskTemplatePackage(Long taskId) {
try {
for (Package pkg : getPackageList()) {
if (pkg.containsTaskTemplate(taskId))
return pkg;
}
return Package.getDefaultPackage(); // depends on control dependency: [try], data = [none]
}
catch (CachingException ex) {
logger.severeException(ex.getMessage(), ex);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public boolean registerCallbackOnExistingExpression(
ConnectionImpl connection,
String topicExpression,
boolean isWildcarded,
ConsumerSetChangeCallback callback)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"registerCallbackOnExistingExpression",
new Object[] {connection, topicExpression, new Boolean(isWildcarded), callback });
boolean areConsumers = false;
RegisteredCallbacks rMonitor = null;
// Add the callback to the index of callbacks
addCallbackToConnectionIndex(connection, topicExpression, isWildcarded, callback);
if(isWildcarded)
rMonitor = (RegisteredCallbacks)_registeredWildcardConsumerMonitors.get(topicExpression);
else
rMonitor = (RegisteredCallbacks)_registeredExactConsumerMonitors.get(topicExpression);
// Get the list of callbacks and add the new one
ArrayList callbackList = rMonitor.getWrappedCallbacks();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "Found existing entry with callbacks: " + callbackList);
WrappedConsumerSetChangeCallback wcb = new WrappedConsumerSetChangeCallback(callback);
//F011127
//When we call the registerconsumermonitor() more than once with the same parameter,
//there will be duplicate of callback in callbacklist.To overcome this leak we are checking before adding into the callbacklist
Iterator it = callbackList.iterator();
boolean alreadyExisting = false;
while(it.hasNext()){
WrappedConsumerSetChangeCallback tmpwcb = (WrappedConsumerSetChangeCallback)it.next();
if(tmpwcb.equals(wcb)){
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "The same callback is already registerd for the topic expression :"+topicExpression+" Hence registration will not be done!");
alreadyExisting = true;
break;
}
}
if(!alreadyExisting)
callbackList.add(wcb);
// Get the list of matching consumers
ArrayList consumerList = rMonitor.getMatchingConsumers();
// Are there consumers for this expression
areConsumers = !consumerList.isEmpty();
// Don't need to adjust the references in the consumer list as they will
// already have a reference to this topic expression
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "registerCallbackOnExistingExpression", new Boolean(areConsumers));
return areConsumers;
} } | public class class_name {
public boolean registerCallbackOnExistingExpression(
ConnectionImpl connection,
String topicExpression,
boolean isWildcarded,
ConsumerSetChangeCallback callback)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"registerCallbackOnExistingExpression",
new Object[] {connection, topicExpression, new Boolean(isWildcarded), callback });
boolean areConsumers = false;
RegisteredCallbacks rMonitor = null;
// Add the callback to the index of callbacks
addCallbackToConnectionIndex(connection, topicExpression, isWildcarded, callback);
if(isWildcarded)
rMonitor = (RegisteredCallbacks)_registeredWildcardConsumerMonitors.get(topicExpression);
else
rMonitor = (RegisteredCallbacks)_registeredExactConsumerMonitors.get(topicExpression);
// Get the list of callbacks and add the new one
ArrayList callbackList = rMonitor.getWrappedCallbacks();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "Found existing entry with callbacks: " + callbackList);
WrappedConsumerSetChangeCallback wcb = new WrappedConsumerSetChangeCallback(callback);
//F011127
//When we call the registerconsumermonitor() more than once with the same parameter,
//there will be duplicate of callback in callbacklist.To overcome this leak we are checking before adding into the callbacklist
Iterator it = callbackList.iterator();
boolean alreadyExisting = false;
while(it.hasNext()){
WrappedConsumerSetChangeCallback tmpwcb = (WrappedConsumerSetChangeCallback)it.next();
if(tmpwcb.equals(wcb)){
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "The same callback is already registerd for the topic expression :"+topicExpression+" Hence registration will not be done!");
alreadyExisting = true; // depends on control dependency: [if], data = [none]
break;
}
}
if(!alreadyExisting)
callbackList.add(wcb);
// Get the list of matching consumers
ArrayList consumerList = rMonitor.getMatchingConsumers();
// Are there consumers for this expression
areConsumers = !consumerList.isEmpty();
// Don't need to adjust the references in the consumer list as they will
// already have a reference to this topic expression
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "registerCallbackOnExistingExpression", new Boolean(areConsumers));
return areConsumers;
} } |
public class class_name {
public void invokeInfoListener(int what, int extra) {
if (infoListener != null) {
infoListener.onInfo(player, what, extra);
}
} } | public class class_name {
public void invokeInfoListener(int what, int extra) {
if (infoListener != null) {
infoListener.onInfo(player, what, extra); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Q setObjects(final Object... objects) {
int index = 1;
for (final Object object : objects) {
setObject(index++, object);
}
return _this();
} } | public class class_name {
public Q setObjects(final Object... objects) {
int index = 1;
for (final Object object : objects) {
setObject(index++, object); // depends on control dependency: [for], data = [object]
}
return _this();
} } |
public class class_name {
public void setSiteManager(CmsSiteManagerImpl siteManager) {
m_siteManager = siteManager;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SITE_CONFIG_FINISHED_0));
}
} } | public class class_name {
public void setSiteManager(CmsSiteManagerImpl siteManager) {
m_siteManager = siteManager;
if (CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SITE_CONFIG_FINISHED_0)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Nullable
public static KeyedStateHandle chooseTheBestStateHandleForInitial(
@Nonnull Collection<KeyedStateHandle> restoreStateHandles,
@Nonnull KeyGroupRange targetKeyGroupRange) {
KeyedStateHandle bestStateHandle = null;
double bestScore = 0;
for (KeyedStateHandle rawStateHandle : restoreStateHandles) {
double handleScore = STATE_HANDLE_EVALUATOR.apply(rawStateHandle, targetKeyGroupRange);
if (handleScore > bestScore) {
bestStateHandle = rawStateHandle;
bestScore = handleScore;
}
}
return bestStateHandle;
} } | public class class_name {
@Nullable
public static KeyedStateHandle chooseTheBestStateHandleForInitial(
@Nonnull Collection<KeyedStateHandle> restoreStateHandles,
@Nonnull KeyGroupRange targetKeyGroupRange) {
KeyedStateHandle bestStateHandle = null;
double bestScore = 0;
for (KeyedStateHandle rawStateHandle : restoreStateHandles) {
double handleScore = STATE_HANDLE_EVALUATOR.apply(rawStateHandle, targetKeyGroupRange);
if (handleScore > bestScore) {
bestStateHandle = rawStateHandle; // depends on control dependency: [if], data = [none]
bestScore = handleScore; // depends on control dependency: [if], data = [none]
}
}
return bestStateHandle;
} } |
public class class_name {
public Set<Weekday> getSet() {
if (this.set == null) {
HashSet<Weekday> hashSet = new HashSet<Weekday>();
int value = getValue().intValue();
for (Weekday weekday : Weekday.values()) {
int mask = (1 << weekday.ordinal());
if ((value & mask) != 0) {
hashSet.add(weekday);
}
}
this.set = Collections.unmodifiableSet(hashSet);
}
return this.set;
} } | public class class_name {
public Set<Weekday> getSet() {
if (this.set == null) {
HashSet<Weekday> hashSet = new HashSet<Weekday>();
int value = getValue().intValue();
for (Weekday weekday : Weekday.values()) {
int mask = (1 << weekday.ordinal());
if ((value & mask) != 0) {
hashSet.add(weekday); // depends on control dependency: [if], data = [none]
}
}
this.set = Collections.unmodifiableSet(hashSet); // depends on control dependency: [if], data = [none]
}
return this.set;
} } |
public class class_name {
public static String removeIgnoreCase(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
return replaceIgnoreCase(str, remove, EMPTY, -1);
} } | public class class_name {
public static String removeIgnoreCase(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str; // depends on control dependency: [if], data = [none]
}
return replaceIgnoreCase(str, remove, EMPTY, -1);
} } |
public class class_name {
@Override
public synchronized ChannelData[] getRunningChannels() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "getRunningChannels");
}
// Note, runtime has child data objects so duplicates may be found.
List<ChannelData> list = new ArrayList<ChannelData>();
for (ChannelContainer channel : this.channelRunningMap.values()) {
list.add(channel.getChannelData().getParent());
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "getRunningChannels");
}
return list.toArray(new ChannelData[list.size()]);
} } | public class class_name {
@Override
public synchronized ChannelData[] getRunningChannels() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "getRunningChannels"); // depends on control dependency: [if], data = [none]
}
// Note, runtime has child data objects so duplicates may be found.
List<ChannelData> list = new ArrayList<ChannelData>();
for (ChannelContainer channel : this.channelRunningMap.values()) {
list.add(channel.getChannelData().getParent()); // depends on control dependency: [for], data = [channel]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "getRunningChannels"); // depends on control dependency: [if], data = [none]
}
return list.toArray(new ChannelData[list.size()]);
} } |
public class class_name {
public void scrollOnce() {
PagerAdapter adapter = getAdapter();
int currentItem = getCurrentItem();
int totalCount;
if (adapter == null || (totalCount = adapter.getCount()) <= 1) {
return;
}
int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;
if (nextItem < 0) {
if (isCycle) {
setCurrentItem(totalCount - 1, isBorderAnimation);
}
} else if (nextItem == totalCount) {
if (isCycle) {
setCurrentItem(0, isBorderAnimation);
}
} else {
setCurrentItem(nextItem, true);
}
} } | public class class_name {
public void scrollOnce() {
PagerAdapter adapter = getAdapter();
int currentItem = getCurrentItem();
int totalCount;
if (adapter == null || (totalCount = adapter.getCount()) <= 1) {
return; // depends on control dependency: [if], data = [none]
}
int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;
if (nextItem < 0) {
if (isCycle) {
setCurrentItem(totalCount - 1, isBorderAnimation); // depends on control dependency: [if], data = [none]
}
} else if (nextItem == totalCount) {
if (isCycle) {
setCurrentItem(0, isBorderAnimation); // depends on control dependency: [if], data = [none]
}
} else {
setCurrentItem(nextItem, true); // depends on control dependency: [if], data = [(nextItem]
}
} } |
public class class_name {
@Override
protected void addBuildListeners(final Project project) {
// Add the default listener
project.addBuildListener(createLogger());
final int count = args.listeners.size();
for (int i = 0; i < count; i++) {
final String className = args.listeners.elementAt(i);
final BuildListener listener = ClasspathUtils.newInstance(className,
Main.class.getClassLoader(), BuildListener.class);
project.setProjectReference(listener);
project.addBuildListener(listener);
}
} } | public class class_name {
@Override
protected void addBuildListeners(final Project project) {
// Add the default listener
project.addBuildListener(createLogger());
final int count = args.listeners.size();
for (int i = 0; i < count; i++) {
final String className = args.listeners.elementAt(i);
final BuildListener listener = ClasspathUtils.newInstance(className,
Main.class.getClassLoader(), BuildListener.class);
project.setProjectReference(listener); // depends on control dependency: [for], data = [none]
project.addBuildListener(listener); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public static void init(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
/**
* Create a new ID/Credential
*/
authzAPI.route(POST,"/authn/cred",API.CRED_REQ,new Code(facade,"Add a New ID/Credential", true) {
@Override
public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
Result<Void> r = context.createUserCred(trans, req);
if(r.isOK()) {
resp.setStatus(HttpStatus.CREATED_201);
} else {
context.error(trans,resp,r);
}
}
});
/**
* gets all credentials by Namespace
*/
authzAPI.route(GET, "/authn/creds/ns/:ns", API.USERS, new Code(facade,"Get Creds for a Namespace",true) {
@Override
public void handle(
AuthzTrans trans,
HttpServletRequest req,
HttpServletResponse resp) throws Exception {
Result<Void> r = context.getCredsByNS(trans, resp, pathParam(req, "ns"));
if(r.isOK()) {
resp.setStatus(HttpStatus.OK_200);
} else {
context.error(trans,resp,r);
}
}
});
/**
* gets all credentials by ID
*/
authzAPI.route(GET, "/authn/creds/id/:id", API.USERS, new Code(facade,"Get Creds by ID",true) {
@Override
public void handle(
AuthzTrans trans,
HttpServletRequest req,
HttpServletResponse resp) throws Exception {
Result<Void> r = context.getCredsByID(trans, resp, pathParam(req, "id"));
if(r.isOK()) {
resp.setStatus(HttpStatus.OK_200);
} else {
context.error(trans,resp,r);
}
}
});
/**
* Update ID/Credential (aka reset)
*/
authzAPI.route(PUT,"/authn/cred",API.CRED_REQ,new Code(facade,"Update an ID/Credential", true) {
@Override
public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
Result<Void> r = context.changeUserCred(trans, req);
if(r.isOK()) {
resp.setStatus(HttpStatus.OK_200);
} else {
context.error(trans,resp,r);
}
}
});
/**
* Extend ID/Credential
* This behavior will accelerate getting out of P1 outages due to ignoring renewal requests, or
* other expiration issues.
*
* Scenario is that people who are solving Password problems at night, are not necessarily those who
* know what the passwords are supposed to be. Also, changing Password, without changing Configurations
* using that password only exacerbates the P1 Issue.
*/
authzAPI.route(PUT,"/authn/cred/:days",API.CRED_REQ,new Code(facade,"Extend an ID/Credential", true) {
@Override
public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
Result<Void> r = context.extendUserCred(trans, req, pathParam(req, "days"));
if(r.isOK()) {
resp.setStatus(HttpStatus.OK_200);
} else {
context.error(trans,resp,r);
}
}
});
/**
* Delete a ID/Credential by Object
*/
authzAPI.route(DELETE,"/authn/cred",API.CRED_REQ,new Code(facade,"Delete a Credential", true) {
@Override
public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
Result<Void> r = context.deleteUserCred(trans, req);
if(r.isOK()) {
resp.setStatus(HttpStatus.OK_200);
} else {
context.error(trans,resp,r);
}
}
});
} } | public class class_name {
public static void init(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
/**
* Create a new ID/Credential
*/
authzAPI.route(POST,"/authn/cred",API.CRED_REQ,new Code(facade,"Add a New ID/Credential", true) {
@Override
public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
Result<Void> r = context.createUserCred(trans, req);
if(r.isOK()) {
resp.setStatus(HttpStatus.CREATED_201);
} else {
context.error(trans,resp,r);
}
}
});
/**
* gets all credentials by Namespace
*/
authzAPI.route(GET, "/authn/creds/ns/:ns", API.USERS, new Code(facade,"Get Creds for a Namespace",true) {
@Override
public void handle(
AuthzTrans trans,
HttpServletRequest req,
HttpServletResponse resp) throws Exception {
Result<Void> r = context.getCredsByNS(trans, resp, pathParam(req, "ns"));
if(r.isOK()) {
resp.setStatus(HttpStatus.OK_200); // depends on control dependency: [if], data = [none]
} else {
context.error(trans,resp,r); // depends on control dependency: [if], data = [none]
}
}
});
/**
* gets all credentials by ID
*/
authzAPI.route(GET, "/authn/creds/id/:id", API.USERS, new Code(facade,"Get Creds by ID",true) {
@Override
public void handle(
AuthzTrans trans,
HttpServletRequest req,
HttpServletResponse resp) throws Exception {
Result<Void> r = context.getCredsByID(trans, resp, pathParam(req, "id"));
if(r.isOK()) {
resp.setStatus(HttpStatus.OK_200);
} else {
context.error(trans,resp,r);
}
}
});
/**
* Update ID/Credential (aka reset)
*/
authzAPI.route(PUT,"/authn/cred",API.CRED_REQ,new Code(facade,"Update an ID/Credential", true) {
@Override
public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
Result<Void> r = context.changeUserCred(trans, req);
if(r.isOK()) {
resp.setStatus(HttpStatus.OK_200);
} else {
context.error(trans,resp,r);
}
}
});
/**
* Extend ID/Credential
* This behavior will accelerate getting out of P1 outages due to ignoring renewal requests, or
* other expiration issues.
*
* Scenario is that people who are solving Password problems at night, are not necessarily those who
* know what the passwords are supposed to be. Also, changing Password, without changing Configurations
* using that password only exacerbates the P1 Issue.
*/
authzAPI.route(PUT,"/authn/cred/:days",API.CRED_REQ,new Code(facade,"Extend an ID/Credential", true) {
@Override
public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
Result<Void> r = context.extendUserCred(trans, req, pathParam(req, "days"));
if(r.isOK()) {
resp.setStatus(HttpStatus.OK_200);
} else {
context.error(trans,resp,r);
}
}
});
/**
* Delete a ID/Credential by Object
*/
authzAPI.route(DELETE,"/authn/cred",API.CRED_REQ,new Code(facade,"Delete a Credential", true) {
@Override
public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
Result<Void> r = context.deleteUserCred(trans, req);
if(r.isOK()) {
resp.setStatus(HttpStatus.OK_200);
} else {
context.error(trans,resp,r);
}
}
});
} } |
public class class_name {
public void invokeHookEmit(List<Object> values, String stream, Collection<Integer> outTasks) {
if (taskHooks.size() != 0) {
EmitInfo emitInfo = new EmitInfo(values, stream, getThisTaskId(), outTasks);
for (ITaskHook taskHook : taskHooks) {
taskHook.emit(emitInfo);
}
}
} } | public class class_name {
public void invokeHookEmit(List<Object> values, String stream, Collection<Integer> outTasks) {
if (taskHooks.size() != 0) {
EmitInfo emitInfo = new EmitInfo(values, stream, getThisTaskId(), outTasks);
for (ITaskHook taskHook : taskHooks) {
taskHook.emit(emitInfo); // depends on control dependency: [for], data = [taskHook]
}
}
} } |
public class class_name {
protected ProviderInfo selectPinpointProvider(String targetIP, List<ProviderInfo> providerInfos) {
ProviderInfo tp = ProviderHelper.toProviderInfo(targetIP);
for (ProviderInfo providerInfo : providerInfos) {
if (providerInfo.getHost().equals(tp.getHost())
&& StringUtils.equals(providerInfo.getProtocolType(), tp.getProtocolType())
&& providerInfo.getPort() == tp.getPort()) {
return providerInfo;
}
}
return null;
} } | public class class_name {
protected ProviderInfo selectPinpointProvider(String targetIP, List<ProviderInfo> providerInfos) {
ProviderInfo tp = ProviderHelper.toProviderInfo(targetIP);
for (ProviderInfo providerInfo : providerInfos) {
if (providerInfo.getHost().equals(tp.getHost())
&& StringUtils.equals(providerInfo.getProtocolType(), tp.getProtocolType())
&& providerInfo.getPort() == tp.getPort()) {
return providerInfo; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public Map<BenchmarkMethod, Integer> getNumberOfMethodsAndRuns()
throws PerfidixMethodCheckException {
final Map<BenchmarkMethod, Integer> returnVal = new HashMap<BenchmarkMethod, Integer>();
// instantiate objects, just for getting runs
final List<BenchmarkMethod> meths = getBenchmarkMethods();
for (final BenchmarkMethod meth : meths) {
// TODO respect data provider
int numberOfRuns = BenchmarkMethod.getNumberOfAnnotatedRuns(meth
.getMethodToBench());
if (numberOfRuns == Bench.NONE_RUN) {
numberOfRuns = conf.getRuns();
}
returnVal.put(meth, numberOfRuns);
}
return returnVal;
} } | public class class_name {
public Map<BenchmarkMethod, Integer> getNumberOfMethodsAndRuns()
throws PerfidixMethodCheckException {
final Map<BenchmarkMethod, Integer> returnVal = new HashMap<BenchmarkMethod, Integer>();
// instantiate objects, just for getting runs
final List<BenchmarkMethod> meths = getBenchmarkMethods();
for (final BenchmarkMethod meth : meths) {
// TODO respect data provider
int numberOfRuns = BenchmarkMethod.getNumberOfAnnotatedRuns(meth
.getMethodToBench());
if (numberOfRuns == Bench.NONE_RUN) {
numberOfRuns = conf.getRuns(); // depends on control dependency: [if], data = [none]
}
returnVal.put(meth, numberOfRuns);
}
return returnVal;
} } |
public class class_name {
public DescribeEC2InstanceLimitsResult withEC2InstanceLimits(EC2InstanceLimit... eC2InstanceLimits) {
if (this.eC2InstanceLimits == null) {
setEC2InstanceLimits(new java.util.ArrayList<EC2InstanceLimit>(eC2InstanceLimits.length));
}
for (EC2InstanceLimit ele : eC2InstanceLimits) {
this.eC2InstanceLimits.add(ele);
}
return this;
} } | public class class_name {
public DescribeEC2InstanceLimitsResult withEC2InstanceLimits(EC2InstanceLimit... eC2InstanceLimits) {
if (this.eC2InstanceLimits == null) {
setEC2InstanceLimits(new java.util.ArrayList<EC2InstanceLimit>(eC2InstanceLimits.length)); // depends on control dependency: [if], data = [none]
}
for (EC2InstanceLimit ele : eC2InstanceLimits) {
this.eC2InstanceLimits.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@Override
void postProcess(TextView textView, List<BannerComponentNode> bannerComponentNodes) {
if (exitNumber != null) {
LayoutInflater inflater = (LayoutInflater) textView.getContext().getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
ViewGroup root = (ViewGroup) textView.getParent();
TextView exitSignView;
if (modifier.equals(LEFT)) {
exitSignView = (TextView) inflater.inflate(R.layout.exit_sign_view_left, root, false);
} else {
exitSignView = (TextView) inflater.inflate(R.layout.exit_sign_view_right, root, false);
}
exitSignView.setText(exitNumber);
textViewUtils.setImageSpan(textView, exitSignView, startIndex, startIndex + exitNumber
.length());
}
} } | public class class_name {
@Override
void postProcess(TextView textView, List<BannerComponentNode> bannerComponentNodes) {
if (exitNumber != null) {
LayoutInflater inflater = (LayoutInflater) textView.getContext().getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
ViewGroup root = (ViewGroup) textView.getParent();
TextView exitSignView;
if (modifier.equals(LEFT)) {
exitSignView = (TextView) inflater.inflate(R.layout.exit_sign_view_left, root, false); // depends on control dependency: [if], data = [none]
} else {
exitSignView = (TextView) inflater.inflate(R.layout.exit_sign_view_right, root, false); // depends on control dependency: [if], data = [none]
}
exitSignView.setText(exitNumber); // depends on control dependency: [if], data = [(exitNumber]
textViewUtils.setImageSpan(textView, exitSignView, startIndex, startIndex + exitNumber
.length()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static TYPE toTYPE(String type) {
if (null == type || type.trim().isEmpty()) {
return TYPE.OBJECT;
} else {
return TYPE.valueOf(type.toUpperCase());
}
} } | public class class_name {
private static TYPE toTYPE(String type) {
if (null == type || type.trim().isEmpty()) {
return TYPE.OBJECT; // depends on control dependency: [if], data = [none]
} else {
return TYPE.valueOf(type.toUpperCase()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected Validator comeOnHibernateValidator(Supplier<VaConfigSetupper> configSetupperSupplier) {
if (isSuppressHibernateValidatorCache()) {
return createHibernateValidator(configSetupperSupplier);
} else { // basically here
if (cachedValidator != null) {
return cachedValidator;
}
synchronized (ActionValidator.class) {
if (cachedValidator != null) {
return cachedValidator;
}
cachedValidator = createHibernateValidator(configSetupperSupplier);
return cachedValidator;
}
}
} } | public class class_name {
protected Validator comeOnHibernateValidator(Supplier<VaConfigSetupper> configSetupperSupplier) {
if (isSuppressHibernateValidatorCache()) {
return createHibernateValidator(configSetupperSupplier); // depends on control dependency: [if], data = [none]
} else { // basically here
if (cachedValidator != null) {
return cachedValidator; // depends on control dependency: [if], data = [none]
}
synchronized (ActionValidator.class) { // depends on control dependency: [if], data = [none]
if (cachedValidator != null) {
return cachedValidator; // depends on control dependency: [if], data = [none]
}
cachedValidator = createHibernateValidator(configSetupperSupplier);
return cachedValidator;
}
}
} } |
public class class_name {
private static boolean encodeFileToFile(String infile, String outfile)
{
boolean success = false;
java.io.InputStream in = null;
java.io.OutputStream out = null;
try
{
in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);
out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
byte[] buffer = new byte[65536]; // 64K
int read = -1;
while ((read = in.read(buffer)) >= 0)
{
out.write(buffer, 0, read);
} // end while: through file
success = true;
}
catch (java.io.IOException exc)
{
}
finally
{
try
{
in.close();
}
catch (Exception exc)
{
}
try
{
out.close();
}
catch (Exception exc)
{
}
} // end finally
return success;
} } | public class class_name {
private static boolean encodeFileToFile(String infile, String outfile)
{
boolean success = false;
java.io.InputStream in = null;
java.io.OutputStream out = null;
try
{
in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); // depends on control dependency: [try], data = [none]
out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); // depends on control dependency: [try], data = [none]
byte[] buffer = new byte[65536]; // 64K
int read = -1;
while ((read = in.read(buffer)) >= 0)
{
out.write(buffer, 0, read); // depends on control dependency: [while], data = [none]
} // end while: through file
success = true; // depends on control dependency: [try], data = [none]
}
catch (java.io.IOException exc)
{
} // depends on control dependency: [catch], data = [none]
finally
{
try
{
in.close(); // depends on control dependency: [try], data = [none]
}
catch (Exception exc)
{
} // depends on control dependency: [catch], data = [none]
try
{
out.close(); // depends on control dependency: [try], data = [none]
}
catch (Exception exc)
{
} // depends on control dependency: [catch], data = [none]
} // end finally
return success;
} } |
public class class_name {
private void enableClipPathSupportIfNecessary() {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (rippleRoundedCornersPx != 0) {
layerType = getLayerType();
setLayerType(LAYER_TYPE_SOFTWARE, null);
} else {
setLayerType(layerType, null);
}
}
} } | public class class_name {
private void enableClipPathSupportIfNecessary() {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (rippleRoundedCornersPx != 0) {
layerType = getLayerType(); // depends on control dependency: [if], data = [none]
setLayerType(LAYER_TYPE_SOFTWARE, null); // depends on control dependency: [if], data = [none]
} else {
setLayerType(layerType, null); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void histogramToStructure(int histogram[] ) {
col_idx[0] = 0;
int index = 0;
for (int i = 1; i <= numCols; i++) {
col_idx[i] = index += histogram[i-1];
}
nz_length = index;
growMaxLength( nz_length , false);
if( col_idx[numCols] != nz_length )
throw new RuntimeException("Egads");
} } | public class class_name {
public void histogramToStructure(int histogram[] ) {
col_idx[0] = 0;
int index = 0;
for (int i = 1; i <= numCols; i++) {
col_idx[i] = index += histogram[i-1]; // depends on control dependency: [for], data = [i]
}
nz_length = index;
growMaxLength( nz_length , false);
if( col_idx[numCols] != nz_length )
throw new RuntimeException("Egads");
} } |
public class class_name {
public static int getAnnotatedParameterIndex(Method method, Class<? extends Annotation> annotationClass) {
Annotation[][] annotationsForParameters = method.getParameterAnnotations();
for (int i = 0; i < annotationsForParameters.length; i++) {
Annotation[] parameterAnnotations = annotationsForParameters[i];
if (hasAnnotation(parameterAnnotations, annotationClass)) {
return i;
}
}
return -1;
} } | public class class_name {
public static int getAnnotatedParameterIndex(Method method, Class<? extends Annotation> annotationClass) {
Annotation[][] annotationsForParameters = method.getParameterAnnotations();
for (int i = 0; i < annotationsForParameters.length; i++) {
Annotation[] parameterAnnotations = annotationsForParameters[i];
if (hasAnnotation(parameterAnnotations, annotationClass)) {
return i; // depends on control dependency: [if], data = [none]
}
}
return -1;
} } |
public class class_name {
private static List<String> split( String str,
String splitter ) {
StringTokenizer tokens = new StringTokenizer(str, splitter);
ArrayList<String> l = new ArrayList<>(tokens.countTokens());
while (tokens.hasMoreTokens()) {
l.add(tokens.nextToken());
}
return l;
} } | public class class_name {
private static List<String> split( String str,
String splitter ) {
StringTokenizer tokens = new StringTokenizer(str, splitter);
ArrayList<String> l = new ArrayList<>(tokens.countTokens());
while (tokens.hasMoreTokens()) {
l.add(tokens.nextToken()); // depends on control dependency: [while], data = [none]
}
return l;
} } |
public class class_name {
public boolean moveTargetPosition(float[] npos, NavMeshQuery navquery, QueryFilter filter) {
// Move along navmesh and update new position.
Result<MoveAlongSurfaceResult> masResult = navquery.moveAlongSurface(m_path.get(m_path.size() - 1), m_target,
npos, filter);
if (masResult.succeeded()) {
m_path = mergeCorridorEndMoved(m_path, masResult.result.getVisited());
// TODO: should we do that?
// Adjust the position to stay on top of the navmesh.
/*
* float h = m_target[1]; navquery->getPolyHeight(m_path[m_npath-1],
* result, &h); result[1] = h;
*/
vCopy(m_target, masResult.result.getResultPos());
return true;
}
return false;
} } | public class class_name {
public boolean moveTargetPosition(float[] npos, NavMeshQuery navquery, QueryFilter filter) {
// Move along navmesh and update new position.
Result<MoveAlongSurfaceResult> masResult = navquery.moveAlongSurface(m_path.get(m_path.size() - 1), m_target,
npos, filter);
if (masResult.succeeded()) {
m_path = mergeCorridorEndMoved(m_path, masResult.result.getVisited()); // depends on control dependency: [if], data = [none]
// TODO: should we do that?
// Adjust the position to stay on top of the navmesh.
/*
* float h = m_target[1]; navquery->getPolyHeight(m_path[m_npath-1],
* result, &h); result[1] = h;
*/
vCopy(m_target, masResult.result.getResultPos()); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public Collection<String> getNames() {
Collection<String> names = new HashSet<String>();
for (InitParam initParam : initParams) {
names.add(initParam.getName());
}
return names;
} } | public class class_name {
public Collection<String> getNames() {
Collection<String> names = new HashSet<String>();
for (InitParam initParam : initParams) {
names.add(initParam.getName());
// depends on control dependency: [for], data = [initParam]
}
return names;
} } |
public class class_name {
protected void validateNumber(final List<Diagnostic> diags) {
BigDecimal value = getValue();
if (value == null) {
return;
}
BigDecimal min = getComponentModel().minValue;
BigDecimal max = getComponentModel().maxValue;
int decimals = getComponentModel().decimalPlaces;
if (min != null && value.compareTo(min) < 0) {
diags.add(createErrorDiagnostic(InternalMessages.DEFAULT_VALIDATION_ERROR_MIN_VALUE,
this, min));
}
if (max != null && value.compareTo(max) > 0) {
diags.add(createErrorDiagnostic(InternalMessages.DEFAULT_VALIDATION_ERROR_MAX_VALUE,
this, max));
}
if (value.scale() > decimals) {
diags.add(createErrorDiagnostic(
InternalMessages.DEFAULT_VALIDATION_ERROR_MAX_DECIMAL_PLACES, this,
decimals));
}
} } | public class class_name {
protected void validateNumber(final List<Diagnostic> diags) {
BigDecimal value = getValue();
if (value == null) {
return; // depends on control dependency: [if], data = [none]
}
BigDecimal min = getComponentModel().minValue;
BigDecimal max = getComponentModel().maxValue;
int decimals = getComponentModel().decimalPlaces;
if (min != null && value.compareTo(min) < 0) {
diags.add(createErrorDiagnostic(InternalMessages.DEFAULT_VALIDATION_ERROR_MIN_VALUE,
this, min)); // depends on control dependency: [if], data = [none]
}
if (max != null && value.compareTo(max) > 0) {
diags.add(createErrorDiagnostic(InternalMessages.DEFAULT_VALIDATION_ERROR_MAX_VALUE,
this, max)); // depends on control dependency: [if], data = [none]
}
if (value.scale() > decimals) {
diags.add(createErrorDiagnostic(
InternalMessages.DEFAULT_VALIDATION_ERROR_MAX_DECIMAL_PLACES, this,
decimals)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void readPreferences() {
boolean runOnStartup = pref.getBoolean("runOnStartup", true);
getRunOnStartupCheckBox().setSelected(runOnStartup);
int maxCpus = pref.getInt("maxCpus", 0);
if (maxCpus <= 0) {
getLimitCpusCheckBox().setSelected(false);
getMaxCpusTextField().setValue(Runtime.getRuntime().availableProcessors());
getMaxCpusTextField().setEnabled(false);
} else {
getLimitCpusCheckBox().setSelected(true);
getMaxCpusTextField().setValue(maxCpus);
getMaxCpusTextField().setEnabled(true);
}
if (getRequireACCheckBox().isEnabled()) {
boolean requireAC = pref.getBoolean("requireAC", false);
int minBattLife = pref.getInt("minBattLife", 0);
int minBattLifeWhileChg = pref.getInt("minBattLifeWhileChg", 0);
getRequireACCheckBox().setSelected(requireAC);
getMinBatteryLifeSlider().setEnabled(!requireAC);
getMinBatteryLifeSlider().setValue(minBattLife);
getMinBatteryLifeWhileChargingSlider().setValue(minBattLifeWhileChg);
} else {
getRequireACCheckBox().setSelected(false);
getMinBatteryLifeSlider().setValue(0);
getMinBatteryLifeWhileChargingSlider().setValue(0);
getRequireACCheckBox().setEnabled(false);
getMinBatteryLifeSlider().setEnabled(false);
getMinBatteryLifeWhileChargingSlider().setEnabled(false);
}
boolean cacheClassDefinitions = pref.getBoolean("cacheClassDefinitions", true);
getCacheClassDefinitionsCheckBox().setSelected(cacheClassDefinitions);
} } | public class class_name {
private void readPreferences() {
boolean runOnStartup = pref.getBoolean("runOnStartup", true);
getRunOnStartupCheckBox().setSelected(runOnStartup);
int maxCpus = pref.getInt("maxCpus", 0);
if (maxCpus <= 0) {
getLimitCpusCheckBox().setSelected(false); // depends on control dependency: [if], data = [none]
getMaxCpusTextField().setValue(Runtime.getRuntime().availableProcessors()); // depends on control dependency: [if], data = [none]
getMaxCpusTextField().setEnabled(false); // depends on control dependency: [if], data = [none]
} else {
getLimitCpusCheckBox().setSelected(true); // depends on control dependency: [if], data = [none]
getMaxCpusTextField().setValue(maxCpus); // depends on control dependency: [if], data = [(maxCpus]
getMaxCpusTextField().setEnabled(true); // depends on control dependency: [if], data = [none]
}
if (getRequireACCheckBox().isEnabled()) {
boolean requireAC = pref.getBoolean("requireAC", false);
int minBattLife = pref.getInt("minBattLife", 0);
int minBattLifeWhileChg = pref.getInt("minBattLifeWhileChg", 0);
getRequireACCheckBox().setSelected(requireAC); // depends on control dependency: [if], data = [none]
getMinBatteryLifeSlider().setEnabled(!requireAC); // depends on control dependency: [if], data = [none]
getMinBatteryLifeSlider().setValue(minBattLife); // depends on control dependency: [if], data = [none]
getMinBatteryLifeWhileChargingSlider().setValue(minBattLifeWhileChg); // depends on control dependency: [if], data = [none]
} else {
getRequireACCheckBox().setSelected(false); // depends on control dependency: [if], data = [none]
getMinBatteryLifeSlider().setValue(0); // depends on control dependency: [if], data = [none]
getMinBatteryLifeWhileChargingSlider().setValue(0); // depends on control dependency: [if], data = [none]
getRequireACCheckBox().setEnabled(false); // depends on control dependency: [if], data = [none]
getMinBatteryLifeSlider().setEnabled(false); // depends on control dependency: [if], data = [none]
getMinBatteryLifeWhileChargingSlider().setEnabled(false); // depends on control dependency: [if], data = [none]
}
boolean cacheClassDefinitions = pref.getBoolean("cacheClassDefinitions", true);
getCacheClassDefinitionsCheckBox().setSelected(cacheClassDefinitions);
} } |
public class class_name {
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
} } | public class class_name {
public static String getExtension(String uri) {
if (uri == null) {
return null; // depends on control dependency: [if], data = [none]
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot); // depends on control dependency: [if], data = [(dot]
} else {
// No extension.
return ""; // depends on control dependency: [if], data = [none]
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.