code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
|---|---|
public class class_name {
private int setWidth(int width) {
m_width = width;
int width_label = (m_width / m_part);
if (m_complementPartWidth) {
int complementaryWidth = m_width - width_label;
width_label = complementaryWidth < 30 ? 30 : complementaryWidth;
}
int width_table = (m_width - 30) - width_label;
m_table.getElement().getStyle().setWidth(width_table, Unit.PX);
return width_table;
} }
|
public class class_name {
private int setWidth(int width) {
m_width = width;
int width_label = (m_width / m_part);
if (m_complementPartWidth) {
int complementaryWidth = m_width - width_label;
width_label = complementaryWidth < 30 ? 30 : complementaryWidth;
// depends on control dependency: [if], data = [none]
}
int width_table = (m_width - 30) - width_label;
m_table.getElement().getStyle().setWidth(width_table, Unit.PX);
return width_table;
} }
|
public class class_name {
public MatcherController initialize() {
this.lastAddTableInfo = null;
for (Map.Entry<Class<?>, TableInfo> entry : this.tables.entrySet()) {
entry.getValue().isValid(true);
}
for (MatcherPattern entry : matcherPatterns) {
entry.isValid(true);
this.matcher.addURI(entry.getTableInfo().getDefaultContentUriInfo().getAuthority(), entry.getPathAndPatternString(), entry.getPatternCode());
entry.initialize();
}
this.initialized = true;
return this;
} }
|
public class class_name {
public MatcherController initialize() {
this.lastAddTableInfo = null;
for (Map.Entry<Class<?>, TableInfo> entry : this.tables.entrySet()) {
entry.getValue().isValid(true); // depends on control dependency: [for], data = [entry]
}
for (MatcherPattern entry : matcherPatterns) {
entry.isValid(true); // depends on control dependency: [for], data = [entry]
this.matcher.addURI(entry.getTableInfo().getDefaultContentUriInfo().getAuthority(), entry.getPathAndPatternString(), entry.getPatternCode()); // depends on control dependency: [for], data = [entry]
entry.initialize(); // depends on control dependency: [for], data = [entry]
}
this.initialized = true;
return this;
} }
|
public class class_name {
public static void join(StringBuilder buf, Iterable<?> values, String separator) {
for (Iterator<?> i = values.iterator(); i.hasNext();) {
buf.append(i.next());
if (i.hasNext()) {
buf.append(separator);
}
}
} }
|
public class class_name {
public static void join(StringBuilder buf, Iterable<?> values, String separator) {
for (Iterator<?> i = values.iterator(); i.hasNext();) {
buf.append(i.next()); // depends on control dependency: [for], data = [i]
if (i.hasNext()) {
buf.append(separator); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
@Beta
public boolean containsCustomEventMappingFor(final String eventType) {
if (eventType == null || eventType.isEmpty()) {
return false;
} else {
return this.eventTypeToEventDataMapping.containsKey(canonicalizeEventType(eventType));
}
} }
|
public class class_name {
@Beta
public boolean containsCustomEventMappingFor(final String eventType) {
if (eventType == null || eventType.isEmpty()) {
return false; // depends on control dependency: [if], data = [none]
} else {
return this.eventTypeToEventDataMapping.containsKey(canonicalizeEventType(eventType)); // depends on control dependency: [if], data = [(eventType]
}
} }
|
public class class_name {
public StrBuilder appendAll(final Iterator<?> it) {
if (it != null) {
while (it.hasNext()) {
append(it.next());
}
}
return this;
} }
|
public class class_name {
public StrBuilder appendAll(final Iterator<?> it) {
if (it != null) {
while (it.hasNext()) {
append(it.next()); // depends on control dependency: [while], data = [none]
}
}
return this;
} }
|
public class class_name {
static int[] toIntArray(List<Integer> integers) {
int[] ints = new int[integers.size()];
int i = 0;
for (Integer n : integers) {
ints[i++] = n;
}
return ints;
} }
|
public class class_name {
static int[] toIntArray(List<Integer> integers) {
int[] ints = new int[integers.size()];
int i = 0;
for (Integer n : integers) {
ints[i++] = n; // depends on control dependency: [for], data = [n]
}
return ints;
} }
|
public class class_name {
private int hash(final String name) {
int h = 0;
for (int i = name.length() - 1; i >= 0; i--) {
char c = name.charAt(i);
if (!caseSensitive) {
if (c >= 'A' && c <= 'Z') {
c += 32;
}
}
h = 31 * h + c;
}
if (h > 0) {
return h;
}
if (h == Integer.MIN_VALUE) {
return Integer.MAX_VALUE;
}
return -h;
} }
|
public class class_name {
private int hash(final String name) {
int h = 0;
for (int i = name.length() - 1; i >= 0; i--) {
char c = name.charAt(i);
if (!caseSensitive) {
if (c >= 'A' && c <= 'Z') {
c += 32; // depends on control dependency: [if], data = [none]
}
}
h = 31 * h + c; // depends on control dependency: [for], data = [none]
}
if (h > 0) {
return h; // depends on control dependency: [if], data = [none]
}
if (h == Integer.MIN_VALUE) {
return Integer.MAX_VALUE; // depends on control dependency: [if], data = [none]
}
return -h;
} }
|
public class class_name {
public void apply(int from, int[]to, int length, Object o) {
ApplyCaseFoldArg arg = (ApplyCaseFoldArg)o;
ScanEnvironment env = arg.env;
Encoding enc = env.enc;
CClassNode cc = arg.cc;
CClassNode ascCc = arg.ascCc;
BitSet bs = cc.bs;
boolean addFlag;
if (ascCc == null) {
addFlag = false;
} else if (Encoding.isAscii(from) == Encoding.isAscii(to[0])) {
addFlag = true;
} else {
addFlag = ascCc.isCodeInCC(enc, from);
if (ascCc.isNot()) addFlag = !addFlag;
}
if (length == 1) {
boolean inCC = cc.isCodeInCC(enc, from);
if (Config.CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS) {
if ((inCC && !cc.isNot()) || (!inCC && cc.isNot())) {
if (addFlag) {
if (enc.minLength() > 1 || to[0] >= BitSet.SINGLE_BYTE_SIZE) {
cc.addCodeRange(env, to[0], to[0], false);
} else {
/* /(?i:[^A-C])/.match("a") ==> fail. */
bs.set(to[0]);
}
}
}
} else {
if (inCC) {
if (addFlag) {
if (enc.minLength() > 1 || to[0] >= BitSet.SINGLE_BYTE_SIZE) {
if (cc.isNot()) cc.clearNotFlag(env);
cc.addCodeRange(env, to[0], to[0], false);
} else {
if (cc.isNot()) {
bs.clear(to[0]);
} else {
bs.set(to[0]);
}
}
}
}
} // CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
} else {
if (cc.isCodeInCC(enc, from) && (!Config.CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS || !cc.isNot())) {
StringNode node = null;
for (int i=0; i<length; i++) {
if (i == 0) {
node = new StringNode();
/* char-class expanded multi-char only
compare with string folded at match time. */
node.setAmbig();
}
node.catCode(to[i], enc);
}
ListNode alt = ListNode.newAlt(node, null);
if (arg.tail == null) {
arg.altRoot = alt;
} else {
arg.tail.setTail(alt);
}
arg.tail = alt;
}
}
} }
|
public class class_name {
public void apply(int from, int[]to, int length, Object o) {
ApplyCaseFoldArg arg = (ApplyCaseFoldArg)o;
ScanEnvironment env = arg.env;
Encoding enc = env.enc;
CClassNode cc = arg.cc;
CClassNode ascCc = arg.ascCc;
BitSet bs = cc.bs;
boolean addFlag;
if (ascCc == null) {
addFlag = false; // depends on control dependency: [if], data = [none]
} else if (Encoding.isAscii(from) == Encoding.isAscii(to[0])) {
addFlag = true; // depends on control dependency: [if], data = [none]
} else {
addFlag = ascCc.isCodeInCC(enc, from); // depends on control dependency: [if], data = [none]
if (ascCc.isNot()) addFlag = !addFlag;
}
if (length == 1) {
boolean inCC = cc.isCodeInCC(enc, from);
if (Config.CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS) {
if ((inCC && !cc.isNot()) || (!inCC && cc.isNot())) {
if (addFlag) {
if (enc.minLength() > 1 || to[0] >= BitSet.SINGLE_BYTE_SIZE) {
cc.addCodeRange(env, to[0], to[0], false); // depends on control dependency: [if], data = [none]
} else {
/* /(?i:[^A-C])/.match("a") ==> fail. */
bs.set(to[0]); // depends on control dependency: [if], data = [none]
}
}
}
} else {
if (inCC) {
if (addFlag) {
if (enc.minLength() > 1 || to[0] >= BitSet.SINGLE_BYTE_SIZE) {
if (cc.isNot()) cc.clearNotFlag(env);
cc.addCodeRange(env, to[0], to[0], false); // depends on control dependency: [if], data = [none]
} else {
if (cc.isNot()) {
bs.clear(to[0]); // depends on control dependency: [if], data = [none]
} else {
bs.set(to[0]); // depends on control dependency: [if], data = [none]
}
}
}
}
} // CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS
} else {
if (cc.isCodeInCC(enc, from) && (!Config.CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS || !cc.isNot())) {
StringNode node = null;
for (int i=0; i<length; i++) {
if (i == 0) {
node = new StringNode(); // depends on control dependency: [if], data = [none]
/* char-class expanded multi-char only
compare with string folded at match time. */
node.setAmbig(); // depends on control dependency: [if], data = [none]
}
node.catCode(to[i], enc); // depends on control dependency: [for], data = [i]
}
ListNode alt = ListNode.newAlt(node, null);
if (arg.tail == null) {
arg.altRoot = alt; // depends on control dependency: [if], data = [none]
} else {
arg.tail.setTail(alt); // depends on control dependency: [if], data = [none]
}
arg.tail = alt; // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
@Process(actionType = HostSelection.class, dependencies = {HostStore.class})
public void onSelectHost(final HostSelection action, final Dispatcher.Channel channel) {
// load the server data on demand
if(!host2server.containsKey(action.getHostName()))
onRefresh(channel);
else {
channel.ack();
}
} }
|
public class class_name {
@Process(actionType = HostSelection.class, dependencies = {HostStore.class})
public void onSelectHost(final HostSelection action, final Dispatcher.Channel channel) {
// load the server data on demand
if(!host2server.containsKey(action.getHostName()))
onRefresh(channel);
else {
channel.ack(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public File[] getFsImageNameCheckpoint(long txid) {
ArrayList<File> list = new ArrayList<File>();
for (Iterator<StorageDirectory> it =
dirIterator(NameNodeDirType.IMAGE); it.hasNext();) {
list.add(getStorageFile(it.next(), NameNodeFile.IMAGE_NEW, txid));
}
return list.toArray(new File[list.size()]);
} }
|
public class class_name {
public File[] getFsImageNameCheckpoint(long txid) {
ArrayList<File> list = new ArrayList<File>();
for (Iterator<StorageDirectory> it =
dirIterator(NameNodeDirType.IMAGE); it.hasNext();) {
list.add(getStorageFile(it.next(), NameNodeFile.IMAGE_NEW, txid)); // depends on control dependency: [for], data = [it]
}
return list.toArray(new File[list.size()]);
} }
|
public class class_name {
public static boolean isValidFormat(String string) {
if (StringUtil.isBlank(string)) {
return false;
}
String[] parts = string.split(SEPARATOR);
if (parts.length != 3) {
return false;
}
try {
Integer.valueOf(parts[1]);
} catch (NumberFormatException e) {
return false;
}
try {
Long.valueOf(parts[2]);
} catch (NumberFormatException e) {
return false;
}
return true;
} }
|
public class class_name {
public static boolean isValidFormat(String string) {
if (StringUtil.isBlank(string)) {
return false; // depends on control dependency: [if], data = [none]
}
String[] parts = string.split(SEPARATOR);
if (parts.length != 3) {
return false; // depends on control dependency: [if], data = [none]
}
try {
Integer.valueOf(parts[1]); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
return false;
} // depends on control dependency: [catch], data = [none]
try {
Long.valueOf(parts[2]); // depends on control dependency: [try], data = [none]
} catch (NumberFormatException e) {
return false;
} // depends on control dependency: [catch], data = [none]
return true;
} }
|
public class class_name {
protected void doRequest (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
InvocationContext context = null;
try {
context = new InvocationContext(request, response);
setContentType(request, response);
Template template = handleRequest(request, response, context);
if (template != null) {
mergeTemplate(template, context);
}
} catch (Exception e) {
log.warning("doRequest failed", "uri", request.getRequestURI(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
} }
|
public class class_name {
protected void doRequest (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
InvocationContext context = null;
try {
context = new InvocationContext(request, response);
setContentType(request, response);
Template template = handleRequest(request, response, context);
if (template != null) {
mergeTemplate(template, context); // depends on control dependency: [if], data = [(template]
}
} catch (Exception e) {
log.warning("doRequest failed", "uri", request.getRequestURI(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
} }
|
public class class_name {
public void addItem(@Nonnull final ExpressionItem item) {
if (item == null) {
throw new PreprocessorException("[Expression]Item is null", this.sources, this.includeStack, null);
}
if (last.isEmptySlot()) {
last = new ExpressionTreeElement(item, this.includeStack, this.sources);
} else {
last = last.addTreeElement(new ExpressionTreeElement(item, this.includeStack, this.sources));
}
} }
|
public class class_name {
public void addItem(@Nonnull final ExpressionItem item) {
if (item == null) {
throw new PreprocessorException("[Expression]Item is null", this.sources, this.includeStack, null);
}
if (last.isEmptySlot()) {
last = new ExpressionTreeElement(item, this.includeStack, this.sources); // depends on control dependency: [if], data = [none]
} else {
last = last.addTreeElement(new ExpressionTreeElement(item, this.includeStack, this.sources)); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static long getOffset(long baseOffset, int[] shape, int[] stride, int... indices) {
//int ret = mappers[shape.length].getOffset(baseOffset, shape, stride, indices);
if (shape.length != stride.length || indices.length != shape.length)
throw new IllegalArgumentException("Indexes, shape, and stride must be the same length");
long offset = baseOffset;
for (int i = 0; i < shape.length; i++) {
if (indices[i] >= shape[i])
throw new IllegalArgumentException(
String.format("J: Index [%d] must not be >= shape[%d]=%d.", i, i, shape[i]));
if (shape[i] != 1) {
offset += indices[i] * stride[i];
}
}
return offset;
} }
|
public class class_name {
public static long getOffset(long baseOffset, int[] shape, int[] stride, int... indices) {
//int ret = mappers[shape.length].getOffset(baseOffset, shape, stride, indices);
if (shape.length != stride.length || indices.length != shape.length)
throw new IllegalArgumentException("Indexes, shape, and stride must be the same length");
long offset = baseOffset;
for (int i = 0; i < shape.length; i++) {
if (indices[i] >= shape[i])
throw new IllegalArgumentException(
String.format("J: Index [%d] must not be >= shape[%d]=%d.", i, i, shape[i]));
if (shape[i] != 1) {
offset += indices[i] * stride[i]; // depends on control dependency: [if], data = [none]
}
}
return offset;
} }
|
public class class_name {
public byte[] processBlock(byte[] in, int inOff, int inLen) {
if (forEncryption) {
return encrypt(in, inOff, inLen);
} else {
return decrypt(in, inOff, inLen);
}
} }
|
public class class_name {
public byte[] processBlock(byte[] in, int inOff, int inLen) {
if (forEncryption) {
return encrypt(in, inOff, inLen);
// depends on control dependency: [if], data = [none]
} else {
return decrypt(in, inOff, inLen);
// depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
@Override
public Content getHeader(String header) {
HtmlTree bodyTree = getBody(true, getWindowTitle(utils.getSimpleName(annotationType)));
HtmlTree htmlTree = (configuration.allowTag(HtmlTag.HEADER))
? HtmlTree.HEADER()
: bodyTree;
addTop(htmlTree);
addNavLinks(true, htmlTree);
if (configuration.allowTag(HtmlTag.HEADER)) {
bodyTree.addContent(htmlTree);
}
bodyTree.addContent(HtmlConstants.START_OF_CLASS_DATA);
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.header);
if (configuration.showModules) {
ModuleElement mdle = configuration.docEnv.getElementUtils().getModuleOf(annotationType);
Content typeModuleLabel = HtmlTree.SPAN(HtmlStyle.moduleLabelInType, contents.moduleLabel);
Content moduleNameDiv = HtmlTree.DIV(HtmlStyle.subTitle, typeModuleLabel);
moduleNameDiv.addContent(Contents.SPACE);
moduleNameDiv.addContent(getModuleLink(mdle, new StringContent(mdle.getQualifiedName())));
div.addContent(moduleNameDiv);
}
PackageElement pkg = utils.containingPackage(annotationType);
if (!pkg.isUnnamed()) {
Content typePackageLabel = HtmlTree.SPAN(HtmlStyle.packageLabelInType, contents.packageLabel);
Content pkgNameDiv = HtmlTree.DIV(HtmlStyle.subTitle, typePackageLabel);
pkgNameDiv.addContent(Contents.SPACE);
Content pkgNameContent = getPackageLink(pkg, new StringContent(utils.getPackageName(pkg)));
pkgNameDiv.addContent(pkgNameContent);
div.addContent(pkgNameDiv);
}
LinkInfoImpl linkInfo = new LinkInfoImpl(configuration,
LinkInfoImpl.Kind.CLASS_HEADER, annotationType);
Content headerContent = new StringContent(header);
Content heading = HtmlTree.HEADING(HtmlConstants.CLASS_PAGE_HEADING, true,
HtmlStyle.title, headerContent);
heading.addContent(getTypeParameterLinks(linkInfo));
div.addContent(heading);
if (configuration.allowTag(HtmlTag.MAIN)) {
mainTree.addContent(div);
} else {
bodyTree.addContent(div);
}
return bodyTree;
} }
|
public class class_name {
@Override
public Content getHeader(String header) {
HtmlTree bodyTree = getBody(true, getWindowTitle(utils.getSimpleName(annotationType)));
HtmlTree htmlTree = (configuration.allowTag(HtmlTag.HEADER))
? HtmlTree.HEADER()
: bodyTree;
addTop(htmlTree);
addNavLinks(true, htmlTree);
if (configuration.allowTag(HtmlTag.HEADER)) {
bodyTree.addContent(htmlTree); // depends on control dependency: [if], data = [none]
}
bodyTree.addContent(HtmlConstants.START_OF_CLASS_DATA);
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.header);
if (configuration.showModules) {
ModuleElement mdle = configuration.docEnv.getElementUtils().getModuleOf(annotationType);
Content typeModuleLabel = HtmlTree.SPAN(HtmlStyle.moduleLabelInType, contents.moduleLabel);
Content moduleNameDiv = HtmlTree.DIV(HtmlStyle.subTitle, typeModuleLabel);
moduleNameDiv.addContent(Contents.SPACE); // depends on control dependency: [if], data = [none]
moduleNameDiv.addContent(getModuleLink(mdle, new StringContent(mdle.getQualifiedName()))); // depends on control dependency: [if], data = [none]
div.addContent(moduleNameDiv); // depends on control dependency: [if], data = [none]
}
PackageElement pkg = utils.containingPackage(annotationType);
if (!pkg.isUnnamed()) {
Content typePackageLabel = HtmlTree.SPAN(HtmlStyle.packageLabelInType, contents.packageLabel);
Content pkgNameDiv = HtmlTree.DIV(HtmlStyle.subTitle, typePackageLabel);
pkgNameDiv.addContent(Contents.SPACE); // depends on control dependency: [if], data = [none]
Content pkgNameContent = getPackageLink(pkg, new StringContent(utils.getPackageName(pkg)));
pkgNameDiv.addContent(pkgNameContent); // depends on control dependency: [if], data = [none]
div.addContent(pkgNameDiv); // depends on control dependency: [if], data = [none]
}
LinkInfoImpl linkInfo = new LinkInfoImpl(configuration,
LinkInfoImpl.Kind.CLASS_HEADER, annotationType);
Content headerContent = new StringContent(header);
Content heading = HtmlTree.HEADING(HtmlConstants.CLASS_PAGE_HEADING, true,
HtmlStyle.title, headerContent);
heading.addContent(getTypeParameterLinks(linkInfo));
div.addContent(heading);
if (configuration.allowTag(HtmlTag.MAIN)) {
mainTree.addContent(div); // depends on control dependency: [if], data = [none]
} else {
bodyTree.addContent(div); // depends on control dependency: [if], data = [none]
}
return bodyTree;
} }
|
public class class_name {
@Override
public synchronized void receiveAck(int blockIndex) {
SendWork work = m_outstandingWork.get(blockIndex);
// releases the BBContainers and cleans up
if (work == null || work.m_ackCounter == null) {
rejoinLog.warn("Received invalid blockIndex ack for targetId " + m_targetId +
" for index " + String.valueOf(blockIndex) +
((work == null) ? " already removed the block." : " ack counter haven't been initialized."));
return;
}
if (work.receiveAck()) {
rejoinLog.trace("Received ack for targetId " + m_targetId +
" removes block for index " + String.valueOf(blockIndex));
m_outstandingWorkCount.decrementAndGet();
m_outstandingWork.remove(blockIndex);
work.discard();
}
else {
rejoinLog.trace("Received ack for targetId " + m_targetId +
" decrements counter for block index " + String.valueOf(blockIndex));
}
} }
|
public class class_name {
@Override
public synchronized void receiveAck(int blockIndex) {
SendWork work = m_outstandingWork.get(blockIndex);
// releases the BBContainers and cleans up
if (work == null || work.m_ackCounter == null) {
rejoinLog.warn("Received invalid blockIndex ack for targetId " + m_targetId +
" for index " + String.valueOf(blockIndex) +
((work == null) ? " already removed the block." : " ack counter haven't been initialized.")); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (work.receiveAck()) {
rejoinLog.trace("Received ack for targetId " + m_targetId +
" removes block for index " + String.valueOf(blockIndex)); // depends on control dependency: [if], data = [none]
m_outstandingWorkCount.decrementAndGet(); // depends on control dependency: [if], data = [none]
m_outstandingWork.remove(blockIndex); // depends on control dependency: [if], data = [none]
work.discard(); // depends on control dependency: [if], data = [none]
}
else {
rejoinLog.trace("Received ack for targetId " + m_targetId +
" decrements counter for block index " + String.valueOf(blockIndex)); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
protected void cleanup() {
try {
if (cancellationHandler != null) {
cancellationHandler.onCancel();
} else if (this instanceof CancellationHandler) {
((CancellationHandler) this).onCancel();
}
} catch (Throwable t) {
// TODO: forward to global ExceptionHandler
log.warn("Unexpected error when cleaning up", t);
}
} }
|
public class class_name {
protected void cleanup() {
try {
if (cancellationHandler != null) {
cancellationHandler.onCancel(); // depends on control dependency: [if], data = [none]
} else if (this instanceof CancellationHandler) {
((CancellationHandler) this).onCancel(); // depends on control dependency: [if], data = [none]
}
} catch (Throwable t) {
// TODO: forward to global ExceptionHandler
log.warn("Unexpected error when cleaning up", t);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public void addImport(String imprt, int lineNo) {
imports.add(imprt);
if (imprt.endsWith(".*")) {
imprt = imprt.substring(0, imprt.lastIndexOf(".*"));
templateClass.importPaths.add(imprt);
}
importLineMap.put(imprt, lineNo);
} }
|
public class class_name {
public void addImport(String imprt, int lineNo) {
imports.add(imprt);
if (imprt.endsWith(".*")) {
imprt = imprt.substring(0, imprt.lastIndexOf(".*")); // depends on control dependency: [if], data = [none]
templateClass.importPaths.add(imprt); // depends on control dependency: [if], data = [none]
}
importLineMap.put(imprt, lineNo);
} }
|
public class class_name {
@Override
public void setWorkingSolution(Solution_ workingSolution) {
super.setWorkingSolution(workingSolution);
if (incrementalScoreCalculator instanceof ConstraintMatchAwareIncrementalScoreCalculator) {
((ConstraintMatchAwareIncrementalScoreCalculator<Solution_>) incrementalScoreCalculator)
.resetWorkingSolution(workingSolution, constraintMatchEnabledPreference);
} else {
incrementalScoreCalculator.resetWorkingSolution(workingSolution);
}
} }
|
public class class_name {
@Override
public void setWorkingSolution(Solution_ workingSolution) {
super.setWorkingSolution(workingSolution);
if (incrementalScoreCalculator instanceof ConstraintMatchAwareIncrementalScoreCalculator) {
((ConstraintMatchAwareIncrementalScoreCalculator<Solution_>) incrementalScoreCalculator)
.resetWorkingSolution(workingSolution, constraintMatchEnabledPreference); // depends on control dependency: [if], data = [none]
} else {
incrementalScoreCalculator.resetWorkingSolution(workingSolution); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public Set<Explanation<E>> computePreciseJustsOptimised(E entailment, int limit) throws OWLException {
this.limit = limit;
foundLaconicJustifications.clear();
ExplanationGenerator<E> gen = explanationGeneratorFactory.createExplanationGenerator(axioms, this);
Set<Explanation<E>> regularJusts = null;
try {
regularJusts = gen.getExplanations(entailment);
}
catch (ExplanationGeneratorInterruptedException e) {
// We have interrupted the generator via our progress monitor
return foundLaconicJustifications;
}
if (isCancelled()) {
return foundLaconicJustifications;
}
lastRegularJusts.clear();
// Initialise the current set of justifications with the regular justifications.
allPreviouslyFoundJustifications = new HashSet<Explanation<E>>();
allPreviouslyFoundJustifications.addAll(regularJusts);
// Set<Explanation<E>> nonLaconicJusts = new HashSet<Explanation<E>>();
// Set<Explanation<E>> laconicJusts = new HashSet<Explanation<E>>();
Set<OWLAxiom> axiomsInPreviousOntology = new HashSet<OWLAxiom>();
// We compute justifications until we can't find anymore
while (true) {
if (isCancelled()) {
return getReconstitutedLaconicJustifications();
}
// Now we take the union of our current set of justifications and compute
// O+ from this set.
Set<OWLAxiom> unionOfAllJustifications = new HashSet<OWLAxiom>();
for (Explanation<E> exp : allPreviouslyFoundJustifications) {
unionOfAllJustifications.addAll(exp.getAxioms());
}
Set<OWLAxiom> oPlus = computeOPlus(unionOfAllJustifications);
// Create our new ontology.
Set<OWLAxiom> augmentedAxioms = new HashSet<OWLAxiom>(oPlus);
///////////////////////////////////////////////////////////////////////////
// OPTIMISATION
//////////////////////////////////////////////////////////////////////////
// Exactly which axioms to we add the ontology? We need to
// limit the axioms that we add to O+ to limit the number of
// intermediate justifications. Without limiting the performance impact
// can be HUGE.
// Basically, if an checker at some stage appeared in a justification that we
// found, but it never appears in O+ then we don't add it to the ontology.
// The rationale behind this is that certain axioms such as equivalent classes
// checker will never ever appear in O+ or in a precise justification.
for (OWLAxiom ax : ont.getLogicalAxioms()) {
// If we have found the checker previously in a justification
// but our O+ doesn't contain it then we don't add it.
if (unionOfAllJustifications.contains(ax) && !oPlus.contains(ax)) {
continue;
}
augmentedAxioms.add(ax);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Next optimisation
if (augmentedAxioms.equals(axiomsInPreviousOntology)) {
break;
}
ExplanationGenerator<E> gen2 = explanationGeneratorFactory.createExplanationGenerator(augmentedAxioms, this);
axiomsInPreviousOntology.clear();
axiomsInPreviousOntology.addAll(augmentedAxioms);
Set<Explanation> allPrevJustsCopy = new HashSet<Explanation>(allPreviouslyFoundJustifications);
// Create a generator that gets ALL explanations from OPlus
Set<Explanation<E>> currentJustifications = null;
try {
currentJustifications = gen2.getExplanations(entailment);
}
catch (ExplanationGeneratorInterruptedException e) {
return getReconstitutedLaconicJustifications();
}
if (isCancelled()) {
return getReconstitutedLaconicJustifications();
}
allPreviouslyFoundJustifications.addAll(currentJustifications);
if (allPreviouslyFoundJustifications.equals(allPrevJustsCopy)) {
break;
}
// The following code used to check if we had found enough laconic justifcations. We don't need this
// anymore - I don't think
// for (Explanation<E> e : currentJustifications) {
// if (nonLaconicJusts.contains(e)) {
// continue;
// }
// if (laconicJusts.contains(e)) {
// continue;
// }
// if (isLaconic(e)) {
// laconicJusts.add(e);
// }
// else {
// nonLaconicJusts.add(e);
// }
// if (laconicJusts.size() == limit) {
// return getReconstitutedLaconicJustifications(laconicJusts);
// }
// }
}
// Set<Explanation<E>> laconicJustifications = new HashSet<Explanation<E>>();
//
// // We should now have our justifications that contain the set of precise justifications.
// // We just need to know which ones are the precise justifications.
// for (Explanation<E> justification : allPreviouslyFoundJustifications) {
// if (nonLaconicJusts.contains(justification)) {
// continue;
// }
// if (laconicJusts.contains(justification)) {
// laconicJustifications.add(justification);
// } else {
// if (isLaconic(justification)) {
// laconicJustifications.add(justification);
// }
// }
// }
return getReconstitutedLaconicJustifications();
} }
|
public class class_name {
public Set<Explanation<E>> computePreciseJustsOptimised(E entailment, int limit) throws OWLException {
this.limit = limit;
foundLaconicJustifications.clear();
ExplanationGenerator<E> gen = explanationGeneratorFactory.createExplanationGenerator(axioms, this);
Set<Explanation<E>> regularJusts = null;
try {
regularJusts = gen.getExplanations(entailment);
}
catch (ExplanationGeneratorInterruptedException e) {
// We have interrupted the generator via our progress monitor
return foundLaconicJustifications;
}
if (isCancelled()) {
return foundLaconicJustifications;
}
lastRegularJusts.clear();
// Initialise the current set of justifications with the regular justifications.
allPreviouslyFoundJustifications = new HashSet<Explanation<E>>();
allPreviouslyFoundJustifications.addAll(regularJusts);
// Set<Explanation<E>> nonLaconicJusts = new HashSet<Explanation<E>>();
// Set<Explanation<E>> laconicJusts = new HashSet<Explanation<E>>();
Set<OWLAxiom> axiomsInPreviousOntology = new HashSet<OWLAxiom>();
// We compute justifications until we can't find anymore
while (true) {
if (isCancelled()) {
return getReconstitutedLaconicJustifications(); // depends on control dependency: [if], data = [none]
}
// Now we take the union of our current set of justifications and compute
// O+ from this set.
Set<OWLAxiom> unionOfAllJustifications = new HashSet<OWLAxiom>();
for (Explanation<E> exp : allPreviouslyFoundJustifications) {
unionOfAllJustifications.addAll(exp.getAxioms()); // depends on control dependency: [for], data = [exp]
}
Set<OWLAxiom> oPlus = computeOPlus(unionOfAllJustifications);
// Create our new ontology.
Set<OWLAxiom> augmentedAxioms = new HashSet<OWLAxiom>(oPlus);
///////////////////////////////////////////////////////////////////////////
// OPTIMISATION
//////////////////////////////////////////////////////////////////////////
// Exactly which axioms to we add the ontology? We need to
// limit the axioms that we add to O+ to limit the number of
// intermediate justifications. Without limiting the performance impact
// can be HUGE.
// Basically, if an checker at some stage appeared in a justification that we
// found, but it never appears in O+ then we don't add it to the ontology.
// The rationale behind this is that certain axioms such as equivalent classes
// checker will never ever appear in O+ or in a precise justification.
for (OWLAxiom ax : ont.getLogicalAxioms()) {
// If we have found the checker previously in a justification
// but our O+ doesn't contain it then we don't add it.
if (unionOfAllJustifications.contains(ax) && !oPlus.contains(ax)) {
continue;
}
augmentedAxioms.add(ax); // depends on control dependency: [for], data = [ax]
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Next optimisation
if (augmentedAxioms.equals(axiomsInPreviousOntology)) {
break;
}
ExplanationGenerator<E> gen2 = explanationGeneratorFactory.createExplanationGenerator(augmentedAxioms, this);
axiomsInPreviousOntology.clear();
axiomsInPreviousOntology.addAll(augmentedAxioms);
Set<Explanation> allPrevJustsCopy = new HashSet<Explanation>(allPreviouslyFoundJustifications);
// Create a generator that gets ALL explanations from OPlus
Set<Explanation<E>> currentJustifications = null;
try {
currentJustifications = gen2.getExplanations(entailment); // depends on control dependency: [try], data = [none]
}
catch (ExplanationGeneratorInterruptedException e) {
return getReconstitutedLaconicJustifications();
} // depends on control dependency: [catch], data = [none]
if (isCancelled()) {
return getReconstitutedLaconicJustifications(); // depends on control dependency: [if], data = [none]
}
allPreviouslyFoundJustifications.addAll(currentJustifications);
if (allPreviouslyFoundJustifications.equals(allPrevJustsCopy)) {
break;
}
// The following code used to check if we had found enough laconic justifcations. We don't need this
// anymore - I don't think
// for (Explanation<E> e : currentJustifications) {
// if (nonLaconicJusts.contains(e)) {
// continue;
// }
// if (laconicJusts.contains(e)) {
// continue;
// }
// if (isLaconic(e)) {
// laconicJusts.add(e);
// }
// else {
// nonLaconicJusts.add(e);
// }
// if (laconicJusts.size() == limit) {
// return getReconstitutedLaconicJustifications(laconicJusts);
// }
// }
}
// Set<Explanation<E>> laconicJustifications = new HashSet<Explanation<E>>();
//
// // We should now have our justifications that contain the set of precise justifications.
// // We just need to know which ones are the precise justifications.
// for (Explanation<E> justification : allPreviouslyFoundJustifications) {
// if (nonLaconicJusts.contains(justification)) {
// continue;
// }
// if (laconicJusts.contains(justification)) {
// laconicJustifications.add(justification);
// } else {
// if (isLaconic(justification)) {
// laconicJustifications.add(justification);
// }
// }
// }
return getReconstitutedLaconicJustifications();
} }
|
public class class_name {
@Override
public ElementReader nextElementReader() throws IOException {
RandomElementReader reader = plyReader.nextElementReader();
if (reader == null) {
return reader;
}
if (!reader.getElementType().getName().equals("vertex")) {
return reader;
}
if (generateNormals) {
RandomElementReader faces = plyReader.getElementReader("face");
NormalGenerator generator = new NormalGenerator();
if (normalMode == NormalMode.ADD_NORMALS_CW) {
generator.setCounterClockwise(false);
}
generator.generateNormals(reader.duplicate(), faces);
}
RectBounds bounds = new RectBounds();
if (texGenStrategy != null) {
// Find the bounds of the model
ElementReader boundsReader = reader.duplicate();
for (Element element = boundsReader.readElement();
element != null; element = boundsReader.readElement()) {
bounds.addPoint(
element.getDouble("x"),
element.getDouble("y"),
element.getDouble("z"));
}
// Generate the texture coordinates.
ElementReader texReader = reader.duplicate();
for (Element element = texReader.readElement();
element != null; element = texReader.readElement()) {
texGenStrategy.generateCoordinates(element, bounds);
}
}
return reader;
} }
|
public class class_name {
@Override
public ElementReader nextElementReader() throws IOException {
RandomElementReader reader = plyReader.nextElementReader();
if (reader == null) {
return reader;
}
if (!reader.getElementType().getName().equals("vertex")) {
return reader;
}
if (generateNormals) {
RandomElementReader faces = plyReader.getElementReader("face");
NormalGenerator generator = new NormalGenerator();
if (normalMode == NormalMode.ADD_NORMALS_CW) {
generator.setCounterClockwise(false); // depends on control dependency: [if], data = [none]
}
generator.generateNormals(reader.duplicate(), faces);
}
RectBounds bounds = new RectBounds();
if (texGenStrategy != null) {
// Find the bounds of the model
ElementReader boundsReader = reader.duplicate();
for (Element element = boundsReader.readElement();
element != null; element = boundsReader.readElement()) {
bounds.addPoint(
element.getDouble("x"),
element.getDouble("y"),
element.getDouble("z"));
}
// Generate the texture coordinates.
ElementReader texReader = reader.duplicate();
for (Element element = texReader.readElement();
element != null; element = texReader.readElement()) {
texGenStrategy.generateCoordinates(element, bounds);
}
}
return reader;
} }
|
public class class_name {
public static void throwException(Throwable t) {
if (hasUnsafe()) {
PlatformDependent0.throwException(t);
} else {
PlatformDependent.<RuntimeException>throwException0(t);
}
} }
|
public class class_name {
public static void throwException(Throwable t) {
if (hasUnsafe()) {
PlatformDependent0.throwException(t); // depends on control dependency: [if], data = [none]
} else {
PlatformDependent.<RuntimeException>throwException0(t); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static String parseToUnicode(String input) {
// Get all the potential aliases
List<AliasCandidate> candidates = getAliasCandidates(input);
// Replace the aliases by their unicode
String result = input;
for (AliasCandidate candidate : candidates) {
Emoji emoji = EmojiManager.getForAlias(candidate.alias);
if (emoji != null) {
if (
emoji.supportsFitzpatrick() ||
(!emoji.supportsFitzpatrick() && candidate.fitzpatrick == null)
) {
String replacement = emoji.getUnicode();
if (candidate.fitzpatrick != null) {
replacement += candidate.fitzpatrick.unicode;
}
result = result.replace(
":" + candidate.fullString + ":",
replacement
);
}
}
}
// Replace the html
for (Emoji emoji : EmojiManager.getAll()) {
result = result.replace(emoji.getHtmlHexadecimal(), emoji.getUnicode());
result = result.replace(emoji.getHtmlDecimal(), emoji.getUnicode());
}
return result;
} }
|
public class class_name {
public static String parseToUnicode(String input) {
// Get all the potential aliases
List<AliasCandidate> candidates = getAliasCandidates(input);
// Replace the aliases by their unicode
String result = input;
for (AliasCandidate candidate : candidates) {
Emoji emoji = EmojiManager.getForAlias(candidate.alias);
if (emoji != null) {
if (
emoji.supportsFitzpatrick() ||
(!emoji.supportsFitzpatrick() && candidate.fitzpatrick == null)
) {
String replacement = emoji.getUnicode();
if (candidate.fitzpatrick != null) {
replacement += candidate.fitzpatrick.unicode; // depends on control dependency: [if], data = [none]
}
result = result.replace(
":" + candidate.fullString + ":",
replacement
); // depends on control dependency: [if], data = []
}
}
}
// Replace the html
for (Emoji emoji : EmojiManager.getAll()) {
result = result.replace(emoji.getHtmlHexadecimal(), emoji.getUnicode()); // depends on control dependency: [for], data = [emoji]
result = result.replace(emoji.getHtmlDecimal(), emoji.getUnicode()); // depends on control dependency: [for], data = [emoji]
}
return result;
} }
|
public class class_name {
@Default
@Produces
@Singleton
public Tracer produceTracer() {
// TCK casts to MockTracer so we cannot use GlobalTracer as a bean!
Tracer tracer = TracerResolver.resolveTracer();
if (tracer == null) {
tracer = GlobalTracer.get();
}
logger.info(String.format("Registering %s to GlobalTracer and providing it as CDI bean.", tracer));
GlobalTracer.register(tracer);
return tracer;
} }
|
public class class_name {
@Default
@Produces
@Singleton
public Tracer produceTracer() {
// TCK casts to MockTracer so we cannot use GlobalTracer as a bean!
Tracer tracer = TracerResolver.resolveTracer();
if (tracer == null) {
tracer = GlobalTracer.get(); // depends on control dependency: [if], data = [none]
}
logger.info(String.format("Registering %s to GlobalTracer and providing it as CDI bean.", tracer));
GlobalTracer.register(tracer);
return tracer;
} }
|
public class class_name {
public void forAllIndices(String template, Properties attributes) throws XDocletException
{
boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false);
// first the default index
_curIndexDef = _curTableDef.getIndex(null);
if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique()))
{
generate(template);
}
for (Iterator it = _curTableDef.getIndices(); it.hasNext(); )
{
_curIndexDef = (IndexDef)it.next();
if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique()))
{
generate(template);
}
}
_curIndexDef = null;
} }
|
public class class_name {
public void forAllIndices(String template, Properties attributes) throws XDocletException
{
boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false);
// first the default index
_curIndexDef = _curTableDef.getIndex(null);
if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique()))
{
generate(template);
}
for (Iterator it = _curTableDef.getIndices(); it.hasNext(); )
{
_curIndexDef = (IndexDef)it.next();
if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique()))
{
generate(template);
// depends on control dependency: [if], data = [none]
}
}
_curIndexDef = null;
} }
|
public class class_name {
public static double sabrBerestyckiNormalVolatilityApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double strike, double maturity)
{
// Apply displacement. Displaced model is just a shift on underlying and strike.
underlying += displacement;
strike += displacement;
double forwardStrikeAverage = (underlying+strike) / 2.0; // Original paper uses a geometric average here
double z;
if(beta < 1.0) {
z = nu / alpha * (Math.pow(underlying, 1.0-beta) - Math.pow(strike, 1.0-beta)) / (1.0-beta);
} else {
z = nu / alpha * Math.log(underlying/strike);
}
double x = Math.log((Math.sqrt(1.0 - 2.0*rho*z + z*z) + z - rho) / (1.0-rho));
double term1;
if(Math.abs(underlying - strike) < 1E-10 * (1+Math.abs(underlying))) {
// ATM case - we assume underlying = strike
term1 = alpha * Math.pow(underlying, beta);
}
else {
term1 = nu * (underlying-strike) / x;
}
double sigma = term1 * (1.0 + maturity * ((-beta*(2-beta)*alpha*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*alpha*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))) + (2.0 -3.0*rho*rho)*nu*nu/24));
return Math.max(sigma, 0.0);
} }
|
public class class_name {
public static double sabrBerestyckiNormalVolatilityApproximation(double alpha, double beta, double rho, double nu, double displacement, double underlying, double strike, double maturity)
{
// Apply displacement. Displaced model is just a shift on underlying and strike.
underlying += displacement;
strike += displacement;
double forwardStrikeAverage = (underlying+strike) / 2.0; // Original paper uses a geometric average here
double z;
if(beta < 1.0) {
z = nu / alpha * (Math.pow(underlying, 1.0-beta) - Math.pow(strike, 1.0-beta)) / (1.0-beta); // depends on control dependency: [if], data = [none]
} else {
z = nu / alpha * Math.log(underlying/strike); // depends on control dependency: [if], data = [none]
}
double x = Math.log((Math.sqrt(1.0 - 2.0*rho*z + z*z) + z - rho) / (1.0-rho));
double term1;
if(Math.abs(underlying - strike) < 1E-10 * (1+Math.abs(underlying))) {
// ATM case - we assume underlying = strike
term1 = alpha * Math.pow(underlying, beta); // depends on control dependency: [if], data = [none]
}
else {
term1 = nu * (underlying-strike) / x; // depends on control dependency: [if], data = [none]
}
double sigma = term1 * (1.0 + maturity * ((-beta*(2-beta)*alpha*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*alpha*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))) + (2.0 -3.0*rho*rho)*nu*nu/24));
return Math.max(sigma, 0.0);
} }
|
public class class_name {
public ServiceCall<Classifier> updateClassifier(UpdateClassifierOptions updateClassifierOptions) {
Validator.notNull(updateClassifierOptions, "updateClassifierOptions cannot be null");
Validator.isTrue((updateClassifierOptions.positiveExamples() != null) || (updateClassifierOptions
.negativeExamples() != null), "At least one of positiveExamples or negativeExamples must be supplied.");
String[] pathSegments = { "v3/classifiers" };
String[] pathParameters = { updateClassifierOptions.classifierId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("watson_vision_combined", "v3", "updateClassifier");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
if (updateClassifierOptions.positiveExamples() != null) {
for (Map.Entry<String, InputStream> entry : updateClassifierOptions.positiveExamples().entrySet()) {
String partName = String.format("%s_positive_examples", entry.getKey());
RequestBody part = RequestUtils.inputStreamBody(entry.getValue(), "application/octet-stream");
multipartBuilder.addFormDataPart(partName, entry.getKey(), part);
}
}
if (updateClassifierOptions.negativeExamples() != null) {
RequestBody negativeExamplesBody = RequestUtils.inputStreamBody(updateClassifierOptions.negativeExamples(),
"application/octet-stream");
multipartBuilder.addFormDataPart("negative_examples", updateClassifierOptions.negativeExamplesFilename(),
negativeExamplesBody);
}
builder.body(multipartBuilder.build());
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Classifier.class));
} }
|
public class class_name {
public ServiceCall<Classifier> updateClassifier(UpdateClassifierOptions updateClassifierOptions) {
Validator.notNull(updateClassifierOptions, "updateClassifierOptions cannot be null");
Validator.isTrue((updateClassifierOptions.positiveExamples() != null) || (updateClassifierOptions
.negativeExamples() != null), "At least one of positiveExamples or negativeExamples must be supplied.");
String[] pathSegments = { "v3/classifiers" };
String[] pathParameters = { updateClassifierOptions.classifierId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("watson_vision_combined", "v3", "updateClassifier");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue()); // depends on control dependency: [for], data = [header]
}
builder.header("Accept", "application/json");
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
if (updateClassifierOptions.positiveExamples() != null) {
for (Map.Entry<String, InputStream> entry : updateClassifierOptions.positiveExamples().entrySet()) {
String partName = String.format("%s_positive_examples", entry.getKey());
RequestBody part = RequestUtils.inputStreamBody(entry.getValue(), "application/octet-stream");
multipartBuilder.addFormDataPart(partName, entry.getKey(), part); // depends on control dependency: [for], data = [entry]
}
}
if (updateClassifierOptions.negativeExamples() != null) {
RequestBody negativeExamplesBody = RequestUtils.inputStreamBody(updateClassifierOptions.negativeExamples(),
"application/octet-stream");
multipartBuilder.addFormDataPart("negative_examples", updateClassifierOptions.negativeExamplesFilename(),
negativeExamplesBody); // depends on control dependency: [if], data = [none]
}
builder.body(multipartBuilder.build());
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Classifier.class));
} }
|
public class class_name {
static public boolean isDateUnit(ucar.units.Unit uu) {
boolean ok = uu.isCompatible(dateReferenceUnit);
if (!ok) return false;
try {
uu.getConverterTo(dateReferenceUnit);
return true;
} catch (ConversionException e) {
return false;
}
} }
|
public class class_name {
static public boolean isDateUnit(ucar.units.Unit uu) {
boolean ok = uu.isCompatible(dateReferenceUnit);
if (!ok) return false;
try {
uu.getConverterTo(dateReferenceUnit); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
} catch (ConversionException e) {
return false;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public DevVarLongStringArray extractLongStringArray(final DeviceData deviceData) {
if (deviceData.getAny()==null) {
System.out.println("any = null !!");
}
return DevVarLongStringArrayHelper.extract(deviceData.getAny());
} }
|
public class class_name {
public DevVarLongStringArray extractLongStringArray(final DeviceData deviceData) {
if (deviceData.getAny()==null) {
System.out.println("any = null !!"); // depends on control dependency: [if], data = [none]
}
return DevVarLongStringArrayHelper.extract(deviceData.getAny());
} }
|
public class class_name {
public static synchronized UserGroupInformation getProxiedUser(
final String toProxy, final Properties prop, final Logger log, final Configuration conf)
throws IOException {
if (conf == null) {
throw new IllegalArgumentException("conf can't be null");
}
UserGroupInformation.setConfiguration(conf);
if (toProxy == null) {
throw new IllegalArgumentException("toProxy can't be null");
}
if (loginUser == null) {
log.info("No login user. Creating login user");
final String keytab = verifySecureProperty(prop, PROXY_KEYTAB_LOCATION, log);
final String proxyUser = verifySecureProperty(prop, PROXY_USER, log);
UserGroupInformation.loginUserFromKeytab(proxyUser, keytab);
loginUser = UserGroupInformation.getLoginUser();
log.info("Logged in with user " + loginUser);
} else {
log.info("loginUser (" + loginUser + ") already created, refreshing tgt.");
loginUser.checkTGTAndReloginFromKeytab();
}
return UserGroupInformation.createProxyUser(toProxy, loginUser);
} }
|
public class class_name {
public static synchronized UserGroupInformation getProxiedUser(
final String toProxy, final Properties prop, final Logger log, final Configuration conf)
throws IOException {
if (conf == null) {
throw new IllegalArgumentException("conf can't be null");
}
UserGroupInformation.setConfiguration(conf);
if (toProxy == null) {
throw new IllegalArgumentException("toProxy can't be null");
}
if (loginUser == null) {
log.info("No login user. Creating login user"); // depends on control dependency: [if], data = [none]
final String keytab = verifySecureProperty(prop, PROXY_KEYTAB_LOCATION, log);
final String proxyUser = verifySecureProperty(prop, PROXY_USER, log);
UserGroupInformation.loginUserFromKeytab(proxyUser, keytab); // depends on control dependency: [if], data = [none]
loginUser = UserGroupInformation.getLoginUser(); // depends on control dependency: [if], data = [none]
log.info("Logged in with user " + loginUser); // depends on control dependency: [if], data = [none]
} else {
log.info("loginUser (" + loginUser + ") already created, refreshing tgt.");
loginUser.checkTGTAndReloginFromKeytab(); // depends on control dependency: [if], data = [none]
}
return UserGroupInformation.createProxyUser(toProxy, loginUser);
} }
|
public class class_name {
void setPhase(Phase phase){
TaskStatus.Phase oldPhase = getPhase();
if (oldPhase != phase){
// sort phase started
if (phase == TaskStatus.Phase.SORT){
setShuffleFinishTime(JobTracker.getClock().getTime());
} else if (phase == TaskStatus.Phase.REDUCE){
setSortFinishTime(JobTracker.getClock().getTime());
}
}
this.phase = phase;
} }
|
public class class_name {
void setPhase(Phase phase){
TaskStatus.Phase oldPhase = getPhase();
if (oldPhase != phase){
// sort phase started
if (phase == TaskStatus.Phase.SORT){
setShuffleFinishTime(JobTracker.getClock().getTime()); // depends on control dependency: [if], data = [none]
} else if (phase == TaskStatus.Phase.REDUCE){
setSortFinishTime(JobTracker.getClock().getTime()); // depends on control dependency: [if], data = [none]
}
}
this.phase = phase;
} }
|
public class class_name {
public void info(String s) {
if (isEnabled() && isInfoEnabled()) {
dispatchLogMessage(new LogEvent(this, LogEvent.INFO_TYPE, s));
}
} }
|
public class class_name {
public void info(String s) {
if (isEnabled() && isInfoEnabled()) {
dispatchLogMessage(new LogEvent(this, LogEvent.INFO_TYPE, s)); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private void groovySection(Reader reader, StringWriter sw) throws IOException {
sw.write("\"\"\");");
int c;
while ((c = reader.read()) != -1) {
if (c == '%') {
c = reader.read();
if (c != '>') {
sw.write('%');
} else {
break;
}
}
/* Don't eat EOL chars in sections - as they are valid instruction separators.
* See http://jira.codehaus.org/browse/GROOVY-980
*/
// if (c != '\n' && c != '\r') {
sw.write(c);
//}
}
sw.write(";\n"+printCommand()+"(\"\"\"");
} }
|
public class class_name {
private void groovySection(Reader reader, StringWriter sw) throws IOException {
sw.write("\"\"\");");
int c;
while ((c = reader.read()) != -1) {
if (c == '%') {
c = reader.read(); // depends on control dependency: [if], data = [none]
if (c != '>') {
sw.write('%'); // depends on control dependency: [if], data = [none]
} else {
break;
}
}
/* Don't eat EOL chars in sections - as they are valid instruction separators.
* See http://jira.codehaus.org/browse/GROOVY-980
*/
// if (c != '\n' && c != '\r') {
sw.write(c);
//}
}
sw.write(";\n"+printCommand()+"(\"\"\"");
} }
|
public class class_name {
@Beta
protected int standardCount(@Nullable Object object) {
for (Entry<?> entry : this.entrySet()) {
if (Objects.equal(entry.getElement(), object)) {
return entry.getCount();
}
}
return 0;
} }
|
public class class_name {
@Beta
protected int standardCount(@Nullable Object object) {
for (Entry<?> entry : this.entrySet()) {
if (Objects.equal(entry.getElement(), object)) {
return entry.getCount(); // depends on control dependency: [if], data = [none]
}
}
return 0;
} }
|
public class class_name {
public DeleteUserAttributesRequest withUserAttributeNames(String... userAttributeNames) {
if (this.userAttributeNames == null) {
setUserAttributeNames(new java.util.ArrayList<String>(userAttributeNames.length));
}
for (String ele : userAttributeNames) {
this.userAttributeNames.add(ele);
}
return this;
} }
|
public class class_name {
public DeleteUserAttributesRequest withUserAttributeNames(String... userAttributeNames) {
if (this.userAttributeNames == null) {
setUserAttributeNames(new java.util.ArrayList<String>(userAttributeNames.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : userAttributeNames) {
this.userAttributeNames.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} }
|
public class class_name {
public static Pair<List<Pinyin>, List<Boolean>> convert2Pair(String complexText, boolean removeTone)
{
List<Pinyin> pinyinList = new LinkedList<Pinyin>();
List<Boolean> booleanList = new LinkedList<Boolean>();
Collection<Token> tokenize = trie.tokenize(complexText);
for (Token token : tokenize)
{
String fragment = token.getFragment();
if (token.isMatch())
{
// 是拼音或拼音的一部分,用map转
Pinyin pinyin = convertSingle(fragment);
pinyinList.add(pinyin);
if (fragment.length() == pinyin.getPinyinWithoutTone().length())
{
booleanList.add(true);
}
else
{
booleanList.add(false);
}
}
else
{
List<Pinyin> pinyinListFragment = PinyinDictionary.convertToPinyin(fragment);
pinyinList.addAll(pinyinListFragment);
for (int i = 0; i < pinyinListFragment.size(); ++i)
{
booleanList.add(true);
}
}
}
makeToneToTheSame(pinyinList);
return new Pair<List<Pinyin>, List<Boolean>>(pinyinList, booleanList);
} }
|
public class class_name {
public static Pair<List<Pinyin>, List<Boolean>> convert2Pair(String complexText, boolean removeTone)
{
List<Pinyin> pinyinList = new LinkedList<Pinyin>();
List<Boolean> booleanList = new LinkedList<Boolean>();
Collection<Token> tokenize = trie.tokenize(complexText);
for (Token token : tokenize)
{
String fragment = token.getFragment();
if (token.isMatch())
{
// 是拼音或拼音的一部分,用map转
Pinyin pinyin = convertSingle(fragment);
pinyinList.add(pinyin); // depends on control dependency: [if], data = [none]
if (fragment.length() == pinyin.getPinyinWithoutTone().length())
{
booleanList.add(true); // depends on control dependency: [if], data = [none]
}
else
{
booleanList.add(false); // depends on control dependency: [if], data = [none]
}
}
else
{
List<Pinyin> pinyinListFragment = PinyinDictionary.convertToPinyin(fragment);
pinyinList.addAll(pinyinListFragment); // depends on control dependency: [if], data = [none]
for (int i = 0; i < pinyinListFragment.size(); ++i)
{
booleanList.add(true); // depends on control dependency: [for], data = [none]
}
}
}
makeToneToTheSame(pinyinList);
return new Pair<List<Pinyin>, List<Boolean>>(pinyinList, booleanList);
} }
|
public class class_name {
@NotNull
public Optional<T> findSingle() {
if (iterator.hasNext()) {
T singleCandidate = iterator.next();
if (iterator.hasNext()) {
throw new IllegalStateException("Stream contains more than one element");
} else {
return Optional.of(singleCandidate);
}
} else {
return Optional.empty();
}
} }
|
public class class_name {
@NotNull
public Optional<T> findSingle() {
if (iterator.hasNext()) {
T singleCandidate = iterator.next();
if (iterator.hasNext()) {
throw new IllegalStateException("Stream contains more than one element");
} else {
return Optional.of(singleCandidate); // depends on control dependency: [if], data = [none]
}
} else {
return Optional.empty(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
// See class comment for timeout semantics. In addition to ensuring we only timeout while
// there are outstanding requests, we also do a secondary consistency check to ensure
// there's no race between the idle timeout and incrementing the numOutstandingRequests
// (see SPARK-7003).
//
// To avoid a race between TransportClientFactory.createClient() and this code which could
// result in an inactive client being returned, this needs to run in a synchronized block.
synchronized (this) {
boolean hasInFlightRequests = responseHandler.numOutstandingRequests() > 0;
boolean isActuallyOverdue =
System.nanoTime() - responseHandler.getTimeOfLastRequestNs() > requestTimeoutNs;
if (e.state() == IdleState.ALL_IDLE && isActuallyOverdue) {
if (hasInFlightRequests) {
String address = getRemoteAddress(ctx.channel());
logger.error("Connection to {} has been quiet for {} ms while there are outstanding " +
"requests. Assuming connection is dead; please adjust spark.network.timeout if " +
"this is wrong.", address, requestTimeoutNs / 1000 / 1000);
client.timeOut();
ctx.close();
} else if (closeIdleConnections) {
// While CloseIdleConnections is enable, we also close idle connection
client.timeOut();
ctx.close();
}
}
}
}
ctx.fireUserEventTriggered(evt);
} }
|
public class class_name {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
// See class comment for timeout semantics. In addition to ensuring we only timeout while
// there are outstanding requests, we also do a secondary consistency check to ensure
// there's no race between the idle timeout and incrementing the numOutstandingRequests
// (see SPARK-7003).
//
// To avoid a race between TransportClientFactory.createClient() and this code which could
// result in an inactive client being returned, this needs to run in a synchronized block.
synchronized (this) {
boolean hasInFlightRequests = responseHandler.numOutstandingRequests() > 0;
boolean isActuallyOverdue =
System.nanoTime() - responseHandler.getTimeOfLastRequestNs() > requestTimeoutNs;
if (e.state() == IdleState.ALL_IDLE && isActuallyOverdue) {
if (hasInFlightRequests) {
String address = getRemoteAddress(ctx.channel());
logger.error("Connection to {} has been quiet for {} ms while there are outstanding " +
"requests. Assuming connection is dead; please adjust spark.network.timeout if " + // depends on control dependency: [if], data = [none]
"this is wrong.", address, requestTimeoutNs / 1000 / 1000);
client.timeOut(); // depends on control dependency: [if], data = [none]
ctx.close(); // depends on control dependency: [if], data = [none]
} else if (closeIdleConnections) {
// While CloseIdleConnections is enable, we also close idle connection
client.timeOut(); // depends on control dependency: [if], data = [none]
ctx.close(); // depends on control dependency: [if], data = [none]
}
}
}
}
ctx.fireUserEventTriggered(evt);
} }
|
public class class_name {
protected String getStringMethodParam(String methodName, String paramKey, String defaultValue) {
if (CommonUtils.isEmpty(configContext)) {
return defaultValue;
}
String o = (String) configContext.get(buildMethodKey(methodName, paramKey));
if (o == null) {
o = (String) configContext.get(paramKey);
return o == null ? defaultValue : o;
} else {
return o;
}
} }
|
public class class_name {
protected String getStringMethodParam(String methodName, String paramKey, String defaultValue) {
if (CommonUtils.isEmpty(configContext)) {
return defaultValue; // depends on control dependency: [if], data = [none]
}
String o = (String) configContext.get(buildMethodKey(methodName, paramKey));
if (o == null) {
o = (String) configContext.get(paramKey); // depends on control dependency: [if], data = [none]
return o == null ? defaultValue : o; // depends on control dependency: [if], data = [none]
} else {
return o; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public CreateClusterResponse createCluster(CreateClusterRequest request) {
checkNotNull(request, "request should not be null.");
checkStringNotEmpty(request.getImageType(), "The imageType should not be null or empty string.");
checkStringNotEmpty(request.getImageVersion(), "The imageVersion should not be null or empty string.");
checkNotNull(request.getInstanceGroups(), "The instanceGroups should not be null.");
StringWriter writer = new StringWriter();
try {
JsonGenerator jsonGenerator = JsonUtils.jsonGeneratorOf(writer);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("imageType", request.getImageType());
jsonGenerator.writeStringField("imageVersion", request.getImageVersion());
jsonGenerator.writeArrayFieldStart("instanceGroups");
for (InstanceGroupConfig instanceGroup : request.getInstanceGroups()) {
jsonGenerator.writeStartObject();
if (instanceGroup.getName() != null) {
jsonGenerator.writeStringField("name", instanceGroup.getName());
}
jsonGenerator.writeStringField("type", instanceGroup.getType());
jsonGenerator.writeStringField("instanceType", instanceGroup.getInstanceType());
jsonGenerator.writeNumberField("instanceCount", instanceGroup.getInstanceCount());
jsonGenerator.writeEndObject();
}
jsonGenerator.writeEndArray();
if (request.getName() != null) {
jsonGenerator.writeStringField("name", request.getName());
}
if (request.getLogUri() != null) {
jsonGenerator.writeStringField("logUri", request.getLogUri());
}
jsonGenerator.writeBooleanField("autoTerminate", request.getAutoTerminate());
if (request.getApplications() != null) {
jsonGenerator.writeArrayFieldStart("applications");
for (ApplicationConfig application : request.getApplications()) {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", application.getName());
jsonGenerator.writeStringField("version", application.getVersion());
if (application.getProperties() != null) {
jsonGenerator.writeObjectFieldStart("properties");
for (Map.Entry<String, Object> entry : application.getProperties().entrySet()) {
jsonGenerator.writeObjectField(entry.getKey(), entry.getValue());
}
jsonGenerator.writeEndObject();
}
jsonGenerator.writeEndObject();
}
jsonGenerator.writeEndArray();
}
if (request.getSteps() != null) {
jsonGenerator.writeArrayFieldStart("steps");
for (StepConfig step : request.getSteps()) {
jsonGenerator.writeStartObject();
if (step.getName() != null) {
jsonGenerator.writeStringField("name", step.getName());
}
jsonGenerator.writeStringField("type", step.getType());
jsonGenerator.writeStringField("actionOnFailure", step.getActionOnFailure());
jsonGenerator.writeObjectFieldStart("properties");
for (Map.Entry<String, String> entry : step.getProperties().entrySet()) {
jsonGenerator.writeStringField(entry.getKey(), entry.getValue());
}
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
}
jsonGenerator.writeEndArray();
}
jsonGenerator.writeEndObject();
jsonGenerator.close();
} catch (IOException e) {
throw new BceClientException("Fail to generate json", e);
}
byte[] json = null;
try {
json = writer.toString().getBytes(DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new BceClientException("Fail to get UTF-8 bytes", e);
}
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, CLUSTER);
internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(json.length));
internalRequest.addHeader(Headers.CONTENT_TYPE, "application/json");
internalRequest.setContent(RestartableInputStream.wrap(json));
if (request.getClientToken() != null) {
internalRequest.addParameter("clientToken", request.getClientToken());
}
return this.invokeHttpClient(internalRequest, CreateClusterResponse.class);
} }
|
public class class_name {
public CreateClusterResponse createCluster(CreateClusterRequest request) {
checkNotNull(request, "request should not be null.");
checkStringNotEmpty(request.getImageType(), "The imageType should not be null or empty string.");
checkStringNotEmpty(request.getImageVersion(), "The imageVersion should not be null or empty string.");
checkNotNull(request.getInstanceGroups(), "The instanceGroups should not be null.");
StringWriter writer = new StringWriter();
try {
JsonGenerator jsonGenerator = JsonUtils.jsonGeneratorOf(writer);
jsonGenerator.writeStartObject(); // depends on control dependency: [try], data = [none]
jsonGenerator.writeStringField("imageType", request.getImageType()); // depends on control dependency: [try], data = [none]
jsonGenerator.writeStringField("imageVersion", request.getImageVersion()); // depends on control dependency: [try], data = [none]
jsonGenerator.writeArrayFieldStart("instanceGroups"); // depends on control dependency: [try], data = [none]
for (InstanceGroupConfig instanceGroup : request.getInstanceGroups()) {
jsonGenerator.writeStartObject(); // depends on control dependency: [for], data = [none]
if (instanceGroup.getName() != null) {
jsonGenerator.writeStringField("name", instanceGroup.getName()); // depends on control dependency: [if], data = [none]
}
jsonGenerator.writeStringField("type", instanceGroup.getType()); // depends on control dependency: [for], data = [instanceGroup]
jsonGenerator.writeStringField("instanceType", instanceGroup.getInstanceType()); // depends on control dependency: [for], data = [instanceGroup]
jsonGenerator.writeNumberField("instanceCount", instanceGroup.getInstanceCount()); // depends on control dependency: [for], data = [instanceGroup]
jsonGenerator.writeEndObject(); // depends on control dependency: [for], data = [none]
}
jsonGenerator.writeEndArray(); // depends on control dependency: [try], data = [none]
if (request.getName() != null) {
jsonGenerator.writeStringField("name", request.getName()); // depends on control dependency: [if], data = [none]
}
if (request.getLogUri() != null) {
jsonGenerator.writeStringField("logUri", request.getLogUri()); // depends on control dependency: [if], data = [none]
}
jsonGenerator.writeBooleanField("autoTerminate", request.getAutoTerminate()); // depends on control dependency: [try], data = [none]
if (request.getApplications() != null) {
jsonGenerator.writeArrayFieldStart("applications"); // depends on control dependency: [if], data = [none]
for (ApplicationConfig application : request.getApplications()) {
jsonGenerator.writeStartObject(); // depends on control dependency: [for], data = [none]
jsonGenerator.writeStringField("name", application.getName()); // depends on control dependency: [for], data = [application]
jsonGenerator.writeStringField("version", application.getVersion()); // depends on control dependency: [for], data = [application]
if (application.getProperties() != null) {
jsonGenerator.writeObjectFieldStart("properties"); // depends on control dependency: [if], data = [none]
for (Map.Entry<String, Object> entry : application.getProperties().entrySet()) {
jsonGenerator.writeObjectField(entry.getKey(), entry.getValue()); // depends on control dependency: [for], data = [entry]
}
jsonGenerator.writeEndObject(); // depends on control dependency: [if], data = [none]
}
jsonGenerator.writeEndObject(); // depends on control dependency: [for], data = [none]
}
jsonGenerator.writeEndArray(); // depends on control dependency: [if], data = [none]
}
if (request.getSteps() != null) {
jsonGenerator.writeArrayFieldStart("steps"); // depends on control dependency: [if], data = [none]
for (StepConfig step : request.getSteps()) {
jsonGenerator.writeStartObject(); // depends on control dependency: [for], data = [none]
if (step.getName() != null) {
jsonGenerator.writeStringField("name", step.getName()); // depends on control dependency: [if], data = [none]
}
jsonGenerator.writeStringField("type", step.getType()); // depends on control dependency: [for], data = [step]
jsonGenerator.writeStringField("actionOnFailure", step.getActionOnFailure()); // depends on control dependency: [for], data = [step]
jsonGenerator.writeObjectFieldStart("properties"); // depends on control dependency: [for], data = [none]
for (Map.Entry<String, String> entry : step.getProperties().entrySet()) {
jsonGenerator.writeStringField(entry.getKey(), entry.getValue()); // depends on control dependency: [for], data = [entry]
}
jsonGenerator.writeEndObject(); // depends on control dependency: [for], data = [none]
jsonGenerator.writeEndObject(); // depends on control dependency: [for], data = [none]
}
jsonGenerator.writeEndArray(); // depends on control dependency: [if], data = [none]
}
jsonGenerator.writeEndObject(); // depends on control dependency: [try], data = [none]
jsonGenerator.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new BceClientException("Fail to generate json", e);
} // depends on control dependency: [catch], data = [none]
byte[] json = null;
try {
json = writer.toString().getBytes(DEFAULT_ENCODING); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
throw new BceClientException("Fail to get UTF-8 bytes", e);
} // depends on control dependency: [catch], data = [none]
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, CLUSTER);
internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(json.length));
internalRequest.addHeader(Headers.CONTENT_TYPE, "application/json");
internalRequest.setContent(RestartableInputStream.wrap(json));
if (request.getClientToken() != null) {
internalRequest.addParameter("clientToken", request.getClientToken()); // depends on control dependency: [if], data = [none]
}
return this.invokeHttpClient(internalRequest, CreateClusterResponse.class);
} }
|
public class class_name {
@Nullable
@Override
public DFA<?, I> findCounterExample(DFA<?, I> automaton, Collection<? extends I> inputs, String property)
throws ModelCheckingException {
final File fsm = findCounterExampleFSM(automaton, inputs, property);
try {
final CompactDFA<I> result;
if (fsm != null) {
result = FSM2DFAParser.getParser(inputs, getString2Input(), LABEL_NAME, LABEL_VALUE).readModel(fsm);
// check if we must keep the FSM
if (!isKeepFiles() && !fsm.delete()) {
throw new ModelCheckingException("Could not delete file: " + fsm.getAbsolutePath());
}
for (Integer state : result.getStates()) {
final boolean deadlocks = result.getInputAlphabet().stream().noneMatch(
i -> result.getSuccessor(state, i) != null);
result.setAccepting(state, deadlocks);
}
} else {
result = null;
}
return result;
} catch (IOException | FSMParseException e) {
throw new ModelCheckingException(e);
}
} }
|
public class class_name {
@Nullable
@Override
public DFA<?, I> findCounterExample(DFA<?, I> automaton, Collection<? extends I> inputs, String property)
throws ModelCheckingException {
final File fsm = findCounterExampleFSM(automaton, inputs, property);
try {
final CompactDFA<I> result;
if (fsm != null) {
result = FSM2DFAParser.getParser(inputs, getString2Input(), LABEL_NAME, LABEL_VALUE).readModel(fsm); // depends on control dependency: [if], data = [(fsm]
// check if we must keep the FSM
if (!isKeepFiles() && !fsm.delete()) {
throw new ModelCheckingException("Could not delete file: " + fsm.getAbsolutePath());
}
for (Integer state : result.getStates()) {
final boolean deadlocks = result.getInputAlphabet().stream().noneMatch(
i -> result.getSuccessor(state, i) != null);
result.setAccepting(state, deadlocks); // depends on control dependency: [for], data = [state]
}
} else {
result = null; // depends on control dependency: [if], data = [none]
}
return result;
} catch (IOException | FSMParseException e) {
throw new ModelCheckingException(e);
}
} }
|
public class class_name {
private void init(Context context, AttributeSet attrs, int defStyle) {
// Attribute initialization
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ProgressButton, defStyle,
R.style.ProgressButton_Pin_Compat);
final Resources res = getResources();
mProgress = a.getInteger(R.styleable.ProgressButton_progress, mProgress);
mMax = a.getInteger(R.styleable.ProgressButton_max, mMax);
int circleColor = res.getColor(R.color.progress_default_circle_color);
circleColor = a.getColor(R.styleable.ProgressButton_circleColor, circleColor);
int progressColor = res.getColor(R.color.progress_default_progress_color);
progressColor = a.getColor(R.styleable.ProgressButton_progressColor, progressColor);
int pinnedDrawable =
a.getResourceId(R.styleable.ProgressButton_pinnedDrawable, R.drawable.pin_progress_pinned);
mPinnedDrawable = res.getDrawable(pinnedDrawable);
mPinnedDrawable.setCallback(this);
int unpinnedDrawable = a.getResourceId(R.styleable.ProgressButton_unpinnedDrawable,
R.drawable.pin_progress_unpinned);
mUnpinnedDrawable = res.getDrawable(unpinnedDrawable);
mUnpinnedDrawable.setCallback(this);
int shadowDrawable =
a.getResourceId(R.styleable.ProgressButton_shadowDrawable, R.drawable.pin_progress_shadow);
mShadowDrawable = res.getDrawable(shadowDrawable);
mShadowDrawable.setCallback(this);
mInnerSize = res.getDimensionPixelSize(R.dimen.progress_inner_size);
mInnerSize = a.getDimensionPixelSize(R.styleable.ProgressButton_innerSize, mInnerSize);
setChecked(a.getBoolean(R.styleable.ProgressButton_pinned, false));
setClickable(a.getBoolean(R.styleable.ProgressButton_android_clickable, false));
setFocusable(a.getBoolean(R.styleable.ProgressButton_android_focusable, false));
setBackgroundDrawable(a.getDrawable(R.styleable.ProgressButton_android_background));
mAnimating = a.getBoolean(R.styleable.ProgressButton_animating, mAnimating);
mAnimationSpeed = a.getInteger(R.styleable.ProgressButton_animationSpeed, mAnimationSpeed);
mAnimationDelay = a.getInteger(R.styleable.ProgressButton_animationDelay, mAnimationDelay);
mAnimationStripWidth =
a.getInteger(R.styleable.ProgressButton_animationStripWidth, mAnimationStripWidth);
a.recycle();
mDrawableSize = mShadowDrawable.getIntrinsicWidth();
mCirclePaint = new Paint();
mCirclePaint.setColor(circleColor);
mCirclePaint.setAntiAlias(true);
mProgressPaint = new Paint();
mProgressPaint.setColor(progressColor);
mProgressPaint.setAntiAlias(true);
if (mAnimating) {
startAnimating();
}
} }
|
public class class_name {
private void init(Context context, AttributeSet attrs, int defStyle) {
// Attribute initialization
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ProgressButton, defStyle,
R.style.ProgressButton_Pin_Compat);
final Resources res = getResources();
mProgress = a.getInteger(R.styleable.ProgressButton_progress, mProgress);
mMax = a.getInteger(R.styleable.ProgressButton_max, mMax);
int circleColor = res.getColor(R.color.progress_default_circle_color);
circleColor = a.getColor(R.styleable.ProgressButton_circleColor, circleColor);
int progressColor = res.getColor(R.color.progress_default_progress_color);
progressColor = a.getColor(R.styleable.ProgressButton_progressColor, progressColor);
int pinnedDrawable =
a.getResourceId(R.styleable.ProgressButton_pinnedDrawable, R.drawable.pin_progress_pinned);
mPinnedDrawable = res.getDrawable(pinnedDrawable);
mPinnedDrawable.setCallback(this);
int unpinnedDrawable = a.getResourceId(R.styleable.ProgressButton_unpinnedDrawable,
R.drawable.pin_progress_unpinned);
mUnpinnedDrawable = res.getDrawable(unpinnedDrawable);
mUnpinnedDrawable.setCallback(this);
int shadowDrawable =
a.getResourceId(R.styleable.ProgressButton_shadowDrawable, R.drawable.pin_progress_shadow);
mShadowDrawable = res.getDrawable(shadowDrawable);
mShadowDrawable.setCallback(this);
mInnerSize = res.getDimensionPixelSize(R.dimen.progress_inner_size);
mInnerSize = a.getDimensionPixelSize(R.styleable.ProgressButton_innerSize, mInnerSize);
setChecked(a.getBoolean(R.styleable.ProgressButton_pinned, false));
setClickable(a.getBoolean(R.styleable.ProgressButton_android_clickable, false));
setFocusable(a.getBoolean(R.styleable.ProgressButton_android_focusable, false));
setBackgroundDrawable(a.getDrawable(R.styleable.ProgressButton_android_background));
mAnimating = a.getBoolean(R.styleable.ProgressButton_animating, mAnimating);
mAnimationSpeed = a.getInteger(R.styleable.ProgressButton_animationSpeed, mAnimationSpeed);
mAnimationDelay = a.getInteger(R.styleable.ProgressButton_animationDelay, mAnimationDelay);
mAnimationStripWidth =
a.getInteger(R.styleable.ProgressButton_animationStripWidth, mAnimationStripWidth);
a.recycle();
mDrawableSize = mShadowDrawable.getIntrinsicWidth();
mCirclePaint = new Paint();
mCirclePaint.setColor(circleColor);
mCirclePaint.setAntiAlias(true);
mProgressPaint = new Paint();
mProgressPaint.setColor(progressColor);
mProgressPaint.setAntiAlias(true);
if (mAnimating) {
startAnimating(); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static void setValue(Object instance, String fieldName, Object value) {
try {
Field f = findFieldRecursively(instance.getClass(), fieldName);
if (f == null)
throw new NoSuchMethodException("Cannot find field " + fieldName + " on " + instance.getClass() + " or superclasses");
f.setAccessible(true);
f.set(instance, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
} }
|
public class class_name {
public static void setValue(Object instance, String fieldName, Object value) {
try {
Field f = findFieldRecursively(instance.getClass(), fieldName);
if (f == null)
throw new NoSuchMethodException("Cannot find field " + fieldName + " on " + instance.getClass() + " or superclasses");
f.setAccessible(true); // depends on control dependency: [try], data = [none]
f.set(instance, value); // 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 {
public Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>> listBySiteSlotNextWithServiceResponseAsync(final String nextPageLink) {
return listBySiteSlotNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<ResourceHealthMetadataInner>>, Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>> call(ServiceResponse<Page<ResourceHealthMetadataInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listBySiteSlotNextWithServiceResponseAsync(nextPageLink));
}
});
} }
|
public class class_name {
public Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>> listBySiteSlotNextWithServiceResponseAsync(final String nextPageLink) {
return listBySiteSlotNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<ResourceHealthMetadataInner>>, Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ResourceHealthMetadataInner>>> call(ServiceResponse<Page<ResourceHealthMetadataInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page); // depends on control dependency: [if], data = [none]
}
return Observable.just(page).concatWith(listBySiteSlotNextWithServiceResponseAsync(nextPageLink));
}
});
} }
|
public class class_name {
private static boolean areMethodNameAndParameterTypesEqual(Method methodA, Method methodB) {
if (!methodA.getName().equals(methodB.getName())) {
return false;
}
Class<?>[] methodAParameterTypes = methodA.getParameterTypes();
Class<?>[] methodBParameterTypes = methodB.getParameterTypes();
if (methodAParameterTypes.length != methodBParameterTypes.length) {
return false;
}
for (int i = 0; i < methodAParameterTypes.length; i++) {
if (!methodAParameterTypes[i].equals(methodBParameterTypes[i])) {
return false;
}
}
return true;
} }
|
public class class_name {
private static boolean areMethodNameAndParameterTypesEqual(Method methodA, Method methodB) {
if (!methodA.getName().equals(methodB.getName())) {
return false; // depends on control dependency: [if], data = [none]
}
Class<?>[] methodAParameterTypes = methodA.getParameterTypes();
Class<?>[] methodBParameterTypes = methodB.getParameterTypes();
if (methodAParameterTypes.length != methodBParameterTypes.length) {
return false;
}
for (int i = 0; i < methodAParameterTypes.length; i++) {
if (!methodAParameterTypes[i].equals(methodBParameterTypes[i])) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} }
|
public class class_name {
public PoolExistsHeaders withLastModified(DateTime lastModified) {
if (lastModified == null) {
this.lastModified = null;
} else {
this.lastModified = new DateTimeRfc1123(lastModified);
}
return this;
} }
|
public class class_name {
public PoolExistsHeaders withLastModified(DateTime lastModified) {
if (lastModified == null) {
this.lastModified = null; // depends on control dependency: [if], data = [none]
} else {
this.lastModified = new DateTimeRfc1123(lastModified); // depends on control dependency: [if], data = [(lastModified]
}
return this;
} }
|
public class class_name {
public TemporalAccessor parse(CharSequence text) {
Jdk8Methods.requireNonNull(text, "text");
try {
return parseToBuilder(text, null).resolve(resolverStyle, resolverFields);
} catch (DateTimeParseException ex) {
throw ex;
} catch (RuntimeException ex) {
throw createError(text, ex);
}
} }
|
public class class_name {
public TemporalAccessor parse(CharSequence text) {
Jdk8Methods.requireNonNull(text, "text");
try {
return parseToBuilder(text, null).resolve(resolverStyle, resolverFields); // depends on control dependency: [try], data = [none]
} catch (DateTimeParseException ex) {
throw ex;
} catch (RuntimeException ex) { // depends on control dependency: [catch], data = [none]
throw createError(text, ex);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private static int drawTail(final Point2DArray points, final NFastDoubleArrayJSO buffer, Direction lastDirection, final Direction tailDirection, final double correction, final OrthogonalPolyLine pline, final double p0x, final double p0y, double p1x, double p1y, final boolean write)
{
final double tailOffset = pline.getTailOffset();
Point2D p1 = points.get(points.size() - 1);
// correct for tailOffset
if (tailOffset > 0)
{
if (!write)
{
p1 = p1.copy();
}
correctEndWithOffset(tailOffset, tailDirection, p1);
p1x = p1.getX();
p1y = p1.getY();
}
// correct for correction
if (correction > 0)
{
// must do this off a cloned Point2D, as we still need the p1, for the last part of the line at the end.
final Point2D p1Copy = p1.copy();
correctEndWithOffset(correction, tailDirection, p1Copy);
p1x = p1Copy.getX();
p1y = p1Copy.getY();
}
final double dx = (p1x - p0x);
final double dy = (p1y - p0y);
int corners = 0;
boolean behind = false;
switch (tailDirection)
{
case NORTH:
behind = dy < 0;
break;
case SOUTH:
behind = dy > 0;
break;
case WEST:
behind = dx < 0;
break;
case EAST:
behind = dx > 0;
break;
case NONE:
// do nothing as NONE is explicitey handled at the end
break;
default:
throw new IllegalStateException("Invalid Direction " + tailDirection);
}
double x = p0x;
double y = p0y;
if (behind)
{
// means p0 is behind.
switch (tailDirection)
{
case NORTH:
case SOUTH:
if (((lastDirection == NORTH) && (tailDirection == SOUTH)) || ((lastDirection == SOUTH) && (tailDirection == NORTH)) || ((dx > 0) && (lastDirection == EAST)) || ((dx < 0) && (lastDirection == WEST)))
{
// A mid point is needed to ensure an attrictive line is drawn.
x = p0x + (dx / 2);
addPoint(buffer, x, y, write);
if ((lastDirection == NORTH) || (lastDirection == NORTH))
{
corners++;
}
}
y = p1y;
addPoint(buffer, x, y, write);
if (lastDirection != tailDirection)
{
corners++;
}
x = p1x;
addPoint(buffer, x, y, write);
corners++;
y = p1.getY();
addPoint(buffer, x, y, write);
corners++;
break;
case WEST:
case EAST:
if (((lastDirection == WEST) && (tailDirection == EAST)) || ((lastDirection == EAST) && (tailDirection == WEST)) || ((dy > 0) && (lastDirection == SOUTH)) || ((dy < 0) && (lastDirection == NORTH)))
{
// A mid point is needed to ensure an attrictive line is drawn.
y = p0y + (dy / 2);
addPoint(buffer, x, y, write);
if ((lastDirection == EAST) || (lastDirection == WEST))
{
corners++;
}
}
x = p1x;
addPoint(buffer, x, y, write);
if (lastDirection != tailDirection)
{
corners++;
}
y = p1y;
addPoint(buffer, x, y, write);
corners++;
x = p1.getX();
addPoint(buffer, x, y, write);
corners++;
break;
default:
throw new IllegalStateException("Invalid Direction " + tailDirection);
}
}
else
{
// means p0 is in front
switch (tailDirection)
{
case NORTH:
case SOUTH:
if (((lastDirection == NORTH) && (tailDirection == SOUTH)) || ((lastDirection == SOUTH) && (tailDirection == NORTH)) || ((dx > 0) && (lastDirection == WEST)) || ((dx < 0) && (lastDirection == EAST)))
{
// A mid point is needed to ensure an attrictive line is drawn.
y = p0y + (dy / 2);
addPoint(buffer, x, y, write);
if ((lastDirection == EAST) || (lastDirection == WEST))
{
lastDirection = (dy < 0) ? NORTH : SOUTH;
corners++;
}
}
x = p1x;
addPoint(buffer, x, y, write);
if ((lastDirection == NORTH) || (lastDirection == SOUTH))
{
corners++;
}
y = p1.getY();
addPoint(buffer, x, y, write);
corners++;
break;
case WEST:
case EAST:
if (((lastDirection == WEST) && (tailDirection == EAST)) || ((lastDirection == EAST) && (tailDirection == WEST)) || ((dy > 0) && (lastDirection == NORTH)) || ((dy < 0) && (lastDirection == SOUTH)))
{
// A mid point is needed to ensure an attrictive line is drawn.
x = p0x + (dx / 2);
addPoint(buffer, x, y, write);
if ((lastDirection == NORTH) || (lastDirection == SOUTH))
{
lastDirection = (dx < 0) ? WEST : EAST;
corners++;
}
}
y = p1y;
addPoint(buffer, x, y, write);
if ((lastDirection == EAST) || (lastDirection == WEST))
{
corners++;
}
x = p1.getX();
addPoint(buffer, x, y, write);
corners++;
break;
default:
throw new IllegalStateException("Invalid Direction " + tailDirection);
}
}
return corners;
} }
|
public class class_name {
private static int drawTail(final Point2DArray points, final NFastDoubleArrayJSO buffer, Direction lastDirection, final Direction tailDirection, final double correction, final OrthogonalPolyLine pline, final double p0x, final double p0y, double p1x, double p1y, final boolean write)
{
final double tailOffset = pline.getTailOffset();
Point2D p1 = points.get(points.size() - 1);
// correct for tailOffset
if (tailOffset > 0)
{
if (!write)
{
p1 = p1.copy(); // depends on control dependency: [if], data = [none]
}
correctEndWithOffset(tailOffset, tailDirection, p1); // depends on control dependency: [if], data = [(tailOffset]
p1x = p1.getX(); // depends on control dependency: [if], data = [none]
p1y = p1.getY(); // depends on control dependency: [if], data = [none]
}
// correct for correction
if (correction > 0)
{
// must do this off a cloned Point2D, as we still need the p1, for the last part of the line at the end.
final Point2D p1Copy = p1.copy();
correctEndWithOffset(correction, tailDirection, p1Copy); // depends on control dependency: [if], data = [(correction]
p1x = p1Copy.getX(); // depends on control dependency: [if], data = [none]
p1y = p1Copy.getY(); // depends on control dependency: [if], data = [none]
}
final double dx = (p1x - p0x);
final double dy = (p1y - p0y);
int corners = 0;
boolean behind = false;
switch (tailDirection)
{
case NORTH:
behind = dy < 0;
break;
case SOUTH:
behind = dy > 0;
break;
case WEST:
behind = dx < 0;
break;
case EAST:
behind = dx > 0;
break;
case NONE:
// do nothing as NONE is explicitey handled at the end
break;
default:
throw new IllegalStateException("Invalid Direction " + tailDirection);
}
double x = p0x;
double y = p0y;
if (behind)
{
// means p0 is behind.
switch (tailDirection)
{
case NORTH:
case SOUTH:
if (((lastDirection == NORTH) && (tailDirection == SOUTH)) || ((lastDirection == SOUTH) && (tailDirection == NORTH)) || ((dx > 0) && (lastDirection == EAST)) || ((dx < 0) && (lastDirection == WEST)))
{
// A mid point is needed to ensure an attrictive line is drawn.
x = p0x + (dx / 2); // depends on control dependency: [if], data = [none]
addPoint(buffer, x, y, write); // depends on control dependency: [if], data = [none]
if ((lastDirection == NORTH) || (lastDirection == NORTH))
{
corners++; // depends on control dependency: [if], data = [none]
}
}
y = p1y;
addPoint(buffer, x, y, write);
if (lastDirection != tailDirection)
{
corners++; // depends on control dependency: [if], data = [none]
}
x = p1x;
addPoint(buffer, x, y, write);
corners++;
y = p1.getY();
addPoint(buffer, x, y, write);
corners++;
break;
case WEST:
case EAST:
if (((lastDirection == WEST) && (tailDirection == EAST)) || ((lastDirection == EAST) && (tailDirection == WEST)) || ((dy > 0) && (lastDirection == SOUTH)) || ((dy < 0) && (lastDirection == NORTH)))
{
// A mid point is needed to ensure an attrictive line is drawn.
y = p0y + (dy / 2); // depends on control dependency: [if], data = [none]
addPoint(buffer, x, y, write); // depends on control dependency: [if], data = [none]
if ((lastDirection == EAST) || (lastDirection == WEST))
{
corners++; // depends on control dependency: [if], data = [none]
}
}
x = p1x;
addPoint(buffer, x, y, write);
if (lastDirection != tailDirection)
{
corners++; // depends on control dependency: [if], data = [none]
}
y = p1y;
addPoint(buffer, x, y, write);
corners++;
x = p1.getX();
addPoint(buffer, x, y, write);
corners++;
break;
default:
throw new IllegalStateException("Invalid Direction " + tailDirection);
}
}
else
{
// means p0 is in front
switch (tailDirection)
{
case NORTH:
case SOUTH:
if (((lastDirection == NORTH) && (tailDirection == SOUTH)) || ((lastDirection == SOUTH) && (tailDirection == NORTH)) || ((dx > 0) && (lastDirection == WEST)) || ((dx < 0) && (lastDirection == EAST)))
{
// A mid point is needed to ensure an attrictive line is drawn.
y = p0y + (dy / 2); // depends on control dependency: [if], data = [none]
addPoint(buffer, x, y, write); // depends on control dependency: [if], data = [none]
if ((lastDirection == EAST) || (lastDirection == WEST))
{
lastDirection = (dy < 0) ? NORTH : SOUTH; // depends on control dependency: [if], data = [none]
corners++; // depends on control dependency: [if], data = [none]
}
}
x = p1x;
addPoint(buffer, x, y, write);
if ((lastDirection == NORTH) || (lastDirection == SOUTH))
{
corners++; // depends on control dependency: [if], data = [none]
}
y = p1.getY();
addPoint(buffer, x, y, write);
corners++;
break;
case WEST:
case EAST:
if (((lastDirection == WEST) && (tailDirection == EAST)) || ((lastDirection == EAST) && (tailDirection == WEST)) || ((dy > 0) && (lastDirection == NORTH)) || ((dy < 0) && (lastDirection == SOUTH)))
{
// A mid point is needed to ensure an attrictive line is drawn.
x = p0x + (dx / 2); // depends on control dependency: [if], data = [none]
addPoint(buffer, x, y, write); // depends on control dependency: [if], data = [none]
if ((lastDirection == NORTH) || (lastDirection == SOUTH))
{
lastDirection = (dx < 0) ? WEST : EAST; // depends on control dependency: [if], data = [none]
corners++; // depends on control dependency: [if], data = [none]
}
}
y = p1y;
addPoint(buffer, x, y, write);
if ((lastDirection == EAST) || (lastDirection == WEST))
{
corners++; // depends on control dependency: [if], data = [none]
}
x = p1.getX();
addPoint(buffer, x, y, write);
corners++;
break;
default:
throw new IllegalStateException("Invalid Direction " + tailDirection);
}
}
return corners;
} }
|
public class class_name {
public static ANVLRecord load(final InputStream is)
throws IOException {
// It doesn't look like a CRLF sequence is possible in UTF-8 without
// it signifying CRLF: The top bits are set in multibyte characters.
// Was thinking of recording CRLF as I was running through this first
// parse but the offsets would then be incorrect if any multibyte
// characters in the intervening gaps between CRLF.
boolean isCRLF = false;
boolean recordStart = false;
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
boolean done = false;
int read = 0;
for (int c = -1, previousCharacter; !done;) {
if (read++ >= MAXIMUM_SIZE) {
throw new IOException("Read " + MAXIMUM_SIZE +
" bytes without finding \\r\\n\\r\\n " +
"End-Of-ANVLRecord");
}
previousCharacter = c;
c = is.read();
if (c == -1) {
throw new IOException("End-Of-Stream before \\r\\n\\r\\n " +
"End-Of-ANVLRecord:\n" +
new String(baos.toByteArray(), UTF8));
}
if (isLF((char)c) && isCR((char)previousCharacter)) {
if (isCRLF) {
// If we just had a CRLF, then its two CRLFs and its end of
// record. We're done.
done = true;
} else {
isCRLF = true;
}
} else if (!recordStart && Character.isWhitespace(c)) {
// Skip any whitespace at start of ANVLRecord.
continue;
} else {
// Clear isCRLF flag if this character is NOT a '\r'.
if (isCRLF && !isCR((char)c)) {
isCRLF = false;
}
// Not whitespace so start record if we haven't already.
if (!recordStart) {
recordStart = true;
}
}
baos.write(c);
}
return load(new String(baos.toByteArray(), UTF8));
} }
|
public class class_name {
public static ANVLRecord load(final InputStream is)
throws IOException {
// It doesn't look like a CRLF sequence is possible in UTF-8 without
// it signifying CRLF: The top bits are set in multibyte characters.
// Was thinking of recording CRLF as I was running through this first
// parse but the offsets would then be incorrect if any multibyte
// characters in the intervening gaps between CRLF.
boolean isCRLF = false;
boolean recordStart = false;
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
boolean done = false;
int read = 0;
for (int c = -1, previousCharacter; !done;) {
if (read++ >= MAXIMUM_SIZE) {
throw new IOException("Read " + MAXIMUM_SIZE +
" bytes without finding \\r\\n\\r\\n " +
"End-Of-ANVLRecord");
}
previousCharacter = c;
c = is.read();
if (c == -1) {
throw new IOException("End-Of-Stream before \\r\\n\\r\\n " +
"End-Of-ANVLRecord:\n" +
new String(baos.toByteArray(), UTF8));
}
if (isLF((char)c) && isCR((char)previousCharacter)) {
if (isCRLF) {
// If we just had a CRLF, then its two CRLFs and its end of
// record. We're done.
done = true; // depends on control dependency: [if], data = [none]
} else {
isCRLF = true; // depends on control dependency: [if], data = [none]
}
} else if (!recordStart && Character.isWhitespace(c)) {
// Skip any whitespace at start of ANVLRecord.
continue;
} else {
// Clear isCRLF flag if this character is NOT a '\r'.
if (isCRLF && !isCR((char)c)) {
isCRLF = false; // depends on control dependency: [if], data = [none]
}
// Not whitespace so start record if we haven't already.
if (!recordStart) {
recordStart = true; // depends on control dependency: [if], data = [none]
}
}
baos.write(c);
}
return load(new String(baos.toByteArray(), UTF8));
} }
|
public class class_name {
private void initAnchorsMap(final Workbook wb,
final ChartsData chartsData) {
try {
if (wb instanceof XSSFWorkbook) {
ChartUtility.initXSSFAnchorsMap((XSSFWorkbook) wb,
chartsData);
}
} catch (Exception e) {
LOG.log(Level.SEVERE,
"Web Form getAnchorsMap Error Exception = "
+ e.getLocalizedMessage(),
e);
}
} }
|
public class class_name {
private void initAnchorsMap(final Workbook wb,
final ChartsData chartsData) {
try {
if (wb instanceof XSSFWorkbook) {
ChartUtility.initXSSFAnchorsMap((XSSFWorkbook) wb,
chartsData);
// depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
LOG.log(Level.SEVERE,
"Web Form getAnchorsMap Error Exception = "
+ e.getLocalizedMessage(),
e);
}
// depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
@Override
public String filter(URL sourceUrl, Metadata sourceMetadata,
String urlString) {
Iterator<Rule> i = rules.iterator();
while (i.hasNext()) {
Rule r = i.next();
Matcher matcher = r.pattern.matcher(urlString);
urlString = matcher.replaceAll(r.substitution);
}
if (urlString.equals("")) {
urlString = null;
}
return urlString;
} }
|
public class class_name {
@Override
public String filter(URL sourceUrl, Metadata sourceMetadata,
String urlString) {
Iterator<Rule> i = rules.iterator();
while (i.hasNext()) {
Rule r = i.next();
Matcher matcher = r.pattern.matcher(urlString);
urlString = matcher.replaceAll(r.substitution); // depends on control dependency: [while], data = [none]
}
if (urlString.equals("")) {
urlString = null; // depends on control dependency: [if], data = [none]
}
return urlString;
} }
|
public class class_name {
public List<Converter<OrmDescriptor>> getAllConverter()
{
List<Converter<OrmDescriptor>> list = new ArrayList<Converter<OrmDescriptor>>();
List<Node> nodeList = model.get("converter");
for(Node node: nodeList)
{
Converter<OrmDescriptor> type = new ConverterImpl<OrmDescriptor>(this, "converter", model, node);
list.add(type);
}
return list;
} }
|
public class class_name {
public List<Converter<OrmDescriptor>> getAllConverter()
{
List<Converter<OrmDescriptor>> list = new ArrayList<Converter<OrmDescriptor>>();
List<Node> nodeList = model.get("converter");
for(Node node: nodeList)
{
Converter<OrmDescriptor> type = new ConverterImpl<OrmDescriptor>(this, "converter", model, node);
list.add(type); // depends on control dependency: [for], data = [none]
}
return list;
} }
|
public class class_name {
public static org.osmdroid.views.overlay.Polygon addPolygonToMap(
MapView map,
List<GeoPoint> pts,
List<List<GeoPoint>> holes, PolygonOptions options) {
org.osmdroid.views.overlay.Polygon polygon1 = new org.osmdroid.views.overlay.Polygon(map);
polygon1.setPoints(pts);
polygon1.getHoles().addAll(holes);
if (options!=null) {
polygon1.setFillColor(options.getFillColor());
polygon1.setTitle(options.getTitle());
polygon1.setStrokeColor(options.getStrokeColor());
polygon1.setStrokeWidth(options.getStrokeWidth());
polygon1.setSubDescription(options.getSubtitle());
polygon1.setInfoWindow(new BasicInfoWindow(R.layout.bonuspack_bubble, map));
}
map.getOverlayManager().add(polygon1);
return polygon1;
} }
|
public class class_name {
public static org.osmdroid.views.overlay.Polygon addPolygonToMap(
MapView map,
List<GeoPoint> pts,
List<List<GeoPoint>> holes, PolygonOptions options) {
org.osmdroid.views.overlay.Polygon polygon1 = new org.osmdroid.views.overlay.Polygon(map);
polygon1.setPoints(pts);
polygon1.getHoles().addAll(holes);
if (options!=null) {
polygon1.setFillColor(options.getFillColor()); // depends on control dependency: [if], data = [(options]
polygon1.setTitle(options.getTitle()); // depends on control dependency: [if], data = [(options]
polygon1.setStrokeColor(options.getStrokeColor()); // depends on control dependency: [if], data = [(options]
polygon1.setStrokeWidth(options.getStrokeWidth()); // depends on control dependency: [if], data = [(options]
polygon1.setSubDescription(options.getSubtitle()); // depends on control dependency: [if], data = [(options]
polygon1.setInfoWindow(new BasicInfoWindow(R.layout.bonuspack_bubble, map)); // depends on control dependency: [if], data = [none]
}
map.getOverlayManager().add(polygon1);
return polygon1;
} }
|
public class class_name {
public JvmAnnotationReference getJvmAnnotationReference(/* @Nullable */ XAnnotation anno) {
if(anno == null)
return null;
JvmAnnotationReference reference = typesFactory.createJvmAnnotationReference();
final JvmType annotation = (JvmType) anno.eGet(
XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE, false);
if (annotation.eIsProxy()) {
JvmAnnotationType copiedProxy = TypesFactory.eINSTANCE.createJvmAnnotationType();
((InternalEObject)copiedProxy).eSetProxyURI(EcoreUtil.getURI(annotation));
reference.setAnnotation(copiedProxy);
} else if (annotation instanceof JvmAnnotationType){
reference.setAnnotation((JvmAnnotationType) annotation);
}
for (XAnnotationElementValuePair val : anno.getElementValuePairs()) {
XExpression valueExpression = val.getValue();
JvmAnnotationValue annotationValue = toJvmAnnotationValue(valueExpression);
if (annotationValue != null) {
JvmOperation op = (JvmOperation) val.eGet(
XAnnotationsPackage.Literals.XANNOTATION_ELEMENT_VALUE_PAIR__ELEMENT, false);
annotationValue.setOperation(op);
reference.getExplicitValues().add(annotationValue);
}
}
if (anno.getValue() != null) {
JvmAnnotationValue value = toJvmAnnotationValue(anno.getValue());
if (value != null) {
reference.getExplicitValues().add(value);
}
}
associate(anno, reference);
return reference;
} }
|
public class class_name {
public JvmAnnotationReference getJvmAnnotationReference(/* @Nullable */ XAnnotation anno) {
if(anno == null)
return null;
JvmAnnotationReference reference = typesFactory.createJvmAnnotationReference();
final JvmType annotation = (JvmType) anno.eGet(
XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE, false);
if (annotation.eIsProxy()) {
JvmAnnotationType copiedProxy = TypesFactory.eINSTANCE.createJvmAnnotationType();
((InternalEObject)copiedProxy).eSetProxyURI(EcoreUtil.getURI(annotation)); // depends on control dependency: [if], data = [none]
reference.setAnnotation(copiedProxy); // depends on control dependency: [if], data = [none]
} else if (annotation instanceof JvmAnnotationType){
reference.setAnnotation((JvmAnnotationType) annotation); // depends on control dependency: [if], data = [none]
}
for (XAnnotationElementValuePair val : anno.getElementValuePairs()) {
XExpression valueExpression = val.getValue();
JvmAnnotationValue annotationValue = toJvmAnnotationValue(valueExpression);
if (annotationValue != null) {
JvmOperation op = (JvmOperation) val.eGet(
XAnnotationsPackage.Literals.XANNOTATION_ELEMENT_VALUE_PAIR__ELEMENT, false);
annotationValue.setOperation(op); // depends on control dependency: [if], data = [none]
reference.getExplicitValues().add(annotationValue); // depends on control dependency: [if], data = [(annotationValue]
}
}
if (anno.getValue() != null) {
JvmAnnotationValue value = toJvmAnnotationValue(anno.getValue());
if (value != null) {
reference.getExplicitValues().add(value); // depends on control dependency: [if], data = [(value]
}
}
associate(anno, reference);
return reference;
} }
|
public class class_name {
public void setLinkSubstitutionHandler(String handlerClassName) {
try {
m_linkSubstitutionHandler = (I_CmsLinkSubstitutionHandler)Class.forName(handlerClassName).newInstance();
} catch (Exception e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
}
} }
|
public class class_name {
public void setLinkSubstitutionHandler(String handlerClassName) {
try {
m_linkSubstitutionHandler = (I_CmsLinkSubstitutionHandler)Class.forName(handlerClassName).newInstance(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private void performNextWrite() {
Append append = getNextAppend();
if (append == null) {
return;
}
long traceId = LoggerHelpers.traceEnter(log, "storeAppend", append);
Timer timer = new Timer();
storeAppend(append)
.whenComplete((v, e) -> {
handleAppendResult(append, e, timer);
LoggerHelpers.traceLeave(log, "storeAppend", traceId, v, e);
})
.whenComplete((v, e) -> append.getData().release());
} }
|
public class class_name {
private void performNextWrite() {
Append append = getNextAppend();
if (append == null) {
return; // depends on control dependency: [if], data = [none]
}
long traceId = LoggerHelpers.traceEnter(log, "storeAppend", append);
Timer timer = new Timer();
storeAppend(append)
.whenComplete((v, e) -> {
handleAppendResult(append, e, timer);
LoggerHelpers.traceLeave(log, "storeAppend", traceId, v, e);
})
.whenComplete((v, e) -> append.getData().release());
} }
|
public class class_name {
public static @Nullable String get(@NotNull Map<String, String[]> requestMap, @NotNull String param) {
String value = null;
String[] valueArray = requestMap.get(param);
if (valueArray != null && valueArray.length > 0) {
value = valueArray[0];
}
// convert encoding to UTF-8 if not form encoding parameter is set
if (value != null && !hasFormEncodingParam(requestMap)) {
value = convertISO88591toUTF8(value);
}
return value;
} }
|
public class class_name {
public static @Nullable String get(@NotNull Map<String, String[]> requestMap, @NotNull String param) {
String value = null;
String[] valueArray = requestMap.get(param);
if (valueArray != null && valueArray.length > 0) {
value = valueArray[0]; // depends on control dependency: [if], data = [none]
}
// convert encoding to UTF-8 if not form encoding parameter is set
if (value != null && !hasFormEncodingParam(requestMap)) {
value = convertISO88591toUTF8(value); // depends on control dependency: [if], data = [(value]
}
return value;
} }
|
public class class_name {
public static ConditionTerm create(StreamTokenizer tokenizer) throws WebDAVException {
ConditionTerm term = new ConditionTerm();
try {
int token = tokenizer.ttype;
if (token == '(')
token = tokenizer.nextToken();
else
throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissing", String.valueOf(token), "(")); //$NON-NLS-1$ //$NON-NLS-2$
while (token == StreamTokenizer.TT_WORD || token == '<' || token == '[') {
term.addConditionFactor(ConditionFactor.create(tokenizer));
token = tokenizer.ttype;
}
if (token == ')')
token = tokenizer.nextToken();
else
throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissing", String.valueOf(token), ")")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (IOException exc) {
// ignore or log?
}
if (!term.getConditionFactors().hasMoreElements())
throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissingStateOrEntity")); //$NON-NLS-1$
return term;
} }
|
public class class_name {
public static ConditionTerm create(StreamTokenizer tokenizer) throws WebDAVException {
ConditionTerm term = new ConditionTerm();
try {
int token = tokenizer.ttype;
if (token == '(')
token = tokenizer.nextToken();
else
throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissing", String.valueOf(token), "(")); //$NON-NLS-1$ //$NON-NLS-2$
while (token == StreamTokenizer.TT_WORD || token == '<' || token == '[') {
term.addConditionFactor(ConditionFactor.create(tokenizer)); // depends on control dependency: [while], data = [(token]
token = tokenizer.ttype; // depends on control dependency: [while], data = [none]
}
if (token == ')')
token = tokenizer.nextToken();
else
throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissing", String.valueOf(token), ")")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (IOException exc) {
// ignore or log?
}
if (!term.getConditionFactors().hasMoreElements())
throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissingStateOrEntity")); //$NON-NLS-1$
return term;
} }
|
public class class_name {
private static String getCanonicalHeaders(HashMap<String, String> headers) {
if (headers.isEmpty()) {
return "";
}
TreeSet<String> headerSet = new TreeSet<String>();
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey().trim().toLowerCase();
if (key.startsWith(AipClientConst.BCE_PREFIX)
|| AipClientConst.BCE_HEADER_TO_SIGN.contains(key)) {
headerSet.add(String.format("%s:%s", Util.uriEncode(key, true),
Util.uriEncode(entry.getValue().trim(), true)));
}
}
return Util.mkString(headerSet.iterator(), '\n');
} }
|
public class class_name {
private static String getCanonicalHeaders(HashMap<String, String> headers) {
if (headers.isEmpty()) {
return ""; // depends on control dependency: [if], data = [none]
}
TreeSet<String> headerSet = new TreeSet<String>();
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey().trim().toLowerCase();
if (key.startsWith(AipClientConst.BCE_PREFIX)
|| AipClientConst.BCE_HEADER_TO_SIGN.contains(key)) {
headerSet.add(String.format("%s:%s", Util.uriEncode(key, true),
Util.uriEncode(entry.getValue().trim(), true))); // depends on control dependency: [if], data = [none]
}
}
return Util.mkString(headerSet.iterator(), '\n');
} }
|
public class class_name {
public Optional<T> ifPresent(final Consumer<? super T> consumer) {
if (isPresent()) {
consumer.accept(get());
}
return this;
} }
|
public class class_name {
public Optional<T> ifPresent(final Consumer<? super T> consumer) {
if (isPresent()) {
consumer.accept(get()); // depends on control dependency: [if], data = [none]
}
return this;
} }
|
public class class_name {
public MarshallerRegistry merge(MarshallerRegistry.Builder marshallerRegistryOverrides) {
if(marshallerRegistryOverrides == null) {
return this;
}
Builder merged = MarshallerRegistry.builder();
merged.copyMarshallersFromRegistry(this.marshallers);
merged.copyMarshallersFromRegistry(marshallerRegistryOverrides.marshallers);
return merged.build();
} }
|
public class class_name {
public MarshallerRegistry merge(MarshallerRegistry.Builder marshallerRegistryOverrides) {
if(marshallerRegistryOverrides == null) {
return this; // depends on control dependency: [if], data = [none]
}
Builder merged = MarshallerRegistry.builder();
merged.copyMarshallersFromRegistry(this.marshallers);
merged.copyMarshallersFromRegistry(marshallerRegistryOverrides.marshallers);
return merged.build();
} }
|
public class class_name {
public EClass getIfcIrregularTimeSeriesValue() {
if (ifcIrregularTimeSeriesValueEClass == null) {
ifcIrregularTimeSeriesValueEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(283);
}
return ifcIrregularTimeSeriesValueEClass;
} }
|
public class class_name {
public EClass getIfcIrregularTimeSeriesValue() {
if (ifcIrregularTimeSeriesValueEClass == null) {
ifcIrregularTimeSeriesValueEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(283);
// depends on control dependency: [if], data = [none]
}
return ifcIrregularTimeSeriesValueEClass;
} }
|
public class class_name {
private void setOption(String opt, List<String> arguments) {
String[] args = new String[arguments.length() + 1];
int k = 0;
args[k++] = opt;
for (List<String> i = arguments; i.nonEmpty(); i=i.tail) {
args[k++] = i.head;
}
options.append(args);
} }
|
public class class_name {
private void setOption(String opt, List<String> arguments) {
String[] args = new String[arguments.length() + 1];
int k = 0;
args[k++] = opt;
for (List<String> i = arguments; i.nonEmpty(); i=i.tail) {
args[k++] = i.head; // depends on control dependency: [for], data = [i]
}
options.append(args);
} }
|
public class class_name {
public String selectOption(final String optionName, final String defaultValue) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Timer.Context ctx = metrics.optionSelectTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(selectOptionSQL);
stmt.setString(1, optionName);
rs = stmt.executeQuery();
if(rs.next()) {
String val = rs.getString(1);
return val != null ? val.trim() : defaultValue;
} else {
return defaultValue;
}
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt, rs);
}
} }
|
public class class_name {
public String selectOption(final String optionName, final String defaultValue) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
Timer.Context ctx = metrics.optionSelectTimer.time();
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(selectOptionSQL);
stmt.setString(1, optionName);
rs = stmt.executeQuery();
if(rs.next()) {
String val = rs.getString(1);
return val != null ? val.trim() : defaultValue; // depends on control dependency: [if], data = [none]
} else {
return defaultValue; // depends on control dependency: [if], data = [none]
}
} finally {
ctx.stop();
SQLUtil.closeQuietly(conn, stmt, rs);
}
} }
|
public class class_name {
public DirWatcher useWatchFile(final String name) {
watchFile = new File(dir, name);
if (!watchFile.isFile() || !watchFile.exists()) {
try {
FileUtil.touch(watchFile);
} catch (IOException ioex) {
throw new DirWatcherException("Invalid watch file: " + name, ioex);
}
}
watchFileLastAccessTime = watchFile.lastModified();
return this;
} }
|
public class class_name {
public DirWatcher useWatchFile(final String name) {
watchFile = new File(dir, name);
if (!watchFile.isFile() || !watchFile.exists()) {
try {
FileUtil.touch(watchFile); // depends on control dependency: [try], data = [none]
} catch (IOException ioex) {
throw new DirWatcherException("Invalid watch file: " + name, ioex);
} // depends on control dependency: [catch], data = [none]
}
watchFileLastAccessTime = watchFile.lastModified();
return this;
} }
|
public class class_name {
public <T> List<T> findList(Class<T> clazz) {
List<T> list = new ArrayList<T>();
for (Entry<String, Object> entry : contextMap.entrySet()) {
if (clazz.isInstance(entry.getValue())) {
list.add(clazz.cast(entry.getValue()));
}
}
return list;
} }
|
public class class_name {
public <T> List<T> findList(Class<T> clazz) {
List<T> list = new ArrayList<T>();
for (Entry<String, Object> entry : contextMap.entrySet()) {
if (clazz.isInstance(entry.getValue())) {
list.add(clazz.cast(entry.getValue())); // depends on control dependency: [if], data = [none]
}
}
return list;
} }
|
public class class_name {
public void marshall(GetRunRequest getRunRequest, ProtocolMarshaller protocolMarshaller) {
if (getRunRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getRunRequest.getArn(), ARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(GetRunRequest getRunRequest, ProtocolMarshaller protocolMarshaller) {
if (getRunRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getRunRequest.getArn(), ARN_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 {
@SuppressWarnings("unused")
final void handleHeaderValue(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) {
StringBuilder stringBuilder = state.stringBuilder;
if (stringBuilder == null) {
stringBuilder = new StringBuilder();
state.parseState = 0;
}
int parseState = state.parseState;
while (buffer.hasRemaining()) {
final byte next = buffer.get();
switch (parseState) {
case NORMAL: {
if (next == '\r') {
parseState = BEGIN_LINE_END;
} else if (next == '\n') {
parseState = LINE_END;
} else if (next == ' ' || next == '\t') {
parseState = WHITESPACE;
} else {
stringBuilder.append((char) next);
}
break;
}
case WHITESPACE: {
if (next == '\r') {
parseState = BEGIN_LINE_END;
} else if (next == '\n') {
parseState = LINE_END;
} else if (next == ' ' || next == '\t') {
} else {
if (stringBuilder.length() > 0) {
stringBuilder.append(' ');
}
stringBuilder.append((char) next);
parseState = NORMAL;
}
break;
}
case LINE_END:
case BEGIN_LINE_END: {
if (next == '\n' && parseState == BEGIN_LINE_END) {
parseState = LINE_END;
} else if (next == '\t' ||
next == ' ') {
//this is a continuation
parseState = WHITESPACE;
} else {
//we have a header
HttpString nextStandardHeader = state.nextHeader;
String headerValue = stringBuilder.toString();
//TODO: we need to decode this according to RFC-2047 if we have seen a =? symbol
builder.getResponseHeaders().add(nextStandardHeader, headerValue);
state.nextHeader = null;
state.leftOver = next;
state.stringBuilder.setLength(0);
if (next == '\r') {
parseState = AWAIT_DATA_END;
} else {
state.state = ResponseParseState.HEADER;
state.parseState = 0;
return;
}
}
break;
}
case AWAIT_DATA_END: {
state.state = ResponseParseState.PARSE_COMPLETE;
return;
}
}
}
//we only write to the state if we did not finish parsing
state.parseState = parseState;
} }
|
public class class_name {
@SuppressWarnings("unused")
final void handleHeaderValue(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) {
StringBuilder stringBuilder = state.stringBuilder;
if (stringBuilder == null) {
stringBuilder = new StringBuilder(); // depends on control dependency: [if], data = [none]
state.parseState = 0; // depends on control dependency: [if], data = [none]
}
int parseState = state.parseState;
while (buffer.hasRemaining()) {
final byte next = buffer.get();
switch (parseState) {
case NORMAL: {
if (next == '\r') {
parseState = BEGIN_LINE_END; // depends on control dependency: [if], data = [none]
} else if (next == '\n') {
parseState = LINE_END; // depends on control dependency: [if], data = [none]
} else if (next == ' ' || next == '\t') {
parseState = WHITESPACE; // depends on control dependency: [if], data = [none]
} else {
stringBuilder.append((char) next); // depends on control dependency: [if], data = [none]
}
break;
}
case WHITESPACE: {
if (next == '\r') {
parseState = BEGIN_LINE_END; // depends on control dependency: [if], data = [none]
} else if (next == '\n') {
parseState = LINE_END; // depends on control dependency: [if], data = [none]
} else if (next == ' ' || next == '\t') {
} else {
if (stringBuilder.length() > 0) {
stringBuilder.append(' '); // depends on control dependency: [if], data = [none]
}
stringBuilder.append((char) next); // depends on control dependency: [if], data = [none]
parseState = NORMAL; // depends on control dependency: [if], data = [none]
}
break;
}
case LINE_END:
case BEGIN_LINE_END: {
if (next == '\n' && parseState == BEGIN_LINE_END) {
parseState = LINE_END; // depends on control dependency: [if], data = [none]
} else if (next == '\t' ||
next == ' ') {
//this is a continuation
parseState = WHITESPACE; // depends on control dependency: [if], data = [none]
} else {
//we have a header
HttpString nextStandardHeader = state.nextHeader;
String headerValue = stringBuilder.toString();
//TODO: we need to decode this according to RFC-2047 if we have seen a =? symbol
builder.getResponseHeaders().add(nextStandardHeader, headerValue); // depends on control dependency: [if], data = [(next]
state.nextHeader = null; // depends on control dependency: [if], data = [none]
state.leftOver = next; // depends on control dependency: [if], data = [none]
state.stringBuilder.setLength(0); // depends on control dependency: [if], data = [none]
if (next == '\r') {
parseState = AWAIT_DATA_END; // depends on control dependency: [if], data = [none]
} else {
state.state = ResponseParseState.HEADER; // depends on control dependency: [if], data = [none]
state.parseState = 0; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
break;
}
case AWAIT_DATA_END: {
state.state = ResponseParseState.PARSE_COMPLETE;
return;
}
}
}
//we only write to the state if we did not finish parsing
state.parseState = parseState;
} }
|
public class class_name {
protected String lookupAlias(final String alias) {
String value = actionsManager.lookupPathAlias(alias);
if (value == null) {
ActionRuntime cfg = actionsManager.lookup(alias);
if (cfg != null) {
value = cfg.getActionPath();
}
}
return value;
} }
|
public class class_name {
protected String lookupAlias(final String alias) {
String value = actionsManager.lookupPathAlias(alias);
if (value == null) {
ActionRuntime cfg = actionsManager.lookup(alias);
if (cfg != null) {
value = cfg.getActionPath(); // depends on control dependency: [if], data = [none]
}
}
return value;
} }
|
public class class_name {
public static DMatrixRMaj copyTriangle(DMatrixRMaj src , DMatrixRMaj dst , boolean upper ) {
if( dst == null ) {
dst = new DMatrixRMaj(src.numRows,src.numCols);
} else if( src.numRows != dst.numRows || src.numCols != dst.numCols ) {
throw new IllegalArgumentException("src and dst must have the same dimensions.");
}
if( upper ) {
int N = Math.min(src.numRows,src.numCols);
for( int i = 0; i < N; i++ ) {
int index = i*src.numCols+i;
System.arraycopy(src.data,index,dst.data,index,src.numCols-i);
}
} else {
for( int i = 0; i < src.numRows; i++ ) {
int length = Math.min(i+1,src.numCols);
int index = i*src.numCols;
System.arraycopy(src.data,index,dst.data,index,length);
}
}
return dst;
} }
|
public class class_name {
public static DMatrixRMaj copyTriangle(DMatrixRMaj src , DMatrixRMaj dst , boolean upper ) {
if( dst == null ) {
dst = new DMatrixRMaj(src.numRows,src.numCols); // depends on control dependency: [if], data = [none]
} else if( src.numRows != dst.numRows || src.numCols != dst.numCols ) {
throw new IllegalArgumentException("src and dst must have the same dimensions.");
}
if( upper ) {
int N = Math.min(src.numRows,src.numCols);
for( int i = 0; i < N; i++ ) {
int index = i*src.numCols+i;
System.arraycopy(src.data,index,dst.data,index,src.numCols-i); // depends on control dependency: [for], data = [i]
}
} else {
for( int i = 0; i < src.numRows; i++ ) {
int length = Math.min(i+1,src.numCols);
int index = i*src.numCols;
System.arraycopy(src.data,index,dst.data,index,length); // depends on control dependency: [for], data = [none]
}
}
return dst;
} }
|
public class class_name {
static public void update(Configuration configs)
{
scoringPolicy = configs.get(MalmoMod.SCORING_CONFIGS, "policy", DEFAULT_NO_SCORING).getInt();
if (scoringPolicy > 0) {
String customLogHandler = configs.get(MalmoMod.SCORING_CONFIGS, "handler", "").getString();
setLogging(Level.INFO, customLogHandler);
}
if (logging)
log("<ScoreInit><Policy>" + scoringPolicy + "</Policy></ScoreInit>");
} }
|
public class class_name {
static public void update(Configuration configs)
{
scoringPolicy = configs.get(MalmoMod.SCORING_CONFIGS, "policy", DEFAULT_NO_SCORING).getInt();
if (scoringPolicy > 0) {
String customLogHandler = configs.get(MalmoMod.SCORING_CONFIGS, "handler", "").getString();
setLogging(Level.INFO, customLogHandler); // depends on control dependency: [if], data = [none]
}
if (logging)
log("<ScoreInit><Policy>" + scoringPolicy + "</Policy></ScoreInit>");
} }
|
public class class_name {
private Map<String, Object> collectClaims(String subject, String[] claimNames, String[] claimLocales)
{
// If no claim is required.
if (claimNames == null || claimNames.length == 0)
{
return null;
}
// Drop empty and duplicate entries from claimLocales.
claimLocales = normalizeClaimLocales(claimLocales);
// Claim values.
Map<String, Object> claims = new HashMap<String, Object>();
// For each requested claim.
for (String claimName : claimNames)
{
// If the claim name is empty.
if (claimName == null || claimName.length() == 0)
{
continue;
}
// Split the claim name into the name part and the tag part.
String[] elements = claimName.split("#", 2);
String name = elements[0];
String tag = (elements.length == 2) ? elements[1] : null;
// If the name part is empty.
if (name == null || name.length() == 0)
{
continue;
}
// Get the claim value of the claim.
Object value = getClaim(name, tag, claimLocales);
// If the claim value was not obtained.
if (value == null)
{
continue;
}
if (tag == null)
{
// Just for an edge case where claimName ends with "#".
claimName = name;
}
// Add the pair of the claim name and the claim value.
claims.put(claimName, value);
}
// If no claim value has been obtained.
if (claims.size() == 0)
{
return null;
}
// Obtained claim values.
return claims;
} }
|
public class class_name {
private Map<String, Object> collectClaims(String subject, String[] claimNames, String[] claimLocales)
{
// If no claim is required.
if (claimNames == null || claimNames.length == 0)
{
return null; // depends on control dependency: [if], data = [none]
}
// Drop empty and duplicate entries from claimLocales.
claimLocales = normalizeClaimLocales(claimLocales);
// Claim values.
Map<String, Object> claims = new HashMap<String, Object>();
// For each requested claim.
for (String claimName : claimNames)
{
// If the claim name is empty.
if (claimName == null || claimName.length() == 0)
{
continue;
}
// Split the claim name into the name part and the tag part.
String[] elements = claimName.split("#", 2);
String name = elements[0];
String tag = (elements.length == 2) ? elements[1] : null;
// If the name part is empty.
if (name == null || name.length() == 0)
{
continue;
}
// Get the claim value of the claim.
Object value = getClaim(name, tag, claimLocales);
// If the claim value was not obtained.
if (value == null)
{
continue;
}
if (tag == null)
{
// Just for an edge case where claimName ends with "#".
claimName = name; // depends on control dependency: [if], data = [none]
}
// Add the pair of the claim name and the claim value.
claims.put(claimName, value); // depends on control dependency: [for], data = [claimName]
}
// If no claim value has been obtained.
if (claims.size() == 0)
{
return null; // depends on control dependency: [if], data = [none]
}
// Obtained claim values.
return claims;
} }
|
public class class_name {
@Deprecated
public static final Timecode getInstance(SampleCount samples, boolean dropFrame, boolean supportDays)
{
final Timecode timecode = getInstance(samples, dropFrame);
if (!supportDays && timecode.getDaysPart() != 0)
{
throw new IllegalArgumentException("supportDays disabled but resulting timecode had a days component: " +
timecode.toEncodedString());
}
else
{
return timecode;
}
} }
|
public class class_name {
@Deprecated
public static final Timecode getInstance(SampleCount samples, boolean dropFrame, boolean supportDays)
{
final Timecode timecode = getInstance(samples, dropFrame);
if (!supportDays && timecode.getDaysPart() != 0)
{
throw new IllegalArgumentException("supportDays disabled but resulting timecode had a days component: " +
timecode.toEncodedString());
}
else
{
return timecode; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
@SuppressWarnings("unchecked")
private E[] leafNodeArrayFor(int i) {
// i is the index into this vector. Each 5 bits represent an index into an array. The
// highest 5 bits (that are less than the shift value) are the index into the top-level
// array. The lowest 5 bits index the the leaf. The guts of this method indexes into the
// array at each level, finally indexing into the leaf node.
if (i >= 0 && i < size) {
if (i >= tailoff()) {
return tail;
}
Node node = root;
for (int level = shift; level > 0; level -= NODE_LENGTH_POW_2) {
node = (Node) node.array[(i >>> level) & LOW_BITS];
}
return (E[]) node.array;
}
throw new IndexOutOfBoundsException();
} }
|
public class class_name {
@SuppressWarnings("unchecked")
private E[] leafNodeArrayFor(int i) {
// i is the index into this vector. Each 5 bits represent an index into an array. The
// highest 5 bits (that are less than the shift value) are the index into the top-level
// array. The lowest 5 bits index the the leaf. The guts of this method indexes into the
// array at each level, finally indexing into the leaf node.
if (i >= 0 && i < size) {
if (i >= tailoff()) {
return tail; // depends on control dependency: [if], data = [none]
}
Node node = root;
for (int level = shift; level > 0; level -= NODE_LENGTH_POW_2) {
node = (Node) node.array[(i >>> level) & LOW_BITS]; // depends on control dependency: [for], data = [level]
}
return (E[]) node.array; // depends on control dependency: [if], data = [none]
}
throw new IndexOutOfBoundsException();
} }
|
public class class_name {
private static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ignored) {
logger.error("Failed to close output stream: "
+ ignored.getMessage());
}
}
} }
|
public class class_name {
private static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ignored) {
logger.error("Failed to close output stream: "
+ ignored.getMessage());
} // depends on control dependency: [catch], data = [none]
}
} }
|
public class class_name {
public int getFixedHeaderSize() {
int msgsize = super.getSerializedSize();
// Fixed header
msgsize += 2 + 2 + 1 + 1 + 1 + 1 + 1 + 2 + 1 + 8 + 8;
// procname to load str if any
if (m_procNameToLoad != null) {
msgsize += m_procNameToLoad.length;
}
// perFragmentStatsRecording and coordinatorTask.
// TODO: We could use only one byte and bitmasks to represent all the
// boolean values used in this class, it can save a little bit space.
msgsize += 2;
// Fragment ID block (20 bytes per sha1-hash)
msgsize += 20 * m_items.size();
// short + str for proc name
msgsize += 2;
if (m_procedureName != null) {
msgsize += m_procedureName.length;
}
// int for which batch (4)
msgsize += 4;
// 1 byte for the timeout flag
msgsize += 1;
msgsize += 1; //m_handleByOriginalLeader
msgsize += m_batchTimeout == BatchTimeoutOverrideType.NO_TIMEOUT ? 0 : 4;
// Involved partitions
msgsize += 2 + m_involvedPartitions.size() * 4;
//nested initiate task message length prefix
msgsize += 4;
return msgsize;
} }
|
public class class_name {
public int getFixedHeaderSize() {
int msgsize = super.getSerializedSize();
// Fixed header
msgsize += 2 + 2 + 1 + 1 + 1 + 1 + 1 + 2 + 1 + 8 + 8;
// procname to load str if any
if (m_procNameToLoad != null) {
msgsize += m_procNameToLoad.length; // depends on control dependency: [if], data = [none]
}
// perFragmentStatsRecording and coordinatorTask.
// TODO: We could use only one byte and bitmasks to represent all the
// boolean values used in this class, it can save a little bit space.
msgsize += 2;
// Fragment ID block (20 bytes per sha1-hash)
msgsize += 20 * m_items.size();
// short + str for proc name
msgsize += 2;
if (m_procedureName != null) {
msgsize += m_procedureName.length; // depends on control dependency: [if], data = [none]
}
// int for which batch (4)
msgsize += 4;
// 1 byte for the timeout flag
msgsize += 1;
msgsize += 1; //m_handleByOriginalLeader
msgsize += m_batchTimeout == BatchTimeoutOverrideType.NO_TIMEOUT ? 0 : 4;
// Involved partitions
msgsize += 2 + m_involvedPartitions.size() * 4;
//nested initiate task message length prefix
msgsize += 4;
return msgsize;
} }
|
public class class_name {
protected Map<String, Object> convertProfileAndPasswordToAttributes(final U profile, final String password) {
final Map<String, Object> storageAttributes = new HashMap<>();
storageAttributes.put(getIdAttribute(), profile.getId());
storageAttributes.put(LINKEDID, profile.getLinkedId());
storageAttributes.put(getUsernameAttribute(), profile.getUsername());
// if a password has been provided, encode it
if (isNotBlank(password)) {
final String encodedPassword;
// encode password if we have a passwordEncoder (MongoDB, SQL but not for LDAP)
if (passwordEncoder != null) {
encodedPassword = passwordEncoder.encode(password);
} else {
encodedPassword = password;
}
storageAttributes.put(getPasswordAttribute(), encodedPassword);
}
// legacy mode: save the defined attributes
if (isLegacyMode()) {
for (final String attributeName : attributeNames) {
storageAttributes.put(attributeName, profile.getAttribute(attributeName));
}
} else {
// new behaviour (>= v2.0): save the serialized profile
storageAttributes.put(SERIALIZED_PROFILE, javaSerializationHelper.serializeToBase64(profile));
}
return storageAttributes;
} }
|
public class class_name {
protected Map<String, Object> convertProfileAndPasswordToAttributes(final U profile, final String password) {
final Map<String, Object> storageAttributes = new HashMap<>();
storageAttributes.put(getIdAttribute(), profile.getId());
storageAttributes.put(LINKEDID, profile.getLinkedId());
storageAttributes.put(getUsernameAttribute(), profile.getUsername());
// if a password has been provided, encode it
if (isNotBlank(password)) {
final String encodedPassword;
// encode password if we have a passwordEncoder (MongoDB, SQL but not for LDAP)
if (passwordEncoder != null) {
encodedPassword = passwordEncoder.encode(password); // depends on control dependency: [if], data = [none]
} else {
encodedPassword = password; // depends on control dependency: [if], data = [none]
}
storageAttributes.put(getPasswordAttribute(), encodedPassword); // depends on control dependency: [if], data = [none]
}
// legacy mode: save the defined attributes
if (isLegacyMode()) {
for (final String attributeName : attributeNames) {
storageAttributes.put(attributeName, profile.getAttribute(attributeName)); // depends on control dependency: [for], data = [attributeName]
}
} else {
// new behaviour (>= v2.0): save the serialized profile
storageAttributes.put(SERIALIZED_PROFILE, javaSerializationHelper.serializeToBase64(profile)); // depends on control dependency: [if], data = [none]
}
return storageAttributes;
} }
|
public class class_name {
public static boolean isChildOf(Resource file, Resource dir) {
while (file != null) {
if (file.equals(dir)) return true;
file = file.getParentResource();
}
return false;
} }
|
public class class_name {
public static boolean isChildOf(Resource file, Resource dir) {
while (file != null) {
if (file.equals(dir)) return true;
file = file.getParentResource(); // depends on control dependency: [while], data = [none]
}
return false;
} }
|
public class class_name {
public synchronized Set<String> regexInTopic(final String topic, final String payload) {
final Set<String> res = new HashSet<>();
final Map<String, List<KafkaDependencyInstanceContext>> eventMap = this.topicEventMap.get(topic);
if (eventMap == null) {
return Collections.emptySet();
}
for (final Map.Entry<String, List<KafkaDependencyInstanceContext>> entry : eventMap.entrySet()) {
final RegexKafkaDependencyMatcher matcher = new RegexKafkaDependencyMatcher(Pattern.compile(entry.getKey()));
if (matcher.isMatch(payload)) {
res.add(entry.getKey());
}
}
return res;
} }
|
public class class_name {
public synchronized Set<String> regexInTopic(final String topic, final String payload) {
final Set<String> res = new HashSet<>();
final Map<String, List<KafkaDependencyInstanceContext>> eventMap = this.topicEventMap.get(topic);
if (eventMap == null) {
return Collections.emptySet(); // depends on control dependency: [if], data = [none]
}
for (final Map.Entry<String, List<KafkaDependencyInstanceContext>> entry : eventMap.entrySet()) {
final RegexKafkaDependencyMatcher matcher = new RegexKafkaDependencyMatcher(Pattern.compile(entry.getKey()));
if (matcher.isMatch(payload)) {
res.add(entry.getKey()); // depends on control dependency: [if], data = [none]
}
}
return res;
} }
|
public class class_name {
public static boolean hasModifier(Method method, ModifierType... modifierTypes) {
if (null == method || ArrayUtil.isEmpty(modifierTypes)) {
return false;
}
return 0 != (method.getModifiers() & modifiersToInt(modifierTypes));
} }
|
public class class_name {
public static boolean hasModifier(Method method, ModifierType... modifierTypes) {
if (null == method || ArrayUtil.isEmpty(modifierTypes)) {
return false;
// depends on control dependency: [if], data = [none]
}
return 0 != (method.getModifiers() & modifiersToInt(modifierTypes));
} }
|
public class class_name {
private CmsGalleryDataBean getInitialSettingsInternal(CmsGalleryConfiguration conf) throws CmsRpcException {
CmsGalleryDataBean data = new CmsGalleryDataBean();
data.setMode(conf.getGalleryMode());
data.setResultViewType(readResultViewType());
boolean galleryShowInvalidDefault = Boolean.parseBoolean(
getWorkplaceSettings().getUserSettings().getAdditionalPreference(PREF_GALLERY_SHOW_INVALID_DEFAULT, true));
data.setIncludeExpiredDefault(galleryShowInvalidDefault);
data.setGalleryStoragePrefix(conf.getGalleryStoragePrefix());
data.setLocales(buildLocalesMap());
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(conf.getLocale())) {
data.setLocale(conf.getLocale());
} else {
data.setLocale(getCmsObject().getRequestContext().getLocale().toString());
}
data.setVfsRootFolders(getRootEntries());
data.setScope(getWorkplaceSettings().getLastSearchScope());
data.setSortOrder(getWorkplaceSettings().getLastGalleryResultOrder());
List<CmsResourceTypeBean> types = null;
data.setTabIds(conf.getGalleryMode().getTabs());
switch (conf.getGalleryMode()) {
case editor:
case view:
case adeView:
case widget:
if (conf.getTabIds() != null) {
data.setTabIds(conf.getTabIds());
}
data.setCurrentElement(conf.getCurrentElement());
String referencePath = conf.getReferencePath();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(referencePath)) {
referencePath = conf.getGalleryPath();
}
data.setReferenceSitePath(referencePath);
types = getResourceTypeBeans(
conf.getGalleryMode(),
data.getReferenceSitePath(),
conf.getResourceTypes(),
conf.getSearchTypes());
data.setTypes(types);
Map<String, CmsGalleryTypeInfo> galleryTypeInfos = readGalleryInfosByTypeBeans(types);
// in case the 'gallerytypes' parameter is set, allow only the given galleries
if (conf.getGalleryTypes() != null) {
Map<String, CmsGalleryTypeInfo> infos = new HashMap<String, CmsGalleryTypeInfo>();
for (int i = 0; i < conf.getGalleryTypes().length; i++) {
CmsGalleryTypeInfo typeInfo = galleryTypeInfos.get(conf.getGalleryTypes()[i]);
if (typeInfo != null) {
infos.put(conf.getGalleryTypes()[i], typeInfo);
}
}
galleryTypeInfos = infos;
}
data.setGalleries(buildGalleriesList(galleryTypeInfos));
String startGallery = conf.getGalleryPath();
// check if the configured gallery path really is an existing gallery
boolean galleryAvailable = false;
for (CmsGalleryFolderBean folderBean : data.getGalleries()) {
if (folderBean.getPath().equals(startGallery)) {
galleryAvailable = true;
break;
}
}
data.setStartGallery(galleryAvailable ? startGallery : null);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(conf.getStartFolder())) {
try {
CmsObject cloneCms = OpenCms.initCmsObject(getCmsObject());
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(conf.getStartSite())) {
cloneCms.getRequestContext().setSiteRoot(conf.getStartSite());
}
if (cloneCms.existsResource(conf.getStartFolder(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
data.setStartFolder(cloneCms.getRequestContext().addSiteRoot(conf.getStartFolder()));
}
} catch (CmsException e) {
log(e.getMessage(), e);
}
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(data.getStartGallery()) && !data.getGalleries().isEmpty()) {
String key = "";
if (!types.isEmpty() && !CmsStringUtil.isEmptyOrWhitespaceOnly(conf.getReferencePath())) {
key = types.get(0).getType();
try {
CmsResource refResource = getCmsObject().readResource(conf.getReferencePath());
String referenceType = OpenCms.getResourceManager().getResourceType(
refResource).getTypeName();
key = CmsGallerySearchBean.getGalleryStorageKey(
data.getGalleryStoragePrefix(),
referenceType);
} catch (Exception e) {
LOG.error("Could not read reference resource: " + conf.getReferencePath());
}
}
if (!data.getGalleries().isEmpty()) {
startGallery = getWorkplaceSettings().getLastUsedGallery(key);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(startGallery)) {
// check the user preferences for any configured start gallery
String galleryTypeName = data.getGalleries().get(0).getType();
startGallery = getWorkplaceSettings().getUserSettings().getStartGallery(
galleryTypeName,
getCmsObject());
if (CmsWorkplace.INPUT_DEFAULT.equals(startGallery)) {
startGallery = OpenCms.getWorkplaceManager().getDefaultUserSettings().getStartGallery(
galleryTypeName);
}
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(startGallery)) {
startGallery = getCmsObject().getRequestContext().removeSiteRoot(startGallery);
}
}
}
// check if the gallery is available in this site and still exists
if (!conf.isResultsSelectable()) {
// if selecting results is explicitly disabled, opening the start gallery does not make much sense
data.setStartGallery(null);
} else if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(startGallery)) {
boolean galleryExists = getCmsObject().existsResource(startGallery);
if (galleryExists) {
data.setStartGallery(startGallery);
} else {
LOG.error("Could not read start gallery: " + startGallery);
data.setStartGallery(null);
}
} else {
data.setStartGallery(null);
}
}
GalleryTabId defaultTab = conf.getTabConfiguration().getDefaultTab();
data.setTabConfiguration(conf.getTabConfiguration());
if (CmsStringUtil.isEmptyOrWhitespaceOnly(data.getStartGallery())
&& CmsStringUtil.isEmptyOrWhitespaceOnly(data.getCurrentElement())
&& CmsStringUtil.isEmptyOrWhitespaceOnly(data.getStartFolder())) {
data.setStartTab(defaultTab);
} else {
data.setStartTab(GalleryTabId.cms_tab_results);
}
break;
case ade:
data.setReferenceSitePath(getCmsObject().getRequestContext().getUri());
types = getResourceTypeBeans(
conf.getGalleryMode(),
data.getReferenceSitePath(),
conf.getResourceTypes(),
conf.getSearchTypes());
data.setTypes(types);
Map<String, CmsGalleryTypeInfo> adeGalleryTypeInfos = readGalleryInfosByTypeBeans(types);
data.setGalleries(buildGalleriesList(adeGalleryTypeInfos));
data.setStartTab(GalleryTabId.cms_tab_types);
break;
default:
break;
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(data.getStartGallery())) {
Set<String> folderFilter = readFolderFilters();
data.setStartFolderFilter(folderFilter);
if ((folderFilter != null) && !folderFilter.isEmpty()) {
try {
data.setVfsPreloadData(
generateVfsPreloadData(
getCmsObject(),
CmsGalleryService.getVfsTreeState(getRequest(), conf.getTreeToken()),
folderFilter));
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
CmsSiteSelectorOptionBuilder optionBuilder = new CmsSiteSelectorOptionBuilder(getCmsObject());
optionBuilder.addNormalSites(true, getWorkplaceSettings().getUserSettings().getStartFolder());
optionBuilder.addSharedSite();
data.setVfsSiteSelectorOptions(optionBuilder.getOptions());
CmsSiteSelectorOptionBuilder sitemapOptionBuilder = new CmsSiteSelectorOptionBuilder(getCmsObject());
sitemapOptionBuilder.addNormalSites(false, null);
if (data.getReferenceSitePath() != null) {
sitemapOptionBuilder.addCurrentSubsite(getCmsObject().addSiteRoot(data.getReferenceSitePath()));
}
data.setSitemapSiteSelectorOptions(sitemapOptionBuilder.getOptions());
data.setDefaultScope(OpenCms.getWorkplaceManager().getGalleryDefaultScope());
return data;
} }
|
public class class_name {
private CmsGalleryDataBean getInitialSettingsInternal(CmsGalleryConfiguration conf) throws CmsRpcException {
CmsGalleryDataBean data = new CmsGalleryDataBean();
data.setMode(conf.getGalleryMode());
data.setResultViewType(readResultViewType());
boolean galleryShowInvalidDefault = Boolean.parseBoolean(
getWorkplaceSettings().getUserSettings().getAdditionalPreference(PREF_GALLERY_SHOW_INVALID_DEFAULT, true));
data.setIncludeExpiredDefault(galleryShowInvalidDefault);
data.setGalleryStoragePrefix(conf.getGalleryStoragePrefix());
data.setLocales(buildLocalesMap());
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(conf.getLocale())) {
data.setLocale(conf.getLocale());
} else {
data.setLocale(getCmsObject().getRequestContext().getLocale().toString());
}
data.setVfsRootFolders(getRootEntries());
data.setScope(getWorkplaceSettings().getLastSearchScope());
data.setSortOrder(getWorkplaceSettings().getLastGalleryResultOrder());
List<CmsResourceTypeBean> types = null;
data.setTabIds(conf.getGalleryMode().getTabs());
switch (conf.getGalleryMode()) {
case editor:
case view:
case adeView:
case widget:
if (conf.getTabIds() != null) {
data.setTabIds(conf.getTabIds());
}
data.setCurrentElement(conf.getCurrentElement());
String referencePath = conf.getReferencePath();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(referencePath)) {
referencePath = conf.getGalleryPath();
}
data.setReferenceSitePath(referencePath);
types = getResourceTypeBeans(
conf.getGalleryMode(),
data.getReferenceSitePath(),
conf.getResourceTypes(),
conf.getSearchTypes());
data.setTypes(types);
Map<String, CmsGalleryTypeInfo> galleryTypeInfos = readGalleryInfosByTypeBeans(types);
// in case the 'gallerytypes' parameter is set, allow only the given galleries
if (conf.getGalleryTypes() != null) {
Map<String, CmsGalleryTypeInfo> infos = new HashMap<String, CmsGalleryTypeInfo>();
for (int i = 0; i < conf.getGalleryTypes().length; i++) {
CmsGalleryTypeInfo typeInfo = galleryTypeInfos.get(conf.getGalleryTypes()[i]);
if (typeInfo != null) {
infos.put(conf.getGalleryTypes()[i], typeInfo);
}
}
galleryTypeInfos = infos;
}
data.setGalleries(buildGalleriesList(galleryTypeInfos));
String startGallery = conf.getGalleryPath();
// check if the configured gallery path really is an existing gallery
boolean galleryAvailable = false;
for (CmsGalleryFolderBean folderBean : data.getGalleries()) {
if (folderBean.getPath().equals(startGallery)) {
galleryAvailable = true; // depends on control dependency: [if], data = [none]
break;
}
}
data.setStartGallery(galleryAvailable ? startGallery : null);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(conf.getStartFolder())) {
try {
CmsObject cloneCms = OpenCms.initCmsObject(getCmsObject());
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(conf.getStartSite())) {
cloneCms.getRequestContext().setSiteRoot(conf.getStartSite()); // depends on control dependency: [if], data = [none]
}
if (cloneCms.existsResource(conf.getStartFolder(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
data.setStartFolder(cloneCms.getRequestContext().addSiteRoot(conf.getStartFolder())); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
log(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(data.getStartGallery()) && !data.getGalleries().isEmpty()) {
String key = "";
if (!types.isEmpty() && !CmsStringUtil.isEmptyOrWhitespaceOnly(conf.getReferencePath())) {
key = types.get(0).getType();
try {
CmsResource refResource = getCmsObject().readResource(conf.getReferencePath());
String referenceType = OpenCms.getResourceManager().getResourceType(
refResource).getTypeName();
key = CmsGallerySearchBean.getGalleryStorageKey(
data.getGalleryStoragePrefix(),
referenceType); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
LOG.error("Could not read reference resource: " + conf.getReferencePath());
} // depends on control dependency: [catch], data = [none]
}
if (!data.getGalleries().isEmpty()) {
startGallery = getWorkplaceSettings().getLastUsedGallery(key);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(startGallery)) {
// check the user preferences for any configured start gallery
String galleryTypeName = data.getGalleries().get(0).getType();
startGallery = getWorkplaceSettings().getUserSettings().getStartGallery(
galleryTypeName,
getCmsObject());
if (CmsWorkplace.INPUT_DEFAULT.equals(startGallery)) {
startGallery = OpenCms.getWorkplaceManager().getDefaultUserSettings().getStartGallery(
galleryTypeName); // depends on control dependency: [if], data = [none]
}
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(startGallery)) {
startGallery = getCmsObject().getRequestContext().removeSiteRoot(startGallery); // depends on control dependency: [if], data = [none]
}
}
}
// check if the gallery is available in this site and still exists
if (!conf.isResultsSelectable()) {
// if selecting results is explicitly disabled, opening the start gallery does not make much sense
data.setStartGallery(null);
} else if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(startGallery)) {
boolean galleryExists = getCmsObject().existsResource(startGallery);
if (galleryExists) {
data.setStartGallery(startGallery);
} else {
LOG.error("Could not read start gallery: " + startGallery);
data.setStartGallery(null);
}
} else {
data.setStartGallery(null);
}
}
GalleryTabId defaultTab = conf.getTabConfiguration().getDefaultTab();
data.setTabConfiguration(conf.getTabConfiguration());
if (CmsStringUtil.isEmptyOrWhitespaceOnly(data.getStartGallery())
&& CmsStringUtil.isEmptyOrWhitespaceOnly(data.getCurrentElement())
&& CmsStringUtil.isEmptyOrWhitespaceOnly(data.getStartFolder())) {
data.setStartTab(defaultTab);
} else {
data.setStartTab(GalleryTabId.cms_tab_results);
}
break;
case ade:
data.setReferenceSitePath(getCmsObject().getRequestContext().getUri());
types = getResourceTypeBeans(
conf.getGalleryMode(),
data.getReferenceSitePath(),
conf.getResourceTypes(),
conf.getSearchTypes());
data.setTypes(types);
Map<String, CmsGalleryTypeInfo> adeGalleryTypeInfos = readGalleryInfosByTypeBeans(types);
data.setGalleries(buildGalleriesList(adeGalleryTypeInfos));
data.setStartTab(GalleryTabId.cms_tab_types);
break;
default:
break;
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(data.getStartGallery())) {
Set<String> folderFilter = readFolderFilters();
data.setStartFolderFilter(folderFilter);
if ((folderFilter != null) && !folderFilter.isEmpty()) {
try {
data.setVfsPreloadData(
generateVfsPreloadData(
getCmsObject(),
CmsGalleryService.getVfsTreeState(getRequest(), conf.getTreeToken()),
folderFilter));
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
CmsSiteSelectorOptionBuilder optionBuilder = new CmsSiteSelectorOptionBuilder(getCmsObject());
optionBuilder.addNormalSites(true, getWorkplaceSettings().getUserSettings().getStartFolder());
optionBuilder.addSharedSite();
data.setVfsSiteSelectorOptions(optionBuilder.getOptions());
CmsSiteSelectorOptionBuilder sitemapOptionBuilder = new CmsSiteSelectorOptionBuilder(getCmsObject());
sitemapOptionBuilder.addNormalSites(false, null);
if (data.getReferenceSitePath() != null) {
sitemapOptionBuilder.addCurrentSubsite(getCmsObject().addSiteRoot(data.getReferenceSitePath()));
}
data.setSitemapSiteSelectorOptions(sitemapOptionBuilder.getOptions());
data.setDefaultScope(OpenCms.getWorkplaceManager().getGalleryDefaultScope());
return data;
} }
|
public class class_name {
public DynamicReport build() {
if (built) {
throw new DJBuilderException("DynamicReport already built. Cannot use more than once.");
} else {
built = true;
}
report.setOptions(options);
if (!globalVariablesGroup.getFooterVariables().isEmpty() || !globalVariablesGroup.getHeaderVariables().isEmpty() || !globalVariablesGroup.getVariables().isEmpty() || hasPercentageColumn()) {
report.getColumnsGroups().add(0, globalVariablesGroup);
}
createChartGroups();
addGlobalCrosstabs();
addSubreportsToGroups();
concatenateReports();
report.setAutoTexts(autoTexts);
return report;
} }
|
public class class_name {
public DynamicReport build() {
if (built) {
throw new DJBuilderException("DynamicReport already built. Cannot use more than once.");
} else {
built = true; // depends on control dependency: [if], data = [none]
}
report.setOptions(options);
if (!globalVariablesGroup.getFooterVariables().isEmpty() || !globalVariablesGroup.getHeaderVariables().isEmpty() || !globalVariablesGroup.getVariables().isEmpty() || hasPercentageColumn()) {
report.getColumnsGroups().add(0, globalVariablesGroup); // depends on control dependency: [if], data = [none]
}
createChartGroups();
addGlobalCrosstabs();
addSubreportsToGroups();
concatenateReports();
report.setAutoTexts(autoTexts);
return report;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
public Class<? extends T> defineClass() {
if (generatedClass == null) {
synchronized (this) {
if (generatedClass == null) {
try {
// first check that the proxy has not already been created
generatedClass = (Class<? extends T>) classLoader.loadClass(this.className);
} catch (ClassNotFoundException e) {
buildClassDefinition();
if (protectionDomain == null) {
generatedClass = (Class<? extends T>) classFile.define();
} else {
generatedClass = (Class<? extends T>) classFile.define(protectionDomain);
}
afterClassLoad(generatedClass);
}
classFile = null;
}
}
}
return generatedClass;
} }
|
public class class_name {
@SuppressWarnings("unchecked")
public Class<? extends T> defineClass() {
if (generatedClass == null) {
synchronized (this) {
if (generatedClass == null) {
try {
// first check that the proxy has not already been created
generatedClass = (Class<? extends T>) classLoader.loadClass(this.className); // depends on control dependency: [try], data = [none]
} catch (ClassNotFoundException e) {
buildClassDefinition();
if (protectionDomain == null) {
generatedClass = (Class<? extends T>) classFile.define(); // depends on control dependency: [if], data = [none]
} else {
generatedClass = (Class<? extends T>) classFile.define(protectionDomain);
}
afterClassLoad(generatedClass);
}
classFile = null; // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
return generatedClass;
} }
|
public class class_name {
@Column(header = Messages.GUI_HISTORY_DIALOG_COL_DATE_PUBLISHED_0, order = 50)
public Date getPublishDate() {
if (m_bean.getPublishDate() == null) {
return null;
}
return new Date(m_bean.getPublishDate().getDate());
} }
|
public class class_name {
@Column(header = Messages.GUI_HISTORY_DIALOG_COL_DATE_PUBLISHED_0, order = 50)
public Date getPublishDate() {
if (m_bean.getPublishDate() == null) {
return null; // depends on control dependency: [if], data = [none]
}
return new Date(m_bean.getPublishDate().getDate());
} }
|
public class class_name {
public S initialize(ExtractorConfig extractorConfig) {
setExtractorImplClassName(extractorConfig.getExtractorImplClassName());
setEntityClass(extractorConfig.getEntityClass());
setRddId(extractorConfig.getRddId());
setPartitionId(extractorConfig.getPartitionId());
Map<String, Serializable> values = extractorConfig.getValues();
if (values.get(USERNAME) != null) {
username(extractorConfig.getString(USERNAME));
}
if (values.get(PASSWORD) != null) {
password(extractorConfig.getString(PASSWORD));
}
if (values.get(HOST) != null) {
host((extractorConfig.getStringArray(HOST)));
}
if (values.get(ES_REST_PORTS) != null) {
port((extractorConfig.getInteger(ES_REST_PORTS)));
}
if (values.get(PORT) != null) {
port((extractorConfig.getInteger(PORT)));
}
if (values.get(COLLECTION) != null) {
table(extractorConfig.getString(COLLECTION));
}
if (values.get(INPUT_COLUMNS) != null) {
inputColumns(extractorConfig.getStringArray(INPUT_COLUMNS));
}
if (values.get(DATABASE) != null) {
catalog(extractorConfig.getString(DATABASE));
}
if (values.get(FILTER_QUERY) != null) {
filters(extractorConfig.getFilterArray(FILTER_QUERY));
}
return (S) this;
} }
|
public class class_name {
public S initialize(ExtractorConfig extractorConfig) {
setExtractorImplClassName(extractorConfig.getExtractorImplClassName());
setEntityClass(extractorConfig.getEntityClass());
setRddId(extractorConfig.getRddId());
setPartitionId(extractorConfig.getPartitionId());
Map<String, Serializable> values = extractorConfig.getValues();
if (values.get(USERNAME) != null) {
username(extractorConfig.getString(USERNAME)); // depends on control dependency: [if], data = [none]
}
if (values.get(PASSWORD) != null) {
password(extractorConfig.getString(PASSWORD)); // depends on control dependency: [if], data = [none]
}
if (values.get(HOST) != null) {
host((extractorConfig.getStringArray(HOST))); // depends on control dependency: [if], data = [none]
}
if (values.get(ES_REST_PORTS) != null) {
port((extractorConfig.getInteger(ES_REST_PORTS))); // depends on control dependency: [if], data = [none]
}
if (values.get(PORT) != null) {
port((extractorConfig.getInteger(PORT))); // depends on control dependency: [if], data = [none]
}
if (values.get(COLLECTION) != null) {
table(extractorConfig.getString(COLLECTION)); // depends on control dependency: [if], data = [none]
}
if (values.get(INPUT_COLUMNS) != null) {
inputColumns(extractorConfig.getStringArray(INPUT_COLUMNS)); // depends on control dependency: [if], data = [none]
}
if (values.get(DATABASE) != null) {
catalog(extractorConfig.getString(DATABASE)); // depends on control dependency: [if], data = [none]
}
if (values.get(FILTER_QUERY) != null) {
filters(extractorConfig.getFilterArray(FILTER_QUERY)); // depends on control dependency: [if], data = [none]
}
return (S) this;
} }
|
public class class_name {
private void readProjectHeader()
{
Table table = m_tables.get("DIR");
MapRow row = table.find("");
if (row != null)
{
setFields(PROJECT_FIELDS, row, m_projectFile.getProjectProperties());
m_wbsFormat = new P3WbsFormat(row);
}
} }
|
public class class_name {
private void readProjectHeader()
{
Table table = m_tables.get("DIR");
MapRow row = table.find("");
if (row != null)
{
setFields(PROJECT_FIELDS, row, m_projectFile.getProjectProperties()); // depends on control dependency: [if], data = [none]
m_wbsFormat = new P3WbsFormat(row); // depends on control dependency: [if], data = [(row]
}
} }
|
public class class_name {
@Nullable
public static CascadingStyleSheet readFromReader (@Nonnull final IHasReader aRP,
@Nonnull final CSSReaderSettings aSettings)
{
ValueEnforcer.notNull (aRP, "ReaderProvider");
ValueEnforcer.notNull (aSettings, "Settings");
// Create the reader
final Reader aReader = aRP.getReader ();
if (aReader == null)
{
// Failed to open reader
return null;
}
// No charset determination, as the Reader already has an implicit Charset
final ECSSVersion eVersion = aSettings.getCSSVersion ();
try
{
final CSSCharStream aCharStream = new CSSCharStream (aReader);
aCharStream.setTabSize (aSettings.getTabSize ());
// Use the default CSS parse error handler if none is provided
ICSSParseErrorHandler aRealParseErrorHandler = aSettings.getCustomErrorHandler ();
if (aRealParseErrorHandler == null)
aRealParseErrorHandler = getDefaultParseErrorHandler ();
// Use the default CSS exception handler if none is provided
ICSSParseExceptionCallback aRealParseExceptionHandler = aSettings.getCustomExceptionHandler ();
if (aRealParseExceptionHandler == null)
aRealParseExceptionHandler = getDefaultParseExceptionHandler ();
final boolean bBrowserCompliantMode = aSettings.isBrowserCompliantMode ();
final CSSNode aNode = _readStyleSheet (aCharStream,
eVersion,
aRealParseErrorHandler,
aRealParseExceptionHandler,
bBrowserCompliantMode);
// Failed to parse content as CSS?
if (aNode == null)
return null;
// Get the interpret error handler
ICSSInterpretErrorHandler aRealInterpretErrorHandler = aSettings.getInterpretErrorHandler ();
if (aRealInterpretErrorHandler == null)
aRealInterpretErrorHandler = getDefaultInterpretErrorHandler ();
// Convert the AST to a domain object
return CSSHandler.readCascadingStyleSheetFromNode (eVersion, aNode, aRealInterpretErrorHandler);
}
finally
{
StreamHelper.close (aReader);
}
} }
|
public class class_name {
@Nullable
public static CascadingStyleSheet readFromReader (@Nonnull final IHasReader aRP,
@Nonnull final CSSReaderSettings aSettings)
{
ValueEnforcer.notNull (aRP, "ReaderProvider");
ValueEnforcer.notNull (aSettings, "Settings");
// Create the reader
final Reader aReader = aRP.getReader ();
if (aReader == null)
{
// Failed to open reader
return null; // depends on control dependency: [if], data = [none]
}
// No charset determination, as the Reader already has an implicit Charset
final ECSSVersion eVersion = aSettings.getCSSVersion ();
try
{
final CSSCharStream aCharStream = new CSSCharStream (aReader);
aCharStream.setTabSize (aSettings.getTabSize ()); // depends on control dependency: [try], data = [none]
// Use the default CSS parse error handler if none is provided
ICSSParseErrorHandler aRealParseErrorHandler = aSettings.getCustomErrorHandler ();
if (aRealParseErrorHandler == null)
aRealParseErrorHandler = getDefaultParseErrorHandler ();
// Use the default CSS exception handler if none is provided
ICSSParseExceptionCallback aRealParseExceptionHandler = aSettings.getCustomExceptionHandler ();
if (aRealParseExceptionHandler == null)
aRealParseExceptionHandler = getDefaultParseExceptionHandler ();
final boolean bBrowserCompliantMode = aSettings.isBrowserCompliantMode ();
final CSSNode aNode = _readStyleSheet (aCharStream,
eVersion,
aRealParseErrorHandler,
aRealParseExceptionHandler,
bBrowserCompliantMode);
// Failed to parse content as CSS?
if (aNode == null)
return null;
// Get the interpret error handler
ICSSInterpretErrorHandler aRealInterpretErrorHandler = aSettings.getInterpretErrorHandler ();
if (aRealInterpretErrorHandler == null)
aRealInterpretErrorHandler = getDefaultInterpretErrorHandler ();
// Convert the AST to a domain object
return CSSHandler.readCascadingStyleSheetFromNode (eVersion, aNode, aRealInterpretErrorHandler); // depends on control dependency: [try], data = [none]
}
finally
{
StreamHelper.close (aReader);
}
} }
|
public class class_name {
protected void putFile(final String name, final FileUpload value) {
if (requestFiles == null) {
requestFiles = new HashMap<>();
}
FileUpload[] fileUploads = requestFiles.get(name);
if (fileUploads != null) {
fileUploads = ArraysUtil.append(fileUploads, value);
} else {
fileUploads = new FileUpload[] {value};
}
requestFiles.put(name, fileUploads);
} }
|
public class class_name {
protected void putFile(final String name, final FileUpload value) {
if (requestFiles == null) {
requestFiles = new HashMap<>(); // depends on control dependency: [if], data = [none]
}
FileUpload[] fileUploads = requestFiles.get(name);
if (fileUploads != null) {
fileUploads = ArraysUtil.append(fileUploads, value); // depends on control dependency: [if], data = [(fileUploads]
} else {
fileUploads = new FileUpload[] {value}; // depends on control dependency: [if], data = [none]
}
requestFiles.put(name, fileUploads);
} }
|
public class class_name {
public void onDoubleClick(DoubleClickEvent event) {
//Check if there was a last click that was handled in this class.
if (null != lastClickPosition) {
// Zoom in on the event location.
Bbox bounds = mapWidget.getMapModel().getMapView().getBounds();
double x = lastClickPosition.getX() - (bounds.getWidth() / 4);
double y = lastClickPosition.getY() - (bounds.getHeight() / 4);
Bbox newBounds = new Bbox(x, y, bounds.getWidth() / 2, bounds.getHeight() / 2);
mapWidget.getMapModel().getMapView().applyBounds(newBounds, ZoomOption.LEVEL_CHANGE);
}
} }
|
public class class_name {
public void onDoubleClick(DoubleClickEvent event) {
//Check if there was a last click that was handled in this class.
if (null != lastClickPosition) {
// Zoom in on the event location.
Bbox bounds = mapWidget.getMapModel().getMapView().getBounds();
double x = lastClickPosition.getX() - (bounds.getWidth() / 4);
double y = lastClickPosition.getY() - (bounds.getHeight() / 4);
Bbox newBounds = new Bbox(x, y, bounds.getWidth() / 2, bounds.getHeight() / 2);
mapWidget.getMapModel().getMapView().applyBounds(newBounds, ZoomOption.LEVEL_CHANGE); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static ContractSummaryBean unmarshallContractSummary(Map<String, Object> source) {
if (source == null) {
return null;
}
ContractSummaryBean bean = new ContractSummaryBean();
bean.setContractId(asLong(source.get("id")));
bean.setCreatedOn(asDate(source.get("createdOn")));
bean.setClientOrganizationId(asString(source.get("clientOrganizationId")));
bean.setClientOrganizationName(asString(source.get("clientOrganizationName")));
bean.setClientId(asString(source.get("clientId")));
bean.setClientName(asString(source.get("clientName")));
bean.setClientVersion(asString(source.get("clientVersion")));
bean.setApiOrganizationId(asString(source.get("apiOrganizationId")));
bean.setApiOrganizationName(asString(source.get("apiOrganizationName")));
bean.setApiId(asString(source.get("apiId")));
bean.setApiName(asString(source.get("apiName")));
bean.setApiVersion(asString(source.get("apiVersion")));
bean.setApiDescription(asString(source.get("apiDescription")));
bean.setPlanName(asString(source.get("planName")));
bean.setPlanId(asString(source.get("planId")));
bean.setPlanVersion(asString(source.get("planVersion")));
postMarshall(bean);
return bean;
} }
|
public class class_name {
public static ContractSummaryBean unmarshallContractSummary(Map<String, Object> source) {
if (source == null) {
return null; // depends on control dependency: [if], data = [none]
}
ContractSummaryBean bean = new ContractSummaryBean();
bean.setContractId(asLong(source.get("id")));
bean.setCreatedOn(asDate(source.get("createdOn")));
bean.setClientOrganizationId(asString(source.get("clientOrganizationId")));
bean.setClientOrganizationName(asString(source.get("clientOrganizationName")));
bean.setClientId(asString(source.get("clientId")));
bean.setClientName(asString(source.get("clientName")));
bean.setClientVersion(asString(source.get("clientVersion")));
bean.setApiOrganizationId(asString(source.get("apiOrganizationId")));
bean.setApiOrganizationName(asString(source.get("apiOrganizationName")));
bean.setApiId(asString(source.get("apiId")));
bean.setApiName(asString(source.get("apiName")));
bean.setApiVersion(asString(source.get("apiVersion")));
bean.setApiDescription(asString(source.get("apiDescription")));
bean.setPlanName(asString(source.get("planName")));
bean.setPlanId(asString(source.get("planId")));
bean.setPlanVersion(asString(source.get("planVersion")));
postMarshall(bean);
return bean;
} }
|
public class class_name {
public static FacesMessage getMessage(String messageId, String... params) {
String summary = null;
String detail = null;
ResourceBundle bundle;
String bundleName;
FacesContext context = FacesContext.getCurrentInstance();
Locale locale = context.getViewRoot().getLocale();
// see if we have a user-provided bundle
Application app = (FacesContext.getCurrentInstance().getApplication());
if (null != (bundleName = app.getMessageBundle())) {
if (null != (bundle = ResourceBundle.getBundle(bundleName, locale,
Thread.currentThread().getContextClassLoader()))) {
// see if we have a hit
try {
summary = bundle.getString(messageId);
detail = bundle.getString(messageId + "_detail");
} catch (MissingResourceException e) {
// ignore
}
}
}
// we couldn't find a summary in the user-provided bundle
if (null == summary) {
// see if we have a summary in the app provided bundle
bundle = ResourceBundle.getBundle(FacesMessage.FACES_MESSAGES, locale,
Thread.currentThread().getContextClassLoader());
if (null == bundle) {
throw new NullPointerException();
}
// see if we have a hit
try {
summary = bundle.getString(messageId);
detail = bundle.getString(messageId + "_detail");
} catch (MissingResourceException e) {
// ignore
}
}
for (int i = 0; i < params.length; i++) {
if (null != summary) {
summary = summary.replace("{" + i + "}", params[i]);
}
if (null != detail) {
detail = detail.replace("{" + i + "}", params[i]);
}
}
// At this point, we have a summary and a bundle.
FacesMessage ret = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail);
ret.setSeverity(FacesMessage.SEVERITY_ERROR);
return ret;
} }
|
public class class_name {
public static FacesMessage getMessage(String messageId, String... params) {
String summary = null;
String detail = null;
ResourceBundle bundle;
String bundleName;
FacesContext context = FacesContext.getCurrentInstance();
Locale locale = context.getViewRoot().getLocale();
// see if we have a user-provided bundle
Application app = (FacesContext.getCurrentInstance().getApplication());
if (null != (bundleName = app.getMessageBundle())) {
if (null != (bundle = ResourceBundle.getBundle(bundleName, locale,
Thread.currentThread().getContextClassLoader()))) {
// see if we have a hit
try {
summary = bundle.getString(messageId); // depends on control dependency: [try], data = [none]
detail = bundle.getString(messageId + "_detail"); // depends on control dependency: [try], data = [none]
} catch (MissingResourceException e) {
// ignore
} // depends on control dependency: [catch], data = [none]
}
}
// we couldn't find a summary in the user-provided bundle
if (null == summary) {
// see if we have a summary in the app provided bundle
bundle = ResourceBundle.getBundle(FacesMessage.FACES_MESSAGES, locale,
Thread.currentThread().getContextClassLoader()); // depends on control dependency: [if], data = [none]
if (null == bundle) {
throw new NullPointerException();
}
// see if we have a hit
try {
summary = bundle.getString(messageId); // depends on control dependency: [try], data = [none]
detail = bundle.getString(messageId + "_detail"); // depends on control dependency: [try], data = [none]
} catch (MissingResourceException e) {
// ignore
} // depends on control dependency: [catch], data = [none]
}
for (int i = 0; i < params.length; i++) {
if (null != summary) {
summary = summary.replace("{" + i + "}", params[i]); // depends on control dependency: [if], data = [none]
}
if (null != detail) {
detail = detail.replace("{" + i + "}", params[i]); // depends on control dependency: [if], data = [none]
}
}
// At this point, we have a summary and a bundle.
FacesMessage ret = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail);
ret.setSeverity(FacesMessage.SEVERITY_ERROR);
return ret;
} }
|
public class class_name {
public static String getDirectEditPath(CmsObject cms, CmsUserSettings userSettings) {
if (userSettings.getStartView().equals(CmsWorkplace.VIEW_DIRECT_EDIT)
| userSettings.getStartView().equals(CmsPageEditorConfiguration.APP_ID)) {
try {
CmsObject cloneCms = OpenCms.initCmsObject(cms);
String startSite = CmsWorkplace.getStartSiteRoot(cloneCms, userSettings);
cloneCms.getRequestContext().setSiteRoot(startSite);
String projectName = userSettings.getStartProject();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(projectName)) {
cloneCms.getRequestContext().setCurrentProject(cloneCms.readProject(projectName));
}
String folder = userSettings.getStartFolder();
CmsResource targetRes = cloneCms.readDefaultFile(folder);
if (targetRes != null) {
return cloneCms.getSitePath(targetRes);
}
} catch (Exception e) {
LOG.debug(e);
}
}
return null;
} }
|
public class class_name {
public static String getDirectEditPath(CmsObject cms, CmsUserSettings userSettings) {
if (userSettings.getStartView().equals(CmsWorkplace.VIEW_DIRECT_EDIT)
| userSettings.getStartView().equals(CmsPageEditorConfiguration.APP_ID)) {
try {
CmsObject cloneCms = OpenCms.initCmsObject(cms);
String startSite = CmsWorkplace.getStartSiteRoot(cloneCms, userSettings);
cloneCms.getRequestContext().setSiteRoot(startSite); // depends on control dependency: [try], data = [none]
String projectName = userSettings.getStartProject();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(projectName)) {
cloneCms.getRequestContext().setCurrentProject(cloneCms.readProject(projectName)); // depends on control dependency: [if], data = [none]
}
String folder = userSettings.getStartFolder();
CmsResource targetRes = cloneCms.readDefaultFile(folder);
if (targetRes != null) {
return cloneCms.getSitePath(targetRes); // depends on control dependency: [if], data = [(targetRes]
}
} catch (Exception e) {
LOG.debug(e);
} // depends on control dependency: [catch], data = [none]
}
return null;
} }
|
public class class_name {
public java.util.List<Reservation> getReservations() {
if (reservations == null) {
reservations = new com.amazonaws.internal.SdkInternalList<Reservation>();
}
return reservations;
} }
|
public class class_name {
public java.util.List<Reservation> getReservations() {
if (reservations == null) {
reservations = new com.amazonaws.internal.SdkInternalList<Reservation>(); // depends on control dependency: [if], data = [none]
}
return reservations;
} }
|
public class class_name {
public <T extends RequestParameter> void addParameters(final List<T> params)
{
for (RequestParameter rp : params)
{
String value = rp.getValue();
String name = rp.getName();
if (!parameters.containsKey(name))
{
ArrayList<String> values = new ArrayList<String>();
if (value != null)
{
values.add(value);
}
parameters.put(name, values);
}
else
{
parameters.get(name).add(value);
}
}
} }
|
public class class_name {
public <T extends RequestParameter> void addParameters(final List<T> params)
{
for (RequestParameter rp : params)
{
String value = rp.getValue();
String name = rp.getName();
if (!parameters.containsKey(name))
{
ArrayList<String> values = new ArrayList<String>();
if (value != null)
{
values.add(value); // depends on control dependency: [if], data = [(value]
}
parameters.put(name, values); // depends on control dependency: [if], data = [none]
}
else
{
parameters.get(name).add(value); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
public void setUserProfiles(java.util.Collection<UserProfileSummary> userProfiles) {
if (userProfiles == null) {
this.userProfiles = null;
return;
}
this.userProfiles = new java.util.ArrayList<UserProfileSummary>(userProfiles);
} }
|
public class class_name {
public void setUserProfiles(java.util.Collection<UserProfileSummary> userProfiles) {
if (userProfiles == null) {
this.userProfiles = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.userProfiles = new java.util.ArrayList<UserProfileSummary>(userProfiles);
} }
|
public class class_name {
private static CaseInsensitiveStringMap catalogOptions(String name, SQLConf conf) {
Map<String, String> allConfs = mapAsJavaMapConverter(conf.getAllConfs()).asJava();
Pattern prefix = Pattern.compile("^spark\\.sql\\.catalog\\." + name + "\\.(.+)");
HashMap<String, String> options = new HashMap<>();
for (Map.Entry<String, String> entry : allConfs.entrySet()) {
Matcher matcher = prefix.matcher(entry.getKey());
if (matcher.matches() && matcher.groupCount() > 0) {
options.put(matcher.group(1), entry.getValue());
}
}
return new CaseInsensitiveStringMap(options);
} }
|
public class class_name {
private static CaseInsensitiveStringMap catalogOptions(String name, SQLConf conf) {
Map<String, String> allConfs = mapAsJavaMapConverter(conf.getAllConfs()).asJava();
Pattern prefix = Pattern.compile("^spark\\.sql\\.catalog\\." + name + "\\.(.+)");
HashMap<String, String> options = new HashMap<>();
for (Map.Entry<String, String> entry : allConfs.entrySet()) {
Matcher matcher = prefix.matcher(entry.getKey());
if (matcher.matches() && matcher.groupCount() > 0) {
options.put(matcher.group(1), entry.getValue()); // depends on control dependency: [if], data = [none]
}
}
return new CaseInsensitiveStringMap(options);
} }
|
public class class_name {
public Object convertToDefaultType(SessionInterface session, Object a) {
if (a == null) {
return a;
}
Type otherType;
if (a instanceof Number) {
if (a instanceof BigInteger) {
a = new BigDecimal((BigInteger) a);
} else if (a instanceof Float) {
a = new Double(((Float) a).doubleValue());
} else if (a instanceof Byte) {
a = ValuePool.getInt(((Byte) a).intValue());
} else if (a instanceof Short) {
a = ValuePool.getInt(((Short) a).intValue());
}
if (a instanceof Integer) {
otherType = Type.SQL_INTEGER;
} else if (a instanceof Long) {
otherType = Type.SQL_BIGINT;
} else if (a instanceof Double) {
otherType = Type.SQL_DOUBLE;
} else if (a instanceof BigDecimal) {
// BEGIN Cherry-picked code change from hsqldb-2.2.8
otherType = Type.SQL_DECIMAL_DEFAULT;
/*
if (typeCode == Types.SQL_DECIMAL
|| typeCode == Types.SQL_NUMERIC) {
return convertToTypeLimits(session, a);
}
BigDecimal val = (BigDecimal) a;
otherType = getNumberType(Types.SQL_DECIMAL,
JavaSystem.precision(val), scale);
*/
// END Cherry-picked code change from hsqldb-2.2.8
} else {
throw Error.error(ErrorCode.X_42561);
}
// BEGIN Cherry-picked code change from hsqldb-2.2.8
switch (typeCode) {
case Types.TINYINT :
case Types.SQL_SMALLINT :
case Types.SQL_INTEGER :
return convertToInt(session, a, Types.INTEGER);
case Types.SQL_BIGINT :
return convertToLong(session, a);
case Types.SQL_REAL :
case Types.SQL_FLOAT :
case Types.SQL_DOUBLE :
return convertToDouble(a);
case Types.SQL_NUMERIC :
case Types.SQL_DECIMAL : {
a = convertToDecimal(a);
BigDecimal dec = (BigDecimal) a;
if (scale != dec.scale()) {
dec = dec.setScale(scale, BigDecimal.ROUND_HALF_DOWN);
}
return dec;
}
default :
throw Error.error(ErrorCode.X_42561);
}
// END Cherry-picked code change from hsqldb-2.2.8
} else if (a instanceof String) {
otherType = Type.SQL_VARCHAR;
} else {
throw Error.error(ErrorCode.X_42561);
}
return convertToType(session, a, otherType);
} }
|
public class class_name {
public Object convertToDefaultType(SessionInterface session, Object a) {
if (a == null) {
return a; // depends on control dependency: [if], data = [none]
}
Type otherType;
if (a instanceof Number) {
if (a instanceof BigInteger) {
a = new BigDecimal((BigInteger) a); // depends on control dependency: [if], data = [none]
} else if (a instanceof Float) {
a = new Double(((Float) a).doubleValue()); // depends on control dependency: [if], data = [none]
} else if (a instanceof Byte) {
a = ValuePool.getInt(((Byte) a).intValue()); // depends on control dependency: [if], data = [none]
} else if (a instanceof Short) {
a = ValuePool.getInt(((Short) a).intValue()); // depends on control dependency: [if], data = [none]
}
if (a instanceof Integer) {
otherType = Type.SQL_INTEGER; // depends on control dependency: [if], data = [none]
} else if (a instanceof Long) {
otherType = Type.SQL_BIGINT; // depends on control dependency: [if], data = [none]
} else if (a instanceof Double) {
otherType = Type.SQL_DOUBLE; // depends on control dependency: [if], data = [none]
} else if (a instanceof BigDecimal) {
// BEGIN Cherry-picked code change from hsqldb-2.2.8
otherType = Type.SQL_DECIMAL_DEFAULT; // depends on control dependency: [if], data = [none]
/*
if (typeCode == Types.SQL_DECIMAL
|| typeCode == Types.SQL_NUMERIC) {
return convertToTypeLimits(session, a);
}
BigDecimal val = (BigDecimal) a;
otherType = getNumberType(Types.SQL_DECIMAL,
JavaSystem.precision(val), scale);
*/
// END Cherry-picked code change from hsqldb-2.2.8
} else {
throw Error.error(ErrorCode.X_42561);
}
// BEGIN Cherry-picked code change from hsqldb-2.2.8
switch (typeCode) {
case Types.TINYINT :
case Types.SQL_SMALLINT :
case Types.SQL_INTEGER :
return convertToInt(session, a, Types.INTEGER);
case Types.SQL_BIGINT :
return convertToLong(session, a);
case Types.SQL_REAL :
case Types.SQL_FLOAT :
case Types.SQL_DOUBLE :
return convertToDouble(a);
case Types.SQL_NUMERIC :
case Types.SQL_DECIMAL : {
a = convertToDecimal(a);
BigDecimal dec = (BigDecimal) a;
if (scale != dec.scale()) {
dec = dec.setScale(scale, BigDecimal.ROUND_HALF_DOWN); // depends on control dependency: [if], data = [(scale]
}
return dec;
}
default :
throw Error.error(ErrorCode.X_42561);
}
// END Cherry-picked code change from hsqldb-2.2.8
} else if (a instanceof String) {
otherType = Type.SQL_VARCHAR;
} else {
throw Error.error(ErrorCode.X_42561);
}
return convertToType(session, a, otherType);
} }
|
public class class_name {
public Set<Deque<Archive>> inverseDependences() throws IOException {
// create a new dependency finder to do the analysis
DependencyFinder dependencyFinder = new DependencyFinder(configuration, DEFAULT_FILTER);
try {
// parse all archives in unnamed module to get compile-time dependences
Stream<Archive> archives =
Stream.concat(configuration.initialArchives().stream(),
configuration.classPathArchives().stream());
if (apiOnly) {
dependencyFinder.parseExportedAPIs(archives);
} else {
dependencyFinder.parse(archives);
}
Graph.Builder<Archive> builder = new Graph.Builder<>();
// include all target nodes
targets().forEach(builder::addNode);
// transpose the module graph
configuration.getModules().values().stream()
.forEach(m -> {
builder.addNode(m);
m.descriptor().requires().stream()
.map(Requires::name)
.map(configuration::findModule) // must be present
.forEach(v -> builder.addEdge(v.get(), m));
});
// add the dependences from the analysis
Map<Archive, Set<Archive>> dependences = dependencyFinder.dependences();
dependences.entrySet().stream()
.forEach(e -> {
Archive u = e.getKey();
builder.addNode(u);
e.getValue().forEach(v -> builder.addEdge(v, u));
});
// transposed dependence graph.
Graph<Archive> graph = builder.build();
trace("targets: %s%n", targets());
// Traverse from the targets and find all paths
// rebuild a graph with all nodes that depends on targets
// targets directly and indirectly
return targets().stream()
.map(t -> findPaths(graph, t))
.flatMap(Set::stream)
.collect(Collectors.toSet());
} finally {
dependencyFinder.shutdown();
}
} }
|
public class class_name {
public Set<Deque<Archive>> inverseDependences() throws IOException {
// create a new dependency finder to do the analysis
DependencyFinder dependencyFinder = new DependencyFinder(configuration, DEFAULT_FILTER);
try {
// parse all archives in unnamed module to get compile-time dependences
Stream<Archive> archives =
Stream.concat(configuration.initialArchives().stream(),
configuration.classPathArchives().stream());
if (apiOnly) {
dependencyFinder.parseExportedAPIs(archives); // depends on control dependency: [if], data = [none]
} else {
dependencyFinder.parse(archives); // depends on control dependency: [if], data = [none]
}
Graph.Builder<Archive> builder = new Graph.Builder<>();
// include all target nodes
targets().forEach(builder::addNode);
// transpose the module graph
configuration.getModules().values().stream()
.forEach(m -> {
builder.addNode(m);
m.descriptor().requires().stream()
.map(Requires::name)
.map(configuration::findModule) // must be present
.forEach(v -> builder.addEdge(v.get(), m));
});
// add the dependences from the analysis
Map<Archive, Set<Archive>> dependences = dependencyFinder.dependences();
dependences.entrySet().stream()
.forEach(e -> {
Archive u = e.getKey();
builder.addNode(u);
e.getValue().forEach(v -> builder.addEdge(v, u));
});
// transposed dependence graph.
Graph<Archive> graph = builder.build();
trace("targets: %s%n", targets());
// Traverse from the targets and find all paths
// rebuild a graph with all nodes that depends on targets
// targets directly and indirectly
return targets().stream()
.map(t -> findPaths(graph, t))
.flatMap(Set::stream)
.collect(Collectors.toSet());
} finally {
dependencyFinder.shutdown();
}
} }
|
public class class_name {
private int binarySearch(List<SparseItemset> candidates, SparseItemset scratch, int begin, int end) {
--end;
while(begin < end) {
final int mid = (begin + end) >>> 1;
SparseItemset midVal = candidates.get(mid);
int cmp = midVal.compareTo(scratch);
if(cmp < 0) {
begin = mid + 1;
}
else if(cmp > 0) {
end = mid - 1;
}
else {
return mid; // key found
}
}
return -(begin + 1); // key not found, return next
} }
|
public class class_name {
private int binarySearch(List<SparseItemset> candidates, SparseItemset scratch, int begin, int end) {
--end;
while(begin < end) {
final int mid = (begin + end) >>> 1;
SparseItemset midVal = candidates.get(mid);
int cmp = midVal.compareTo(scratch);
if(cmp < 0) {
begin = mid + 1; // depends on control dependency: [if], data = [none]
}
else if(cmp > 0) {
end = mid - 1; // depends on control dependency: [if], data = [none]
}
else {
return mid; // key found // depends on control dependency: [if], data = [none]
}
}
return -(begin + 1); // key not found, return next
} }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.