code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
protected String buildOpenCmsButtonRow(I_CmsWidgetDialog widgetDialog, String paramId) {
StringBuffer result = new StringBuffer(2048);
// flag indicating if at least one button is active
boolean buttonsActive = false;
// generate button row start HTML
result.append(buildOpenCmsButtonRow(CmsWorkplace.HTML_START, widgetDialog));
// build the link buttons
if (getHtmlWidgetOption().showLinkDialog()) {
result.append(
widgetDialog.button(
"javascript:setActiveEditor('"
+ paramId
+ "');openLinkDialog('"
+ Messages.get().getBundle(widgetDialog.getLocale()).key(Messages.GUI_BUTTON_LINKTO_0)
+ "');",
null,
"link",
"button.linkto",
widgetDialog.getButtonStyle()));
buttonsActive = true;
}
if (getHtmlWidgetOption().showAnchorDialog()) {
result.append(
widgetDialog.button(
"javascript:setActiveEditor('"
+ paramId
+ "');openAnchorDialog('"
+ Messages.get().getBundle(widgetDialog.getLocale()).key(
Messages.ERR_EDITOR_MESSAGE_NOSELECTION_0)
+ "');",
null,
"anchor",
Messages.GUI_BUTTON_ANCHOR_0,
widgetDialog.getButtonStyle()));
buttonsActive = true;
}
if (!buttonsActive) {
// no active buttons to show, return empty String
return "";
}
// generate button row end HTML
result.append(buildOpenCmsButtonRow(CmsWorkplace.HTML_END, widgetDialog));
// show the active buttons
return result.toString();
} } | public class class_name {
protected String buildOpenCmsButtonRow(I_CmsWidgetDialog widgetDialog, String paramId) {
StringBuffer result = new StringBuffer(2048);
// flag indicating if at least one button is active
boolean buttonsActive = false;
// generate button row start HTML
result.append(buildOpenCmsButtonRow(CmsWorkplace.HTML_START, widgetDialog));
// build the link buttons
if (getHtmlWidgetOption().showLinkDialog()) {
result.append(
widgetDialog.button(
"javascript:setActiveEditor('"
+ paramId
+ "');openLinkDialog('"
+ Messages.get().getBundle(widgetDialog.getLocale()).key(Messages.GUI_BUTTON_LINKTO_0)
+ "');",
null,
"link",
"button.linkto",
widgetDialog.getButtonStyle())); // depends on control dependency: [if], data = [none]
buttonsActive = true; // depends on control dependency: [if], data = [none]
}
if (getHtmlWidgetOption().showAnchorDialog()) {
result.append(
widgetDialog.button(
"javascript:setActiveEditor('"
+ paramId
+ "');openAnchorDialog('"
+ Messages.get().getBundle(widgetDialog.getLocale()).key(
Messages.ERR_EDITOR_MESSAGE_NOSELECTION_0)
+ "');",
null,
"anchor",
Messages.GUI_BUTTON_ANCHOR_0,
widgetDialog.getButtonStyle())); // depends on control dependency: [if], data = [none]
buttonsActive = true; // depends on control dependency: [if], data = [none]
}
if (!buttonsActive) {
// no active buttons to show, return empty String
return ""; // depends on control dependency: [if], data = [none]
}
// generate button row end HTML
result.append(buildOpenCmsButtonRow(CmsWorkplace.HTML_END, widgetDialog));
// show the active buttons
return result.toString();
} } |
public class class_name {
public static double blackScholesOptionImpliedVolatility(
double forward,
double optionMaturity,
double optionStrike,
double payoffUnit,
double optionValue)
{
// Limit the maximum number of iterations, to ensure this calculation returns fast, e.g. in cases when there is no such thing as an implied vol
// TODO: An exception should be thrown, when there is no implied volatility for the given value.
int maxIterations = 500;
double maxAccuracy = 1E-15;
if(optionStrike <= 0.0)
{
// Actually it is not an option
return 0.0;
}
else
{
// Calculate an lower and upper bound for the volatility
double p = NormalDistribution.inverseCumulativeDistribution((optionValue/payoffUnit+optionStrike)/(forward+optionStrike)) / Math.sqrt(optionMaturity);
double q = 2.0 * Math.abs(Math.log(forward/optionStrike)) / optionMaturity;
double volatilityLowerBound = p + Math.sqrt(Math.max(p * p - q, 0.0));
double volatilityUpperBound = p + Math.sqrt( p * p + q );
// If strike is close to forward the two bounds are close to the analytic solution
if(Math.abs(volatilityLowerBound - volatilityUpperBound) < maxAccuracy) {
return (volatilityLowerBound+volatilityUpperBound) / 2.0;
}
// Solve for implied volatility
NewtonsMethod solver = new NewtonsMethod(0.5*(volatilityLowerBound+volatilityUpperBound) /* guess */);
while(solver.getAccuracy() > maxAccuracy && !solver.isDone() && solver.getNumberOfIterations() < maxIterations) {
double volatility = solver.getNextPoint();
// Calculate analytic value
double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit;
double derivativeAnalytic = forward * Math.sqrt(optionMaturity) * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0*Math.PI) * payoffUnit;
double error = valueAnalytic - optionValue;
solver.setValueAndDerivative(error,derivativeAnalytic);
}
return solver.getBestPoint();
}
} } | public class class_name {
public static double blackScholesOptionImpliedVolatility(
double forward,
double optionMaturity,
double optionStrike,
double payoffUnit,
double optionValue)
{
// Limit the maximum number of iterations, to ensure this calculation returns fast, e.g. in cases when there is no such thing as an implied vol
// TODO: An exception should be thrown, when there is no implied volatility for the given value.
int maxIterations = 500;
double maxAccuracy = 1E-15;
if(optionStrike <= 0.0)
{
// Actually it is not an option
return 0.0; // depends on control dependency: [if], data = [none]
}
else
{
// Calculate an lower and upper bound for the volatility
double p = NormalDistribution.inverseCumulativeDistribution((optionValue/payoffUnit+optionStrike)/(forward+optionStrike)) / Math.sqrt(optionMaturity);
double q = 2.0 * Math.abs(Math.log(forward/optionStrike)) / optionMaturity;
double volatilityLowerBound = p + Math.sqrt(Math.max(p * p - q, 0.0));
double volatilityUpperBound = p + Math.sqrt( p * p + q );
// If strike is close to forward the two bounds are close to the analytic solution
if(Math.abs(volatilityLowerBound - volatilityUpperBound) < maxAccuracy) {
return (volatilityLowerBound+volatilityUpperBound) / 2.0; // depends on control dependency: [if], data = [none]
}
// Solve for implied volatility
NewtonsMethod solver = new NewtonsMethod(0.5*(volatilityLowerBound+volatilityUpperBound) /* guess */);
while(solver.getAccuracy() > maxAccuracy && !solver.isDone() && solver.getNumberOfIterations() < maxIterations) {
double volatility = solver.getNextPoint();
// Calculate analytic value
double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit;
double derivativeAnalytic = forward * Math.sqrt(optionMaturity) * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0*Math.PI) * payoffUnit;
double error = valueAnalytic - optionValue;
solver.setValueAndDerivative(error,derivativeAnalytic); // depends on control dependency: [while], data = [none]
}
return solver.getBestPoint(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public BufferedImage rotate() {
BufferedImage dest = new BufferedImage(height, width,
BufferedImage.TYPE_INT_ARGB);
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++) {
dest.setRGB(height - j - 1, i, image.getRGB(i, j));
}
image = dest;
return image;
} } | public class class_name {
public BufferedImage rotate() {
BufferedImage dest = new BufferedImage(height, width,
BufferedImage.TYPE_INT_ARGB);
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++) {
dest.setRGB(height - j - 1, i, image.getRGB(i, j)); // depends on control dependency: [for], data = [j]
}
image = dest;
return image;
} } |
public class class_name {
private void queryForCoursesWithMaxStudentCount() {
//TODO `MAX` in queries doesn't work yet, so we use navigation
Extent<Course> courses = pm.getExtent(Course.class);
Course maxCourse = null;
int maxStudents = -1;
for (Course c: courses) {
if (c.getStudents().size() > maxStudents) {
maxStudents = c.getStudents().size();
maxCourse = c;
}
}
if (maxCourse != null) {
System.out.println(">> Query for course with most students returned: " +
maxCourse.getName());
} else {
System.out.println(">> Query for course with most students returned no courses.");
}
} } | public class class_name {
private void queryForCoursesWithMaxStudentCount() {
//TODO `MAX` in queries doesn't work yet, so we use navigation
Extent<Course> courses = pm.getExtent(Course.class);
Course maxCourse = null;
int maxStudents = -1;
for (Course c: courses) {
if (c.getStudents().size() > maxStudents) {
maxStudents = c.getStudents().size(); // depends on control dependency: [if], data = [none]
maxCourse = c; // depends on control dependency: [if], data = [none]
}
}
if (maxCourse != null) {
System.out.println(">> Query for course with most students returned: " +
maxCourse.getName());
} else {
System.out.println(">> Query for course with most students returned no courses."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
MolgenisValidationException translateNotNullViolation(PSQLException pSqlException) {
ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage();
String tableName = serverErrorMessage.getTable();
String message = serverErrorMessage.getMessage();
Matcher matcher =
Pattern.compile("null value in column \"?(.*?)\"? violates not-null constraint")
.matcher(message);
boolean matches = matcher.matches();
if (matches) {
// exception message when adding data that does not match constraint
String columnName = matcher.group(1);
EntityTypeDescription entityTypeDescription =
entityTypeRegistry.getEntityTypeDescription(tableName);
entityTypeDescription.getAttributeDescriptionMap().get(columnName);
ConstraintViolation constraintViolation =
new ConstraintViolation(
format(
"The attribute '%s' of entity '%s' can not be null.",
tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)),
null);
return new MolgenisValidationException(singleton(constraintViolation));
} else {
// exception message when applying constraint on existing data
matcher = Pattern.compile("column \"(.*?)\" contains null values").matcher(message);
matches = matcher.matches();
if (!matches) {
throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
}
String columnName = matcher.group(1);
ConstraintViolation constraintViolation =
new ConstraintViolation(
format(
"The attribute '%s' of entity '%s' contains null values.",
tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)),
null);
return new MolgenisValidationException(singleton(constraintViolation));
}
} } | public class class_name {
MolgenisValidationException translateNotNullViolation(PSQLException pSqlException) {
ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage();
String tableName = serverErrorMessage.getTable();
String message = serverErrorMessage.getMessage();
Matcher matcher =
Pattern.compile("null value in column \"?(.*?)\"? violates not-null constraint")
.matcher(message);
boolean matches = matcher.matches();
if (matches) {
// exception message when adding data that does not match constraint
String columnName = matcher.group(1);
EntityTypeDescription entityTypeDescription =
entityTypeRegistry.getEntityTypeDescription(tableName);
entityTypeDescription.getAttributeDescriptionMap().get(columnName); // depends on control dependency: [if], data = [none]
ConstraintViolation constraintViolation =
new ConstraintViolation(
format(
"The attribute '%s' of entity '%s' can not be null.",
tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)),
null);
return new MolgenisValidationException(singleton(constraintViolation)); // depends on control dependency: [if], data = [none]
} else {
// exception message when applying constraint on existing data
matcher = Pattern.compile("column \"(.*?)\" contains null values").matcher(message); // depends on control dependency: [if], data = [none]
matches = matcher.matches(); // depends on control dependency: [if], data = [none]
if (!matches) {
throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
}
String columnName = matcher.group(1);
ConstraintViolation constraintViolation =
new ConstraintViolation(
format(
"The attribute '%s' of entity '%s' contains null values.",
tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)),
null);
return new MolgenisValidationException(singleton(constraintViolation)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void initContextMenu() {
m_contextMenu.removeItems();
MenuItem main = m_contextMenu.addItem("", null);
main.setIcon(FontOpenCms.CONTEXT_MENU);
main.setDescription(CmsVaadinUtils.getMessageText(Messages.GUI_MENU_TITLE_0));
CmsContextMenuTreeBuilder treeBuilder = new CmsContextMenuTreeBuilder(getDialogContext());
CmsTreeNode<I_CmsContextMenuItem> tree = treeBuilder.buildAll(
OpenCms.getWorkplaceAppManager().getMenuItemProvider().getMenuItems());
for (CmsTreeNode<I_CmsContextMenuItem> node : tree.getChildren()) {
createMenuEntry(main, node, treeBuilder);
}
} } | public class class_name {
private void initContextMenu() {
m_contextMenu.removeItems();
MenuItem main = m_contextMenu.addItem("", null);
main.setIcon(FontOpenCms.CONTEXT_MENU);
main.setDescription(CmsVaadinUtils.getMessageText(Messages.GUI_MENU_TITLE_0));
CmsContextMenuTreeBuilder treeBuilder = new CmsContextMenuTreeBuilder(getDialogContext());
CmsTreeNode<I_CmsContextMenuItem> tree = treeBuilder.buildAll(
OpenCms.getWorkplaceAppManager().getMenuItemProvider().getMenuItems());
for (CmsTreeNode<I_CmsContextMenuItem> node : tree.getChildren()) {
createMenuEntry(main, node, treeBuilder); // depends on control dependency: [for], data = [node]
}
} } |
public class class_name {
public static SendRequest childPaysForParent(Wallet wallet, Transaction parentTransaction, Coin feeRaise) {
TransactionOutput outputToSpend = null;
for (final TransactionOutput output : parentTransaction.getOutputs()) {
if (output.isMine(wallet) && output.isAvailableForSpending()
&& output.getValue().isGreaterThan(feeRaise)) {
outputToSpend = output;
break;
}
}
// TODO spend another confirmed output of own wallet if needed
checkNotNull(outputToSpend, "Can't find adequately sized output that spends to us");
final Transaction tx = new Transaction(parentTransaction.getParams());
tx.addInput(outputToSpend);
tx.addOutput(outputToSpend.getValue().subtract(feeRaise), wallet.freshAddress(KeyPurpose.CHANGE));
tx.setPurpose(Transaction.Purpose.RAISE_FEE);
final SendRequest req = forTx(tx);
req.completed = true;
return req;
} } | public class class_name {
public static SendRequest childPaysForParent(Wallet wallet, Transaction parentTransaction, Coin feeRaise) {
TransactionOutput outputToSpend = null;
for (final TransactionOutput output : parentTransaction.getOutputs()) {
if (output.isMine(wallet) && output.isAvailableForSpending()
&& output.getValue().isGreaterThan(feeRaise)) {
outputToSpend = output; // depends on control dependency: [if], data = [none]
break;
}
}
// TODO spend another confirmed output of own wallet if needed
checkNotNull(outputToSpend, "Can't find adequately sized output that spends to us");
final Transaction tx = new Transaction(parentTransaction.getParams());
tx.addInput(outputToSpend);
tx.addOutput(outputToSpend.getValue().subtract(feeRaise), wallet.freshAddress(KeyPurpose.CHANGE));
tx.setPurpose(Transaction.Purpose.RAISE_FEE);
final SendRequest req = forTx(tx);
req.completed = true;
return req;
} } |
public class class_name {
public DetectTextResult withTextDetections(TextDetection... textDetections) {
if (this.textDetections == null) {
setTextDetections(new java.util.ArrayList<TextDetection>(textDetections.length));
}
for (TextDetection ele : textDetections) {
this.textDetections.add(ele);
}
return this;
} } | public class class_name {
public DetectTextResult withTextDetections(TextDetection... textDetections) {
if (this.textDetections == null) {
setTextDetections(new java.util.ArrayList<TextDetection>(textDetections.length)); // depends on control dependency: [if], data = [none]
}
for (TextDetection ele : textDetections) {
this.textDetections.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@Override
public Set<EmbeddableType<?>> getEmbeddables()
{
Set embeddableEntities = null;
if (embeddables != null)
{
embeddableEntities = new HashSet(embeddables.values());
}
return embeddableEntities;
} } | public class class_name {
@Override
public Set<EmbeddableType<?>> getEmbeddables()
{
Set embeddableEntities = null;
if (embeddables != null)
{
embeddableEntities = new HashSet(embeddables.values());
// depends on control dependency: [if], data = [(embeddables]
}
return embeddableEntities;
} } |
public class class_name {
public void merge(final List<ResteasyDeploymentData> deploymentData) throws DeploymentUnitProcessingException {
for (ResteasyDeploymentData data : deploymentData) {
scannedApplicationClasses.addAll(data.getScannedApplicationClasses());
if (scanResources) {
scannedResourceClasses.addAll(data.getScannedResourceClasses());
scannedJndiComponentResources.addAll(data.getScannedJndiComponentResources());
}
if (scanProviders) {
scannedProviderClasses.addAll(data.getScannedProviderClasses());
}
}
} } | public class class_name {
public void merge(final List<ResteasyDeploymentData> deploymentData) throws DeploymentUnitProcessingException {
for (ResteasyDeploymentData data : deploymentData) {
scannedApplicationClasses.addAll(data.getScannedApplicationClasses());
if (scanResources) {
scannedResourceClasses.addAll(data.getScannedResourceClasses()); // depends on control dependency: [if], data = [none]
scannedJndiComponentResources.addAll(data.getScannedJndiComponentResources()); // depends on control dependency: [if], data = [none]
}
if (scanProviders) {
scannedProviderClasses.addAll(data.getScannedProviderClasses()); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public Integer getLength()
{
if(childNode.getAttribute("length") != null && !childNode.getAttribute("length").equals("null"))
{
return Integer.valueOf(childNode.getAttribute("length"));
}
return null;
} } | public class class_name {
public Integer getLength()
{
if(childNode.getAttribute("length") != null && !childNode.getAttribute("length").equals("null"))
{
return Integer.valueOf(childNode.getAttribute("length")); // depends on control dependency: [if], data = [(childNode.getAttribute("length")]
}
return null;
} } |
public class class_name {
public void setSubjectAlternativeNames(java.util.Collection<String> subjectAlternativeNames) {
if (subjectAlternativeNames == null) {
this.subjectAlternativeNames = null;
return;
}
this.subjectAlternativeNames = new java.util.ArrayList<String>(subjectAlternativeNames);
} } | public class class_name {
public void setSubjectAlternativeNames(java.util.Collection<String> subjectAlternativeNames) {
if (subjectAlternativeNames == null) {
this.subjectAlternativeNames = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.subjectAlternativeNames = new java.util.ArrayList<String>(subjectAlternativeNames);
} } |
public class class_name {
public boolean contains(ChronoInterval<T> interval) {
for (ChronoInterval<T> i : this.intervals) {
if (i.equals(interval)) {
return true;
}
}
return false;
} } | public class class_name {
public boolean contains(ChronoInterval<T> interval) {
for (ChronoInterval<T> i : this.intervals) {
if (i.equals(interval)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
@Override
public Iterable<Long> ids() {
return new Iterable<Long>() {
/**
* {@inheritDoc}
*/
@Override
public Iterator<Long> iterator() {
return new Iterator<Long>() {
int index = -1;
private Iterator<Long> currentResults = null;
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
boolean hasNext = false;
if (currentResults != null) {
hasNext = currentResults.hasNext();
}
if (!hasNext) {
while (!hasNext && ++index < results.size()) {
// Get an iterator from the next feature index
// results
currentResults = results.get(index).ids()
.iterator();
hasNext = currentResults.hasNext();
}
}
return hasNext;
}
/**
* {@inheritDoc}
*/
@Override
public Long next() {
Long id = null;
if (currentResults != null) {
id = currentResults.next();
}
return id;
}
};
}
};
} } | public class class_name {
@Override
public Iterable<Long> ids() {
return new Iterable<Long>() {
/**
* {@inheritDoc}
*/
@Override
public Iterator<Long> iterator() {
return new Iterator<Long>() {
int index = -1;
private Iterator<Long> currentResults = null;
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
boolean hasNext = false;
if (currentResults != null) {
hasNext = currentResults.hasNext(); // depends on control dependency: [if], data = [none]
}
if (!hasNext) {
while (!hasNext && ++index < results.size()) {
// Get an iterator from the next feature index
// results
currentResults = results.get(index).ids()
.iterator(); // depends on control dependency: [while], data = [none]
hasNext = currentResults.hasNext(); // depends on control dependency: [while], data = [none]
}
}
return hasNext;
}
/**
* {@inheritDoc}
*/
@Override
public Long next() {
Long id = null;
if (currentResults != null) {
id = currentResults.next(); // depends on control dependency: [if], data = [none]
}
return id;
}
};
}
};
} } |
public class class_name {
public Map<String, Serializable> getState() {
Map<String, Serializable> ret = new HashMap<>();
// get potential eviction policy state
if (evictionPolicy.getState() != null) {
ret.put(EVICTION_STATE_KEY, (Serializable) evictionPolicy.getState());
}
// get potential trigger policy state
if (triggerPolicy.getState() != null) {
ret.put(TRIGGER_STATE_KEY, (Serializable) triggerPolicy.getState());
}
ret.put(QUEUE, (Serializable) this.queue);
ret.put(EXPIRED_EVENTS, (Serializable) this.expiredEvents);
ret.put(PRE_WINDOW_EVENTS, (Serializable) this.prevWindowEvents);
ret.put(EVENTS_SINCE_LAST_EXPIRY, this.eventsSinceLastExpiry.get());
return ret;
} } | public class class_name {
public Map<String, Serializable> getState() {
Map<String, Serializable> ret = new HashMap<>();
// get potential eviction policy state
if (evictionPolicy.getState() != null) {
ret.put(EVICTION_STATE_KEY, (Serializable) evictionPolicy.getState()); // depends on control dependency: [if], data = [none]
}
// get potential trigger policy state
if (triggerPolicy.getState() != null) {
ret.put(TRIGGER_STATE_KEY, (Serializable) triggerPolicy.getState()); // depends on control dependency: [if], data = [none]
}
ret.put(QUEUE, (Serializable) this.queue);
ret.put(EXPIRED_EVENTS, (Serializable) this.expiredEvents);
ret.put(PRE_WINDOW_EVENTS, (Serializable) this.prevWindowEvents);
ret.put(EVENTS_SINCE_LAST_EXPIRY, this.eventsSinceLastExpiry.get());
return ret;
} } |
public class class_name {
private Node<T> moveRedRight(Node<T> h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.right) && !isRed(h.right.left);
flipColors(h);
if (h.left.left != null && h.left.left.red) {
h = rotateRight(h);
flipColors(h);
}
return h;
} } | public class class_name {
private Node<T> moveRedRight(Node<T> h) {
// assert (h != null);
// assert isRed(h) && !isRed(h.right) && !isRed(h.right.left);
flipColors(h);
if (h.left.left != null && h.left.left.red) {
h = rotateRight(h);
// depends on control dependency: [if], data = [none]
flipColors(h);
// depends on control dependency: [if], data = [none]
}
return h;
} } |
public class class_name {
public void marshall(GetClientCertificatesRequest getClientCertificatesRequest, ProtocolMarshaller protocolMarshaller) {
if (getClientCertificatesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getClientCertificatesRequest.getPosition(), POSITION_BINDING);
protocolMarshaller.marshall(getClientCertificatesRequest.getLimit(), LIMIT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(GetClientCertificatesRequest getClientCertificatesRequest, ProtocolMarshaller protocolMarshaller) {
if (getClientCertificatesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getClientCertificatesRequest.getPosition(), POSITION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(getClientCertificatesRequest.getLimit(), LIMIT_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void addAll(Configuration other, String prefix) {
final StringBuilder bld = new StringBuilder();
bld.append(prefix);
final int pl = bld.length();
synchronized (this.confData) {
synchronized (other.confData) {
for (Map.Entry<String, Object> entry : other.confData.entrySet()) {
bld.setLength(pl);
bld.append(entry.getKey());
this.confData.put(bld.toString(), entry.getValue());
}
}
}
} } | public class class_name {
public void addAll(Configuration other, String prefix) {
final StringBuilder bld = new StringBuilder();
bld.append(prefix);
final int pl = bld.length();
synchronized (this.confData) {
synchronized (other.confData) {
for (Map.Entry<String, Object> entry : other.confData.entrySet()) {
bld.setLength(pl); // depends on control dependency: [for], data = [none]
bld.append(entry.getKey()); // depends on control dependency: [for], data = [entry]
this.confData.put(bld.toString(), entry.getValue()); // depends on control dependency: [for], data = [entry]
}
}
}
} } |
public class class_name {
private void updateArtworkType(List<Artwork> artworkList, ArtworkType type) {
for (Artwork artwork : artworkList) {
artwork.setArtworkType(type);
}
} } | public class class_name {
private void updateArtworkType(List<Artwork> artworkList, ArtworkType type) {
for (Artwork artwork : artworkList) {
artwork.setArtworkType(type); // depends on control dependency: [for], data = [artwork]
}
} } |
public class class_name {
public static synchronized void subscribe(String key, RpcConfigListener listener) {
List<RpcConfigListener> listeners = CFG_LISTENER.get(key);
if (listeners == null) {
listeners = new ArrayList<RpcConfigListener>();
CFG_LISTENER.put(key, listeners);
}
listeners.add(listener);
} } | public class class_name {
public static synchronized void subscribe(String key, RpcConfigListener listener) {
List<RpcConfigListener> listeners = CFG_LISTENER.get(key);
if (listeners == null) {
listeners = new ArrayList<RpcConfigListener>(); // depends on control dependency: [if], data = [none]
CFG_LISTENER.put(key, listeners); // depends on control dependency: [if], data = [none]
}
listeners.add(listener);
} } |
public class class_name {
protected void parseProcessEnginePlugin(Element element, List<ProcessEnginePluginXml> plugins) {
ProcessEnginePluginXmlImpl plugin = new ProcessEnginePluginXmlImpl();
Map<String, String> properties = new HashMap<String, String>();
for (Element childElement : element.elements()) {
if(PLUGIN_CLASS.equals(childElement.getTagName())) {
plugin.setPluginClass(childElement.getText());
} else if(PROPERTIES.equals(childElement.getTagName())) {
parseProperties(childElement, properties);
}
}
plugin.setProperties(properties);
plugins.add(plugin);
} } | public class class_name {
protected void parseProcessEnginePlugin(Element element, List<ProcessEnginePluginXml> plugins) {
ProcessEnginePluginXmlImpl plugin = new ProcessEnginePluginXmlImpl();
Map<String, String> properties = new HashMap<String, String>();
for (Element childElement : element.elements()) {
if(PLUGIN_CLASS.equals(childElement.getTagName())) {
plugin.setPluginClass(childElement.getText()); // depends on control dependency: [if], data = [none]
} else if(PROPERTIES.equals(childElement.getTagName())) {
parseProperties(childElement, properties); // depends on control dependency: [if], data = [none]
}
}
plugin.setProperties(properties);
plugins.add(plugin);
} } |
public class class_name {
public OrganizationModel attachOrganization(ArchiveModel archiveModel, String organizationName)
{
OrganizationModel model = getUnique(getQuery().traverse(g -> g.has(OrganizationModel.NAME, organizationName)).getRawTraversal());
if (model == null)
{
model = create();
model.setName(organizationName);
model.addArchiveModel(archiveModel);
}
else
{
return attachOrganization(model, archiveModel);
}
return model;
} } | public class class_name {
public OrganizationModel attachOrganization(ArchiveModel archiveModel, String organizationName)
{
OrganizationModel model = getUnique(getQuery().traverse(g -> g.has(OrganizationModel.NAME, organizationName)).getRawTraversal());
if (model == null)
{
model = create(); // depends on control dependency: [if], data = [none]
model.setName(organizationName); // depends on control dependency: [if], data = [none]
model.addArchiveModel(archiveModel); // depends on control dependency: [if], data = [none]
}
else
{
return attachOrganization(model, archiveModel); // depends on control dependency: [if], data = [(model]
}
return model;
} } |
public class class_name {
@Override
public String getAttributeValue(final int fingerprint) {
String attVal = null;
final NameTest test = new NameTest(Type.ATTRIBUTE, fingerprint, getNamePool());
final AxisIterator iterator = iterateAxis(Axis.ATTRIBUTE, test);
final NodeInfo attribute = (NodeInfo)iterator.next();
if (attribute != null) {
attVal = attribute.getStringValue();
}
return attVal;
} } | public class class_name {
@Override
public String getAttributeValue(final int fingerprint) {
String attVal = null;
final NameTest test = new NameTest(Type.ATTRIBUTE, fingerprint, getNamePool());
final AxisIterator iterator = iterateAxis(Axis.ATTRIBUTE, test);
final NodeInfo attribute = (NodeInfo)iterator.next();
if (attribute != null) {
attVal = attribute.getStringValue(); // depends on control dependency: [if], data = [none]
}
return attVal;
} } |
public class class_name {
public void assign(RuleContext ruleContext, Object value, List<ProxyField> list)
{
for (ProxyField proxyField: list)
{
assign(getRuleProxyField(proxyField),value,ruleContext,true);
}
} } | public class class_name {
public void assign(RuleContext ruleContext, Object value, List<ProxyField> list)
{
for (ProxyField proxyField: list)
{
assign(getRuleProxyField(proxyField),value,ruleContext,true); // depends on control dependency: [for], data = [proxyField]
}
} } |
public class class_name {
public static <E extends Comparable> void retainTopKeyComparable(Counter<E> c, int num) {
int numToPurge = c.size() - num;
if (numToPurge <= 0) {
return;
}
List<E> l = Counters.toSortedListKeyComparable(c);
Collections.reverse(l);
for (int i = 0; i < numToPurge; i++) {
c.remove(l.get(i));
}
} } | public class class_name {
public static <E extends Comparable> void retainTopKeyComparable(Counter<E> c, int num) {
int numToPurge = c.size() - num;
if (numToPurge <= 0) {
return;
// depends on control dependency: [if], data = [none]
}
List<E> l = Counters.toSortedListKeyComparable(c);
Collections.reverse(l);
for (int i = 0; i < numToPurge; i++) {
c.remove(l.get(i));
// depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
protected void shutdown(Presence unavailablePresence) {
// Set presence to offline.
if (packetWriter != null) {
packetWriter.sendPacket(unavailablePresence);
}
this.setWasAuthenticated(authenticated);
authenticated = false;
if (packetReader != null) {
packetReader.shutdown();
}
if (packetWriter != null) {
packetWriter.shutdown();
}
// Wait 150 ms for processes to clean-up, then shutdown.
try {
Thread.sleep(150);
} catch (Exception e) {
// Ignore.
}
// Set socketClosed to true. This will cause the PacketReader
// and PacketWriter to ignore any Exceptions that are thrown
// because of a read/write from/to a closed stream.
// It is *important* that this is done before socket.close()!
socketClosed = true;
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
for (Plugin plugin : plugins) {
plugin.shutdown();
}
// In most cases the close() should be successful, so set
// connected to false here.
connected = false;
reader = null;
writer = null;
saslAuthentication.init();
} } | public class class_name {
protected void shutdown(Presence unavailablePresence) {
// Set presence to offline.
if (packetWriter != null) {
packetWriter.sendPacket(unavailablePresence); // depends on control dependency: [if], data = [none]
}
this.setWasAuthenticated(authenticated);
authenticated = false;
if (packetReader != null) {
packetReader.shutdown(); // depends on control dependency: [if], data = [none]
}
if (packetWriter != null) {
packetWriter.shutdown(); // depends on control dependency: [if], data = [none]
}
// Wait 150 ms for processes to clean-up, then shutdown.
try {
Thread.sleep(150); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// Ignore.
} // depends on control dependency: [catch], data = [none]
// Set socketClosed to true. This will cause the PacketReader
// and PacketWriter to ignore any Exceptions that are thrown
// because of a read/write from/to a closed stream.
// It is *important* that this is done before socket.close()!
socketClosed = true;
try {
socket.close(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
for (Plugin plugin : plugins) {
plugin.shutdown(); // depends on control dependency: [for], data = [plugin]
}
// In most cases the close() should be successful, so set
// connected to false here.
connected = false;
reader = null;
writer = null;
saslAuthentication.init();
} } |
public class class_name {
private static void putGoogleAnalyticsTrackingIdIntoFlowScope(final RequestContext context, final String value) {
if (StringUtils.isBlank(value)) {
context.getFlowScope().remove(ATTRIBUTE_FLOWSCOPE_GOOGLE_ANALYTICS_TRACKING_ID);
} else {
context.getFlowScope().put(ATTRIBUTE_FLOWSCOPE_GOOGLE_ANALYTICS_TRACKING_ID, value);
}
} } | public class class_name {
private static void putGoogleAnalyticsTrackingIdIntoFlowScope(final RequestContext context, final String value) {
if (StringUtils.isBlank(value)) {
context.getFlowScope().remove(ATTRIBUTE_FLOWSCOPE_GOOGLE_ANALYTICS_TRACKING_ID); // depends on control dependency: [if], data = [none]
} else {
context.getFlowScope().put(ATTRIBUTE_FLOWSCOPE_GOOGLE_ANALYTICS_TRACKING_ID, value); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(StartGatewayRequest startGatewayRequest, ProtocolMarshaller protocolMarshaller) {
if (startGatewayRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startGatewayRequest.getGatewayARN(), GATEWAYARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(StartGatewayRequest startGatewayRequest, ProtocolMarshaller protocolMarshaller) {
if (startGatewayRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startGatewayRequest.getGatewayARN(), GATEWAYARN_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void addTokens(String metadata, StringTokenizer tokens) {
Node mnode = this.rootCond.addToken(metadata);
Node thenode = mnode;
while (tokens.hasMoreTokens()) {
Node newnode = thenode.addToken(tokens.nextToken());
thenode = newnode;
}
} } | public class class_name {
public void addTokens(String metadata, StringTokenizer tokens) {
Node mnode = this.rootCond.addToken(metadata);
Node thenode = mnode;
while (tokens.hasMoreTokens()) {
Node newnode = thenode.addToken(tokens.nextToken());
thenode = newnode; // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public final void fillWriteBuffer(boolean shouldOptimize) {
if (toWrite == 0 && readQ.remainingCapacity() > 0) {
getWbuf().clear();
Operation o=getNextWritableOp();
while(o != null && toWrite < getWbuf().capacity()) {
synchronized(o) {
assert o.getState() == OperationState.WRITING;
ByteBuffer obuf = o.getBuffer();
assert obuf != null : "Didn't get a write buffer from " + o;
int bytesToCopy = Math.min(getWbuf().remaining(), obuf.remaining());
byte[] b = new byte[bytesToCopy];
obuf.get(b);
getWbuf().put(b);
getLogger().debug("After copying stuff from %s: %s", o, getWbuf());
if (!o.getBuffer().hasRemaining()) {
o.writeComplete();
transitionWriteItem();
preparePending();
if (shouldOptimize) {
optimize();
}
o=getNextWritableOp();
}
toWrite += bytesToCopy;
}
}
getWbuf().flip();
assert toWrite <= getWbuf().capacity() : "toWrite exceeded capacity: "
+ this;
assert toWrite == getWbuf().remaining() : "Expected " + toWrite
+ " remaining, got " + getWbuf().remaining();
} else {
getLogger().debug("Buffer is full, skipping");
}
} } | public class class_name {
public final void fillWriteBuffer(boolean shouldOptimize) {
if (toWrite == 0 && readQ.remainingCapacity() > 0) {
getWbuf().clear(); // depends on control dependency: [if], data = [none]
Operation o=getNextWritableOp();
while(o != null && toWrite < getWbuf().capacity()) {
synchronized(o) { // depends on control dependency: [while], data = [(o]
assert o.getState() == OperationState.WRITING;
ByteBuffer obuf = o.getBuffer();
assert obuf != null : "Didn't get a write buffer from " + o;
int bytesToCopy = Math.min(getWbuf().remaining(), obuf.remaining());
byte[] b = new byte[bytesToCopy];
obuf.get(b);
getWbuf().put(b);
getLogger().debug("After copying stuff from %s: %s", o, getWbuf());
if (!o.getBuffer().hasRemaining()) {
o.writeComplete(); // depends on control dependency: [if], data = [none]
transitionWriteItem(); // depends on control dependency: [if], data = [none]
preparePending(); // depends on control dependency: [if], data = [none]
if (shouldOptimize) {
optimize(); // depends on control dependency: [if], data = [none]
}
o=getNextWritableOp(); // depends on control dependency: [if], data = [none]
}
toWrite += bytesToCopy;
}
}
getWbuf().flip(); // depends on control dependency: [if], data = [none]
assert toWrite <= getWbuf().capacity() : "toWrite exceeded capacity: "
+ this; // depends on control dependency: [if], data = [none]
assert toWrite == getWbuf().remaining() : "Expected " + toWrite
+ " remaining, got " + getWbuf().remaining(); // depends on control dependency: [if], data = [none]
} else {
getLogger().debug("Buffer is full, skipping"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
E removeAt(int i) {
// assert i >= 0 && i < size;
modCount++;
int s = --size;
if (s == i) // removed last element
queue[i] = null;
else {
E moved = (E) queue[s];
queue[s] = null;
siftDown(i, moved);
if (queue[i] == moved) {
siftUp(i, moved);
if (queue[i] != moved)
return moved;
}
}
return null;
} } | public class class_name {
@SuppressWarnings("unchecked")
E removeAt(int i) {
// assert i >= 0 && i < size;
modCount++;
int s = --size;
if (s == i) // removed last element
queue[i] = null;
else {
E moved = (E) queue[s];
queue[s] = null; // depends on control dependency: [if], data = [none]
siftDown(i, moved); // depends on control dependency: [if], data = [none]
if (queue[i] == moved) {
siftUp(i, moved); // depends on control dependency: [if], data = [moved)]
if (queue[i] != moved)
return moved;
}
}
return null;
} } |
public class class_name {
public void set(String propName, Object value) {
if (propName.equals(PROP_IDENTIFIER)) {
setIdentifier(((IdentifierType) value));
}
if (propName.equals(PROP_VIEW_IDENTIFIERS)) {
getViewIdentifiers().add(((com.ibm.wsspi.security.wim.model.ViewIdentifierType) value));
}
if (propName.equals(PROP_PARENT)) {
setParent(((Entity) value));
}
if (propName.equals(PROP_CHILDREN)) {
getChildren().add(((com.ibm.wsspi.security.wim.model.Entity) value));
}
if (propName.equals(PROP_GROUPS)) {
getGroups().add(((com.ibm.wsspi.security.wim.model.Group) value));
}
if (propName.equals(PROP_CREATE_TIMESTAMP)) {
setCreateTimestamp(((Date) value));
}
if (propName.equals(PROP_MODIFY_TIMESTAMP)) {
setModifyTimestamp(((Date) value));
}
if (propName.equals(PROP_ENTITLEMENT_INFO)) {
setEntitlementInfo(((EntitlementInfoType) value));
}
if (propName.equals(PROP_CHANGE_TYPE)) {
setChangeType(((String) value));
}
} } | public class class_name {
public void set(String propName, Object value) {
if (propName.equals(PROP_IDENTIFIER)) {
setIdentifier(((IdentifierType) value)); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_VIEW_IDENTIFIERS)) {
getViewIdentifiers().add(((com.ibm.wsspi.security.wim.model.ViewIdentifierType) value)); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_PARENT)) {
setParent(((Entity) value)); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_CHILDREN)) {
getChildren().add(((com.ibm.wsspi.security.wim.model.Entity) value)); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_GROUPS)) {
getGroups().add(((com.ibm.wsspi.security.wim.model.Group) value)); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_CREATE_TIMESTAMP)) {
setCreateTimestamp(((Date) value)); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_MODIFY_TIMESTAMP)) {
setModifyTimestamp(((Date) value)); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_ENTITLEMENT_INFO)) {
setEntitlementInfo(((EntitlementInfoType) value)); // depends on control dependency: [if], data = [none]
}
if (propName.equals(PROP_CHANGE_TYPE)) {
setChangeType(((String) value)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static IAtomContainer removeNonChiralHydrogens(IAtomContainer org) {
Map<IAtom, IAtom> map = new HashMap<IAtom, IAtom>(); // maps original atoms to clones.
List<IAtom> remove = new ArrayList<IAtom>(); // lists removed Hs.
// Clone atoms except those to be removed.
IAtomContainer cpy = org.getBuilder().newInstance(IAtomContainer.class);
int count = org.getAtomCount();
for (int i = 0; i < count; i++) {
// Clone/remove this atom?
IAtom atom = org.getAtom(i);
boolean addToRemove = false;
if (suppressibleHydrogen(org, atom)) {
// test whether connected to a single hetero atom only, otherwise keep
if (org.getConnectedAtomsList(atom).size() == 1) {
IAtom neighbour = org.getConnectedAtomsList(atom).get(0);
// keep if the neighbouring hetero atom has stereo information, otherwise continue checking
Integer stereoParity = neighbour.getStereoParity();
if (stereoParity == null || stereoParity == 0) {
addToRemove = true;
// keep if any of the bonds of the hetero atom have stereo information
for (IBond bond : org.getConnectedBondsList(neighbour)) {
IBond.Stereo bondStereo = bond.getStereo();
if (bondStereo != null && bondStereo != IBond.Stereo.NONE) addToRemove = false;
IAtom neighboursNeighbour = bond.getOther(neighbour);
// remove in any case if the hetero atom is connected to more than one hydrogen
if (neighboursNeighbour.getSymbol().equals("H") && !neighboursNeighbour.equals(atom)) {
addToRemove = true;
break;
}
}
}
}
}
if (addToRemove)
remove.add(atom);
else
addClone(atom, cpy, map);
}
// rescue any false positives, i.e., hydrogens that are stereo-relevant
// the use of IStereoElement is not fully integrated yet to describe stereo information
for (IStereoElement stereoElement : org.stereoElements()) {
if (stereoElement instanceof ITetrahedralChirality) {
ITetrahedralChirality tetChirality = (ITetrahedralChirality) stereoElement;
for (IAtom atom : tetChirality.getLigands()) {
if (atom.getSymbol().equals("H") && remove.contains(atom)) {
remove.remove(atom);
addClone(atom, cpy, map);
}
}
} else if (stereoElement instanceof IDoubleBondStereochemistry) {
IDoubleBondStereochemistry dbs = (IDoubleBondStereochemistry) stereoElement;
IBond stereoBond = dbs.getStereoBond();
for (IAtom neighbor : org.getConnectedAtomsList(stereoBond.getBegin())) {
if (remove.remove(neighbor)) addClone(neighbor, cpy, map);
}
for (IAtom neighbor : org.getConnectedAtomsList(stereoBond.getEnd())) {
if (remove.remove(neighbor)) addClone(neighbor, cpy, map);
}
}
}
// Clone bonds except those involving removed atoms.
count = org.getBondCount();
for (int i = 0; i < count; i++) {
// Check bond.
final IBond bond = org.getBond(i);
boolean removedBond = false;
final int length = bond.getAtomCount();
for (int k = 0; k < length; k++) {
if (remove.contains(bond.getAtom(k))) {
removedBond = true;
break;
}
}
// Clone/remove this bond?
if (!removedBond) {
IBond clone = null;
try {
clone = (IBond) org.getBond(i).clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assert clone != null;
clone.setAtoms(new IAtom[]{map.get(bond.getBegin()), map.get(bond.getEnd())});
cpy.addBond(clone);
}
}
// Recompute hydrogen counts of neighbours of removed Hydrogens.
for (IAtom aRemove : remove) {
// Process neighbours.
for (IAtom iAtom : org.getConnectedAtomsList(aRemove)) {
final IAtom neighb = map.get(iAtom);
if (neighb == null) continue; // since for the case of H2, neight H has a heavy atom neighbor
neighb.setImplicitHydrogenCount((neighb.getImplicitHydrogenCount() == null ? 0 : neighb
.getImplicitHydrogenCount()) + 1);
}
}
for (IAtom atom : cpy.atoms()) {
if (atom.getImplicitHydrogenCount() == null) atom.setImplicitHydrogenCount(0);
}
cpy.addProperties(org.getProperties());
cpy.setFlags(org.getFlags());
return (cpy);
} } | public class class_name {
public static IAtomContainer removeNonChiralHydrogens(IAtomContainer org) {
Map<IAtom, IAtom> map = new HashMap<IAtom, IAtom>(); // maps original atoms to clones.
List<IAtom> remove = new ArrayList<IAtom>(); // lists removed Hs.
// Clone atoms except those to be removed.
IAtomContainer cpy = org.getBuilder().newInstance(IAtomContainer.class);
int count = org.getAtomCount();
for (int i = 0; i < count; i++) {
// Clone/remove this atom?
IAtom atom = org.getAtom(i);
boolean addToRemove = false;
if (suppressibleHydrogen(org, atom)) {
// test whether connected to a single hetero atom only, otherwise keep
if (org.getConnectedAtomsList(atom).size() == 1) {
IAtom neighbour = org.getConnectedAtomsList(atom).get(0);
// keep if the neighbouring hetero atom has stereo information, otherwise continue checking
Integer stereoParity = neighbour.getStereoParity();
if (stereoParity == null || stereoParity == 0) {
addToRemove = true; // depends on control dependency: [if], data = [none]
// keep if any of the bonds of the hetero atom have stereo information
for (IBond bond : org.getConnectedBondsList(neighbour)) {
IBond.Stereo bondStereo = bond.getStereo();
if (bondStereo != null && bondStereo != IBond.Stereo.NONE) addToRemove = false;
IAtom neighboursNeighbour = bond.getOther(neighbour);
// remove in any case if the hetero atom is connected to more than one hydrogen
if (neighboursNeighbour.getSymbol().equals("H") && !neighboursNeighbour.equals(atom)) {
addToRemove = true; // depends on control dependency: [if], data = [none]
break;
}
}
}
}
}
if (addToRemove)
remove.add(atom);
else
addClone(atom, cpy, map);
}
// rescue any false positives, i.e., hydrogens that are stereo-relevant
// the use of IStereoElement is not fully integrated yet to describe stereo information
for (IStereoElement stereoElement : org.stereoElements()) {
if (stereoElement instanceof ITetrahedralChirality) {
ITetrahedralChirality tetChirality = (ITetrahedralChirality) stereoElement;
for (IAtom atom : tetChirality.getLigands()) {
if (atom.getSymbol().equals("H") && remove.contains(atom)) {
remove.remove(atom); // depends on control dependency: [if], data = [none]
addClone(atom, cpy, map); // depends on control dependency: [if], data = [none]
}
}
} else if (stereoElement instanceof IDoubleBondStereochemistry) {
IDoubleBondStereochemistry dbs = (IDoubleBondStereochemistry) stereoElement;
IBond stereoBond = dbs.getStereoBond();
for (IAtom neighbor : org.getConnectedAtomsList(stereoBond.getBegin())) {
if (remove.remove(neighbor)) addClone(neighbor, cpy, map);
}
for (IAtom neighbor : org.getConnectedAtomsList(stereoBond.getEnd())) {
if (remove.remove(neighbor)) addClone(neighbor, cpy, map);
}
}
}
// Clone bonds except those involving removed atoms.
count = org.getBondCount();
for (int i = 0; i < count; i++) {
// Check bond.
final IBond bond = org.getBond(i);
boolean removedBond = false;
final int length = bond.getAtomCount();
for (int k = 0; k < length; k++) {
if (remove.contains(bond.getAtom(k))) {
removedBond = true; // depends on control dependency: [if], data = [none]
break;
}
}
// Clone/remove this bond?
if (!removedBond) {
IBond clone = null;
try {
clone = (IBond) org.getBond(i).clone(); // depends on control dependency: [try], data = [none]
} catch (CloneNotSupportedException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
assert clone != null;
clone.setAtoms(new IAtom[]{map.get(bond.getBegin()), map.get(bond.getEnd())}); // depends on control dependency: [if], data = [none]
cpy.addBond(clone); // depends on control dependency: [if], data = [none]
}
}
// Recompute hydrogen counts of neighbours of removed Hydrogens.
for (IAtom aRemove : remove) {
// Process neighbours.
for (IAtom iAtom : org.getConnectedAtomsList(aRemove)) {
final IAtom neighb = map.get(iAtom);
if (neighb == null) continue; // since for the case of H2, neight H has a heavy atom neighbor
neighb.setImplicitHydrogenCount((neighb.getImplicitHydrogenCount() == null ? 0 : neighb
.getImplicitHydrogenCount()) + 1); // depends on control dependency: [for], data = [none]
}
}
for (IAtom atom : cpy.atoms()) {
if (atom.getImplicitHydrogenCount() == null) atom.setImplicitHydrogenCount(0);
}
cpy.addProperties(org.getProperties());
cpy.setFlags(org.getFlags());
return (cpy);
} } |
public class class_name {
public Elements attr(String attributeKey, String attributeValue) {
for (Element element : this) {
element.attr(attributeKey, attributeValue);
}
return this;
} } | public class class_name {
public Elements attr(String attributeKey, String attributeValue) {
for (Element element : this) {
element.attr(attributeKey, attributeValue); // depends on control dependency: [for], data = [element]
}
return this;
} } |
public class class_name {
public static String[] getClassSimpleFields(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
int length = fields.length;
Collection<Field> fieldCollection = new ArrayList<Field>();
for (int i = 0; i < length; i++) {
Field field = fields[i];
if (isSimpleType(field)) {
fieldCollection.add(field);
}
}
String[] fieldNames = new String[fieldCollection.size()];
int i = 0;
for (Iterator iterator = fieldCollection.iterator(); iterator.hasNext(); ) {
Field field = (Field) iterator.next();
fieldNames[i] = field.getName();
i++;
}
return fieldNames;
} } | public class class_name {
public static String[] getClassSimpleFields(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
int length = fields.length;
Collection<Field> fieldCollection = new ArrayList<Field>();
for (int i = 0; i < length; i++) {
Field field = fields[i];
if (isSimpleType(field)) {
fieldCollection.add(field); // depends on control dependency: [if], data = [none]
}
}
String[] fieldNames = new String[fieldCollection.size()];
int i = 0;
for (Iterator iterator = fieldCollection.iterator(); iterator.hasNext(); ) {
Field field = (Field) iterator.next();
fieldNames[i] = field.getName(); // depends on control dependency: [for], data = [none]
i++; // depends on control dependency: [for], data = [none]
}
return fieldNames;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static Object instantiateInstanceWithClientConfig(String className, IClientConfig clientConfig)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Class clazz = Class.forName(className);
if (IClientConfigAware.class.isAssignableFrom(clazz)) {
IClientConfigAware obj = (IClientConfigAware) clazz.newInstance();
obj.initWithNiwsConfig(clientConfig);
return obj;
} else {
try {
if (clazz.getConstructor(IClientConfig.class) != null) {
return clazz.getConstructor(IClientConfig.class).newInstance(clientConfig);
}
} catch (NoSuchMethodException ignored) {
// OK for a class to not take an IClientConfig
} catch (SecurityException | IllegalArgumentException | InvocationTargetException e) {
logger.warn("Error getting/invoking IClientConfig constructor of {}", className, e);
}
}
logger.warn("Class " + className + " neither implements IClientConfigAware nor provides a constructor with IClientConfig as the parameter. Only default constructor will be used.");
return clazz.newInstance();
} } | public class class_name {
@SuppressWarnings("unchecked")
public static Object instantiateInstanceWithClientConfig(String className, IClientConfig clientConfig)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Class clazz = Class.forName(className);
if (IClientConfigAware.class.isAssignableFrom(clazz)) {
IClientConfigAware obj = (IClientConfigAware) clazz.newInstance();
obj.initWithNiwsConfig(clientConfig);
return obj;
} else {
try {
if (clazz.getConstructor(IClientConfig.class) != null) {
return clazz.getConstructor(IClientConfig.class).newInstance(clientConfig); // depends on control dependency: [if], data = [none]
}
} catch (NoSuchMethodException ignored) {
// OK for a class to not take an IClientConfig
} catch (SecurityException | IllegalArgumentException | InvocationTargetException e) { // depends on control dependency: [catch], data = [none]
logger.warn("Error getting/invoking IClientConfig constructor of {}", className, e);
} // depends on control dependency: [catch], data = [none]
}
logger.warn("Class " + className + " neither implements IClientConfigAware nor provides a constructor with IClientConfig as the parameter. Only default constructor will be used.");
return clazz.newInstance();
} } |
public class class_name {
public E borrowObject() throws Exception
{
assertOpen();
long starttime = System.currentTimeMillis();
for (; ;)
{
E obj = null;
// if there are any sleeping, just grab one of those
synchronized (this)
{
obj = pool.remove();
// otherwise
if (null == obj)
{
// check if we can create one
// (note we know that the num sleeping is 0, else we wouldn't be here)
if (maxActive < 0 || numActive < maxActive)
{
// allow new object to be created
}
else
{
// the pool is exhausted
switch (whenExhaustedAction)
{
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try
{
if (maxWait <= 0)
{
wait();
}
else
{
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = maxWait - elapsed;
if (waitTime > 0)
{
wait(waitTime);
}
}
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
throw e;
}
if (maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait))
{
throw new NoSuchElementException("Timeout waiting for idle object");
}
else
{
continue; // keep looping
}
default:
throw new IllegalArgumentException("WhenExhaustedAction property " + whenExhaustedAction + " not recognized.");
}
}
}
numActive++;
}
// create new object when needed
boolean newlyCreated = false;
if (null == obj)
{
try
{
obj = factory.makeObject(this);
newlyCreated = true;
return obj;
}
finally
{
if (!newlyCreated)
{
// object cannot be created
synchronized (this)
{
numActive--;
notifyAll();
}
}
}
}
// activate & validate the object
try
{
factory.activateObject(obj);
if (testOnBorrow && !factory.validateObject(obj))
{
throw new Exception("ValidateObject failed");
}
return obj;
}
catch (Throwable e)
{
reportException("object activation or validation failed ", e);
synchronized (this)
{
// object cannot be activated or is invalid
numActive--;
notifyAll();
}
destroyObject(obj);
if (newlyCreated)
{
throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage());
}
// keep looping
}
}
} } | public class class_name {
public E borrowObject() throws Exception
{
assertOpen();
long starttime = System.currentTimeMillis();
for (; ;)
{
E obj = null;
// if there are any sleeping, just grab one of those
synchronized (this)
{
obj = pool.remove();
// otherwise
if (null == obj)
{
// check if we can create one
// (note we know that the num sleeping is 0, else we wouldn't be here)
if (maxActive < 0 || numActive < maxActive)
{
// allow new object to be created
}
else
{
// the pool is exhausted
switch (whenExhaustedAction)
{
case WHEN_EXHAUSTED_GROW:
// allow new object to be created
break;
case WHEN_EXHAUSTED_FAIL:
throw new NoSuchElementException("Pool exhausted");
case WHEN_EXHAUSTED_BLOCK:
try
{
if (maxWait <= 0)
{
wait();
// depends on control dependency: [if], data = [none]
}
else
{
// this code may be executed again after a notify then continue cycle
// so, need to calculate the amount of time to wait
final long elapsed = (System.currentTimeMillis() - starttime);
final long waitTime = maxWait - elapsed;
if (waitTime > 0)
{
wait(waitTime);
// depends on control dependency: [if], data = [(waitTime]
}
}
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
throw e;
}
// depends on control dependency: [catch], data = [none]
if (maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait))
{
throw new NoSuchElementException("Timeout waiting for idle object");
}
else
{
continue; // keep looping
}
default:
throw new IllegalArgumentException("WhenExhaustedAction property " + whenExhaustedAction + " not recognized.");
}
}
}
numActive++;
}
// create new object when needed
boolean newlyCreated = false;
if (null == obj)
{
try
{
obj = factory.makeObject(this);
// depends on control dependency: [try], data = [none]
newlyCreated = true;
// depends on control dependency: [try], data = [none]
return obj;
// depends on control dependency: [try], data = [none]
}
finally
{
if (!newlyCreated)
{
// object cannot be created
synchronized (this)
// depends on control dependency: [if], data = [none]
{
numActive--;
notifyAll();
}
}
}
}
// activate & validate the object
try
{
factory.activateObject(obj);
// depends on control dependency: [try], data = [none]
if (testOnBorrow && !factory.validateObject(obj))
{
throw new Exception("ValidateObject failed");
}
return obj;
// depends on control dependency: [try], data = [none]
}
catch (Throwable e)
{
reportException("object activation or validation failed ", e);
synchronized (this)
{
// object cannot be activated or is invalid
numActive--;
notifyAll();
}
destroyObject(obj);
if (newlyCreated)
{
throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage());
}
// keep looping
}
// depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void pasteHoneycombImpl(@IntRange(from = 0) int min, @IntRange(from = 0) int max) {
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = clipboard.getPrimaryClip();
if (clip != null) {
for (int i = 0; i < clip.getItemCount(); i++) {
ClipData.Item item = clip.getItemAt(i);
String selectedText = item.coerceToText(getContext()).toString();
MentionsEditable text = getMentionsText();
MentionSpan[] spans = text.getSpans(min, max, MentionSpan.class);
/*
* We need to remove the span between min and max. This is required because in
* {@link SpannableStringBuilder#replace(int, int, CharSequence)} existing spans within
* the Editable that entirely cover the replaced range are retained, but any that
* were strictly within the range that was replaced are removed. In our case the existing
* spans are retained if the selection entirely covers the span. So, we just remove
* the existing span and replace the new text with that span.
*/
for (MentionSpan span : spans) {
if (text.getSpanEnd(span) == min) {
// We do not want to remove the span, when we want to paste anything just next
// to the existing span. In this case "text.getSpanEnd(span)" will be equal
// to min.
continue;
}
text.removeSpan(span);
}
Intent intent = item.getIntent();
// Just set the plain text if we do not have mentions data in the intent/bundle
if (intent == null) {
text.replace(min, max, selectedText);
continue;
}
Bundle bundle = intent.getExtras();
if (bundle == null) {
text.replace(min, max, selectedText);
continue;
}
bundle.setClassLoader(getContext().getClassLoader());
int[] spanStart = bundle.getIntArray(KEY_MENTION_SPAN_STARTS);
Parcelable[] parcelables = bundle.getParcelableArray(KEY_MENTION_SPANS);
if (parcelables == null || parcelables.length <= 0 || spanStart == null || spanStart.length <= 0) {
text.replace(min, max, selectedText);
continue;
}
// Set the MentionSpan in text.
SpannableStringBuilder s = new SpannableStringBuilder(selectedText);
for (int j = 0; j < parcelables.length; j++) {
MentionSpan mentionSpan = (MentionSpan) parcelables[j];
s.setSpan(mentionSpan, spanStart[j], spanStart[j] + mentionSpan.getDisplayString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
text.replace(min, max, s);
}
}
} } | public class class_name {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void pasteHoneycombImpl(@IntRange(from = 0) int min, @IntRange(from = 0) int max) {
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = clipboard.getPrimaryClip();
if (clip != null) {
for (int i = 0; i < clip.getItemCount(); i++) {
ClipData.Item item = clip.getItemAt(i);
String selectedText = item.coerceToText(getContext()).toString();
MentionsEditable text = getMentionsText();
MentionSpan[] spans = text.getSpans(min, max, MentionSpan.class);
/*
* We need to remove the span between min and max. This is required because in
* {@link SpannableStringBuilder#replace(int, int, CharSequence)} existing spans within
* the Editable that entirely cover the replaced range are retained, but any that
* were strictly within the range that was replaced are removed. In our case the existing
* spans are retained if the selection entirely covers the span. So, we just remove
* the existing span and replace the new text with that span.
*/
for (MentionSpan span : spans) {
if (text.getSpanEnd(span) == min) {
// We do not want to remove the span, when we want to paste anything just next
// to the existing span. In this case "text.getSpanEnd(span)" will be equal
// to min.
continue;
}
text.removeSpan(span); // depends on control dependency: [for], data = [span]
}
Intent intent = item.getIntent();
// Just set the plain text if we do not have mentions data in the intent/bundle
if (intent == null) {
text.replace(min, max, selectedText); // depends on control dependency: [if], data = [none]
continue;
}
Bundle bundle = intent.getExtras();
if (bundle == null) {
text.replace(min, max, selectedText); // depends on control dependency: [if], data = [none]
continue;
}
bundle.setClassLoader(getContext().getClassLoader()); // depends on control dependency: [for], data = [none]
int[] spanStart = bundle.getIntArray(KEY_MENTION_SPAN_STARTS);
Parcelable[] parcelables = bundle.getParcelableArray(KEY_MENTION_SPANS);
if (parcelables == null || parcelables.length <= 0 || spanStart == null || spanStart.length <= 0) {
text.replace(min, max, selectedText); // depends on control dependency: [if], data = [none]
continue;
}
// Set the MentionSpan in text.
SpannableStringBuilder s = new SpannableStringBuilder(selectedText);
for (int j = 0; j < parcelables.length; j++) {
MentionSpan mentionSpan = (MentionSpan) parcelables[j];
s.setSpan(mentionSpan, spanStart[j], spanStart[j] + mentionSpan.getDisplayString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // depends on control dependency: [for], data = [j]
}
text.replace(min, max, s); // depends on control dependency: [for], data = [none]
}
}
} } |
public class class_name {
@Override
public void visitExtendsClause(GroovySourceAST t, int visit) {
SimpleGroovyClassDoc currentClassDoc = getCurrentClassDoc();
if (visit == OPENING_VISIT) {
for (GroovySourceAST superClassNode : findTypeNames(t)) {
String superClassName = extractName(superClassNode);
if (currentClassDoc.isInterface()) {
currentClassDoc.addInterfaceName(superClassName);
} else {
currentClassDoc.setSuperClassName(superClassName);
}
}
}
} } | public class class_name {
@Override
public void visitExtendsClause(GroovySourceAST t, int visit) {
SimpleGroovyClassDoc currentClassDoc = getCurrentClassDoc();
if (visit == OPENING_VISIT) {
for (GroovySourceAST superClassNode : findTypeNames(t)) {
String superClassName = extractName(superClassNode);
if (currentClassDoc.isInterface()) {
currentClassDoc.addInterfaceName(superClassName); // depends on control dependency: [if], data = [none]
} else {
currentClassDoc.setSuperClassName(superClassName); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public void transform(Source source, Result outputTarget)
throws TransformerException
{
createResultContentHandler(outputTarget);
/*
* According to JAXP1.2, new SAXSource()/StreamSource()
* should create an empty input tree, with a default root node.
* new DOMSource()creates an empty document using DocumentBuilder.
* newDocument(); Use DocumentBuilder.newDocument() for all 3 situations,
* since there is no clear spec. how to create an empty tree when
* both SAXSource() and StreamSource() are used.
*/
if ((source instanceof StreamSource && source.getSystemId()==null &&
((StreamSource)source).getInputStream()==null &&
((StreamSource)source).getReader()==null)||
(source instanceof SAXSource &&
((SAXSource)source).getInputSource()==null &&
((SAXSource)source).getXMLReader()==null )||
(source instanceof DOMSource && ((DOMSource)source).getNode()==null)){
try {
DocumentBuilderFactory builderF = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderF.newDocumentBuilder();
String systemID = source.getSystemId();
source = new DOMSource(builder.newDocument());
// Copy system ID from original, empty Source to new Source
if (systemID != null) {
source.setSystemId(systemID);
}
} catch (ParserConfigurationException e){
throw new TransformerException(e.getMessage());
}
}
try
{
if (source instanceof DOMSource)
{
DOMSource dsource = (DOMSource) source;
m_systemID = dsource.getSystemId();
Node dNode = dsource.getNode();
if (null != dNode)
{
try
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
this.startDocument();
try
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
{
String data = dNode.getNodeValue();
char[] chars = data.toCharArray();
characters(chars, 0, chars.length);
}
else
{
org.apache.xml.serializer.TreeWalker walker;
walker = new org.apache.xml.serializer.TreeWalker(this, m_systemID);
walker.traverse(dNode);
}
}
finally
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
this.endDocument();
}
}
catch (SAXException se)
{
throw new TransformerException(se);
}
return;
}
else
{
String messageStr = XSLMessages.createMessage(
XSLTErrorResources.ER_ILLEGAL_DOMSOURCE_INPUT, null);
throw new IllegalArgumentException(messageStr);
}
}
InputSource xmlSource = SAXSource.sourceToInputSource(source);
if (null == xmlSource)
{
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_SOURCE_TYPE, new Object[]{source.getClass().getName()})); //"Can't transform a Source of type "
//+ source.getClass().getName() + "!");
}
if (null != xmlSource.getSystemId())
m_systemID = xmlSource.getSystemId();
XMLReader reader = null;
boolean managedReader = false;
try
{
if (source instanceof SAXSource) {
reader = ((SAXSource) source).getXMLReader();
}
if (null == reader) {
try {
reader = XMLReaderManager.getInstance().getXMLReader();
managedReader = true;
} catch (SAXException se) {
throw new TransformerException(se);
}
} else {
try {
reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
} catch (org.xml.sax.SAXException se) {
// We don't care.
}
}
// Get the input content handler, which will handle the
// parse events and create the source tree.
ContentHandler inputHandler = this;
reader.setContentHandler(inputHandler);
if (inputHandler instanceof org.xml.sax.DTDHandler)
reader.setDTDHandler((org.xml.sax.DTDHandler) inputHandler);
try
{
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/properties/lexical-handler",
inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty(
"http://xml.org/sax/properties/declaration-handler",
inputHandler);
}
catch (org.xml.sax.SAXException se){}
try
{
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/handlers/LexicalHandler",
inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty("http://xml.org/sax/handlers/DeclHandler",
inputHandler);
}
catch (org.xml.sax.SAXNotRecognizedException snre){}
reader.parse(xmlSource);
}
catch (org.apache.xml.utils.WrappedRuntimeException wre)
{
Throwable throwable = wre.getException();
while (throwable
instanceof org.apache.xml.utils.WrappedRuntimeException)
{
throwable =
((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
}
throw new TransformerException(wre.getException());
}
catch (org.xml.sax.SAXException se)
{
throw new TransformerException(se);
}
catch (IOException ioe)
{
throw new TransformerException(ioe);
} finally {
if (managedReader) {
XMLReaderManager.getInstance().releaseXMLReader(reader);
}
}
}
finally
{
if(null != m_outputStream)
{
try
{
m_outputStream.close();
}
catch(IOException ioe){}
m_outputStream = null;
}
}
} } | public class class_name {
public void transform(Source source, Result outputTarget)
throws TransformerException
{
createResultContentHandler(outputTarget);
/*
* According to JAXP1.2, new SAXSource()/StreamSource()
* should create an empty input tree, with a default root node.
* new DOMSource()creates an empty document using DocumentBuilder.
* newDocument(); Use DocumentBuilder.newDocument() for all 3 situations,
* since there is no clear spec. how to create an empty tree when
* both SAXSource() and StreamSource() are used.
*/
if ((source instanceof StreamSource && source.getSystemId()==null &&
((StreamSource)source).getInputStream()==null &&
((StreamSource)source).getReader()==null)||
(source instanceof SAXSource &&
((SAXSource)source).getInputSource()==null &&
((SAXSource)source).getXMLReader()==null )||
(source instanceof DOMSource && ((DOMSource)source).getNode()==null)){
try {
DocumentBuilderFactory builderF = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderF.newDocumentBuilder();
String systemID = source.getSystemId();
source = new DOMSource(builder.newDocument()); // depends on control dependency: [try], data = [none]
// Copy system ID from original, empty Source to new Source
if (systemID != null) {
source.setSystemId(systemID); // depends on control dependency: [if], data = [(systemID]
}
} catch (ParserConfigurationException e){
throw new TransformerException(e.getMessage());
} // depends on control dependency: [catch], data = [none]
}
try
{
if (source instanceof DOMSource)
{
DOMSource dsource = (DOMSource) source;
m_systemID = dsource.getSystemId(); // depends on control dependency: [if], data = [none]
Node dNode = dsource.getNode();
if (null != dNode)
{
try
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
this.startDocument();
try
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
{
String data = dNode.getNodeValue();
char[] chars = data.toCharArray();
characters(chars, 0, chars.length); // depends on control dependency: [if], data = [none]
}
else
{
org.apache.xml.serializer.TreeWalker walker;
walker = new org.apache.xml.serializer.TreeWalker(this, m_systemID); // depends on control dependency: [if], data = [none]
walker.traverse(dNode); // depends on control dependency: [if], data = [none]
}
}
finally
{
if(dNode.getNodeType() == Node.ATTRIBUTE_NODE)
this.endDocument();
}
}
catch (SAXException se)
{
throw new TransformerException(se);
} // depends on control dependency: [catch], data = [none]
return; // depends on control dependency: [if], data = [none]
}
else
{
String messageStr = XSLMessages.createMessage(
XSLTErrorResources.ER_ILLEGAL_DOMSOURCE_INPUT, null);
throw new IllegalArgumentException(messageStr);
}
}
InputSource xmlSource = SAXSource.sourceToInputSource(source);
if (null == xmlSource)
{
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_SOURCE_TYPE, new Object[]{source.getClass().getName()})); //"Can't transform a Source of type "
//+ source.getClass().getName() + "!");
}
if (null != xmlSource.getSystemId())
m_systemID = xmlSource.getSystemId();
XMLReader reader = null;
boolean managedReader = false;
try
{
if (source instanceof SAXSource) {
reader = ((SAXSource) source).getXMLReader(); // depends on control dependency: [if], data = [none]
}
if (null == reader) {
try {
reader = XMLReaderManager.getInstance().getXMLReader(); // depends on control dependency: [try], data = [none]
managedReader = true; // depends on control dependency: [try], data = [none]
} catch (SAXException se) {
throw new TransformerException(se);
} // depends on control dependency: [catch], data = [none]
} else {
try {
reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
true); // depends on control dependency: [try], data = [none]
} catch (org.xml.sax.SAXException se) {
// We don't care.
} // depends on control dependency: [catch], data = [none]
}
// Get the input content handler, which will handle the
// parse events and create the source tree.
ContentHandler inputHandler = this;
reader.setContentHandler(inputHandler); // depends on control dependency: [try], data = [none]
if (inputHandler instanceof org.xml.sax.DTDHandler)
reader.setDTDHandler((org.xml.sax.DTDHandler) inputHandler);
try
{
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/properties/lexical-handler",
inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty(
"http://xml.org/sax/properties/declaration-handler",
inputHandler);
}
catch (org.xml.sax.SAXException se){} // depends on control dependency: [catch], data = [none]
try
{
if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
reader.setProperty("http://xml.org/sax/handlers/LexicalHandler",
inputHandler);
if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
reader.setProperty("http://xml.org/sax/handlers/DeclHandler",
inputHandler);
}
catch (org.xml.sax.SAXNotRecognizedException snre){} // depends on control dependency: [catch], data = [none]
reader.parse(xmlSource); // depends on control dependency: [try], data = [none]
}
catch (org.apache.xml.utils.WrappedRuntimeException wre)
{
Throwable throwable = wre.getException();
while (throwable
instanceof org.apache.xml.utils.WrappedRuntimeException)
{
throwable =
((org.apache.xml.utils.WrappedRuntimeException) throwable).getException(); // depends on control dependency: [while], data = [none]
}
throw new TransformerException(wre.getException());
} // depends on control dependency: [catch], data = [none]
catch (org.xml.sax.SAXException se)
{
throw new TransformerException(se);
} // depends on control dependency: [catch], data = [none]
catch (IOException ioe)
{
throw new TransformerException(ioe);
} finally { // depends on control dependency: [catch], data = [none]
if (managedReader) {
XMLReaderManager.getInstance().releaseXMLReader(reader); // depends on control dependency: [if], data = [none]
}
}
}
finally
{
if(null != m_outputStream)
{
try
{
m_outputStream.close(); // depends on control dependency: [try], data = [none]
}
catch(IOException ioe){} // depends on control dependency: [catch], data = [none]
m_outputStream = null; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public boolean isMemberInURLQuery(LdapURL[] urls, String dn) throws WIMException {
boolean result = false;
String[] attrIds = {};
String rdn = LdapHelper.getRDN(dn);
if (urls != null) {
for (int i = 0; i < urls.length; i++) {
LdapURL ldapURL = urls[i];
if (ldapURL.parsedOK()) {
String searchBase = ldapURL.get_dn();
// If dn is not under base, no need to do search
if (LdapHelper.isUnderBases(dn, searchBase)) {
int searchScope = ldapURL.get_searchScope();
String searchFilter = ldapURL.get_filter();
if (searchScope == SearchControls.SUBTREE_SCOPE) {
if (searchFilter == null) {
result = true;
break;
} else {
NamingEnumeration<SearchResult> nenu = search(dn, searchFilter, SearchControls.SUBTREE_SCOPE, attrIds);
if (nenu.hasMoreElements()) {
result = true;
break;
}
}
} else {
if (searchFilter == null) {
searchFilter = rdn;
} else {
searchFilter = "(&(" + searchFilter + ")(" + rdn + "))";
}
NamingEnumeration<SearchResult> nenu = search(searchBase, searchFilter, searchScope, attrIds);
if (nenu.hasMoreElements()) {
SearchResult thisEntry = nenu.nextElement();
if (thisEntry == null) {
continue;
}
String returnedDN = LdapHelper.prepareDN(thisEntry.getName(), searchBase);
if (dn.equalsIgnoreCase(returnedDN)) {
result = true;
break;
}
}
}
}
}
}
}
return result;
} } | public class class_name {
public boolean isMemberInURLQuery(LdapURL[] urls, String dn) throws WIMException {
boolean result = false;
String[] attrIds = {};
String rdn = LdapHelper.getRDN(dn);
if (urls != null) {
for (int i = 0; i < urls.length; i++) {
LdapURL ldapURL = urls[i];
if (ldapURL.parsedOK()) {
String searchBase = ldapURL.get_dn();
// If dn is not under base, no need to do search
if (LdapHelper.isUnderBases(dn, searchBase)) {
int searchScope = ldapURL.get_searchScope();
String searchFilter = ldapURL.get_filter();
if (searchScope == SearchControls.SUBTREE_SCOPE) {
if (searchFilter == null) {
result = true; // depends on control dependency: [if], data = [none]
break;
} else {
NamingEnumeration<SearchResult> nenu = search(dn, searchFilter, SearchControls.SUBTREE_SCOPE, attrIds);
if (nenu.hasMoreElements()) {
result = true; // depends on control dependency: [if], data = [none]
break;
}
}
} else {
if (searchFilter == null) {
searchFilter = rdn; // depends on control dependency: [if], data = [none]
} else {
searchFilter = "(&(" + searchFilter + ")(" + rdn + "))";
}
NamingEnumeration<SearchResult> nenu = search(searchBase, searchFilter, searchScope, attrIds); // depends on control dependency: [if], data = [none]
if (nenu.hasMoreElements()) {
SearchResult thisEntry = nenu.nextElement();
if (thisEntry == null) {
continue;
}
String returnedDN = LdapHelper.prepareDN(thisEntry.getName(), searchBase);
if (dn.equalsIgnoreCase(returnedDN)) {
result = true; // depends on control dependency: [if], data = [none]
break;
}
}
}
}
}
}
}
return result;
} } |
public class class_name {
public void render(
File outputDirectory,
ApplicationTemplate applicationTemplate,
File applicationDirectory,
List<String> renderers,
Map<String,String> options,
Map<String,String> typeAnnotations )
throws IOException {
options = fixOptions( options );
if( renderers.size() > 1 )
options.put( DocConstants.OPTION_GEN_IMAGES_ONCE, "true" );
for( String renderer : renderers ) {
Renderer r = Renderer.which( renderer );
if( r == null ) {
this.logger.severe( "No renderer called '" + renderer +"' was found. Skipping it." );
continue;
}
String subDirName = renderer.toLowerCase();
String locale = options.get( DocConstants.OPTION_LOCALE );
if( locale != null )
subDirName += "_" + locale;
File subDir = new File( outputDirectory, subDirName );
buildRenderer( subDir, applicationTemplate, applicationDirectory, r, typeAnnotations ).render( options );
}
} } | public class class_name {
public void render(
File outputDirectory,
ApplicationTemplate applicationTemplate,
File applicationDirectory,
List<String> renderers,
Map<String,String> options,
Map<String,String> typeAnnotations )
throws IOException {
options = fixOptions( options );
if( renderers.size() > 1 )
options.put( DocConstants.OPTION_GEN_IMAGES_ONCE, "true" );
for( String renderer : renderers ) {
Renderer r = Renderer.which( renderer );
if( r == null ) {
this.logger.severe( "No renderer called '" + renderer +"' was found. Skipping it." ); // depends on control dependency: [if], data = [none]
continue;
}
String subDirName = renderer.toLowerCase();
String locale = options.get( DocConstants.OPTION_LOCALE );
if( locale != null )
subDirName += "_" + locale;
File subDir = new File( outputDirectory, subDirName );
buildRenderer( subDir, applicationTemplate, applicationDirectory, r, typeAnnotations ).render( options );
}
} } |
public class class_name {
public static int cnNumericToArabic( String cnn, boolean flag )
{
cnn = cnn.trim();
if ( cnn.length() == 1 ) return isCNNumeric(cnn.charAt(0));
if ( flag ) cnn = cnn.replace('佰', '百')
.replace('仟', '千').replace('拾', '十').replace('零', ' ');
int yi = -1, wan = -1, qian = -1, bai = -1, shi = -1;
int val = 0;
yi = cnn.lastIndexOf('亿');
if ( yi > -1 ) {
val += cnNumericToArabic( cnn.substring(0, yi), false ) * 100000000;
if ( yi < cnn.length() - 1 ) {
cnn = cnn.substring(yi + 1, cnn.length());
} else {
cnn = "";
}
if ( cnn.length() == 1 ) {
int arbic = isCNNumeric(cnn.charAt(0));
if ( arbic <= 10 )
val += arbic * 10000000;
cnn = "";
}
}
wan = cnn.lastIndexOf('万');
if ( wan > -1 ) {
val += cnNumericToArabic( cnn.substring(0, wan), false ) * 10000;
if ( wan < cnn.length() - 1 ) {
cnn = cnn.substring(wan + 1, cnn.length());
} else {
cnn = "";
}
if ( cnn.length() == 1 ) {
int arbic = isCNNumeric(cnn.charAt(0));
if ( arbic <= 10 )
val += arbic * 1000;
cnn = "";
}
}
qian = cnn.lastIndexOf('千');
if ( qian > -1 ) {
val += cnNumericToArabic( cnn.substring(0, qian), false ) * 1000;
if ( qian < cnn.length() - 1 ) {
cnn = cnn.substring(qian + 1, cnn.length());
} else {
cnn = "";
}
if ( cnn.length() == 1 ) {
int arbic = isCNNumeric(cnn.charAt(0));
if ( arbic <= 10 )
val += arbic * 100;
cnn = "";
}
}
bai = cnn.lastIndexOf('百');
if ( bai > -1 ) {
val += cnNumericToArabic( cnn.substring(0, bai), false ) * 100;
if ( bai < cnn.length() - 1 ) {
cnn = cnn.substring(bai + 1, cnn.length());
} else {
cnn = "";
}
if ( cnn.length() == 1 ) {
int arbic = isCNNumeric(cnn.charAt(0));
if ( arbic <= 10 )
val += arbic * 10;
cnn = "";
}
}
shi = cnn.lastIndexOf('十');
if ( shi > -1 ) {
if ( shi == 0 ) {
val += 1 * 10;
} else {
val += cnNumericToArabic( cnn.substring(0, shi), false ) * 10;
}
if ( shi < cnn.length() - 1 ){
cnn = cnn.substring(shi + 1, cnn.length());
} else {
cnn = "";
}
}
cnn = cnn.trim();
for ( int j = 0; j < cnn.length(); j++ ) {
val += isCNNumeric(cnn.charAt(j)) * Math.pow(10, cnn.length() - j - 1);
}
return val;
} } | public class class_name {
public static int cnNumericToArabic( String cnn, boolean flag )
{
cnn = cnn.trim();
if ( cnn.length() == 1 ) return isCNNumeric(cnn.charAt(0));
if ( flag ) cnn = cnn.replace('佰', '百')
.replace('仟', '千').replace('拾', '十').replace('零', ' ');
int yi = -1, wan = -1, qian = -1, bai = -1, shi = -1;
int val = 0;
yi = cnn.lastIndexOf('亿');
if ( yi > -1 ) {
val += cnNumericToArabic( cnn.substring(0, yi), false ) * 100000000; // depends on control dependency: [if], data = [none]
if ( yi < cnn.length() - 1 ) {
cnn = cnn.substring(yi + 1, cnn.length()); // depends on control dependency: [if], data = [none]
} else {
cnn = ""; // depends on control dependency: [if], data = [none]
}
if ( cnn.length() == 1 ) {
int arbic = isCNNumeric(cnn.charAt(0));
if ( arbic <= 10 )
val += arbic * 10000000;
cnn = ""; // depends on control dependency: [if], data = [none]
}
}
wan = cnn.lastIndexOf('万');
if ( wan > -1 ) {
val += cnNumericToArabic( cnn.substring(0, wan), false ) * 10000; // depends on control dependency: [if], data = [none]
if ( wan < cnn.length() - 1 ) {
cnn = cnn.substring(wan + 1, cnn.length()); // depends on control dependency: [if], data = [none]
} else {
cnn = ""; // depends on control dependency: [if], data = [none]
}
if ( cnn.length() == 1 ) {
int arbic = isCNNumeric(cnn.charAt(0));
if ( arbic <= 10 )
val += arbic * 1000;
cnn = ""; // depends on control dependency: [if], data = [none]
}
}
qian = cnn.lastIndexOf('千');
if ( qian > -1 ) {
val += cnNumericToArabic( cnn.substring(0, qian), false ) * 1000; // depends on control dependency: [if], data = [none]
if ( qian < cnn.length() - 1 ) {
cnn = cnn.substring(qian + 1, cnn.length()); // depends on control dependency: [if], data = [none]
} else {
cnn = ""; // depends on control dependency: [if], data = [none]
}
if ( cnn.length() == 1 ) {
int arbic = isCNNumeric(cnn.charAt(0));
if ( arbic <= 10 )
val += arbic * 100;
cnn = ""; // depends on control dependency: [if], data = [none]
}
}
bai = cnn.lastIndexOf('百');
if ( bai > -1 ) {
val += cnNumericToArabic( cnn.substring(0, bai), false ) * 100; // depends on control dependency: [if], data = [none]
if ( bai < cnn.length() - 1 ) {
cnn = cnn.substring(bai + 1, cnn.length()); // depends on control dependency: [if], data = [none]
} else {
cnn = ""; // depends on control dependency: [if], data = [none]
}
if ( cnn.length() == 1 ) {
int arbic = isCNNumeric(cnn.charAt(0));
if ( arbic <= 10 )
val += arbic * 10;
cnn = ""; // depends on control dependency: [if], data = [none]
}
}
shi = cnn.lastIndexOf('十');
if ( shi > -1 ) {
if ( shi == 0 ) {
val += 1 * 10; // depends on control dependency: [if], data = [none]
} else {
val += cnNumericToArabic( cnn.substring(0, shi), false ) * 10; // depends on control dependency: [if], data = [none]
}
if ( shi < cnn.length() - 1 ){
cnn = cnn.substring(shi + 1, cnn.length()); // depends on control dependency: [if], data = [none]
} else {
cnn = ""; // depends on control dependency: [if], data = [none]
}
}
cnn = cnn.trim();
for ( int j = 0; j < cnn.length(); j++ ) {
val += isCNNumeric(cnn.charAt(j)) * Math.pow(10, cnn.length() - j - 1); // depends on control dependency: [for], data = [j]
}
return val;
} } |
public class class_name {
public static int toInt(String string, int from) {
int val = 0;
boolean started = false;
boolean minus = false;
for (int i = from; i < string.length(); i++) {
char b = string.charAt(i);
if (b <= ' ') {
if (started)
break;
} else if (b >= '0' && b <= '9') {
val = val * 10 + (b - '0');
started = true;
} else if (b == '-' && !started) {
minus = true;
} else
break;
}
if (started)
return minus ? (-val) : val;
throw new NumberFormatException(string);
} } | public class class_name {
public static int toInt(String string, int from) {
int val = 0;
boolean started = false;
boolean minus = false;
for (int i = from; i < string.length(); i++) {
char b = string.charAt(i);
if (b <= ' ') {
if (started)
break;
} else if (b >= '0' && b <= '9') {
val = val * 10 + (b - '0');
// depends on control dependency: [if], data = [(b]
started = true;
// depends on control dependency: [if], data = [none]
} else if (b == '-' && !started) {
minus = true;
// depends on control dependency: [if], data = [none]
} else
break;
}
if (started)
return minus ? (-val) : val;
throw new NumberFormatException(string);
} } |
public class class_name {
public Node popNode(Class<? extends Node> cls, String uri) {
synchronized (nodeStack) {
// Check if fragment is in suppression mode
if (suppress) {
if (!suppressedNodeStack.isEmpty()) {
// Check if node is on the suppressed stack
Node suppressed = popNode(suppressedNodeStack, cls, uri);
if (suppressed != null) {
// Popped node from suppressed stack
return suppressed;
}
} else {
// If suppression parent popped, then cancel the suppress mode
suppress = false;
}
}
return popNode(nodeStack, cls, uri);
}
} } | public class class_name {
public Node popNode(Class<? extends Node> cls, String uri) {
synchronized (nodeStack) {
// Check if fragment is in suppression mode
if (suppress) {
if (!suppressedNodeStack.isEmpty()) {
// Check if node is on the suppressed stack
Node suppressed = popNode(suppressedNodeStack, cls, uri);
if (suppressed != null) {
// Popped node from suppressed stack
return suppressed; // depends on control dependency: [if], data = [none]
}
} else {
// If suppression parent popped, then cancel the suppress mode
suppress = false; // depends on control dependency: [if], data = [none]
}
}
return popNode(nodeStack, cls, uri);
}
} } |
public class class_name {
public final void synpred43_InternalPureXbase_fragment() throws RecognitionException {
// InternalPureXbase.g:5153:6: ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )
// InternalPureXbase.g:5153:7: ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) )
{
// InternalPureXbase.g:5153:7: ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) )
// InternalPureXbase.g:5154:7: () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) )
{
// InternalPureXbase.g:5154:7: ()
// InternalPureXbase.g:5155:7:
{
}
// InternalPureXbase.g:5156:7: ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )?
int alt136=2;
int LA136_0 = input.LA(1);
if ( (LA136_0==RULE_ID||LA136_0==15||LA136_0==41) ) {
alt136=1;
}
switch (alt136) {
case 1 :
// InternalPureXbase.g:5157:8: ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )*
{
// InternalPureXbase.g:5157:8: ( ( ruleJvmFormalParameter ) )
// InternalPureXbase.g:5158:9: ( ruleJvmFormalParameter )
{
// InternalPureXbase.g:5158:9: ( ruleJvmFormalParameter )
// InternalPureXbase.g:5159:10: ruleJvmFormalParameter
{
pushFollow(FOLLOW_47);
ruleJvmFormalParameter();
state._fsp--;
if (state.failed) return ;
}
}
// InternalPureXbase.g:5162:8: ( ',' ( ( ruleJvmFormalParameter ) ) )*
loop135:
do {
int alt135=2;
int LA135_0 = input.LA(1);
if ( (LA135_0==57) ) {
alt135=1;
}
switch (alt135) {
case 1 :
// InternalPureXbase.g:5163:9: ',' ( ( ruleJvmFormalParameter ) )
{
match(input,57,FOLLOW_11); if (state.failed) return ;
// InternalPureXbase.g:5164:9: ( ( ruleJvmFormalParameter ) )
// InternalPureXbase.g:5165:10: ( ruleJvmFormalParameter )
{
// InternalPureXbase.g:5165:10: ( ruleJvmFormalParameter )
// InternalPureXbase.g:5166:11: ruleJvmFormalParameter
{
pushFollow(FOLLOW_47);
ruleJvmFormalParameter();
state._fsp--;
if (state.failed) return ;
}
}
}
break;
default :
break loop135;
}
} while (true);
}
break;
}
// InternalPureXbase.g:5171:7: ( ( '|' ) )
// InternalPureXbase.g:5172:8: ( '|' )
{
// InternalPureXbase.g:5172:8: ( '|' )
// InternalPureXbase.g:5173:9: '|'
{
match(input,63,FOLLOW_2); if (state.failed) return ;
}
}
}
}
} } | public class class_name {
public final void synpred43_InternalPureXbase_fragment() throws RecognitionException {
// InternalPureXbase.g:5153:6: ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )
// InternalPureXbase.g:5153:7: ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) )
{
// InternalPureXbase.g:5153:7: ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) )
// InternalPureXbase.g:5154:7: () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) )
{
// InternalPureXbase.g:5154:7: ()
// InternalPureXbase.g:5155:7:
{
}
// InternalPureXbase.g:5156:7: ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )?
int alt136=2;
int LA136_0 = input.LA(1);
if ( (LA136_0==RULE_ID||LA136_0==15||LA136_0==41) ) {
alt136=1;
}
switch (alt136) {
case 1 :
// InternalPureXbase.g:5157:8: ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )*
{
// InternalPureXbase.g:5157:8: ( ( ruleJvmFormalParameter ) )
// InternalPureXbase.g:5158:9: ( ruleJvmFormalParameter )
{
// InternalPureXbase.g:5158:9: ( ruleJvmFormalParameter )
// InternalPureXbase.g:5159:10: ruleJvmFormalParameter
{
pushFollow(FOLLOW_47);
ruleJvmFormalParameter();
state._fsp--;
if (state.failed) return ;
}
}
// InternalPureXbase.g:5162:8: ( ',' ( ( ruleJvmFormalParameter ) ) )*
loop135:
do {
int alt135=2;
int LA135_0 = input.LA(1);
if ( (LA135_0==57) ) {
alt135=1; // depends on control dependency: [if], data = [none]
}
switch (alt135) {
case 1 :
// InternalPureXbase.g:5163:9: ',' ( ( ruleJvmFormalParameter ) )
{
match(input,57,FOLLOW_11); if (state.failed) return ;
// InternalPureXbase.g:5164:9: ( ( ruleJvmFormalParameter ) )
// InternalPureXbase.g:5165:10: ( ruleJvmFormalParameter )
{
// InternalPureXbase.g:5165:10: ( ruleJvmFormalParameter )
// InternalPureXbase.g:5166:11: ruleJvmFormalParameter
{
pushFollow(FOLLOW_47);
ruleJvmFormalParameter();
state._fsp--;
if (state.failed) return ;
}
}
}
break;
default :
break loop135;
}
} while (true);
}
break;
}
// InternalPureXbase.g:5171:7: ( ( '|' ) )
// InternalPureXbase.g:5172:8: ( '|' )
{
// InternalPureXbase.g:5172:8: ( '|' )
// InternalPureXbase.g:5173:9: '|'
{
match(input,63,FOLLOW_2); if (state.failed) return ;
}
}
}
}
} } |
public class class_name {
public static void multInner(DMatrix1Row a , DMatrix1Row c )
{
c.reshape(a.numCols,a.numCols);
if( a.numCols >= EjmlParameters.MULT_INNER_SWITCH ) {
MatrixMultProduct_DDRM.inner_small(a, c);
} else {
MatrixMultProduct_DDRM.inner_reorder(a, c);
}
} } | public class class_name {
public static void multInner(DMatrix1Row a , DMatrix1Row c )
{
c.reshape(a.numCols,a.numCols);
if( a.numCols >= EjmlParameters.MULT_INNER_SWITCH ) {
MatrixMultProduct_DDRM.inner_small(a, c); // depends on control dependency: [if], data = [none]
} else {
MatrixMultProduct_DDRM.inner_reorder(a, c); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static char eatBackslash(String a, int[] n) {
if (!a.startsWith("\\")) {
n[0] = 0;
return ((char) 0);
}
// Unicodes BS u XXXX
if (a.startsWith("\\u")) {
try {
n[0] = 6;
return ((char) Integer.parseInt(a.substring(2, 6), 16));
} catch (Exception e) {
n[0] = -1;
return ((char) 0);
}
}
// Unicodes BS uu XXXX
if (a.startsWith("\\uu")) {
try {
n[0] = 7;
return ((char) Integer.parseInt(a.substring(3, 7), 16));
} catch (Exception e) {
n[0] = -1;
return ((char) 0);
}
}
// Classical escape sequences
if (a.startsWith("\\b")) {
n[0] = 2;
return ((char) 8);
}
if (a.startsWith("\\t")) {
n[0] = 2;
return ((char) 9);
}
if (a.startsWith("\\n")) {
n[0] = 2;
return ((char) 10);
}
if (a.startsWith("\\f")) {
n[0] = 2;
return ((char) 12);
}
if (a.startsWith("\\r")) {
n[0] = 2;
return ((char) 13);
}
if (a.startsWith("\\\\")) {
n[0] = 2;
return ('\\');
}
if (a.startsWith("\\\"")) {
n[0] = 2;
return ('"');
}
if (a.startsWith("\\'")) {
n[0] = 2;
return ('\'');
}
// Octal codes
n[0] = 1;
while (n[0] < a.length() && a.charAt(n[0]) >= '0' && a.charAt(n[0]) <= '8')
n[0]++;
if (n[0] == 1) {
n[0] = 0;
return ((char) 0);
}
try {
return ((char) Integer.parseInt(a.substring(1, n[0]), 8));
} catch (Exception e) {
}
n[0] = -1;
return ((char) 0);
} } | public class class_name {
public static char eatBackslash(String a, int[] n) {
if (!a.startsWith("\\")) {
n[0] = 0; // depends on control dependency: [if], data = [none]
return ((char) 0); // depends on control dependency: [if], data = [none]
}
// Unicodes BS u XXXX
if (a.startsWith("\\u")) {
try {
n[0] = 6; // depends on control dependency: [try], data = [none]
return ((char) Integer.parseInt(a.substring(2, 6), 16)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
n[0] = -1;
return ((char) 0);
} // depends on control dependency: [catch], data = [none]
}
// Unicodes BS uu XXXX
if (a.startsWith("\\uu")) {
try {
n[0] = 7; // depends on control dependency: [try], data = [none]
return ((char) Integer.parseInt(a.substring(3, 7), 16)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
n[0] = -1;
return ((char) 0);
} // depends on control dependency: [catch], data = [none]
}
// Classical escape sequences
if (a.startsWith("\\b")) {
n[0] = 2; // depends on control dependency: [if], data = [none]
return ((char) 8); // depends on control dependency: [if], data = [none]
}
if (a.startsWith("\\t")) {
n[0] = 2; // depends on control dependency: [if], data = [none]
return ((char) 9); // depends on control dependency: [if], data = [none]
}
if (a.startsWith("\\n")) {
n[0] = 2; // depends on control dependency: [if], data = [none]
return ((char) 10); // depends on control dependency: [if], data = [none]
}
if (a.startsWith("\\f")) {
n[0] = 2; // depends on control dependency: [if], data = [none]
return ((char) 12); // depends on control dependency: [if], data = [none]
}
if (a.startsWith("\\r")) {
n[0] = 2; // depends on control dependency: [if], data = [none]
return ((char) 13); // depends on control dependency: [if], data = [none]
}
if (a.startsWith("\\\\")) {
n[0] = 2; // depends on control dependency: [if], data = [none]
return ('\\'); // depends on control dependency: [if], data = [none]
}
if (a.startsWith("\\\"")) {
n[0] = 2; // depends on control dependency: [if], data = [none]
return ('"'); // depends on control dependency: [if], data = [none]
}
if (a.startsWith("\\'")) {
n[0] = 2; // depends on control dependency: [if], data = [none]
return ('\''); // depends on control dependency: [if], data = [none]
}
// Octal codes
n[0] = 1;
while (n[0] < a.length() && a.charAt(n[0]) >= '0' && a.charAt(n[0]) <= '8')
n[0]++;
if (n[0] == 1) {
n[0] = 0; // depends on control dependency: [if], data = [none]
return ((char) 0); // depends on control dependency: [if], data = [none]
}
try {
return ((char) Integer.parseInt(a.substring(1, n[0]), 8)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
} // depends on control dependency: [catch], data = [none]
n[0] = -1;
return ((char) 0);
} } |
public class class_name {
public InstanceId getInstanceId()
{
if (m_instanceId == null)
{
try
{
byte[] data =
m_zk.getData(CoreZK.instance_id, false, null);
JSONObject idJSON = new JSONObject(new String(data, "UTF-8"));
m_instanceId = new InstanceId(idJSON.getInt("coord"),
idJSON.getLong("timestamp"));
}
catch (Exception e)
{
String msg = "Unable to get instance ID info from " + CoreZK.instance_id;
hostLog.error(msg);
throw new RuntimeException(msg, e);
}
}
return m_instanceId;
} } | public class class_name {
public InstanceId getInstanceId()
{
if (m_instanceId == null)
{
try
{
byte[] data =
m_zk.getData(CoreZK.instance_id, false, null);
JSONObject idJSON = new JSONObject(new String(data, "UTF-8"));
m_instanceId = new InstanceId(idJSON.getInt("coord"),
idJSON.getLong("timestamp")); // depends on control dependency: [try], data = [none]
}
catch (Exception e)
{
String msg = "Unable to get instance ID info from " + CoreZK.instance_id;
hostLog.error(msg);
throw new RuntimeException(msg, e);
} // depends on control dependency: [catch], data = [none]
}
return m_instanceId;
} } |
public class class_name {
private static byte[] convertLinesToBytes(List<Line> lines) {
List<Line> dataLines = new ArrayList<>();
int byteCount = 0;
for (Line line : lines) {
if (line.getRecordType() == LineRecordType.DATA) {
dataLines.add(line);
byteCount += line.getByteCount();
}
}
byte[] bytes = new byte[byteCount];
int i = 0;
for (Line line : dataLines) {
for (byte b : line.getData()) {
bytes[i] = b;
i++;
}
}
return bytes;
} } | public class class_name {
private static byte[] convertLinesToBytes(List<Line> lines) {
List<Line> dataLines = new ArrayList<>();
int byteCount = 0;
for (Line line : lines) {
if (line.getRecordType() == LineRecordType.DATA) {
dataLines.add(line); // depends on control dependency: [if], data = [none]
byteCount += line.getByteCount(); // depends on control dependency: [if], data = [none]
}
}
byte[] bytes = new byte[byteCount];
int i = 0;
for (Line line : dataLines) {
for (byte b : line.getData()) {
bytes[i] = b; // depends on control dependency: [for], data = [b]
i++; // depends on control dependency: [for], data = [none]
}
}
return bytes;
} } |
public class class_name {
@Override
public JsonNode getAttribute(String attrName) {
Lock lock = lockForRead();
try {
return cacheJsonObjs.get(attrName);
} finally {
lock.unlock();
}
} } | public class class_name {
@Override
public JsonNode getAttribute(String attrName) {
Lock lock = lockForRead();
try {
return cacheJsonObjs.get(attrName); // depends on control dependency: [try], data = [none]
} finally {
lock.unlock();
}
} } |
public class class_name {
public static Class<?> getValidationClassInstance(Class<?> dataType, boolean isCql3Enabled)
{
resetMapperForCQL3(isCql3Enabled);
Class<?> validation_class;
validation_class = validationClassMapper.get(dataType);
if (validation_class == null)
{
if (dataType.isEnum())
{
validation_class = UTF8Type.class;
}
else
{
validation_class = BytesType.class;
}
}
resetMapperForThrift(isCql3Enabled);
return validation_class;
} } | public class class_name {
public static Class<?> getValidationClassInstance(Class<?> dataType, boolean isCql3Enabled)
{
resetMapperForCQL3(isCql3Enabled);
Class<?> validation_class;
validation_class = validationClassMapper.get(dataType);
if (validation_class == null)
{
if (dataType.isEnum())
{
validation_class = UTF8Type.class; // depends on control dependency: [if], data = [none]
}
else
{
validation_class = BytesType.class; // depends on control dependency: [if], data = [none]
}
}
resetMapperForThrift(isCql3Enabled);
return validation_class;
} } |
public class class_name {
public static void main(String[] args) {
System.out.printf("TFile Dumper (TFile %s, BCFile %s)\n", TFile.API_VERSION
.toString(), BCFile.API_VERSION.toString());
if (args.length == 0) {
System.out
.println("Usage: java ... org.apache.hadoop.io.file.tfile.TFile tfile-path [tfile-path ...]");
System.exit(0);
}
Configuration conf = new Configuration();
for (String file : args) {
System.out.println("===" + file + "===");
try {
TFileDumper.dumpInfo(file, System.out, conf);
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
} } | public class class_name {
public static void main(String[] args) {
System.out.printf("TFile Dumper (TFile %s, BCFile %s)\n", TFile.API_VERSION
.toString(), BCFile.API_VERSION.toString());
if (args.length == 0) {
System.out
.println("Usage: java ... org.apache.hadoop.io.file.tfile.TFile tfile-path [tfile-path ...]"); // depends on control dependency: [if], data = [none]
System.exit(0); // depends on control dependency: [if], data = [0)]
}
Configuration conf = new Configuration();
for (String file : args) {
System.out.println("===" + file + "==="); // depends on control dependency: [for], data = [file]
try {
TFileDumper.dumpInfo(file, System.out, conf); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
e.printStackTrace(System.err);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private double sumlogneg(double[][] f) {
int m = f.length;
int n = f[0].length;
double sum = 0.0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
sum += Math.log(-f[i][j]);
}
}
return sum;
} } | public class class_name {
private double sumlogneg(double[][] f) {
int m = f.length;
int n = f[0].length;
double sum = 0.0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
sum += Math.log(-f[i][j]); // depends on control dependency: [for], data = [j]
}
}
return sum;
} } |
public class class_name {
@Override
public void releaseConfig(Config config) {
synchronized (configCache) {
ClassLoader classloader = findClassloaderForRegisteredConfig(config);
if (classloader != null) {
close(classloader);
} else {
closeConfig(config);
}
}
} } | public class class_name {
@Override
public void releaseConfig(Config config) {
synchronized (configCache) {
ClassLoader classloader = findClassloaderForRegisteredConfig(config);
if (classloader != null) {
close(classloader); // depends on control dependency: [if], data = [(classloader]
} else {
closeConfig(config); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public DBI build(Environment environment,
PooledDataSourceFactory configuration,
ManagedDataSource dataSource,
String name) {
// Create the instance
final DBI dbi = this.newInstance(dataSource);
// Manage the data source that created this instance.
environment.lifecycle().manage(dataSource);
// Setup the required health checks.
final Optional<String> validationQuery = configuration.getValidationQuery();
environment.healthChecks().register(name, new DBIHealthCheck(
environment.getHealthCheckExecutorService(),
configuration.getValidationQueryTimeout().orElseGet(() -> Duration.seconds(5)),
dbi,
validationQuery));
// Setup logging.
dbi.setSQLLog(new LogbackLog(LOGGER, Level.TRACE));
// Setup the timing collector
dbi.setTimingCollector(new InstrumentedTimingCollector(environment.metrics(),
new SanerNamingStrategy()));
if (configuration.isAutoCommentsEnabled()) {
dbi.setStatementRewriter(new NamePrependingStatementRewriter(new ColonPrefixNamedParamStatementRewriter()));
}
// Add the default argument and column mapper factories.
this.configure(dbi, configuration);
return dbi;
} } | public class class_name {
public DBI build(Environment environment,
PooledDataSourceFactory configuration,
ManagedDataSource dataSource,
String name) {
// Create the instance
final DBI dbi = this.newInstance(dataSource);
// Manage the data source that created this instance.
environment.lifecycle().manage(dataSource);
// Setup the required health checks.
final Optional<String> validationQuery = configuration.getValidationQuery();
environment.healthChecks().register(name, new DBIHealthCheck(
environment.getHealthCheckExecutorService(),
configuration.getValidationQueryTimeout().orElseGet(() -> Duration.seconds(5)),
dbi,
validationQuery));
// Setup logging.
dbi.setSQLLog(new LogbackLog(LOGGER, Level.TRACE));
// Setup the timing collector
dbi.setTimingCollector(new InstrumentedTimingCollector(environment.metrics(),
new SanerNamingStrategy()));
if (configuration.isAutoCommentsEnabled()) {
dbi.setStatementRewriter(new NamePrependingStatementRewriter(new ColonPrefixNamedParamStatementRewriter())); // depends on control dependency: [if], data = [none]
}
// Add the default argument and column mapper factories.
this.configure(dbi, configuration);
return dbi;
} } |
public class class_name {
public static void main( final String[] args )
{
// Security.addProvider( new BouncyCastleProvider() );
String[] serviceTypes = getServiceTypes();
if ( serviceTypes != null )
{
for ( int i = 0; i < serviceTypes.length; i++ )
{
String serviceType = serviceTypes[i];
String[] serviceProviders = getCryptoImpls( serviceType );
if ( serviceProviders != null )
{
System.out.println( serviceType + ": provider list" );
for ( int j = 0; j < serviceProviders.length; j++ )
{
String provider = serviceProviders[j];
System.out.println( " " + provider );
}
}
else
{
System.out.println( serviceType + ": does not have any providers in this environment" );
}
}
}
} } | public class class_name {
public static void main( final String[] args )
{
// Security.addProvider( new BouncyCastleProvider() );
String[] serviceTypes = getServiceTypes();
if ( serviceTypes != null )
{
for ( int i = 0; i < serviceTypes.length; i++ )
{
String serviceType = serviceTypes[i];
String[] serviceProviders = getCryptoImpls( serviceType );
if ( serviceProviders != null )
{
System.out.println( serviceType + ": provider list" ); // depends on control dependency: [if], data = [none]
for ( int j = 0; j < serviceProviders.length; j++ )
{
String provider = serviceProviders[j];
System.out.println( " " + provider ); // depends on control dependency: [for], data = [none]
}
}
else
{
System.out.println( serviceType + ": does not have any providers in this environment" ); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public Point3d[] getVertices() {
Point3d[] vtxs = new Point3d[numVertices];
for (int i = 0; i < numVertices; i++) {
vtxs[i] = pointBuffer[vertexPointIndices[i]].pnt;
}
return vtxs;
} } | public class class_name {
public Point3d[] getVertices() {
Point3d[] vtxs = new Point3d[numVertices];
for (int i = 0; i < numVertices; i++) {
vtxs[i] = pointBuffer[vertexPointIndices[i]].pnt; // depends on control dependency: [for], data = [i]
}
return vtxs;
} } |
public class class_name {
public void marshall(SubmitJobRequest submitJobRequest, ProtocolMarshaller protocolMarshaller) {
if (submitJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(submitJobRequest.getJobName(), JOBNAME_BINDING);
protocolMarshaller.marshall(submitJobRequest.getJobQueue(), JOBQUEUE_BINDING);
protocolMarshaller.marshall(submitJobRequest.getArrayProperties(), ARRAYPROPERTIES_BINDING);
protocolMarshaller.marshall(submitJobRequest.getDependsOn(), DEPENDSON_BINDING);
protocolMarshaller.marshall(submitJobRequest.getJobDefinition(), JOBDEFINITION_BINDING);
protocolMarshaller.marshall(submitJobRequest.getParameters(), PARAMETERS_BINDING);
protocolMarshaller.marshall(submitJobRequest.getContainerOverrides(), CONTAINEROVERRIDES_BINDING);
protocolMarshaller.marshall(submitJobRequest.getNodeOverrides(), NODEOVERRIDES_BINDING);
protocolMarshaller.marshall(submitJobRequest.getRetryStrategy(), RETRYSTRATEGY_BINDING);
protocolMarshaller.marshall(submitJobRequest.getTimeout(), TIMEOUT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(SubmitJobRequest submitJobRequest, ProtocolMarshaller protocolMarshaller) {
if (submitJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(submitJobRequest.getJobName(), JOBNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(submitJobRequest.getJobQueue(), JOBQUEUE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(submitJobRequest.getArrayProperties(), ARRAYPROPERTIES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(submitJobRequest.getDependsOn(), DEPENDSON_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(submitJobRequest.getJobDefinition(), JOBDEFINITION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(submitJobRequest.getParameters(), PARAMETERS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(submitJobRequest.getContainerOverrides(), CONTAINEROVERRIDES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(submitJobRequest.getNodeOverrides(), NODEOVERRIDES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(submitJobRequest.getRetryStrategy(), RETRYSTRATEGY_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(submitJobRequest.getTimeout(), TIMEOUT_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public boolean hasAccess(final TargetMode _targetMode,
final Instance _instance)
throws EFapsException
{
boolean ret = super.hasAccess(_targetMode, _instance);
if (ret && getCommands().size() > 0 && !AppAccessHandler.excludeMode()) {
ret = false;
for (final AbstractCommand cmd : getCommands()) {
if (cmd.hasAccess(_targetMode, _instance)) {
ret = true;
break;
}
}
}
return ret;
} } | public class class_name {
@Override
public boolean hasAccess(final TargetMode _targetMode,
final Instance _instance)
throws EFapsException
{
boolean ret = super.hasAccess(_targetMode, _instance);
if (ret && getCommands().size() > 0 && !AppAccessHandler.excludeMode()) {
ret = false;
for (final AbstractCommand cmd : getCommands()) {
if (cmd.hasAccess(_targetMode, _instance)) {
ret = true; // depends on control dependency: [if], data = [none]
break;
}
}
}
return ret;
} } |
public class class_name {
private List<SecurityConstraint> getConstraintsFromHttpMethodElement(SecurityMetadata securityMetadataFromDD, Collection<String> urlPatterns,
ServletSecurityElement servletSecurity) {
List<SecurityConstraint> securityConstraints = new ArrayList<SecurityConstraint>();
Collection<HttpMethodConstraintElement> httpMethodConstraints = servletSecurity.getHttpMethodConstraints();
for (HttpMethodConstraintElement httpMethodConstraint : httpMethodConstraints) {
String method = httpMethodConstraint.getMethodName();
List<String> methods = new ArrayList<String>();
methods.add(method);
WebResourceCollection webResourceCollection = new WebResourceCollection((List<String>) urlPatterns, methods, new ArrayList<String>(), securityMetadataFromDD.isDenyUncoveredHttpMethods());
List<WebResourceCollection> webResourceCollections = new ArrayList<WebResourceCollection>();
webResourceCollections.add(webResourceCollection);
securityConstraints.add(createSecurityConstraint(securityMetadataFromDD, webResourceCollections, httpMethodConstraint, false));
}
return securityConstraints;
} } | public class class_name {
private List<SecurityConstraint> getConstraintsFromHttpMethodElement(SecurityMetadata securityMetadataFromDD, Collection<String> urlPatterns,
ServletSecurityElement servletSecurity) {
List<SecurityConstraint> securityConstraints = new ArrayList<SecurityConstraint>();
Collection<HttpMethodConstraintElement> httpMethodConstraints = servletSecurity.getHttpMethodConstraints();
for (HttpMethodConstraintElement httpMethodConstraint : httpMethodConstraints) {
String method = httpMethodConstraint.getMethodName();
List<String> methods = new ArrayList<String>();
methods.add(method); // depends on control dependency: [for], data = [none]
WebResourceCollection webResourceCollection = new WebResourceCollection((List<String>) urlPatterns, methods, new ArrayList<String>(), securityMetadataFromDD.isDenyUncoveredHttpMethods());
List<WebResourceCollection> webResourceCollections = new ArrayList<WebResourceCollection>();
webResourceCollections.add(webResourceCollection); // depends on control dependency: [for], data = [none]
securityConstraints.add(createSecurityConstraint(securityMetadataFromDD, webResourceCollections, httpMethodConstraint, false)); // depends on control dependency: [for], data = [httpMethodConstraint]
}
return securityConstraints;
} } |
public class class_name {
public double getVariance() {
if (!DATA_LIST.isEmpty()) {
double sum = 0;
double sumOfSquares = 0;
double average = 0;
for (DataPoint dataPoint : DATA_LIST) {
sumOfSquares += (dataPoint.getValue() * dataPoint.getValue());
sum += dataPoint.getValue();
}
average = sum / DATA_LIST.size();
return (sumOfSquares / DATA_LIST.size()) - average * average;
}
return 0;
} } | public class class_name {
public double getVariance() {
if (!DATA_LIST.isEmpty()) {
double sum = 0;
double sumOfSquares = 0;
double average = 0;
for (DataPoint dataPoint : DATA_LIST) {
sumOfSquares += (dataPoint.getValue() * dataPoint.getValue()); // depends on control dependency: [for], data = [dataPoint]
sum += dataPoint.getValue(); // depends on control dependency: [for], data = [dataPoint]
}
average = sum / DATA_LIST.size(); // depends on control dependency: [if], data = [none]
return (sumOfSquares / DATA_LIST.size()) - average * average; // depends on control dependency: [if], data = [none]
}
return 0;
} } |
public class class_name {
private String convertPattern(final String pattern, boolean datanucleusFormat) {
String wStr;
if (datanucleusFormat) {
wStr = "*";
} else {
wStr = ".*";
}
return pattern
.replaceAll("([^\\\\])%", "$1" + wStr).replaceAll("\\\\%", "%").replaceAll("^%", wStr)
.replaceAll("([^\\\\])_", "$1.").replaceAll("\\\\_", "_").replaceAll("^_", ".");
} } | public class class_name {
private String convertPattern(final String pattern, boolean datanucleusFormat) {
String wStr;
if (datanucleusFormat) {
wStr = "*"; // depends on control dependency: [if], data = [none]
} else {
wStr = ".*"; // depends on control dependency: [if], data = [none]
}
return pattern
.replaceAll("([^\\\\])%", "$1" + wStr).replaceAll("\\\\%", "%").replaceAll("^%", wStr)
.replaceAll("([^\\\\])_", "$1.").replaceAll("\\\\_", "_").replaceAll("^_", ".");
} } |
public class class_name {
public Map<String,String> getRequestHeaders() {
// If we already set the headers when logging request metadata, use them
if (super.getRequestHeaders() != null)
return super.getRequestHeaders();
try {
Map<String,String> headers = null;
String headersVar = getAttributeValueSmart(HEADERS_VARIABLE);
if (headersVar != null) {
Process processVO = getProcessDefinition();
Variable variableVO = processVO.getVariable(headersVar);
if (variableVO == null)
throw new ActivityException("Headers variable '" + headersVar + "' is not defined for process " + processVO.getLabel());
if (!variableVO.getType().startsWith("java.util.Map"))
throw new ActivityException("Headers variable '" + headersVar + "' must be of type java.util.Map");
Object headersObj = getVariableValue(headersVar);
if (headersObj != null) {
headers = new HashMap<>();
for (Object key : ((Map<?,?>)headersObj).keySet()) {
headers.put(key.toString(), ((Map<?,?>)headersObj).get(key).toString());
}
}
}
Object authProvider = getAuthProvider();
if (authProvider instanceof AuthTokenProvider) {
if (headers == null)
headers = new HashMap<>();
URL endpoint = new URL(getEndpointUri());
String user = getAttribute(AUTH_USER);
String password = getAttribute(AUTH_PASSWORD);
String appId = getAttribute(AUTH_APP_ID);
if (appId != null && appId.length() > 0) {
Map<String,String> options = new HashMap<>();
options.put("appId", appId);
((AuthTokenProvider) authProvider).setOptions(options);
}
String token = new String(((AuthTokenProvider)authProvider).getToken(endpoint, user, password));
headers.put("Authorization", "Bearer " + token);
}
// Set the headers so that we don't try and set them next time this method gets called
super.setRequestHeaders(headers);
return headers;
}
catch (Exception ex) {
logger.severeException(ex.getMessage(), ex);
return null;
}
} } | public class class_name {
public Map<String,String> getRequestHeaders() {
// If we already set the headers when logging request metadata, use them
if (super.getRequestHeaders() != null)
return super.getRequestHeaders();
try {
Map<String,String> headers = null;
String headersVar = getAttributeValueSmart(HEADERS_VARIABLE);
if (headersVar != null) {
Process processVO = getProcessDefinition();
Variable variableVO = processVO.getVariable(headersVar);
if (variableVO == null)
throw new ActivityException("Headers variable '" + headersVar + "' is not defined for process " + processVO.getLabel());
if (!variableVO.getType().startsWith("java.util.Map"))
throw new ActivityException("Headers variable '" + headersVar + "' must be of type java.util.Map");
Object headersObj = getVariableValue(headersVar);
if (headersObj != null) {
headers = new HashMap<>(); // depends on control dependency: [if], data = [none]
for (Object key : ((Map<?,?>)headersObj).keySet()) {
headers.put(key.toString(), ((Map<?,?>)headersObj).get(key).toString()); // depends on control dependency: [for], data = [key]
}
}
}
Object authProvider = getAuthProvider();
if (authProvider instanceof AuthTokenProvider) {
if (headers == null)
headers = new HashMap<>();
URL endpoint = new URL(getEndpointUri());
String user = getAttribute(AUTH_USER);
String password = getAttribute(AUTH_PASSWORD);
String appId = getAttribute(AUTH_APP_ID);
if (appId != null && appId.length() > 0) {
Map<String,String> options = new HashMap<>();
options.put("appId", appId); // depends on control dependency: [if], data = [none]
((AuthTokenProvider) authProvider).setOptions(options); // depends on control dependency: [if], data = [none]
}
String token = new String(((AuthTokenProvider)authProvider).getToken(endpoint, user, password));
headers.put("Authorization", "Bearer " + token); // depends on control dependency: [if], data = [none]
}
// Set the headers so that we don't try and set them next time this method gets called
super.setRequestHeaders(headers); // depends on control dependency: [try], data = [none]
return headers; // depends on control dependency: [try], data = [none]
}
catch (Exception ex) {
logger.severeException(ex.getMessage(), ex);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void set( T a ) {
if( a.getType() == getType() )
mat.set(a.getMatrix());
else {
setMatrix(a.mat.copy());
}
} } | public class class_name {
public void set( T a ) {
if( a.getType() == getType() )
mat.set(a.getMatrix());
else {
setMatrix(a.mat.copy()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static IndexedCorpus load(Reader reader, JsonOptions options) throws IOException {
Terminology termino = null;
OccurrenceStore occurrenceStore = null;
IndexedCorpus indexedCorpus = null;
JsonFactory jsonFactory = new JsonFactory();
JsonParser jp = jsonFactory.createParser(reader); // or Stream, Reader
jp.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
jp.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
String fieldname;
String compLemma = null;
String substring = null;
int fileSource = -1;
String wordLemma = null;
boolean isSWT;
String syntacticLabel = null;
boolean neoclassicalAffix = false;
int begin = -1;
int end = -1;
int nbWordAnnos = -1;
int nbSpottedTerms = -1;
Term b;
Term v;
String text;
String base;
String variant;
// String rule;
String relationType;
Map<Integer, String> inputSources = Maps.newTreeMap();
Map<String, List<TempVecEntry>> contextVectors = Maps.newHashMap();
// useful var for debug
JsonToken tok;
Lang lang = null;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (METADATA.equals(fieldname)) {
jp.nextToken();
String terminoName = null;
String corpusID = null;
String occurrenceStorage = null;
String persitentStorePath = null;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (LANG.equals(fieldname)) {
lang = Lang.forName(jp.nextTextValue());
} else if (NAME.equals(fieldname)) {
terminoName = jp.nextTextValue();
} else if (NB_WORD_ANNOTATIONS.equals(fieldname)) {
nbWordAnnos = jp.nextIntValue(-1);
} else if (NB_SPOTTED_TERMS.equals(fieldname)) {
nbSpottedTerms = jp.nextIntValue(-1);
} else if (CORPUS_ID.equals(fieldname)) {
corpusID = jp.nextTextValue();
} else if (OCCURRENCE_STORAGE.equals(fieldname)) {
occurrenceStorage = jp.nextTextValue();
} else if (OCCURRENCE_PERSITENT_STORE_PATH.equals(fieldname)) {
persitentStorePath = jp.nextTextValue();
}
}
Preconditions.checkState(lang != null, "The property meta.lang must be defined");
Preconditions.checkState(terminoName != null, "The property meta.name must be defined");
if(occurrenceStorage != null && occurrenceStorage.equals(OCCURRENCE_STORAGE_DISK)) {
Preconditions.checkNotNull(persitentStorePath, "Missing attribute " + OCCURRENCE_PERSITENT_STORE_PATH);
Preconditions.checkNotNull(lang, "Missing metadata attribute " + LANG);
occurrenceStore = TermSuiteFactory.createPersitentOccurrenceStore(persitentStorePath, lang);
} else {
Preconditions.checkNotNull(lang, "Missing metadata attribute " + LANG);
occurrenceStore = TermSuiteFactory.createMemoryOccurrenceStore(lang);
}
termino = TermSuiteFactory.createTerminology(lang, terminoName);
if(corpusID != null)
termino.setCorpusId(corpusID);
if(nbWordAnnos != -1)
termino.setNbWordAnnotations(new AtomicLong(nbWordAnnos));
if(nbSpottedTerms != -1)
termino.setNbSpottedTerms(new AtomicLong(nbSpottedTerms));
indexedCorpus = new IndexedCorpus(termino, occurrenceStore);
if(options.isMetadataOnly())
return indexedCorpus;
} else if (TERM_WORDS.equals(fieldname)) {
jp.nextToken();
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
WordBuilder wordBuilder = WordBuilder.start(termino);
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (LEMMA.equals(fieldname))
wordBuilder.setLemma(jp.nextTextValue());
else if (COMPOUND_TYPE.equals(fieldname))
wordBuilder.setCompoundType(CompoundType.fromName(jp.nextTextValue()));
else if (STEM.equals(fieldname))
wordBuilder.setStem(jp.nextTextValue());
else if (COMPONENTS.equals(fieldname)) {
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (LEMMA.equals(fieldname))
compLemma = jp.nextTextValue();
else if (SUBSTRING.equals(fieldname))
substring = jp.nextTextValue();
else if (BEGIN.equals(fieldname))
begin = jp.nextIntValue(-2);
else if (COMPOUND_NEOCLASSICAL_AFFIX.equals(fieldname))
neoclassicalAffix = jp.nextBooleanValue();
else if (END.equals(fieldname))
end = jp.nextIntValue(-2);
}
wordBuilder.addComponent(begin, end, substring, compLemma, neoclassicalAffix);
}
}
}
Word word = wordBuilder.create();
termino.getWords().put(word.getLemma(), word);
}
} else if (TERMS.equals(fieldname)) {
jp.nextToken();
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
TermBuilder builder = TermBuilder.start(termino);
List<TempVecEntry> currentContextVector = Lists.newArrayList();
Map<TermProperty, Object> properties = null;
String currentGroupingKey = null;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (PROPERTIES.equals(fieldname)) {
properties = readProperties(TermProperty.class, jp);
Preconditions.checkState(properties.containsKey(TermProperty.GROUPING_KEY), MSG_NO_GROUPING_KEY_SET);
currentGroupingKey = (String)properties.get(TermProperty.GROUPING_KEY);
} else if (TERM_WORDS.equals(fieldname)) {
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
wordLemma = null;
syntacticLabel = null;
isSWT = false;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (LEMMA.equals(fieldname))
wordLemma = jp.nextTextValue();
else if (IS_SWT.equals(fieldname))
isSWT = jp.nextBooleanValue();
else if (SYN.equals(fieldname))
syntacticLabel = jp.nextTextValue();
}
Preconditions.checkState(wordLemma != null, MSG_EXPECT_PROP_FOR_TERM_WORD, LEMMA);
Preconditions.checkState(termino.getWords().containsKey(wordLemma), MSG_WORD_NOT_FOUND, wordLemma);
Preconditions.checkState(syntacticLabel != null, MSG_EXPECT_PROP_FOR_TERM_WORD, SYN);
builder.addWord(termino.getWords().get(wordLemma), syntacticLabel, isSWT);
}
} else if (TERM_CONTEXT.equals(fieldname)) {
@SuppressWarnings("unused")
int totalCooccs = 0;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (TOTAL_COOCCURRENCES.equals(fieldname))
/*
* value never used since the total will
* be reincremented in the contextVector
*/
totalCooccs = jp.nextIntValue(-1);
else if (CO_OCCURRENCES.equals(fieldname)) {
jp.nextToken();
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
TempVecEntry entry = new TempVecEntry();
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (NB_COCCS.equals(fieldname))
entry.setNbCooccs(jp.nextIntValue(-1));
else if (ASSOC_RATE.equals(fieldname)) {
jp.nextToken();
entry.setAssocRate(jp.getFloatValue());
} else if (CO_TERM.equals(fieldname))
entry.setTermGroupingKey(jp.nextTextValue());
else if (FILE.equals(fieldname)) {
fileSource = jp.nextIntValue(-1);
}
}
currentContextVector.add(entry);
}
}
}
} else
throw new IllegalStateException("Unexpected field name for term: " + fieldname);
//end if fieldname
} // end term object
Preconditions.checkState(currentGroupingKey != null, MSG_NO_GKEY_FOR_TERM);
Term t = builder.create();
t.setProperties(properties);
termino.getTerms().put(t.getGroupingKey(), t);
if(options.isWithContexts())
contextVectors.put(currentGroupingKey, currentContextVector);
}// end array of terms
} else if (INPUT_SOURCES.equals(fieldname)) {
jp.nextToken();
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
String id = jp.getCurrentName();
try {
inputSources.put(Integer.parseInt(id),jp.nextTextValue());
} catch(NumberFormatException e) {
IOUtils.closeQuietly(jp);
throw new IllegalArgumentException("Bad format for input source key: " + id);
}
}
} else if (TERM_RELATIONS.equals(fieldname)) {
jp.nextToken();
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
base = null;
variant = null;
relationType = null;
Map<RelationProperty,Object> properties = new HashMap<>();
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (FROM.equals(fieldname))
base = jp.nextTextValue();
else if (TO.equals(fieldname))
variant = jp.nextTextValue();
else if (RELATION_TYPE.equals(fieldname))
relationType = jp.nextTextValue();
else if (PROPERTIES.equals(fieldname))
properties = readProperties(RelationProperty.class, jp);
}
Preconditions.checkNotNull(base, MSG_EXPECT_PROP_FOR_VAR, FROM);
Preconditions.checkNotNull(variant, MSG_EXPECT_PROP_FOR_VAR, TO);
b = termino.getTerms().get(base);
v = termino.getTerms().get(variant);
if(b != null && v != null) {
RelationType vType = RelationType.fromShortName(relationType);
Relation tv = new Relation(
vType,
b,
v);
tv.setProperties(properties);
termino.getRelations().add(tv);
} else {
if(b==null)
LOGGER.warn("Could not build variant because term \"{}\" was not found.", base);
if(v==null)
LOGGER.warn("Could not build variant because term \"{}\" was not found.", variant);
}
// Preconditions.checkNotNull(b, MSG_TERM_DOES_NOT_EXIST, base);
// Preconditions.checkNotNull(v, MSG_TERM_DOES_NOT_EXIST, variant);
} // end syntactic variations array
} else if (TERM_OCCURRENCES.equals(fieldname)) {
tok = jp.nextToken();
if(tok == JsonToken.START_ARRAY) {
String tid;
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
tid = null;
begin = -1;
end = -1;
fileSource = -1;
text = null;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (BEGIN.equals(fieldname))
begin = jp.nextIntValue(-1);
else if (TEXT.equals(fieldname))
text = jp.nextTextValue();
else if (END.equals(fieldname))
end = jp.nextIntValue(-1);
else if (TERM_ID.equals(fieldname))
tid = jp.nextTextValue();
else if (FILE.equals(fieldname)) {
fileSource = jp.nextIntValue(-1);
}
}
Preconditions.checkArgument(begin != -1, MSG_EXPECT_PROP_FOR_OCCURRENCE, BEGIN);
Preconditions.checkArgument(end != -1, MSG_EXPECT_PROP_FOR_OCCURRENCE, END);
Preconditions.checkArgument(fileSource != -1, MSG_EXPECT_PROP_FOR_OCCURRENCE, FILE);
String documentUrl = inputSources.get(fileSource);
Preconditions.checkNotNull(documentUrl, MSG_NO_FILE_SOURCE_WITH_ID, fileSource);
Preconditions.checkNotNull(text, MSG_EXPECT_PROP_FOR_OCCURRENCE, TEXT);
Term term = termino.getTerms().get(tid);
Preconditions.checkNotNull(term, MSG_NO_SUCH_TERM_IN_TERMINO, tid);
indexedCorpus.getOccurrenceStore().addOccurrence(term, documentUrl, begin, end, text);
}
}
// end occurrences
}
}
jp.close();
if(options.isWithContexts()) {
/*
* map term ids with terms in context vectors and
* set context vectors
*/
List<TempVecEntry> currentTempVecList;
Term term = null;
Term coTerm = null;
ContextVector contextVector;
for(String groupingKey:contextVectors.keySet()) {
currentTempVecList = contextVectors.get(groupingKey);
term = termino.getTerms().get(groupingKey);
if(!currentTempVecList.isEmpty()) {
contextVector = new ContextVector(term);
for(TempVecEntry tempVecEntry:currentTempVecList) {
coTerm = termino.getTerms().get(tempVecEntry.getTermGroupingKey());
contextVector.addEntry(coTerm, tempVecEntry.getNbCooccs(), tempVecEntry.getAssocRate());
}
term.setContext(contextVector);
}
}
}
return indexedCorpus;
} } | public class class_name {
public static IndexedCorpus load(Reader reader, JsonOptions options) throws IOException {
Terminology termino = null;
OccurrenceStore occurrenceStore = null;
IndexedCorpus indexedCorpus = null;
JsonFactory jsonFactory = new JsonFactory();
JsonParser jp = jsonFactory.createParser(reader); // or Stream, Reader
jp.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
jp.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
String fieldname;
String compLemma = null;
String substring = null;
int fileSource = -1;
String wordLemma = null;
boolean isSWT;
String syntacticLabel = null;
boolean neoclassicalAffix = false;
int begin = -1;
int end = -1;
int nbWordAnnos = -1;
int nbSpottedTerms = -1;
Term b;
Term v;
String text;
String base;
String variant;
// String rule;
String relationType;
Map<Integer, String> inputSources = Maps.newTreeMap();
Map<String, List<TempVecEntry>> contextVectors = Maps.newHashMap();
// useful var for debug
JsonToken tok;
Lang lang = null;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (METADATA.equals(fieldname)) {
jp.nextToken();
String terminoName = null;
String corpusID = null;
String occurrenceStorage = null;
String persitentStorePath = null;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName(); // depends on control dependency: [while], data = [none]
if (LANG.equals(fieldname)) {
lang = Lang.forName(jp.nextTextValue()); // depends on control dependency: [if], data = [none]
} else if (NAME.equals(fieldname)) {
terminoName = jp.nextTextValue(); // depends on control dependency: [if], data = [none]
} else if (NB_WORD_ANNOTATIONS.equals(fieldname)) {
nbWordAnnos = jp.nextIntValue(-1); // depends on control dependency: [if], data = [none]
} else if (NB_SPOTTED_TERMS.equals(fieldname)) {
nbSpottedTerms = jp.nextIntValue(-1); // depends on control dependency: [if], data = [none]
} else if (CORPUS_ID.equals(fieldname)) {
corpusID = jp.nextTextValue(); // depends on control dependency: [if], data = [none]
} else if (OCCURRENCE_STORAGE.equals(fieldname)) {
occurrenceStorage = jp.nextTextValue(); // depends on control dependency: [if], data = [none]
} else if (OCCURRENCE_PERSITENT_STORE_PATH.equals(fieldname)) {
persitentStorePath = jp.nextTextValue(); // depends on control dependency: [if], data = [none]
}
}
Preconditions.checkState(lang != null, "The property meta.lang must be defined");
Preconditions.checkState(terminoName != null, "The property meta.name must be defined");
if(occurrenceStorage != null && occurrenceStorage.equals(OCCURRENCE_STORAGE_DISK)) {
Preconditions.checkNotNull(persitentStorePath, "Missing attribute " + OCCURRENCE_PERSITENT_STORE_PATH); // depends on control dependency: [if], data = [none]
Preconditions.checkNotNull(lang, "Missing metadata attribute " + LANG); // depends on control dependency: [if], data = [none]
occurrenceStore = TermSuiteFactory.createPersitentOccurrenceStore(persitentStorePath, lang); // depends on control dependency: [if], data = [none]
} else {
Preconditions.checkNotNull(lang, "Missing metadata attribute " + LANG); // depends on control dependency: [if], data = [none]
occurrenceStore = TermSuiteFactory.createMemoryOccurrenceStore(lang); // depends on control dependency: [if], data = [none]
}
termino = TermSuiteFactory.createTerminology(lang, terminoName);
if(corpusID != null)
termino.setCorpusId(corpusID);
if(nbWordAnnos != -1)
termino.setNbWordAnnotations(new AtomicLong(nbWordAnnos));
if(nbSpottedTerms != -1)
termino.setNbSpottedTerms(new AtomicLong(nbSpottedTerms));
indexedCorpus = new IndexedCorpus(termino, occurrenceStore);
if(options.isMetadataOnly())
return indexedCorpus;
} else if (TERM_WORDS.equals(fieldname)) {
jp.nextToken();
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
WordBuilder wordBuilder = WordBuilder.start(termino);
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName(); // depends on control dependency: [while], data = [none]
if (LEMMA.equals(fieldname))
wordBuilder.setLemma(jp.nextTextValue());
else if (COMPOUND_TYPE.equals(fieldname))
wordBuilder.setCompoundType(CompoundType.fromName(jp.nextTextValue()));
else if (STEM.equals(fieldname))
wordBuilder.setStem(jp.nextTextValue());
else if (COMPONENTS.equals(fieldname)) {
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName(); // depends on control dependency: [while], data = [none]
if (LEMMA.equals(fieldname))
compLemma = jp.nextTextValue();
else if (SUBSTRING.equals(fieldname))
substring = jp.nextTextValue();
else if (BEGIN.equals(fieldname))
begin = jp.nextIntValue(-2);
else if (COMPOUND_NEOCLASSICAL_AFFIX.equals(fieldname))
neoclassicalAffix = jp.nextBooleanValue();
else if (END.equals(fieldname))
end = jp.nextIntValue(-2);
}
wordBuilder.addComponent(begin, end, substring, compLemma, neoclassicalAffix); // depends on control dependency: [while], data = [none]
}
}
}
Word word = wordBuilder.create();
termino.getWords().put(word.getLemma(), word); // depends on control dependency: [while], data = [none]
}
} else if (TERMS.equals(fieldname)) {
jp.nextToken();
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
TermBuilder builder = TermBuilder.start(termino);
List<TempVecEntry> currentContextVector = Lists.newArrayList();
Map<TermProperty, Object> properties = null;
String currentGroupingKey = null;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName(); // depends on control dependency: [while], data = [none]
if (PROPERTIES.equals(fieldname)) {
properties = readProperties(TermProperty.class, jp); // depends on control dependency: [if], data = [none]
Preconditions.checkState(properties.containsKey(TermProperty.GROUPING_KEY), MSG_NO_GROUPING_KEY_SET); // depends on control dependency: [if], data = [none]
currentGroupingKey = (String)properties.get(TermProperty.GROUPING_KEY); // depends on control dependency: [if], data = [none]
} else if (TERM_WORDS.equals(fieldname)) {
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
wordLemma = null; // depends on control dependency: [while], data = [none]
syntacticLabel = null; // depends on control dependency: [while], data = [none]
isSWT = false; // depends on control dependency: [while], data = [none]
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName(); // depends on control dependency: [while], data = [none]
if (LEMMA.equals(fieldname))
wordLemma = jp.nextTextValue();
else if (IS_SWT.equals(fieldname))
isSWT = jp.nextBooleanValue();
else if (SYN.equals(fieldname))
syntacticLabel = jp.nextTextValue();
}
Preconditions.checkState(wordLemma != null, MSG_EXPECT_PROP_FOR_TERM_WORD, LEMMA); // depends on control dependency: [while], data = [none]
Preconditions.checkState(termino.getWords().containsKey(wordLemma), MSG_WORD_NOT_FOUND, wordLemma); // depends on control dependency: [while], data = [none]
Preconditions.checkState(syntacticLabel != null, MSG_EXPECT_PROP_FOR_TERM_WORD, SYN); // depends on control dependency: [while], data = [none]
builder.addWord(termino.getWords().get(wordLemma), syntacticLabel, isSWT); // depends on control dependency: [while], data = [none]
}
} else if (TERM_CONTEXT.equals(fieldname)) {
@SuppressWarnings("unused")
int totalCooccs = 0;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName(); // depends on control dependency: [while], data = [none]
if (TOTAL_COOCCURRENCES.equals(fieldname))
/*
* value never used since the total will
* be reincremented in the contextVector
*/
totalCooccs = jp.nextIntValue(-1);
else if (CO_OCCURRENCES.equals(fieldname)) {
jp.nextToken(); // depends on control dependency: [if], data = [none]
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
TempVecEntry entry = new TempVecEntry();
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName(); // depends on control dependency: [while], data = [none]
if (NB_COCCS.equals(fieldname))
entry.setNbCooccs(jp.nextIntValue(-1));
else if (ASSOC_RATE.equals(fieldname)) {
jp.nextToken(); // depends on control dependency: [if], data = [none]
entry.setAssocRate(jp.getFloatValue()); // depends on control dependency: [if], data = [none]
} else if (CO_TERM.equals(fieldname))
entry.setTermGroupingKey(jp.nextTextValue());
else if (FILE.equals(fieldname)) {
fileSource = jp.nextIntValue(-1); // depends on control dependency: [if], data = [none]
}
}
currentContextVector.add(entry); // depends on control dependency: [while], data = [none]
}
}
}
} else
throw new IllegalStateException("Unexpected field name for term: " + fieldname);
//end if fieldname
} // end term object
Preconditions.checkState(currentGroupingKey != null, MSG_NO_GKEY_FOR_TERM); // depends on control dependency: [while], data = [none]
Term t = builder.create();
t.setProperties(properties); // depends on control dependency: [while], data = [none]
termino.getTerms().put(t.getGroupingKey(), t); // depends on control dependency: [while], data = [none]
if(options.isWithContexts())
contextVectors.put(currentGroupingKey, currentContextVector);
}// end array of terms
} else if (INPUT_SOURCES.equals(fieldname)) {
jp.nextToken();
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
String id = jp.getCurrentName();
try {
inputSources.put(Integer.parseInt(id),jp.nextTextValue()); // depends on control dependency: [try], data = [none]
} catch(NumberFormatException e) {
IOUtils.closeQuietly(jp);
throw new IllegalArgumentException("Bad format for input source key: " + id);
} // depends on control dependency: [catch], data = [none]
}
} else if (TERM_RELATIONS.equals(fieldname)) {
jp.nextToken();
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
base = null;
variant = null;
relationType = null;
Map<RelationProperty,Object> properties = new HashMap<>();
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName(); // depends on control dependency: [while], data = [none]
if (FROM.equals(fieldname))
base = jp.nextTextValue();
else if (TO.equals(fieldname))
variant = jp.nextTextValue();
else if (RELATION_TYPE.equals(fieldname))
relationType = jp.nextTextValue();
else if (PROPERTIES.equals(fieldname))
properties = readProperties(RelationProperty.class, jp);
}
Preconditions.checkNotNull(base, MSG_EXPECT_PROP_FOR_VAR, FROM);
Preconditions.checkNotNull(variant, MSG_EXPECT_PROP_FOR_VAR, TO);
b = termino.getTerms().get(base);
v = termino.getTerms().get(variant);
if(b != null && v != null) {
RelationType vType = RelationType.fromShortName(relationType);
Relation tv = new Relation(
vType,
b,
v);
tv.setProperties(properties);
termino.getRelations().add(tv);
} else {
if(b==null)
LOGGER.warn("Could not build variant because term \"{}\" was not found.", base);
if(v==null)
LOGGER.warn("Could not build variant because term \"{}\" was not found.", variant);
}
// Preconditions.checkNotNull(b, MSG_TERM_DOES_NOT_EXIST, base);
// Preconditions.checkNotNull(v, MSG_TERM_DOES_NOT_EXIST, variant);
} // end syntactic variations array
} else if (TERM_OCCURRENCES.equals(fieldname)) {
tok = jp.nextToken();
if(tok == JsonToken.START_ARRAY) {
String tid;
while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
tid = null;
begin = -1;
end = -1;
fileSource = -1;
text = null;
while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
fieldname = jp.getCurrentName();
if (BEGIN.equals(fieldname))
begin = jp.nextIntValue(-1);
else if (TEXT.equals(fieldname))
text = jp.nextTextValue();
else if (END.equals(fieldname))
end = jp.nextIntValue(-1);
else if (TERM_ID.equals(fieldname))
tid = jp.nextTextValue();
else if (FILE.equals(fieldname)) {
fileSource = jp.nextIntValue(-1);
}
}
Preconditions.checkArgument(begin != -1, MSG_EXPECT_PROP_FOR_OCCURRENCE, BEGIN);
Preconditions.checkArgument(end != -1, MSG_EXPECT_PROP_FOR_OCCURRENCE, END);
Preconditions.checkArgument(fileSource != -1, MSG_EXPECT_PROP_FOR_OCCURRENCE, FILE);
String documentUrl = inputSources.get(fileSource);
Preconditions.checkNotNull(documentUrl, MSG_NO_FILE_SOURCE_WITH_ID, fileSource);
Preconditions.checkNotNull(text, MSG_EXPECT_PROP_FOR_OCCURRENCE, TEXT);
Term term = termino.getTerms().get(tid);
Preconditions.checkNotNull(term, MSG_NO_SUCH_TERM_IN_TERMINO, tid);
indexedCorpus.getOccurrenceStore().addOccurrence(term, documentUrl, begin, end, text);
}
}
// end occurrences
}
}
jp.close();
if(options.isWithContexts()) {
/*
* map term ids with terms in context vectors and
* set context vectors
*/
List<TempVecEntry> currentTempVecList;
Term term = null;
Term coTerm = null;
ContextVector contextVector;
for(String groupingKey:contextVectors.keySet()) {
currentTempVecList = contextVectors.get(groupingKey);
term = termino.getTerms().get(groupingKey);
if(!currentTempVecList.isEmpty()) {
contextVector = new ContextVector(term);
for(TempVecEntry tempVecEntry:currentTempVecList) {
coTerm = termino.getTerms().get(tempVecEntry.getTermGroupingKey());
contextVector.addEntry(coTerm, tempVecEntry.getNbCooccs(), tempVecEntry.getAssocRate());
}
term.setContext(contextVector);
}
}
}
return indexedCorpus;
} } |
public class class_name {
private boolean readMessage(ByteBuffer buffer) {
// logger.finest("readMessage: " + bytesRead + " bytes read, remaining=" +
// remainingBytes.length + ", state=" + state.toString() + ", recurse=" +
// recurse);
buffer.position(0);
int bytesWeHaveBeenReading = 0;
switch (state) {
case SERVICELIST:
StringBuilder builder = new StringBuilder();
builder.append(buffer.asCharBuffer());
parseServiceList(builder.toString());
buffer.position(0);// reset position!
bytesWeHaveBeenReading = buffer.limit(); // bytesWeHaveBeenreading = all
// bytes in buffer!
break;
case HANDSHAKE:
if (buffer.limit() >= 6) {
byte[] dst = new byte[6];
buffer.position(0);// read from start!
buffer.get(dst);
buffer.position(0);// reset position!
bytesWeHaveBeenReading = 6; // 6 bytes will be removed from buffer
String handShake = new String(dst);
if (!handShake.equals("STP/1\n")) {
close();
connectionHandler.onException(
new CommunicationException("Expected STP/1, got: " + handShake));
}
setState(State.EMPTY);
connectionHandler.onHandshake(true);
}
break;
case EMPTY: // read 4 byte header: STP/0
if (buffer.limit() >= 4) {
byte[] headerPrefix = new byte[4];
buffer.get(headerPrefix);
buffer.position(0);
bytesWeHaveBeenReading = 4;
ByteString incomingPrefix = ByteString.copyFrom(headerPrefix);
if (stpPrefix.equals(incomingPrefix)) {
setState(State.STP);
/*
if(buffer.hasRemaining()){
buffer.compact();
readMessage(buffer, buffer.position(), true);
} else {
buffer.clear();
}
*/
} else {
close();
connectionHandler.onException(
new CommunicationException("Expected empty header"));
}
}
break;
case STP:
// Try to read size
buffer.position(0);
if (buffer.limit() <= 0) {
logger.finest("STP: Empty buffer");
break;
}
int messageSize = readRawVarint32(buffer);// read part of buffer
bytesWeHaveBeenReading = buffer.position();
buffer.position(0);
// If we got size, read more, if not just leave it!
if (buffer.limit() >= bytesWeHaveBeenReading + messageSize) {
buffer.position(bytesWeHaveBeenReading);
// Read type and Payload!
int messageType = buffer.get();
bytesWeHaveBeenReading += 1;
byte[] payload = new byte[--messageSize];
buffer.get(payload);
buffer.position(0);
bytesWeHaveBeenReading += messageSize; // 32 bits = 4 bytes :-)
setState(State.EMPTY);
try {
processMessage(messageType, payload);
} catch (IOException e) {
close();
connectionHandler.onException(new CommunicationException(
"Error while processing the message: " + e.getMessage()));
}
} else {
// 4 + messageSize because of the int at the beginning
logger.finest(String.format("Tried to read a message and expected %d bytes, but got %d",
(4 + messageSize), buffer.limit()));
buffer.position(0);
bytesWeHaveBeenReading = 0;
}
break;
}
// Pop number of read bytes from
if (bytesWeHaveBeenReading > 0) {
// Pop X bytes, and keep message for the rest
int rest = buffer.limit() - bytesWeHaveBeenReading;
if (rest <= 0) {
buffer.clear();
buffer.limit(0);
} else {
byte[] temp = new byte[rest];
buffer.position(bytesWeHaveBeenReading);
buffer.get(temp, 0, rest);
buffer.clear();
buffer.limit(rest);
buffer.position(0);
buffer.put(temp, 0, rest);
buffer.position(0);// set position back to start!
}
logger.finest(String.format("Did read message of %d bytes, new buffer size is %d",
bytesWeHaveBeenReading, buffer.limit()));
return true; // We did read a message :-)
} else {
if (buffer.limit() > 0) {
logger.finest("Did NOT read message from buffer of size " + buffer.limit());
} else {
logger.finest("No messages in empty buffer");
}
return false;
}
} } | public class class_name {
private boolean readMessage(ByteBuffer buffer) {
// logger.finest("readMessage: " + bytesRead + " bytes read, remaining=" +
// remainingBytes.length + ", state=" + state.toString() + ", recurse=" +
// recurse);
buffer.position(0);
int bytesWeHaveBeenReading = 0;
switch (state) {
case SERVICELIST:
StringBuilder builder = new StringBuilder();
builder.append(buffer.asCharBuffer());
parseServiceList(builder.toString());
buffer.position(0);// reset position!
bytesWeHaveBeenReading = buffer.limit(); // bytesWeHaveBeenreading = all
// bytes in buffer!
break;
case HANDSHAKE:
if (buffer.limit() >= 6) {
byte[] dst = new byte[6];
buffer.position(0);// read from start! // depends on control dependency: [if], data = [none]
buffer.get(dst); // depends on control dependency: [if], data = [none]
buffer.position(0);// reset position! // depends on control dependency: [if], data = [none]
bytesWeHaveBeenReading = 6; // 6 bytes will be removed from buffer // depends on control dependency: [if], data = [none]
String handShake = new String(dst);
if (!handShake.equals("STP/1\n")) {
close(); // depends on control dependency: [if], data = [none]
connectionHandler.onException(
new CommunicationException("Expected STP/1, got: " + handShake)); // depends on control dependency: [if], data = [none]
}
setState(State.EMPTY); // depends on control dependency: [if], data = [none]
connectionHandler.onHandshake(true); // depends on control dependency: [if], data = [none]
}
break;
case EMPTY: // read 4 byte header: STP/0
if (buffer.limit() >= 4) {
byte[] headerPrefix = new byte[4];
buffer.get(headerPrefix); // depends on control dependency: [if], data = [none]
buffer.position(0); // depends on control dependency: [if], data = [none]
bytesWeHaveBeenReading = 4; // depends on control dependency: [if], data = [none]
ByteString incomingPrefix = ByteString.copyFrom(headerPrefix);
if (stpPrefix.equals(incomingPrefix)) {
setState(State.STP); // depends on control dependency: [if], data = [none]
/*
if(buffer.hasRemaining()){
buffer.compact();
readMessage(buffer, buffer.position(), true);
} else {
buffer.clear();
}
*/
} else {
close(); // depends on control dependency: [if], data = [none]
connectionHandler.onException(
new CommunicationException("Expected empty header")); // depends on control dependency: [if], data = [none]
}
}
break;
case STP:
// Try to read size
buffer.position(0);
if (buffer.limit() <= 0) {
logger.finest("STP: Empty buffer"); // depends on control dependency: [if], data = [none]
break;
}
int messageSize = readRawVarint32(buffer);// read part of buffer
bytesWeHaveBeenReading = buffer.position();
buffer.position(0);
// If we got size, read more, if not just leave it!
if (buffer.limit() >= bytesWeHaveBeenReading + messageSize) {
buffer.position(bytesWeHaveBeenReading); // depends on control dependency: [if], data = [none]
// Read type and Payload!
int messageType = buffer.get();
bytesWeHaveBeenReading += 1; // depends on control dependency: [if], data = [none]
byte[] payload = new byte[--messageSize];
buffer.get(payload); // depends on control dependency: [if], data = [none]
buffer.position(0); // depends on control dependency: [if], data = [none]
bytesWeHaveBeenReading += messageSize; // 32 bits = 4 bytes :-) // depends on control dependency: [if], data = [none]
setState(State.EMPTY); // depends on control dependency: [if], data = [none]
try {
processMessage(messageType, payload); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
close();
connectionHandler.onException(new CommunicationException(
"Error while processing the message: " + e.getMessage()));
} // depends on control dependency: [catch], data = [none]
} else {
// 4 + messageSize because of the int at the beginning
logger.finest(String.format("Tried to read a message and expected %d bytes, but got %d",
(4 + messageSize), buffer.limit())); // depends on control dependency: [if], data = [none]
buffer.position(0); // depends on control dependency: [if], data = [none]
bytesWeHaveBeenReading = 0; // depends on control dependency: [if], data = [none]
}
break;
}
// Pop number of read bytes from
if (bytesWeHaveBeenReading > 0) {
// Pop X bytes, and keep message for the rest
int rest = buffer.limit() - bytesWeHaveBeenReading;
if (rest <= 0) {
buffer.clear(); // depends on control dependency: [if], data = [none]
buffer.limit(0); // depends on control dependency: [if], data = [none]
} else {
byte[] temp = new byte[rest];
buffer.position(bytesWeHaveBeenReading); // depends on control dependency: [if], data = [none]
buffer.get(temp, 0, rest); // depends on control dependency: [if], data = [none]
buffer.clear(); // depends on control dependency: [if], data = [none]
buffer.limit(rest); // depends on control dependency: [if], data = [(rest]
buffer.position(0); // depends on control dependency: [if], data = [none]
buffer.put(temp, 0, rest); // depends on control dependency: [if], data = [none]
buffer.position(0);// set position back to start! // depends on control dependency: [if], data = [none]
}
logger.finest(String.format("Did read message of %d bytes, new buffer size is %d",
bytesWeHaveBeenReading, buffer.limit())); // depends on control dependency: [if], data = [none]
return true; // We did read a message :-) // depends on control dependency: [if], data = [none]
} else {
if (buffer.limit() > 0) {
logger.finest("Did NOT read message from buffer of size " + buffer.limit()); // depends on control dependency: [if], data = [none]
} else {
logger.finest("No messages in empty buffer"); // depends on control dependency: [if], data = [none]
}
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected final OnDemandStatsProducer getProducer(Class producerClass, String producerId, String category, String subsystem, boolean tracingSupported){
OnDemandStatsProducer<T> producer = (OnDemandStatsProducer<T>) ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId);
if (producer == null) {
producer = new OnDemandStatsProducer<T>(producerId, category, subsystem, getStatsFactory());
producer.setTracingSupported(tracingSupported);
ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(producer);
//check for annotations
createClassLevelAccumulators(producer, producerClass);
for (Method method : producerClass.getMethods()){
createMethodLevelAccumulators(producer, method);
}
}
try {
return (OnDemandStatsProducer) ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId);
} catch (ClassCastException e) {
LOGGER.error("getProducer(): Unexpected producer type", e);
return null;
}
} } | public class class_name {
protected final OnDemandStatsProducer getProducer(Class producerClass, String producerId, String category, String subsystem, boolean tracingSupported){
OnDemandStatsProducer<T> producer = (OnDemandStatsProducer<T>) ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId);
if (producer == null) {
producer = new OnDemandStatsProducer<T>(producerId, category, subsystem, getStatsFactory()); // depends on control dependency: [if], data = [(producer]
producer.setTracingSupported(tracingSupported); // depends on control dependency: [if], data = [none]
ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(producer); // depends on control dependency: [if], data = [(producer]
//check for annotations
createClassLevelAccumulators(producer, producerClass); // depends on control dependency: [if], data = [(producer]
for (Method method : producerClass.getMethods()){
createMethodLevelAccumulators(producer, method); // depends on control dependency: [for], data = [method]
}
}
try {
return (OnDemandStatsProducer) ProducerRegistryFactory.getProducerRegistryInstance().getProducer(producerId); // depends on control dependency: [try], data = [none]
} catch (ClassCastException e) {
LOGGER.error("getProducer(): Unexpected producer type", e);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static synchronized void registerEngine(RenderEngine engine) {
if (null == availableEngines) {
availableEngines = new HashMap();
}
availableEngines.put(engine.getName(), engine);
} } | public class class_name {
public static synchronized void registerEngine(RenderEngine engine) {
if (null == availableEngines) {
availableEngines = new HashMap(); // depends on control dependency: [if], data = [none]
}
availableEngines.put(engine.getName(), engine);
} } |
public class class_name {
private boolean parseCRLFs(WsByteBuffer buff) throws MalformedMessageException {
byte b;
// scan through up to 4 characters
for (int i = 0; i < 4; i++) {
if (this.bytePosition >= this.byteLimit) {
if (!fillByteCache(buff)) {
// no more data
return false;
}
}
b = this.byteCache[this.bytePosition++];
if (BNFHeaders.CR == b) {
// ignore CR characters
continue;
} else if (BNFHeaders.LF == b) {
// line feed found
this.numCRLFs++;
} else if (BNFHeaders.SPACE == b || BNFHeaders.TAB == b) {
// Check for multi-line header values
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Multiline header follows");
}
this.bIsMultiLine = true;
if (null == this.lastHdrInSequence) {
// can't start off with a multiline value
throw new MalformedMessageException("Incorrect multiline header value");
}
this.currentElem = this.lastHdrInSequence;
this.stateOfParsing = PARSING_VALUE;
this.numCRLFs = 0;
return true;
} else {
// found end...move pointer back one
this.bytePosition--;
break; // out of for loop
}
if (2 <= this.numCRLFs) {
// found double LFs, end of headers
this.eohPosition = findCurrentBufferPosition(buff);
buff.position(this.eohPosition);
break; // out of for loop
}
} // end of for loop
// we're about to either start parsing another header or
// we've reached the end of the headers
this.bIsMultiLine = false;
this.stateOfParsing = PARSING_HEADER;
this.numCRLFs = 0;
return true;
} } | public class class_name {
private boolean parseCRLFs(WsByteBuffer buff) throws MalformedMessageException {
byte b;
// scan through up to 4 characters
for (int i = 0; i < 4; i++) {
if (this.bytePosition >= this.byteLimit) {
if (!fillByteCache(buff)) {
// no more data
return false; // depends on control dependency: [if], data = [none]
}
}
b = this.byteCache[this.bytePosition++];
if (BNFHeaders.CR == b) {
// ignore CR characters
continue;
} else if (BNFHeaders.LF == b) {
// line feed found
this.numCRLFs++;
} else if (BNFHeaders.SPACE == b || BNFHeaders.TAB == b) {
// Check for multi-line header values
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Multiline header follows");
}
this.bIsMultiLine = true;
if (null == this.lastHdrInSequence) {
// can't start off with a multiline value
throw new MalformedMessageException("Incorrect multiline header value");
}
this.currentElem = this.lastHdrInSequence;
this.stateOfParsing = PARSING_VALUE;
this.numCRLFs = 0;
return true;
} else {
// found end...move pointer back one
this.bytePosition--;
break; // out of for loop
}
if (2 <= this.numCRLFs) {
// found double LFs, end of headers
this.eohPosition = findCurrentBufferPosition(buff);
buff.position(this.eohPosition);
break; // out of for loop
}
} // end of for loop
// we're about to either start parsing another header or
// we've reached the end of the headers
this.bIsMultiLine = false;
this.stateOfParsing = PARSING_HEADER;
this.numCRLFs = 0;
return true;
} } |
public class class_name {
@Override
public void handleSelection(final CmsResourceTypeBean selectedType) {
CmsObject cms = A_CmsUI.getCmsObject();
m_selectedType = selectedType;
try {
CmsNewResourceBuilder builder = new CmsNewResourceBuilder(cms);
builder.addCallback(new I_Callback() {
public void onError(Exception e) {
m_dialogContext.error(e);
}
public void onResourceCreated(CmsNewResourceBuilder builderParam) {
finish(Lists.newArrayList(builderParam.getCreatedResource().getStructureId()));
}
});
m_selectedType = selectedType;
Boolean useDefaultLocation = m_defaultLocationCheckbox.getValue();
if (useDefaultLocation.booleanValue() && (m_selectedType.getCreatePath() != null)) {
try {
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(
cms,
m_folderResource.getRootPath());
CmsResourceTypeConfig typeConfig = configData.getResourceType(m_selectedType.getType());
if (typeConfig != null) {
typeConfig.configureCreateNewElement(cms, m_folderResource.getRootPath(), builder);
}
} catch (Exception e) {
m_dialogContext.error(e);
}
} else {
boolean explorerNameGenerationMode = false;
String sitePath = cms.getRequestContext().removeSiteRoot(m_folderResource.getRootPath());
String namePattern = m_selectedType.getNamePattern();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(namePattern)) {
namePattern = OpenCms.getWorkplaceManager().getDefaultNamePattern(m_selectedType.getType());
explorerNameGenerationMode = true;
}
String fileName = CmsStringUtil.joinPaths(sitePath, namePattern);
builder.setPatternPath(fileName);
builder.setType(m_selectedType.getType());
builder.setExplorerNameGeneration(explorerNameGenerationMode);
}
CmsPropertyDialogExtension ext = new CmsPropertyDialogExtension(A_CmsUI.get(), null);
CmsAppWorkplaceUi.get().disableGlobalShortcuts();
ext.editPropertiesForNewResource(builder);
finish(new ArrayList<CmsUUID>());
} catch (Exception e) {
throw new RuntimeException(e);
}
} } | public class class_name {
@Override
public void handleSelection(final CmsResourceTypeBean selectedType) {
CmsObject cms = A_CmsUI.getCmsObject();
m_selectedType = selectedType;
try {
CmsNewResourceBuilder builder = new CmsNewResourceBuilder(cms);
builder.addCallback(new I_Callback() {
public void onError(Exception e) {
m_dialogContext.error(e);
}
public void onResourceCreated(CmsNewResourceBuilder builderParam) {
finish(Lists.newArrayList(builderParam.getCreatedResource().getStructureId()));
}
}); // depends on control dependency: [try], data = [none]
m_selectedType = selectedType; // depends on control dependency: [try], data = [none]
Boolean useDefaultLocation = m_defaultLocationCheckbox.getValue();
if (useDefaultLocation.booleanValue() && (m_selectedType.getCreatePath() != null)) {
try {
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(
cms,
m_folderResource.getRootPath());
CmsResourceTypeConfig typeConfig = configData.getResourceType(m_selectedType.getType());
if (typeConfig != null) {
typeConfig.configureCreateNewElement(cms, m_folderResource.getRootPath(), builder); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
m_dialogContext.error(e);
} // depends on control dependency: [catch], data = [none]
} else {
boolean explorerNameGenerationMode = false;
String sitePath = cms.getRequestContext().removeSiteRoot(m_folderResource.getRootPath());
String namePattern = m_selectedType.getNamePattern();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(namePattern)) {
namePattern = OpenCms.getWorkplaceManager().getDefaultNamePattern(m_selectedType.getType()); // depends on control dependency: [if], data = [none]
explorerNameGenerationMode = true; // depends on control dependency: [if], data = [none]
}
String fileName = CmsStringUtil.joinPaths(sitePath, namePattern);
builder.setPatternPath(fileName); // depends on control dependency: [if], data = [none]
builder.setType(m_selectedType.getType()); // depends on control dependency: [if], data = [none]
builder.setExplorerNameGeneration(explorerNameGenerationMode); // depends on control dependency: [if], data = [none]
}
CmsPropertyDialogExtension ext = new CmsPropertyDialogExtension(A_CmsUI.get(), null);
CmsAppWorkplaceUi.get().disableGlobalShortcuts(); // depends on control dependency: [try], data = [none]
ext.editPropertiesForNewResource(builder); // depends on control dependency: [try], data = [none]
finish(new ArrayList<CmsUUID>()); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@GET
@Path("friendswith")
@RolesAllowed({"ROLE_ADMIN", "ROLE_USER"})
public Response friendsWith(@Context HttpServletRequest request,
@QueryParam("pageSize") @DefaultValue("10") int pageSize,
@QueryParam("cursorKey") String cursorKey) {
Long userId = (Long) request.getAttribute(OAuth2Filter.NAME_USER_ID);
CursorPage<DUser> page = userService.getFriendsWith(userId, pageSize, cursorKey);
// Only return basic user information about your friends
Collection<DUser> users = new ArrayList<>();
for (DUser user : page.getItems()) {
DUser limitedUserInfo = new DUser();
limitedUserInfo.setId(user.getId());
limitedUserInfo.setUsername(user.getUsername());
users.add(limitedUserInfo);
}
page.setItems(users);
return Response.ok(page).build();
} } | public class class_name {
@GET
@Path("friendswith")
@RolesAllowed({"ROLE_ADMIN", "ROLE_USER"})
public Response friendsWith(@Context HttpServletRequest request,
@QueryParam("pageSize") @DefaultValue("10") int pageSize,
@QueryParam("cursorKey") String cursorKey) {
Long userId = (Long) request.getAttribute(OAuth2Filter.NAME_USER_ID);
CursorPage<DUser> page = userService.getFriendsWith(userId, pageSize, cursorKey);
// Only return basic user information about your friends
Collection<DUser> users = new ArrayList<>();
for (DUser user : page.getItems()) {
DUser limitedUserInfo = new DUser();
limitedUserInfo.setId(user.getId()); // depends on control dependency: [for], data = [user]
limitedUserInfo.setUsername(user.getUsername()); // depends on control dependency: [for], data = [user]
users.add(limitedUserInfo); // depends on control dependency: [for], data = [user]
}
page.setItems(users);
return Response.ok(page).build();
} } |
public class class_name {
protected <T extends SemanticType.Atom> T construct(Disjunct type, LifetimeRelation lifetimes, Combinator<T> kind) {
T result = null;
Conjunct[] conjuncts = type.conjuncts;
for (int i = 0; i != conjuncts.length; ++i) {
Conjunct conjunct = conjuncts[i];
if (!isVoid(conjunct, lifetimes)) {
T tmp = construct(conjunct, lifetimes, kind);
if (tmp == null) {
// This indicates one of the conjuncts did not generate a proper
// extraction. In this case, we can simply ignore it.
} else if (result == null) {
result = tmp;
} else {
result = kind.union(result, tmp, lifetimes);
}
}
}
return result;
} } | public class class_name {
protected <T extends SemanticType.Atom> T construct(Disjunct type, LifetimeRelation lifetimes, Combinator<T> kind) {
T result = null;
Conjunct[] conjuncts = type.conjuncts;
for (int i = 0; i != conjuncts.length; ++i) {
Conjunct conjunct = conjuncts[i];
if (!isVoid(conjunct, lifetimes)) {
T tmp = construct(conjunct, lifetimes, kind);
if (tmp == null) {
// This indicates one of the conjuncts did not generate a proper
// extraction. In this case, we can simply ignore it.
} else if (result == null) {
result = tmp; // depends on control dependency: [if], data = [none]
} else {
result = kind.union(result, tmp, lifetimes); // depends on control dependency: [if], data = [(result]
}
}
}
return result;
} } |
public class class_name {
public static int[] broadcastOutputShape(int[] left,int[] right) {
assertBroadcastable(left, right);
if(Arrays.equals(left,right))
return left;
int n = Math.max(left.length,right.length);
List<Integer> dims = new ArrayList<>();
int leftIdx = left.length - 1;
int rightIdx = right.length - 1;
for(int i = n - 1; i >= 0; i--) {
if(leftIdx < 0) {
dims.add(right[rightIdx]);
}
else if(rightIdx < 0) {
dims.add(left[leftIdx]);
}
else if(left[leftIdx] != right[rightIdx] && right[rightIdx] == 1 || left[leftIdx] == 1) {
dims.add(Math.max(left[leftIdx],right[rightIdx]));
}
else if(left[leftIdx] == right[rightIdx]) {
dims.add(left[leftIdx]);
}
else {
throw new IllegalArgumentException("Unable to broadcast dimension " + i + " due to shape mismatch. Right shape must be 1.");
}
leftIdx--;
rightIdx--;
}
Collections.reverse(dims);
return Ints.toArray(dims);
} } | public class class_name {
public static int[] broadcastOutputShape(int[] left,int[] right) {
assertBroadcastable(left, right);
if(Arrays.equals(left,right))
return left;
int n = Math.max(left.length,right.length);
List<Integer> dims = new ArrayList<>();
int leftIdx = left.length - 1;
int rightIdx = right.length - 1;
for(int i = n - 1; i >= 0; i--) {
if(leftIdx < 0) {
dims.add(right[rightIdx]); // depends on control dependency: [if], data = [none]
}
else if(rightIdx < 0) {
dims.add(left[leftIdx]); // depends on control dependency: [if], data = [none]
}
else if(left[leftIdx] != right[rightIdx] && right[rightIdx] == 1 || left[leftIdx] == 1) {
dims.add(Math.max(left[leftIdx],right[rightIdx])); // depends on control dependency: [if], data = [none]
}
else if(left[leftIdx] == right[rightIdx]) {
dims.add(left[leftIdx]); // depends on control dependency: [if], data = [(left[leftIdx]]
}
else {
throw new IllegalArgumentException("Unable to broadcast dimension " + i + " due to shape mismatch. Right shape must be 1.");
}
leftIdx--; // depends on control dependency: [for], data = [none]
rightIdx--; // depends on control dependency: [for], data = [none]
}
Collections.reverse(dims);
return Ints.toArray(dims);
} } |
public class class_name {
public void recalcContentHeightPercent() {
if (stopPartsPositioning) return;
if (!isVisible()) return;
Element contentElt = content.getElement();
if (contentHeightPercent > 0) {
final JQMHeader header = getHeader();
final JQMFooter footer = getFooter();
int headerH = header == null || isFixedToolbarsHidden() ? 0 : header.getOffsetHeight();
int footerH = footer == null || isFixedToolbarsHidden() ? 0 : footer.getOffsetHeight();
int windowH = Window.getClientHeight();
int clientH = contentElt.getPropertyInt("clientHeight");
int offsetH = contentElt.getPropertyInt("offsetHeight");
int diff = offsetH - clientH; // border, ...
if (diff < 0) diff = 0;
double h = (windowH - headerH - footerH - diff) * 0.01d * contentHeightPercent;
h = Math.floor(h);
contentElt.getStyle().setProperty("minHeight", String.valueOf(Math.round(h)) + "px");
contentElt.getStyle().setProperty("paddingTop", "0");
contentElt.getStyle().setProperty("paddingBottom", "0");
} else {
contentElt.getStyle().clearProperty("minHeight");
contentElt.getStyle().clearProperty("paddingTop");
contentElt.getStyle().clearProperty("paddingBottom");
}
} } | public class class_name {
public void recalcContentHeightPercent() {
if (stopPartsPositioning) return;
if (!isVisible()) return;
Element contentElt = content.getElement();
if (contentHeightPercent > 0) {
final JQMHeader header = getHeader();
final JQMFooter footer = getFooter();
int headerH = header == null || isFixedToolbarsHidden() ? 0 : header.getOffsetHeight();
int footerH = footer == null || isFixedToolbarsHidden() ? 0 : footer.getOffsetHeight();
int windowH = Window.getClientHeight();
int clientH = contentElt.getPropertyInt("clientHeight");
int offsetH = contentElt.getPropertyInt("offsetHeight");
int diff = offsetH - clientH; // border, ...
if (diff < 0) diff = 0;
double h = (windowH - headerH - footerH - diff) * 0.01d * contentHeightPercent;
h = Math.floor(h); // depends on control dependency: [if], data = [none]
contentElt.getStyle().setProperty("minHeight", String.valueOf(Math.round(h)) + "px"); // depends on control dependency: [if], data = [none]
contentElt.getStyle().setProperty("paddingTop", "0"); // depends on control dependency: [if], data = [none]
contentElt.getStyle().setProperty("paddingBottom", "0"); // depends on control dependency: [if], data = [none]
} else {
contentElt.getStyle().clearProperty("minHeight"); // depends on control dependency: [if], data = [none]
contentElt.getStyle().clearProperty("paddingTop"); // depends on control dependency: [if], data = [none]
contentElt.getStyle().clearProperty("paddingBottom"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(HyperParameterAlgorithmSpecification hyperParameterAlgorithmSpecification, ProtocolMarshaller protocolMarshaller) {
if (hyperParameterAlgorithmSpecification == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(hyperParameterAlgorithmSpecification.getTrainingImage(), TRAININGIMAGE_BINDING);
protocolMarshaller.marshall(hyperParameterAlgorithmSpecification.getTrainingInputMode(), TRAININGINPUTMODE_BINDING);
protocolMarshaller.marshall(hyperParameterAlgorithmSpecification.getAlgorithmName(), ALGORITHMNAME_BINDING);
protocolMarshaller.marshall(hyperParameterAlgorithmSpecification.getMetricDefinitions(), METRICDEFINITIONS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(HyperParameterAlgorithmSpecification hyperParameterAlgorithmSpecification, ProtocolMarshaller protocolMarshaller) {
if (hyperParameterAlgorithmSpecification == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(hyperParameterAlgorithmSpecification.getTrainingImage(), TRAININGIMAGE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(hyperParameterAlgorithmSpecification.getTrainingInputMode(), TRAININGINPUTMODE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(hyperParameterAlgorithmSpecification.getAlgorithmName(), ALGORITHMNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(hyperParameterAlgorithmSpecification.getMetricDefinitions(), METRICDEFINITIONS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void addIntHeader(String name, int value)
{
try{_httpResponse.addIntField(name,value);}
catch(IllegalStateException e){LogSupport.ignore(log,e);}
} } | public class class_name {
public void addIntHeader(String name, int value)
{
try{_httpResponse.addIntField(name,value);} // depends on control dependency: [try], data = [none]
catch(IllegalStateException e){LogSupport.ignore(log,e);} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public DynamoDBQueryExpression<T> withQueryFilterEntry(String attributeName, Condition condition) {
if (queryFilter == null) {
queryFilter = new HashMap<String,Condition>();
}
queryFilter.put(attributeName, condition);
return this;
} } | public class class_name {
public DynamoDBQueryExpression<T> withQueryFilterEntry(String attributeName, Condition condition) {
if (queryFilter == null) {
queryFilter = new HashMap<String,Condition>(); // depends on control dependency: [if], data = [none]
}
queryFilter.put(attributeName, condition);
return this;
} } |
public class class_name {
public void printC(Object object) {
StackTraceElement[] stackTraceElements = StackTraceHelper.getStackTrace();
StackTraceElement stackTraceElement = stackTraceElements[2]; // 调用本类的对象类型堆栈
StringBuilder builder = new StringBuilder();
builder.append(" ------------------------------------------------------------ ");
builder.append(StringHelper.line());
builder.append(StackTraceHelper
.buildStackTrace(new StackTraceElement[]{stackTraceElement}));
builder.append(" ");
if (object == null) {
builder.append("<null>");
} else {
builder.append(object.getClass().getSimpleName());
builder.append(" =============== ");
String content = buildObjectToString(object);
builder.append(buildContent(content));
}
builder.append(StringHelper.line());
builder.append(" ------------------------------------------------------------ ");
System.out.println(builder.toString());
} } | public class class_name {
public void printC(Object object) {
StackTraceElement[] stackTraceElements = StackTraceHelper.getStackTrace();
StackTraceElement stackTraceElement = stackTraceElements[2]; // 调用本类的对象类型堆栈
StringBuilder builder = new StringBuilder();
builder.append(" ------------------------------------------------------------ ");
builder.append(StringHelper.line());
builder.append(StackTraceHelper
.buildStackTrace(new StackTraceElement[]{stackTraceElement}));
builder.append(" ");
if (object == null) {
builder.append("<null>"); // depends on control dependency: [if], data = [none]
} else {
builder.append(object.getClass().getSimpleName()); // depends on control dependency: [if], data = [(object]
builder.append(" =============== "); // depends on control dependency: [if], data = [none]
String content = buildObjectToString(object);
builder.append(buildContent(content)); // depends on control dependency: [if], data = [none]
}
builder.append(StringHelper.line());
builder.append(" ------------------------------------------------------------ ");
System.out.println(builder.toString());
} } |
public class class_name {
public java.util.List<ServiceTypeDetail> getServiceType() {
if (serviceType == null) {
serviceType = new com.amazonaws.internal.SdkInternalList<ServiceTypeDetail>();
}
return serviceType;
} } | public class class_name {
public java.util.List<ServiceTypeDetail> getServiceType() {
if (serviceType == null) {
serviceType = new com.amazonaws.internal.SdkInternalList<ServiceTypeDetail>(); // depends on control dependency: [if], data = [none]
}
return serviceType;
} } |
public class class_name {
public AbstractScope<?, ?> getAbstractScope() {
AbstractScope<?, ?> scope = scopes.peek();
// NOTE(dylandavidson): Use for-each loop to avoid slow ArrayList#get performance.
for (Node scopeRoot : scopeRoots) {
scope = scopeCreator.createScope(scopeRoot, scope);
scopes.push(scope);
}
scopeRoots.clear();
return scope;
} } | public class class_name {
public AbstractScope<?, ?> getAbstractScope() {
AbstractScope<?, ?> scope = scopes.peek();
// NOTE(dylandavidson): Use for-each loop to avoid slow ArrayList#get performance.
for (Node scopeRoot : scopeRoots) {
scope = scopeCreator.createScope(scopeRoot, scope); // depends on control dependency: [for], data = [scopeRoot]
scopes.push(scope); // depends on control dependency: [for], data = [none]
}
scopeRoots.clear();
return scope;
} } |
public class class_name {
private EnumElement readEnumElement(String documentation) {
String name = readName();
EnumElement.Builder builder = EnumElement.builder()
.name(name)
.qualifiedName(prefix + name)
.documentation(documentation);
if (readChar() != '{') throw unexpected("expected '{'");
while (true) {
String valueDocumentation = readDocumentation();
if (peekChar() == '}') {
pos++;
break;
}
Object declared = readDeclaration(valueDocumentation, Context.ENUM);
if (declared instanceof EnumConstantElement) {
builder.addConstant((EnumConstantElement) declared);
} else if (declared instanceof OptionElement) {
builder.addOption((OptionElement) declared);
}
}
return builder.build();
} } | public class class_name {
private EnumElement readEnumElement(String documentation) {
String name = readName();
EnumElement.Builder builder = EnumElement.builder()
.name(name)
.qualifiedName(prefix + name)
.documentation(documentation);
if (readChar() != '{') throw unexpected("expected '{'");
while (true) {
String valueDocumentation = readDocumentation();
if (peekChar() == '}') {
pos++; // depends on control dependency: [if], data = [none]
break;
}
Object declared = readDeclaration(valueDocumentation, Context.ENUM);
if (declared instanceof EnumConstantElement) {
builder.addConstant((EnumConstantElement) declared); // depends on control dependency: [if], data = [none]
} else if (declared instanceof OptionElement) {
builder.addOption((OptionElement) declared); // depends on control dependency: [if], data = [none]
}
}
return builder.build();
} } |
public class class_name {
public synchronized int addColumn(Vector col) {
if (isFinished)
throw new IllegalStateException(
"Cannot add columns to a MatrixBuilder that is finished");
DoubleVector column = Vectors.asDouble(col);
if (column.length() > numRows)
numRows = column.length();
// Vector instances can take on the maximum possible array size when the
// vector length isn't specified. This ruins the matrix size
// specification since the matrix shouldn't actually be that big.
// However, because this is an implementation artifact, we can't check
// for it explicitly with an exception. Therefore, put in an assert to
// indicate what is likely going on if asserts are enabled for debugging
// they symptoms.
assert column.length() != Integer.MAX_VALUE : "adding a column whose " +
"length is Integer.MAX_VALUE (was likley left unspecified in the " +
" constructor).";
// Special case for sparse Vectors, for which we already know the
// non-zero indices for the column
if (column instanceof SparseVector) {
SparseVector s = (SparseVector)column;
int[] nonZero = s.getNonZeroIndices();
nonZeroValues += nonZero.length;
System.out.println(nonZero.length);
try {
matrixDos.writeInt(nonZero.length);
for (int i : nonZero) {
double val = column.get(i);
matrixDos.writeInt(i); // write the row index
matrixDos.writeFloat((float)val);
}
} catch (IOException ioe) {
throw new IOError(ioe);
}
}
// For dense Vectors, find which values are non-zero and write only
// those
else {
int nonZero = 0;
for (int i = 0; i < column.length(); ++i) {
double d = column.get(i);
if (d != 0d)
nonZero++;
}
// Update the matrix count
nonZeroValues += nonZero;
try {
matrixDos.writeInt(nonZero);
// Write the number of non-zero values in the column
for (int i = 0; i < column.length(); ++i) {
double value = column.get(i);
if (value != 0d) {
matrixDos.writeInt(i); // write the row index
matrixDos.writeFloat((float)value);
}
}
} catch (IOException ioe) {
throw new IOError(ioe);
}
}
return ++curCol;
} } | public class class_name {
public synchronized int addColumn(Vector col) {
if (isFinished)
throw new IllegalStateException(
"Cannot add columns to a MatrixBuilder that is finished");
DoubleVector column = Vectors.asDouble(col);
if (column.length() > numRows)
numRows = column.length();
// Vector instances can take on the maximum possible array size when the
// vector length isn't specified. This ruins the matrix size
// specification since the matrix shouldn't actually be that big.
// However, because this is an implementation artifact, we can't check
// for it explicitly with an exception. Therefore, put in an assert to
// indicate what is likely going on if asserts are enabled for debugging
// they symptoms.
assert column.length() != Integer.MAX_VALUE : "adding a column whose " +
"length is Integer.MAX_VALUE (was likley left unspecified in the " +
" constructor).";
// Special case for sparse Vectors, for which we already know the
// non-zero indices for the column
if (column instanceof SparseVector) {
SparseVector s = (SparseVector)column;
int[] nonZero = s.getNonZeroIndices();
nonZeroValues += nonZero.length; // depends on control dependency: [if], data = [none]
System.out.println(nonZero.length); // depends on control dependency: [if], data = [none]
try {
matrixDos.writeInt(nonZero.length); // depends on control dependency: [try], data = [none]
for (int i : nonZero) {
double val = column.get(i);
matrixDos.writeInt(i); // write the row index // depends on control dependency: [for], data = [i]
matrixDos.writeFloat((float)val); // depends on control dependency: [for], data = [i]
}
} catch (IOException ioe) {
throw new IOError(ioe);
} // depends on control dependency: [catch], data = [none]
}
// For dense Vectors, find which values are non-zero and write only
// those
else {
int nonZero = 0;
for (int i = 0; i < column.length(); ++i) {
double d = column.get(i);
if (d != 0d)
nonZero++;
}
// Update the matrix count
nonZeroValues += nonZero; // depends on control dependency: [if], data = [none]
try {
matrixDos.writeInt(nonZero); // depends on control dependency: [try], data = [none]
// Write the number of non-zero values in the column
for (int i = 0; i < column.length(); ++i) {
double value = column.get(i);
if (value != 0d) {
matrixDos.writeInt(i); // write the row index // depends on control dependency: [if], data = [none]
matrixDos.writeFloat((float)value); // depends on control dependency: [if], data = [none]
}
}
} catch (IOException ioe) {
throw new IOError(ioe);
} // depends on control dependency: [catch], data = [none]
}
return ++curCol;
} } |
public class class_name {
@Override
public AppResponse postNewApp(WebResource resource, ResourcePath<Apps> appsResponsePath,
AppDetailsRequest appsRequest, File file) {
try {
FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.bodyPart(new FileDataBodyPart("file", file));
multiPart.bodyPart(new FormDataBodyPart("data", appsRequest, MediaType.APPLICATION_JSON_TYPE));
return resource.path(appsResponsePath.getPath()).type(MediaType.MULTIPART_FORM_DATA_TYPE).post(AppResponse.class,
multiPart);
} catch (UniformInterfaceException e) {
throw new ApiException(e.getResponse().getEntity(ErrorResponse.class), e);
}
} } | public class class_name {
@Override
public AppResponse postNewApp(WebResource resource, ResourcePath<Apps> appsResponsePath,
AppDetailsRequest appsRequest, File file) {
try {
FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.bodyPart(new FileDataBodyPart("file", file)); // depends on control dependency: [try], data = [none]
multiPart.bodyPart(new FormDataBodyPart("data", appsRequest, MediaType.APPLICATION_JSON_TYPE)); // depends on control dependency: [try], data = [none]
return resource.path(appsResponsePath.getPath()).type(MediaType.MULTIPART_FORM_DATA_TYPE).post(AppResponse.class,
multiPart); // depends on control dependency: [try], data = [none]
} catch (UniformInterfaceException e) {
throw new ApiException(e.getResponse().getEntity(ErrorResponse.class), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected static Factory createConfiguredFactory ()
{
String implClass;
try {
implClass = System.getProperty("com.samskivert.util.Log");
} catch (SecurityException se) {
// in a sandbox
return null;
}
if (!StringUtil.isBlank(implClass)) {
try {
return (Factory)Class.forName(implClass).newInstance();
} catch (Throwable t) {
System.err.println("Unable to instantiate logging implementation: " + implClass);
t.printStackTrace(System.err);
}
}
return null;
} } | public class class_name {
protected static Factory createConfiguredFactory ()
{
String implClass;
try {
implClass = System.getProperty("com.samskivert.util.Log"); // depends on control dependency: [try], data = [none]
} catch (SecurityException se) {
// in a sandbox
return null;
} // depends on control dependency: [catch], data = [none]
if (!StringUtil.isBlank(implClass)) {
try {
return (Factory)Class.forName(implClass).newInstance(); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
System.err.println("Unable to instantiate logging implementation: " + implClass);
t.printStackTrace(System.err);
} // depends on control dependency: [catch], data = [none]
}
return null;
} } |
public class class_name {
public static String LV_CCRD(int ivcord) {
//Translate known vertical coordinates or look for parameter name.
String vcoord = "";
//Check for numeric vertical coordinates.
if ((ivcord >= 0) && (ivcord < vertCoords.length)) {
vcoord = vertCoords[ivcord];
} else if (ivcord > 100) {
// Check for character name as vertical coordinate. Check that
// each character is an alphanumeric character.
vcoord = ST_ITOC(ivcord);
/*
Check for bad values
DO i = 1, 4
v = vcoord (i:i)
IF ( ( ( v .lt. 'A' ) .or. ( v .gt. 'Z' ) ) .and.
+ ( ( v .lt. '0' ) .or. ( v .gt. '9' ) ) ) THEN
ier = -1
END IF
END DO
END IF
*/
}
return vcoord;
} } | public class class_name {
public static String LV_CCRD(int ivcord) {
//Translate known vertical coordinates or look for parameter name.
String vcoord = "";
//Check for numeric vertical coordinates.
if ((ivcord >= 0) && (ivcord < vertCoords.length)) {
vcoord = vertCoords[ivcord];
// depends on control dependency: [if], data = [none]
} else if (ivcord > 100) {
// Check for character name as vertical coordinate. Check that
// each character is an alphanumeric character.
vcoord = ST_ITOC(ivcord);
// depends on control dependency: [if], data = [(ivcord]
/*
Check for bad values
DO i = 1, 4
v = vcoord (i:i)
IF ( ( ( v .lt. 'A' ) .or. ( v .gt. 'Z' ) ) .and.
+ ( ( v .lt. '0' ) .or. ( v .gt. '9' ) ) ) THEN
ier = -1
END IF
END DO
END IF
*/
}
return vcoord;
} } |
public class class_name {
public INDArray[] output(MultiDataSetIterator iterator){
List<INDArray[]> outputs = new ArrayList<>();
while(iterator.hasNext()){
MultiDataSet next = iterator.next();
INDArray[] out = output(false, next.getFeatures(), next.getFeaturesMaskArrays(), next.getLabelsMaskArrays());
outputs.add(out);
}
INDArray[][] arr = outputs.toArray(new INDArray[outputs.size()][0]);
return DataSetUtil.mergeFeatures(arr, null).getFirst();
} } | public class class_name {
public INDArray[] output(MultiDataSetIterator iterator){
List<INDArray[]> outputs = new ArrayList<>();
while(iterator.hasNext()){
MultiDataSet next = iterator.next();
INDArray[] out = output(false, next.getFeatures(), next.getFeaturesMaskArrays(), next.getLabelsMaskArrays());
outputs.add(out); // depends on control dependency: [while], data = [none]
}
INDArray[][] arr = outputs.toArray(new INDArray[outputs.size()][0]);
return DataSetUtil.mergeFeatures(arr, null).getFirst();
} } |
public class class_name {
public void marshall(UpdateConnectorDefinitionRequest updateConnectorDefinitionRequest, ProtocolMarshaller protocolMarshaller) {
if (updateConnectorDefinitionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateConnectorDefinitionRequest.getConnectorDefinitionId(), CONNECTORDEFINITIONID_BINDING);
protocolMarshaller.marshall(updateConnectorDefinitionRequest.getName(), NAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UpdateConnectorDefinitionRequest updateConnectorDefinitionRequest, ProtocolMarshaller protocolMarshaller) {
if (updateConnectorDefinitionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateConnectorDefinitionRequest.getConnectorDefinitionId(), CONNECTORDEFINITIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateConnectorDefinitionRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void learnFern(boolean positive, ImageRectangle r) {
float rectWidth = r.getWidth();
float rectHeight = r.getHeight();
float c_x = r.x0+(rectWidth-1)/2f;
float c_y = r.y0+(rectHeight-1)/2f;
for( int i = 0; i < ferns.length; i++ ) {
// first learn it with no noise
int value = computeFernValue(c_x, c_y, rectWidth, rectHeight,ferns[i]);
TldFernFeature f = managers[i].lookupFern(value);
increment(f,positive);
}
} } | public class class_name {
public void learnFern(boolean positive, ImageRectangle r) {
float rectWidth = r.getWidth();
float rectHeight = r.getHeight();
float c_x = r.x0+(rectWidth-1)/2f;
float c_y = r.y0+(rectHeight-1)/2f;
for( int i = 0; i < ferns.length; i++ ) {
// first learn it with no noise
int value = computeFernValue(c_x, c_y, rectWidth, rectHeight,ferns[i]);
TldFernFeature f = managers[i].lookupFern(value);
increment(f,positive); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
public void applyDefaults() {
if (getName() == null) {
setName(DEFAULT_NAME);
}
if (getFeatureStyles().size() == 0) {
getFeatureStyles().add(new FeatureStyleInfo());
}
for (FeatureStyleInfo featureStyle : getFeatureStyles()) {
featureStyle.applyDefaults();
}
if (getLabelStyle().getLabelAttributeName() == null) {
getLabelStyle().setLabelAttributeName(LabelStyleInfo.ATTRIBUTE_NAME_ID);
}
getLabelStyle().getBackgroundStyle().applyDefaults();
getLabelStyle().getFontStyle().applyDefaults();
} } | public class class_name {
public void applyDefaults() {
if (getName() == null) {
setName(DEFAULT_NAME); // depends on control dependency: [if], data = [none]
}
if (getFeatureStyles().size() == 0) {
getFeatureStyles().add(new FeatureStyleInfo()); // depends on control dependency: [if], data = [none]
}
for (FeatureStyleInfo featureStyle : getFeatureStyles()) {
featureStyle.applyDefaults(); // depends on control dependency: [for], data = [featureStyle]
}
if (getLabelStyle().getLabelAttributeName() == null) {
getLabelStyle().setLabelAttributeName(LabelStyleInfo.ATTRIBUTE_NAME_ID); // depends on control dependency: [if], data = [none]
}
getLabelStyle().getBackgroundStyle().applyDefaults();
getLabelStyle().getFontStyle().applyDefaults();
} } |
public class class_name {
public Observable<ServiceResponse<Page<UsageInner>>> listMultiRoleUsagesSinglePageAsync(final String resourceGroupName, final String name) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (name == null) {
throw new IllegalArgumentException("Parameter name is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.listMultiRoleUsages(resourceGroupName, name, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<UsageInner>>>>() {
@Override
public Observable<ServiceResponse<Page<UsageInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<UsageInner>> result = listMultiRoleUsagesDelegate(response);
return Observable.just(new ServiceResponse<Page<UsageInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<UsageInner>>> listMultiRoleUsagesSinglePageAsync(final String resourceGroupName, final String name) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (name == null) {
throw new IllegalArgumentException("Parameter name is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.listMultiRoleUsages(resourceGroupName, name, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<UsageInner>>>>() {
@Override
public Observable<ServiceResponse<Page<UsageInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<UsageInner>> result = listMultiRoleUsagesDelegate(response);
return Observable.just(new ServiceResponse<Page<UsageInner>>(result.body(), result.response())); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
private void cleanupWriterSocket(PrintWriter pwriter) {
try {
if (pwriter != null) {
pwriter.flush();
pwriter.close();
}
} catch (Exception e) {
LOG.info("Error closing PrintWriter ", e);
} finally {
try {
close();
} catch (Exception e) {
LOG.error("Error closing a command socket ", e);
}
}
} } | public class class_name {
private void cleanupWriterSocket(PrintWriter pwriter) {
try {
if (pwriter != null) {
pwriter.flush(); // depends on control dependency: [if], data = [none]
pwriter.close(); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
LOG.info("Error closing PrintWriter ", e);
} finally { // depends on control dependency: [catch], data = [none]
try {
close(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
LOG.error("Error closing a command socket ", e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private static CmsRelationType valueOfInternal(String name) {
if (name != null) {
String valueUp = name.toUpperCase();
for (int i = 0; i < VALUE_ARRAY.length; i++) {
if (valueUp.equals(VALUE_ARRAY[i].m_name)) {
return VALUE_ARRAY[i];
}
}
// deprecated types
if (valueUp.equals("REFERENCE") || valueUp.equals("XML_REFERENCE")) {
return XML_WEAK;
} else if (valueUp.equals("ATTACHMENT") || valueUp.equals("XML_ATTACHMENT")) {
return XML_STRONG;
}
// user defined
for (int i = 0; i < getAllUserDefined().size(); i++) {
CmsRelationType type = getAllUserDefined().get(i);
if (valueUp.equals(type.m_name)) {
return type;
}
}
}
return null;
} } | public class class_name {
private static CmsRelationType valueOfInternal(String name) {
if (name != null) {
String valueUp = name.toUpperCase();
for (int i = 0; i < VALUE_ARRAY.length; i++) {
if (valueUp.equals(VALUE_ARRAY[i].m_name)) {
return VALUE_ARRAY[i]; // depends on control dependency: [if], data = [none]
}
}
// deprecated types
if (valueUp.equals("REFERENCE") || valueUp.equals("XML_REFERENCE")) {
return XML_WEAK; // depends on control dependency: [if], data = [none]
} else if (valueUp.equals("ATTACHMENT") || valueUp.equals("XML_ATTACHMENT")) {
return XML_STRONG; // depends on control dependency: [if], data = [none]
}
// user defined
for (int i = 0; i < getAllUserDefined().size(); i++) {
CmsRelationType type = getAllUserDefined().get(i);
if (valueUp.equals(type.m_name)) {
return type; // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
public Whitelist addEnforcedAttribute(String tag, String attribute, String value) {
Validate.notEmpty(tag);
Validate.notEmpty(attribute);
Validate.notEmpty(value);
TagName tagName = TagName.valueOf(tag);
tagNames.add(tagName);
AttributeKey attrKey = AttributeKey.valueOf(attribute);
AttributeValue attrVal = AttributeValue.valueOf(value);
if (enforcedAttributes.containsKey(tagName)) {
enforcedAttributes.get(tagName).put(attrKey, attrVal);
} else {
Map<AttributeKey, AttributeValue> attrMap = new HashMap<>();
attrMap.put(attrKey, attrVal);
enforcedAttributes.put(tagName, attrMap);
}
return this;
} } | public class class_name {
public Whitelist addEnforcedAttribute(String tag, String attribute, String value) {
Validate.notEmpty(tag);
Validate.notEmpty(attribute);
Validate.notEmpty(value);
TagName tagName = TagName.valueOf(tag);
tagNames.add(tagName);
AttributeKey attrKey = AttributeKey.valueOf(attribute);
AttributeValue attrVal = AttributeValue.valueOf(value);
if (enforcedAttributes.containsKey(tagName)) {
enforcedAttributes.get(tagName).put(attrKey, attrVal); // depends on control dependency: [if], data = [none]
} else {
Map<AttributeKey, AttributeValue> attrMap = new HashMap<>();
attrMap.put(attrKey, attrVal); // depends on control dependency: [if], data = [none]
enforcedAttributes.put(tagName, attrMap); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public Observable<ServiceResponse<DomainModelResults>> analyzeImageByDomainInStreamWithServiceResponseAsync(String model, byte[] image, String language) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (model == null) {
throw new IllegalArgumentException("Parameter model is required and cannot be null.");
}
if (image == null) {
throw new IllegalArgumentException("Parameter image is required and cannot be null.");
}
String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
RequestBody imageConverted = RequestBody.create(MediaType.parse("application/octet-stream"), image);
return service.analyzeImageByDomainInStream(model, language, imageConverted, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<DomainModelResults>>>() {
@Override
public Observable<ServiceResponse<DomainModelResults>> call(Response<ResponseBody> response) {
try {
ServiceResponse<DomainModelResults> clientResponse = analyzeImageByDomainInStreamDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<DomainModelResults>> analyzeImageByDomainInStreamWithServiceResponseAsync(String model, byte[] image, String language) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
if (model == null) {
throw new IllegalArgumentException("Parameter model is required and cannot be null.");
}
if (image == null) {
throw new IllegalArgumentException("Parameter image is required and cannot be null.");
}
String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
RequestBody imageConverted = RequestBody.create(MediaType.parse("application/octet-stream"), image);
return service.analyzeImageByDomainInStream(model, language, imageConverted, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<DomainModelResults>>>() {
@Override
public Observable<ServiceResponse<DomainModelResults>> call(Response<ResponseBody> response) {
try {
ServiceResponse<DomainModelResults> clientResponse = analyzeImageByDomainInStreamDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
boolean addNoParaToken(Token noParaToken) {
tokens.add(noParaToken);
if (CharTable.isBlank(peek())) {
next(); // 无参指令之后紧随的一个空白字符仅为分隔符,不参与后续扫描
}
if (lookForwardLineFeedAndEof() && deletePreviousTextTokenBlankTails()) {
prepareNextScan(peek() != EOF ? 1 : 0);
} else {
prepareNextScan(0);
}
previousTextToken = null;
return true;
} } | public class class_name {
boolean addNoParaToken(Token noParaToken) {
tokens.add(noParaToken);
if (CharTable.isBlank(peek())) {
next(); // 无参指令之后紧随的一个空白字符仅为分隔符,不参与后续扫描
// depends on control dependency: [if], data = [none]
}
if (lookForwardLineFeedAndEof() && deletePreviousTextTokenBlankTails()) {
prepareNextScan(peek() != EOF ? 1 : 0);
// depends on control dependency: [if], data = [none]
} else {
prepareNextScan(0);
// depends on control dependency: [if], data = [none]
}
previousTextToken = null;
return true;
} } |
public class class_name {
public static DiscoMatchType getMatchType(boolean isSubsume, boolean isPlugin) {
if (isSubsume) {
if (isPlugin) {
// If plugin and subsume -> this is an exact match
return DiscoMatchType.Exact;
}
return DiscoMatchType.Subsume;
} else {
if (isPlugin) {
return DiscoMatchType.Plugin;
}
}
return DiscoMatchType.Fail;
} } | public class class_name {
public static DiscoMatchType getMatchType(boolean isSubsume, boolean isPlugin) {
if (isSubsume) {
if (isPlugin) {
// If plugin and subsume -> this is an exact match
return DiscoMatchType.Exact; // depends on control dependency: [if], data = [none]
}
return DiscoMatchType.Subsume; // depends on control dependency: [if], data = [none]
} else {
if (isPlugin) {
return DiscoMatchType.Plugin; // depends on control dependency: [if], data = [none]
}
}
return DiscoMatchType.Fail;
} } |
public class class_name {
protected I_CmsSearchDocument createDefaultIndexDocument() {
try {
return m_index.getFieldConfiguration().createDocument(m_cms, m_res, m_index, null);
} catch (CmsException e) {
LOG.error(
"Default document for "
+ m_res.getRootPath()
+ " and index "
+ m_index.getName()
+ " could not be created.",
e);
return null;
}
} } | public class class_name {
protected I_CmsSearchDocument createDefaultIndexDocument() {
try {
return m_index.getFieldConfiguration().createDocument(m_cms, m_res, m_index, null); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
LOG.error(
"Default document for "
+ m_res.getRootPath()
+ " and index "
+ m_index.getName()
+ " could not be created.",
e);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void truncate(Zxid zxid) throws IOException {
int lastKeepIdx = getFileIdx(zxid);
for (int i = lastKeepIdx + 1; i < logFiles.size(); ++i) {
// Deletes all the log files after the file which contains the
// transaction with zxid.
File file = logFiles.get(i);
boolean result = file.delete();
if (!result) {
LOG.warn("The file {} might not be deleted successfully.",
file.getName());
}
}
if (lastKeepIdx != -1) {
File file = this.logFiles.get(lastKeepIdx);
try (SimpleLog log = new SimpleLog(file)) {
log.truncate(zxid);
}
}
logFiles.subList(lastKeepIdx+ 1, logFiles.size()).clear();
this.currentLog = getLastLog();
this.lastSeenZxid = getLatestZxid();
} } | public class class_name {
@Override
public void truncate(Zxid zxid) throws IOException {
int lastKeepIdx = getFileIdx(zxid);
for (int i = lastKeepIdx + 1; i < logFiles.size(); ++i) {
// Deletes all the log files after the file which contains the
// transaction with zxid.
File file = logFiles.get(i);
boolean result = file.delete();
if (!result) {
LOG.warn("The file {} might not be deleted successfully.",
file.getName()); // depends on control dependency: [if], data = [none]
}
}
if (lastKeepIdx != -1) {
File file = this.logFiles.get(lastKeepIdx);
try (SimpleLog log = new SimpleLog(file)) {
log.truncate(zxid);
}
}
logFiles.subList(lastKeepIdx+ 1, logFiles.size()).clear();
this.currentLog = getLastLog();
this.lastSeenZxid = getLatestZxid();
} } |
public class class_name {
public char[] quoteAsString(String input) {
TextBuffer textBuffer = _textBuffer;
if (textBuffer == null) {
// no allocator; can add if we must, shouldn't need to
_textBuffer = textBuffer = new TextBuffer(null);
}
char[] outputBuffer = textBuffer.emptyAndGetCurrentSegment();
final int[] escCodes = sOutputEscapes128;
final int escCodeCount = escCodes.length;
int inPtr = 0;
final int inputLen = input.length();
int outPtr = 0;
outer_loop: while (inPtr < inputLen) {
tight_loop: while (true) {
char c = input.charAt(inPtr);
if (c < escCodeCount && escCodes[c] != 0) {
break tight_loop;
}
if (outPtr >= outputBuffer.length) {
outputBuffer = textBuffer.finishCurrentSegment();
outPtr = 0;
}
outputBuffer[outPtr++] = c;
if (++inPtr >= inputLen) {
break outer_loop;
}
}
// something to escape; 2 or 6-char variant?
int escCode = escCodes[input.charAt(inPtr++)];
int length = _appendSingleEscape(escCode, _quoteBuffer);
if ((outPtr + length) > outputBuffer.length) {
int first = outputBuffer.length - outPtr;
if (first > 0) {
System.arraycopy(_quoteBuffer, 0, outputBuffer, outPtr, first);
}
outputBuffer = textBuffer.finishCurrentSegment();
int second = length - first;
System.arraycopy(_quoteBuffer, first, outputBuffer, outPtr, second);
outPtr += second;
}
else {
System.arraycopy(_quoteBuffer, 0, outputBuffer, outPtr, length);
outPtr += length;
}
}
textBuffer.setCurrentLength(outPtr);
return textBuffer.contentsAsArray();
} } | public class class_name {
public char[] quoteAsString(String input) {
TextBuffer textBuffer = _textBuffer;
if (textBuffer == null) {
// no allocator; can add if we must, shouldn't need to
_textBuffer = textBuffer = new TextBuffer(null); // depends on control dependency: [if], data = [null)]
}
char[] outputBuffer = textBuffer.emptyAndGetCurrentSegment();
final int[] escCodes = sOutputEscapes128;
final int escCodeCount = escCodes.length;
int inPtr = 0;
final int inputLen = input.length();
int outPtr = 0;
outer_loop: while (inPtr < inputLen) {
tight_loop: while (true) {
char c = input.charAt(inPtr);
if (c < escCodeCount && escCodes[c] != 0) {
break tight_loop;
}
if (outPtr >= outputBuffer.length) {
outputBuffer = textBuffer.finishCurrentSegment(); // depends on control dependency: [if], data = [none]
outPtr = 0; // depends on control dependency: [if], data = [none]
}
outputBuffer[outPtr++] = c; // depends on control dependency: [while], data = [none]
if (++inPtr >= inputLen) {
break outer_loop;
}
}
// something to escape; 2 or 6-char variant?
int escCode = escCodes[input.charAt(inPtr++)];
int length = _appendSingleEscape(escCode, _quoteBuffer);
if ((outPtr + length) > outputBuffer.length) {
int first = outputBuffer.length - outPtr;
if (first > 0) {
System.arraycopy(_quoteBuffer, 0, outputBuffer, outPtr, first); // depends on control dependency: [if], data = [none]
}
outputBuffer = textBuffer.finishCurrentSegment(); // depends on control dependency: [if], data = [none]
int second = length - first;
System.arraycopy(_quoteBuffer, first, outputBuffer, outPtr, second); // depends on control dependency: [if], data = [none]
outPtr += second; // depends on control dependency: [if], data = [none]
}
else {
System.arraycopy(_quoteBuffer, 0, outputBuffer, outPtr, length); // depends on control dependency: [if], data = [none]
outPtr += length; // depends on control dependency: [if], data = [none]
}
}
textBuffer.setCurrentLength(outPtr);
return textBuffer.contentsAsArray();
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.