code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public static Map<String,Object> processParameters(
final FragmentSignature fragmentSignature,
final Map<String, Object> specifiedParameters, final boolean parametersAreSynthetic) {
Validate.notNull(fragmentSignature, "Fragment signature cannot be null");
if (specifiedParameters == null || specifiedParameters.size() == 0) {
if (fragmentSignature.hasParameters()) {
// Fragment signature requires parameters, but we haven't specified them!
throw new TemplateProcessingException(
"Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " +
"declares parameters, but fragment selection did not specify any parameters.");
}
return null;
}
if (parametersAreSynthetic && !fragmentSignature.hasParameters()) {
throw new TemplateProcessingException(
"Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " +
"declares no parameters, but fragment selection did specify parameters in a synthetic manner " +
"(without names), which is not correct due to the fact parameters cannot be assigned names " +
"unless signature specifies these names.");
}
if (parametersAreSynthetic) {
// No need to match parameter names, just apply the ones from the signature
final List<String> signatureParameterNames = fragmentSignature.getParameterNames();
if (signatureParameterNames.size() != specifiedParameters.size()) {
throw new TemplateProcessingException(
"Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " +
"declares " + signatureParameterNames.size() + " parameters, but fragment selection specifies " +
specifiedParameters.size() + " parameters. Fragment selection does not correctly match.");
}
final Map<String,Object> processedParameters = new HashMap<String, Object>(signatureParameterNames.size() + 1, 1.0f);
int index = 0;
for (final String parameterName : signatureParameterNames) {
final String syntheticParameterName = getSyntheticParameterNameForIndex(index++);
final Object parameterValue = specifiedParameters.get(syntheticParameterName);
processedParameters.put(parameterName, parameterValue);
}
return processedParameters;
}
if (!fragmentSignature.hasParameters()) {
// Parameters in fragment selection are not synthetic, and fragment signature has no parameters,
// so we just use the "specified parameters".
return specifiedParameters;
}
// Parameters are not synthetic and signature does specify parameters, so their names should match (all
// the parameters specified at the fragment signature should be specified at the fragment selection,
// though fragment selection can specify more parameters, not present at the signature.
final List<String> parameterNames = fragmentSignature.getParameterNames();
for (final String parameterName : parameterNames) {
if (!specifiedParameters.containsKey(parameterName)) {
throw new TemplateProcessingException(
"Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " +
"declares parameter \"" + parameterName + "\", which is not specified at the fragment " +
"selection.");
}
}
return specifiedParameters;
} } | public class class_name {
public static Map<String,Object> processParameters(
final FragmentSignature fragmentSignature,
final Map<String, Object> specifiedParameters, final boolean parametersAreSynthetic) {
Validate.notNull(fragmentSignature, "Fragment signature cannot be null");
if (specifiedParameters == null || specifiedParameters.size() == 0) {
if (fragmentSignature.hasParameters()) {
// Fragment signature requires parameters, but we haven't specified them!
throw new TemplateProcessingException(
"Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " +
"declares parameters, but fragment selection did not specify any parameters.");
}
return null; // depends on control dependency: [if], data = [none]
}
if (parametersAreSynthetic && !fragmentSignature.hasParameters()) {
throw new TemplateProcessingException(
"Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " +
"declares no parameters, but fragment selection did specify parameters in a synthetic manner " +
"(without names), which is not correct due to the fact parameters cannot be assigned names " +
"unless signature specifies these names.");
}
if (parametersAreSynthetic) {
// No need to match parameter names, just apply the ones from the signature
final List<String> signatureParameterNames = fragmentSignature.getParameterNames();
if (signatureParameterNames.size() != specifiedParameters.size()) {
throw new TemplateProcessingException(
"Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " +
"declares " + signatureParameterNames.size() + " parameters, but fragment selection specifies " +
specifiedParameters.size() + " parameters. Fragment selection does not correctly match.");
}
final Map<String,Object> processedParameters = new HashMap<String, Object>(signatureParameterNames.size() + 1, 1.0f);
int index = 0;
for (final String parameterName : signatureParameterNames) {
final String syntheticParameterName = getSyntheticParameterNameForIndex(index++);
final Object parameterValue = specifiedParameters.get(syntheticParameterName);
processedParameters.put(parameterName, parameterValue); // depends on control dependency: [for], data = [parameterName]
}
return processedParameters; // depends on control dependency: [if], data = [none]
}
if (!fragmentSignature.hasParameters()) {
// Parameters in fragment selection are not synthetic, and fragment signature has no parameters,
// so we just use the "specified parameters".
return specifiedParameters; // depends on control dependency: [if], data = [none]
}
// Parameters are not synthetic and signature does specify parameters, so their names should match (all
// the parameters specified at the fragment signature should be specified at the fragment selection,
// though fragment selection can specify more parameters, not present at the signature.
final List<String> parameterNames = fragmentSignature.getParameterNames();
for (final String parameterName : parameterNames) {
if (!specifiedParameters.containsKey(parameterName)) {
throw new TemplateProcessingException(
"Cannot resolve fragment. Signature \"" + fragmentSignature.getStringRepresentation() + "\" " +
"declares parameter \"" + parameterName + "\", which is not specified at the fragment " +
"selection.");
}
}
return specifiedParameters;
} } |
public class class_name {
@Override
public IndexTreePath<E> next() {
Iterator<IndexTreePath<E>> enumeration = queue.peek();
IndexTreePath<E> nextPath = enumeration.next();
Iterator<IndexTreePath<E>> children;
if(nextPath.getEntry() instanceof LeafEntry) {
children = EMPTY_ENUMERATION;
}
else {
N node = index.getNode(nextPath.getEntry());
children = node.children(nextPath);
}
if(!enumeration.hasNext()) {
queue.remove();
}
if(children.hasNext()) {
queue.offer(children);
}
return nextPath;
} } | public class class_name {
@Override
public IndexTreePath<E> next() {
Iterator<IndexTreePath<E>> enumeration = queue.peek();
IndexTreePath<E> nextPath = enumeration.next();
Iterator<IndexTreePath<E>> children;
if(nextPath.getEntry() instanceof LeafEntry) {
children = EMPTY_ENUMERATION; // depends on control dependency: [if], data = [none]
}
else {
N node = index.getNode(nextPath.getEntry());
children = node.children(nextPath); // depends on control dependency: [if], data = [none]
}
if(!enumeration.hasNext()) {
queue.remove(); // depends on control dependency: [if], data = [none]
}
if(children.hasNext()) {
queue.offer(children); // depends on control dependency: [if], data = [none]
}
return nextPath;
} } |
public class class_name {
public Map<String, List<CmsJspContentAccessValueWrapper>> getValueList() {
if (m_valueList == null) {
m_valueList = CmsCollectionsGenericWrapper.createLazyMap(new CmsValueListTransformer());
}
return m_valueList;
} } | public class class_name {
public Map<String, List<CmsJspContentAccessValueWrapper>> getValueList() {
if (m_valueList == null) {
m_valueList = CmsCollectionsGenericWrapper.createLazyMap(new CmsValueListTransformer()); // depends on control dependency: [if], data = [none]
}
return m_valueList;
} } |
public class class_name {
private boolean parseJsonParams(Object[] params) throws Exception
{
boolean checkValidity = true;
if (params[0] == null) {
throw new Exception("@SnapshotSave JSON blob is null");
}
if (!(params[0] instanceof String)) {
throw new Exception("@SnapshotSave JSON blob is a " +
params[0].getClass().getSimpleName() +
" and should be a java.lang.String");
}
final JSONObject jsObj = new JSONObject((String)params[0]);
// IZZY - Make service an enum and store it in the object if
// we every introduce another one
if (jsObj.has(SnapshotUtil.JSON_SERVICE)) {
String service = jsObj.getString(SnapshotUtil.JSON_SERVICE);
if (service.equalsIgnoreCase("log_truncation")) {
m_truncationRequest = true;
if (!VoltDB.instance().getCommandLog().isEnabled()) {
throw new Exception("Cannot ask for a command log truncation snapshot when " +
"command logging is not present or enabled.");
}
// for CL truncation, don't care about any of the rest of the blob.
return checkValidity;
}
else {
throw new Exception("Unknown snapshot save service type: " + service);
}
}
m_stype = SnapshotPathType.valueOf(jsObj.optString(SnapshotUtil.JSON_PATH_TYPE, SnapshotPathType.SNAP_PATH.toString()));
if (jsObj.has(SnapshotUtil.JSON_URIPATH)) {
m_path = jsObj.getString(SnapshotUtil.JSON_URIPATH);
if (m_path.isEmpty()) {
throw new Exception("uripath cannot be empty");
}
} else {
m_stype = SnapshotPathType.SNAP_AUTO;
m_path = "file:///" + VoltDB.instance().getCommandLogSnapshotPath();
}
URI pathURI = new URI(m_path);
String pathURIScheme = pathURI.getScheme();
if (pathURIScheme == null) {
throw new Exception("URI scheme cannot be null");
}
if (!pathURIScheme.equals("file")) {
throw new Exception("Unsupported URI scheme " + pathURIScheme +
" if this is a file path then you must prepend file://");
}
m_path = pathURI.getPath();
if (jsObj.has(SnapshotUtil.JSON_NONCE)) {
m_nonce = jsObj.getString(SnapshotUtil.JSON_NONCE);
if (m_nonce.isEmpty()) {
throw new Exception("nonce cannot be empty");
}
} else {
m_nonce = MAGIC_NONCE_PREFIX + System.currentTimeMillis();
//This is a valid JSON
checkValidity = false;
}
Object blockingObj = false;
if (jsObj.has(SnapshotUtil.JSON_BLOCK)) {
blockingObj = jsObj.get(SnapshotUtil.JSON_BLOCK);
}
if (blockingObj instanceof Number) {
m_blocking = ((Number)blockingObj).byteValue() == 0 ? false : true;
} else if (blockingObj instanceof Boolean) {
m_blocking = (Boolean)blockingObj;
} else if (blockingObj instanceof String) {
m_blocking = Boolean.valueOf((String)blockingObj);
} else {
throw new Exception(blockingObj.getClass().getName() + " is not supported as " +
" type for the block parameter");
}
m_format = SnapshotFormat.NATIVE;
String formatString = jsObj.optString(SnapshotUtil.JSON_FORMAT,SnapshotFormat.NATIVE.toString());
m_terminus = jsObj.has(SnapshotUtil.JSON_TERMINUS) ? jsObj.getLong(SnapshotUtil.JSON_TERMINUS) : null;
/*
* Try and be very flexible about what we will accept
* as the type of the block parameter.
*/
try {
m_format = SnapshotFormat.getEnumIgnoreCase(formatString);
} catch (IllegalArgumentException argException) {
throw new Exception("@SnapshotSave format param is a " + m_format +
" and should be one of [\"native\" | \"csv\"]");
}
m_data = (String)params[0];
return checkValidity;
} } | public class class_name {
private boolean parseJsonParams(Object[] params) throws Exception
{
boolean checkValidity = true;
if (params[0] == null) {
throw new Exception("@SnapshotSave JSON blob is null");
}
if (!(params[0] instanceof String)) {
throw new Exception("@SnapshotSave JSON blob is a " +
params[0].getClass().getSimpleName() +
" and should be a java.lang.String");
}
final JSONObject jsObj = new JSONObject((String)params[0]);
// IZZY - Make service an enum and store it in the object if
// we every introduce another one
if (jsObj.has(SnapshotUtil.JSON_SERVICE)) {
String service = jsObj.getString(SnapshotUtil.JSON_SERVICE);
if (service.equalsIgnoreCase("log_truncation")) {
m_truncationRequest = true; // depends on control dependency: [if], data = [none]
if (!VoltDB.instance().getCommandLog().isEnabled()) {
throw new Exception("Cannot ask for a command log truncation snapshot when " +
"command logging is not present or enabled.");
}
// for CL truncation, don't care about any of the rest of the blob.
return checkValidity; // depends on control dependency: [if], data = [none]
}
else {
throw new Exception("Unknown snapshot save service type: " + service);
}
}
m_stype = SnapshotPathType.valueOf(jsObj.optString(SnapshotUtil.JSON_PATH_TYPE, SnapshotPathType.SNAP_PATH.toString()));
if (jsObj.has(SnapshotUtil.JSON_URIPATH)) {
m_path = jsObj.getString(SnapshotUtil.JSON_URIPATH);
if (m_path.isEmpty()) {
throw new Exception("uripath cannot be empty");
}
} else {
m_stype = SnapshotPathType.SNAP_AUTO;
m_path = "file:///" + VoltDB.instance().getCommandLogSnapshotPath();
}
URI pathURI = new URI(m_path);
String pathURIScheme = pathURI.getScheme();
if (pathURIScheme == null) {
throw new Exception("URI scheme cannot be null");
}
if (!pathURIScheme.equals("file")) {
throw new Exception("Unsupported URI scheme " + pathURIScheme +
" if this is a file path then you must prepend file://");
}
m_path = pathURI.getPath();
if (jsObj.has(SnapshotUtil.JSON_NONCE)) {
m_nonce = jsObj.getString(SnapshotUtil.JSON_NONCE);
if (m_nonce.isEmpty()) {
throw new Exception("nonce cannot be empty");
}
} else {
m_nonce = MAGIC_NONCE_PREFIX + System.currentTimeMillis();
//This is a valid JSON
checkValidity = false;
}
Object blockingObj = false;
if (jsObj.has(SnapshotUtil.JSON_BLOCK)) {
blockingObj = jsObj.get(SnapshotUtil.JSON_BLOCK);
}
if (blockingObj instanceof Number) {
m_blocking = ((Number)blockingObj).byteValue() == 0 ? false : true;
} else if (blockingObj instanceof Boolean) {
m_blocking = (Boolean)blockingObj;
} else if (blockingObj instanceof String) {
m_blocking = Boolean.valueOf((String)blockingObj);
} else {
throw new Exception(blockingObj.getClass().getName() + " is not supported as " +
" type for the block parameter");
}
m_format = SnapshotFormat.NATIVE;
String formatString = jsObj.optString(SnapshotUtil.JSON_FORMAT,SnapshotFormat.NATIVE.toString());
m_terminus = jsObj.has(SnapshotUtil.JSON_TERMINUS) ? jsObj.getLong(SnapshotUtil.JSON_TERMINUS) : null;
/*
* Try and be very flexible about what we will accept
* as the type of the block parameter.
*/
try {
m_format = SnapshotFormat.getEnumIgnoreCase(formatString);
} catch (IllegalArgumentException argException) {
throw new Exception("@SnapshotSave format param is a " + m_format +
" and should be one of [\"native\" | \"csv\"]");
}
m_data = (String)params[0];
return checkValidity;
} } |
public class class_name {
@Override
public EClass getIfcTimeSeries() {
if (ifcTimeSeriesEClass == null) {
ifcTimeSeriesEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(723);
}
return ifcTimeSeriesEClass;
} } | public class class_name {
@Override
public EClass getIfcTimeSeries() {
if (ifcTimeSeriesEClass == null) {
ifcTimeSeriesEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(723);
// depends on control dependency: [if], data = [none]
}
return ifcTimeSeriesEClass;
} } |
public class class_name {
public static Pair<String, List<Process>> setupZkTunnel(Config config,
NetworkUtils.TunnelConfig tunnelConfig) {
// Remove all spaces
String connectionString = Context.stateManagerConnectionString(config).replaceAll("\\s+", "");
List<Pair<InetSocketAddress, Process>> ret = new ArrayList<>();
// For zookeeper, connection String can be a list of host:port, separated by comma
String[] endpoints = connectionString.split(",");
for (String endpoint : endpoints) {
InetSocketAddress address = NetworkUtils.getInetSocketAddress(endpoint);
// Get the tunnel process if needed
Pair<InetSocketAddress, Process> pair =
NetworkUtils.establishSSHTunnelIfNeeded(
address, tunnelConfig, NetworkUtils.TunnelType.PORT_FORWARD);
ret.add(pair);
}
// Construct the new ConnectionString and tunnel processes
StringBuilder connectionStringBuilder = new StringBuilder();
List<Process> tunnelProcesses = new ArrayList<>();
String delim = "";
for (Pair<InetSocketAddress, Process> pair : ret) {
// Join the list of String with comma as delim
if (pair.first != null) {
connectionStringBuilder.append(delim).
append(pair.first.getHostName()).append(":").append(pair.first.getPort());
delim = ",";
// If tunneled
if (pair.second != null) {
tunnelProcesses.add(pair.second);
}
}
}
String newConnectionString = connectionStringBuilder.toString();
return new Pair<String, List<Process>>(newConnectionString, tunnelProcesses);
} } | public class class_name {
public static Pair<String, List<Process>> setupZkTunnel(Config config,
NetworkUtils.TunnelConfig tunnelConfig) {
// Remove all spaces
String connectionString = Context.stateManagerConnectionString(config).replaceAll("\\s+", "");
List<Pair<InetSocketAddress, Process>> ret = new ArrayList<>();
// For zookeeper, connection String can be a list of host:port, separated by comma
String[] endpoints = connectionString.split(",");
for (String endpoint : endpoints) {
InetSocketAddress address = NetworkUtils.getInetSocketAddress(endpoint);
// Get the tunnel process if needed
Pair<InetSocketAddress, Process> pair =
NetworkUtils.establishSSHTunnelIfNeeded(
address, tunnelConfig, NetworkUtils.TunnelType.PORT_FORWARD);
ret.add(pair); // depends on control dependency: [for], data = [none]
}
// Construct the new ConnectionString and tunnel processes
StringBuilder connectionStringBuilder = new StringBuilder();
List<Process> tunnelProcesses = new ArrayList<>();
String delim = "";
for (Pair<InetSocketAddress, Process> pair : ret) {
// Join the list of String with comma as delim
if (pair.first != null) {
connectionStringBuilder.append(delim).
append(pair.first.getHostName()).append(":").append(pair.first.getPort()); // depends on control dependency: [if], data = [none]
delim = ","; // depends on control dependency: [if], data = [none]
// If tunneled
if (pair.second != null) {
tunnelProcesses.add(pair.second); // depends on control dependency: [if], data = [(pair.second]
}
}
}
String newConnectionString = connectionStringBuilder.toString();
return new Pair<String, List<Process>>(newConnectionString, tunnelProcesses);
} } |
public class class_name {
public byte[] malloc(int size)
{
byte[] retval = null;
// first check the parachute
JNIMemoryParachute.getParachute().packChute();
try
{
if (SHOULD_RETRY_FAILED_ALLOCS)
{
int allocationAttempts = 0;
int backoffTimeout = 10; // start at 10 milliseconds
while (true)
{
try
{
// log.debug("attempting malloc of size: {}", size);
retval = new byte[size];
// log.debug("malloced block of size: {}", size);
// we succeed, so break out
break;
}
catch (final OutOfMemoryError e)
{
// try clearing our queue now and do it again. Why?
// because the first failure may have allowed us to
// catch a RefCounted no longer in use, and the second
// attempt may have freed that memory.
// do a JNI collect before the alloc
++allocationAttempts;
if (allocationAttempts >= MAX_ALLOCATION_ATTEMPTS)
{
// try pulling our rip cord
JNIMemoryParachute.getParachute().pullCord();
// do one last "hope gc" to free our own memory
JNIReference.getMgr().gcInternal();
// and throw the error back to the native code
throw e;
}
log.debug("retrying ({}) allocation of {} bytes",
allocationAttempts, size);
try
{
// give the finalizer a chance
if (allocationAttempts <= 1)
{
// first just yield
Thread.yield();
}
else
{
Thread.sleep(backoffTimeout);
// and slowly get longer...
backoffTimeout = (int) (backoffTimeout * FALLBACK_TIME_DECAY);
}
}
catch (InterruptedException e1)
{
// reset the interruption so underlying
// code can also interrupt
Thread.currentThread().interrupt();
// and throw the error condition
throw e;
}
// do a JNI collect before the alloc
JNIReference.getMgr().gcInternal();
}
}
}
else
{
retval = new byte[size];
}
addToBuffer(retval);
retval[retval.length - 1] = 0;
// log.debug("malloc: {}({}:{})", new Object[]
// {
// retval.hashCode(), retval.length, size
// });
}
catch (Throwable t)
{
// do not let an exception leak out since we go back to native code.
retval = null;
}
return retval;
} } | public class class_name {
public byte[] malloc(int size)
{
byte[] retval = null;
// first check the parachute
JNIMemoryParachute.getParachute().packChute();
try
{
if (SHOULD_RETRY_FAILED_ALLOCS)
{
int allocationAttempts = 0;
int backoffTimeout = 10; // start at 10 milliseconds
while (true)
{
try
{
// log.debug("attempting malloc of size: {}", size);
retval = new byte[size]; // depends on control dependency: [try], data = [none]
// log.debug("malloced block of size: {}", size);
// we succeed, so break out
break;
}
catch (final OutOfMemoryError e)
{
// try clearing our queue now and do it again. Why?
// because the first failure may have allowed us to
// catch a RefCounted no longer in use, and the second
// attempt may have freed that memory.
// do a JNI collect before the alloc
++allocationAttempts;
if (allocationAttempts >= MAX_ALLOCATION_ATTEMPTS)
{
// try pulling our rip cord
JNIMemoryParachute.getParachute().pullCord(); // depends on control dependency: [if], data = [none]
// do one last "hope gc" to free our own memory
JNIReference.getMgr().gcInternal(); // depends on control dependency: [if], data = [none]
// and throw the error back to the native code
throw e;
}
log.debug("retrying ({}) allocation of {} bytes",
allocationAttempts, size);
try
{
// give the finalizer a chance
if (allocationAttempts <= 1)
{
// first just yield
Thread.yield(); // depends on control dependency: [if], data = [none]
}
else
{
Thread.sleep(backoffTimeout); // depends on control dependency: [if], data = [none]
// and slowly get longer...
backoffTimeout = (int) (backoffTimeout * FALLBACK_TIME_DECAY); // depends on control dependency: [if], data = [none]
}
}
catch (InterruptedException e1)
{
// reset the interruption so underlying
// code can also interrupt
Thread.currentThread().interrupt();
// and throw the error condition
throw e;
} // depends on control dependency: [catch], data = [none]
// do a JNI collect before the alloc
JNIReference.getMgr().gcInternal();
} // depends on control dependency: [catch], data = [none]
}
}
else
{
retval = new byte[size]; // depends on control dependency: [if], data = [none]
}
addToBuffer(retval); // depends on control dependency: [try], data = [none]
retval[retval.length - 1] = 0; // depends on control dependency: [try], data = [none]
// log.debug("malloc: {}({}:{})", new Object[]
// {
// retval.hashCode(), retval.length, size
// });
}
catch (Throwable t)
{
// do not let an exception leak out since we go back to native code.
retval = null;
} // depends on control dependency: [catch], data = [none]
return retval;
} } |
public class class_name {
public static String toStr(Number number) {
if (null == number) {
throw new NullPointerException("Number is null !");
}
if (false == ObjectUtil.isValidIfNumber(number)) {
throw new IllegalArgumentException("Number is non-finite!");
}
// 去掉小数点儿后多余的0
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} } | public class class_name {
public static String toStr(Number number) {
if (null == number) {
throw new NullPointerException("Number is null !");
}
if (false == ObjectUtil.isValidIfNumber(number)) {
throw new IllegalArgumentException("Number is non-finite!");
}
// 去掉小数点儿后多余的0
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
// depends on control dependency: [while], data = [none]
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
// depends on control dependency: [if], data = [none]
}
}
return string;
} } |
public class class_name {
public Map<String, String> results(OutputVariable outputVariable, TimeUnit timeUnit, boolean includeTimes) {
if (engine == null) {
throw new RuntimeException("[benchmark error] engine not set for benchmark");
}
double[] runtimes = new double[times.size()];
for (int i = 0; i < times.size(); ++i) {
runtimes[i] = times.get(i);
}
Map<String, String> result = new LinkedHashMap<String, String>();
result.put("library", FuzzyLite.LIBRARY);
result.put("name", name);
result.put("inputs", String.valueOf(engine.numberOfInputVariables()));
result.put("outputs", String.valueOf(engine.numberOfOutputVariables()));
result.put("ruleBlocks", String.valueOf(engine.numberOfRuleBlocks()));
int rules = 0;
for (RuleBlock ruleBlock : engine.getRuleBlocks()) {
rules += ruleBlock.numberOfRules();
}
result.put("rules", String.valueOf(rules));
result.put("runs", String.valueOf(times.size()));
result.put("evaluations", String.valueOf(expected.size()));
if (canComputeErrors()) {
List<String> names = new LinkedList<String>();
double meanRange = 0.0;
double rmse = Math.sqrt(meanSquaredError());
double nrmse = 0.0;
double weights = 0.0;
for (OutputVariable y : engine.getOutputVariables()) {
if (outputVariable == null || outputVariable == y) {
names.add(y.getName());
meanRange += y.range();
nrmse += Math.sqrt(meanSquaredError(y)) * 1.0 / y.range();
weights += 1.0 / y.range();
}
}
meanRange /= names.size();
nrmse /= weights;
result.put("outputVariable", Op.join(names, ","));
result.put("range", Op.str(meanRange));
result.put("tolerance", String.format("%6.3e", getTolerance()));
result.put("errors", String.valueOf(allErrors(outputVariable)));
result.put("nfErrors", String.valueOf(nonFiniteErrors(outputVariable)));
result.put("accErrors", String.valueOf(accuracyErrors(outputVariable)));
result.put("rmse", String.format("%6.6e", rmse));
result.put("nrmse", String.format("%6.6e", nrmse));
}
result.put("units", timeUnit.name().toLowerCase());
result.put("sum(t)", String.valueOf(
convert(Op.sum(runtimes), TimeUnit.NanoSeconds, timeUnit)));
result.put("mean(t)", String.valueOf(
convert(Op.mean(runtimes), TimeUnit.NanoSeconds, timeUnit)));
result.put("sd(t)", String.valueOf(
convert(Op.standardDeviation(runtimes), TimeUnit.NanoSeconds, timeUnit)));
if (includeTimes) {
for (int i = 0; i < runtimes.length; ++i) {
result.put("t" + (i + 1), String.valueOf(
convert(runtimes[i], TimeUnit.NanoSeconds, timeUnit)));
}
}
return result;
} } | public class class_name {
public Map<String, String> results(OutputVariable outputVariable, TimeUnit timeUnit, boolean includeTimes) {
if (engine == null) {
throw new RuntimeException("[benchmark error] engine not set for benchmark");
}
double[] runtimes = new double[times.size()];
for (int i = 0; i < times.size(); ++i) {
runtimes[i] = times.get(i); // depends on control dependency: [for], data = [i]
}
Map<String, String> result = new LinkedHashMap<String, String>();
result.put("library", FuzzyLite.LIBRARY);
result.put("name", name);
result.put("inputs", String.valueOf(engine.numberOfInputVariables()));
result.put("outputs", String.valueOf(engine.numberOfOutputVariables()));
result.put("ruleBlocks", String.valueOf(engine.numberOfRuleBlocks()));
int rules = 0;
for (RuleBlock ruleBlock : engine.getRuleBlocks()) {
rules += ruleBlock.numberOfRules(); // depends on control dependency: [for], data = [ruleBlock]
}
result.put("rules", String.valueOf(rules));
result.put("runs", String.valueOf(times.size()));
result.put("evaluations", String.valueOf(expected.size()));
if (canComputeErrors()) {
List<String> names = new LinkedList<String>();
double meanRange = 0.0;
double rmse = Math.sqrt(meanSquaredError());
double nrmse = 0.0;
double weights = 0.0;
for (OutputVariable y : engine.getOutputVariables()) {
if (outputVariable == null || outputVariable == y) {
names.add(y.getName()); // depends on control dependency: [if], data = [none]
meanRange += y.range(); // depends on control dependency: [if], data = [none]
nrmse += Math.sqrt(meanSquaredError(y)) * 1.0 / y.range(); // depends on control dependency: [if], data = [none]
weights += 1.0 / y.range(); // depends on control dependency: [if], data = [none]
}
}
meanRange /= names.size(); // depends on control dependency: [if], data = [none]
nrmse /= weights; // depends on control dependency: [if], data = [none]
result.put("outputVariable", Op.join(names, ",")); // depends on control dependency: [if], data = [none]
result.put("range", Op.str(meanRange)); // depends on control dependency: [if], data = [none]
result.put("tolerance", String.format("%6.3e", getTolerance())); // depends on control dependency: [if], data = [none]
result.put("errors", String.valueOf(allErrors(outputVariable))); // depends on control dependency: [if], data = [none]
result.put("nfErrors", String.valueOf(nonFiniteErrors(outputVariable))); // depends on control dependency: [if], data = [none]
result.put("accErrors", String.valueOf(accuracyErrors(outputVariable))); // depends on control dependency: [if], data = [none]
result.put("rmse", String.format("%6.6e", rmse)); // depends on control dependency: [if], data = [none]
result.put("nrmse", String.format("%6.6e", nrmse)); // depends on control dependency: [if], data = [none]
}
result.put("units", timeUnit.name().toLowerCase());
result.put("sum(t)", String.valueOf(
convert(Op.sum(runtimes), TimeUnit.NanoSeconds, timeUnit)));
result.put("mean(t)", String.valueOf(
convert(Op.mean(runtimes), TimeUnit.NanoSeconds, timeUnit)));
result.put("sd(t)", String.valueOf(
convert(Op.standardDeviation(runtimes), TimeUnit.NanoSeconds, timeUnit)));
if (includeTimes) {
for (int i = 0; i < runtimes.length; ++i) {
result.put("t" + (i + 1), String.valueOf(
convert(runtimes[i], TimeUnit.NanoSeconds, timeUnit))); // depends on control dependency: [for], data = [i]
}
}
return result;
} } |
public class class_name {
private void fireSocketOpened(final String remoteInfo) {
synchronized (listenerList) {
for (Iterator iter = listenerList.iterator(); iter.hasNext();) {
SocketNodeEventListener snel =
(SocketNodeEventListener) iter.next();
if (snel != null) {
snel.socketOpened(remoteInfo);
}
}
}
} } | public class class_name {
private void fireSocketOpened(final String remoteInfo) {
synchronized (listenerList) {
for (Iterator iter = listenerList.iterator(); iter.hasNext();) {
SocketNodeEventListener snel =
(SocketNodeEventListener) iter.next();
if (snel != null) {
snel.socketOpened(remoteInfo); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public GetTemplateSummaryResult withCapabilities(Capability... capabilities) {
com.amazonaws.internal.SdkInternalList<String> capabilitiesCopy = new com.amazonaws.internal.SdkInternalList<String>(capabilities.length);
for (Capability value : capabilities) {
capabilitiesCopy.add(value.toString());
}
if (getCapabilities() == null) {
setCapabilities(capabilitiesCopy);
} else {
getCapabilities().addAll(capabilitiesCopy);
}
return this;
} } | public class class_name {
public GetTemplateSummaryResult withCapabilities(Capability... capabilities) {
com.amazonaws.internal.SdkInternalList<String> capabilitiesCopy = new com.amazonaws.internal.SdkInternalList<String>(capabilities.length);
for (Capability value : capabilities) {
capabilitiesCopy.add(value.toString()); // depends on control dependency: [for], data = [value]
}
if (getCapabilities() == null) {
setCapabilities(capabilitiesCopy); // depends on control dependency: [if], data = [none]
} else {
getCapabilities().addAll(capabilitiesCopy); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public static String generatePartitionPath(LinkedHashMap<String, String> partitions) {
StringBuilder builder = new StringBuilder();
for(Map.Entry<String, String> pair: partitions.entrySet()) {
builder.append(String.format(PARTITION_PATH, pair.getKey(), pair.getValue()));
}
return builder.toString();
} } | public class class_name {
public static String generatePartitionPath(LinkedHashMap<String, String> partitions) {
StringBuilder builder = new StringBuilder();
for(Map.Entry<String, String> pair: partitions.entrySet()) {
builder.append(String.format(PARTITION_PATH, pair.getKey(), pair.getValue())); // depends on control dependency: [for], data = [pair]
}
return builder.toString();
} } |
public class class_name {
public static void uninstallModule(String moduleName) {
Module module = INSTALLED_MODULES.get(moduleName);
if (module != null) {
try {
module.uninstall();
INSTALLED_MODULES.remove(moduleName);
} catch (Exception e) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Error when uninstall module " + moduleName, e);
}
}
}
} } | public class class_name {
public static void uninstallModule(String moduleName) {
Module module = INSTALLED_MODULES.get(moduleName);
if (module != null) {
try {
module.uninstall(); // depends on control dependency: [try], data = [none]
INSTALLED_MODULES.remove(moduleName); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Error when uninstall module " + moduleName, e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
void getLuma22Unsafe(byte[] pic, int picW, int imgH, byte[] blk, int blkOff, int blkStride, int x, int y,
int blkW, int blkH) {
getLuma20UnsafeNoRound(pic, picW, imgH, tmp1, 0, blkW, x, y - 2, blkW, blkH + 7);
getLuma02NoRoundInt(tmp1, blkW, tmp2, blkOff, blkStride, 0, 2, blkW, blkH);
for (int j = 0; j < blkH; j++) {
for (int i = 0; i < blkW; i++) {
blk[blkOff + i] = (byte) clip((tmp2[blkOff + i] + 512) >> 10, -128, 127);
}
blkOff += blkStride;
}
} } | public class class_name {
void getLuma22Unsafe(byte[] pic, int picW, int imgH, byte[] blk, int blkOff, int blkStride, int x, int y,
int blkW, int blkH) {
getLuma20UnsafeNoRound(pic, picW, imgH, tmp1, 0, blkW, x, y - 2, blkW, blkH + 7);
getLuma02NoRoundInt(tmp1, blkW, tmp2, blkOff, blkStride, 0, 2, blkW, blkH);
for (int j = 0; j < blkH; j++) {
for (int i = 0; i < blkW; i++) {
blk[blkOff + i] = (byte) clip((tmp2[blkOff + i] + 512) >> 10, -128, 127); // depends on control dependency: [for], data = [i]
}
blkOff += blkStride; // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
private void doRun() throws InterruptedException {
boolean migrating = false;
for (; ; ) {
if (!migrationManager.areMigrationTasksAllowed()) {
break;
}
MigrationRunnable runnable = queue.poll(1, TimeUnit.SECONDS);
if (runnable == null) {
break;
}
migrating |= runnable instanceof MigrationManager.MigrateTask;
processTask(runnable);
if (migrating && partitionMigrationInterval > 0) {
Thread.sleep(partitionMigrationInterval);
}
}
boolean hasNoTasks = !queue.hasMigrationTasks();
if (hasNoTasks) {
if (migrating) {
logger.info("All migration tasks have been completed. ("
+ migrationManager.getStats().formatToString(logger.isFineEnabled()) + ")");
}
Thread.sleep(sleepTime);
} else if (!migrationManager.areMigrationTasksAllowed()) {
Thread.sleep(sleepTime);
}
} } | public class class_name {
private void doRun() throws InterruptedException {
boolean migrating = false;
for (; ; ) {
if (!migrationManager.areMigrationTasksAllowed()) {
break;
}
MigrationRunnable runnable = queue.poll(1, TimeUnit.SECONDS);
if (runnable == null) {
break;
}
migrating |= runnable instanceof MigrationManager.MigrateTask;
processTask(runnable);
if (migrating && partitionMigrationInterval > 0) {
Thread.sleep(partitionMigrationInterval); // depends on control dependency: [if], data = [none]
}
}
boolean hasNoTasks = !queue.hasMigrationTasks();
if (hasNoTasks) {
if (migrating) {
logger.info("All migration tasks have been completed. ("
+ migrationManager.getStats().formatToString(logger.isFineEnabled()) + ")"); // depends on control dependency: [if], data = [none]
}
Thread.sleep(sleepTime);
} else if (!migrationManager.areMigrationTasksAllowed()) {
Thread.sleep(sleepTime);
}
} } |
public class class_name {
private View configureHeader(WrapperView wv, final int position) {
View header = wv.mHeader == null ? popHeader() : wv.mHeader;
header = mDelegate.getHeaderView(position, header, wv);
if (header == null) {
throw new NullPointerException("Header view must not be null.");
}
//if the header isn't clickable, the listselector will be drawn on top of the header
header.setClickable(true);
header.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mOnHeaderClickListener != null){
long headerId = mDelegate.getHeaderId(position);
mOnHeaderClickListener.onHeaderClick(v, position, headerId);
}
}
});
return header;
} } | public class class_name {
private View configureHeader(WrapperView wv, final int position) {
View header = wv.mHeader == null ? popHeader() : wv.mHeader;
header = mDelegate.getHeaderView(position, header, wv);
if (header == null) {
throw new NullPointerException("Header view must not be null.");
}
//if the header isn't clickable, the listselector will be drawn on top of the header
header.setClickable(true);
header.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mOnHeaderClickListener != null){
long headerId = mDelegate.getHeaderId(position);
mOnHeaderClickListener.onHeaderClick(v, position, headerId); // depends on control dependency: [if], data = [none]
}
}
});
return header;
} } |
public class class_name {
public void marshall(DescribeMetricFiltersRequest describeMetricFiltersRequest, ProtocolMarshaller protocolMarshaller) {
if (describeMetricFiltersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeMetricFiltersRequest.getLogGroupName(), LOGGROUPNAME_BINDING);
protocolMarshaller.marshall(describeMetricFiltersRequest.getFilterNamePrefix(), FILTERNAMEPREFIX_BINDING);
protocolMarshaller.marshall(describeMetricFiltersRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(describeMetricFiltersRequest.getLimit(), LIMIT_BINDING);
protocolMarshaller.marshall(describeMetricFiltersRequest.getMetricName(), METRICNAME_BINDING);
protocolMarshaller.marshall(describeMetricFiltersRequest.getMetricNamespace(), METRICNAMESPACE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DescribeMetricFiltersRequest describeMetricFiltersRequest, ProtocolMarshaller protocolMarshaller) {
if (describeMetricFiltersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeMetricFiltersRequest.getLogGroupName(), LOGGROUPNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(describeMetricFiltersRequest.getFilterNamePrefix(), FILTERNAMEPREFIX_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(describeMetricFiltersRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(describeMetricFiltersRequest.getLimit(), LIMIT_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(describeMetricFiltersRequest.getMetricName(), METRICNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(describeMetricFiltersRequest.getMetricNamespace(), METRICNAMESPACE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public BusinessRemoteWrapper getRemoteBusinessWrapper(WrapperId wrapperId)
{
int remoteIndex = wrapperId.ivInterfaceIndex;
BusinessRemoteWrapper wrapper = null;
String wrapperInterfaceName = "";
if (remoteIndex < ivBusinessRemote.length)
{
wrapper = ivBusinessRemote[remoteIndex];
wrapperInterfaceName = ivBMD.ivBusinessRemoteInterfaceClasses[remoteIndex].getName();
}
// Is the BusinessRemoteWrapper for the correct interface name?
String interfaceName = wrapperId.ivInterfaceClassName;
if ((wrapper == null) || (!wrapperInterfaceName.equals(interfaceName)))
{
// Nope, index must be invalid, so we need to search the entire
// array to find the one that matches the desired interface name.
// Fix up the WrapperId with index that matches this server.
wrapper = null;
for (int i = 0; i < ivBusinessRemote.length; ++i)
{
wrapperInterfaceName = ivBMD.ivBusinessRemoteInterfaceClasses[i].getName();
if (wrapperInterfaceName.equals(interfaceName))
{
// This is the correct wrapper.
remoteIndex = i;
wrapper = ivBusinessRemote[remoteIndex];
wrapperId.ivInterfaceIndex = remoteIndex;
break;
}
}
// d739542 Begin
if (wrapper == null) {
throw new IllegalStateException("Remote " + interfaceName + " interface not defined");
}
// d739542 End
}
registerServant(wrapper, remoteIndex);
return wrapper;
} } | public class class_name {
public BusinessRemoteWrapper getRemoteBusinessWrapper(WrapperId wrapperId)
{
int remoteIndex = wrapperId.ivInterfaceIndex;
BusinessRemoteWrapper wrapper = null;
String wrapperInterfaceName = "";
if (remoteIndex < ivBusinessRemote.length)
{
wrapper = ivBusinessRemote[remoteIndex]; // depends on control dependency: [if], data = [none]
wrapperInterfaceName = ivBMD.ivBusinessRemoteInterfaceClasses[remoteIndex].getName(); // depends on control dependency: [if], data = [none]
}
// Is the BusinessRemoteWrapper for the correct interface name?
String interfaceName = wrapperId.ivInterfaceClassName;
if ((wrapper == null) || (!wrapperInterfaceName.equals(interfaceName)))
{
// Nope, index must be invalid, so we need to search the entire
// array to find the one that matches the desired interface name.
// Fix up the WrapperId with index that matches this server.
wrapper = null; // depends on control dependency: [if], data = [none]
for (int i = 0; i < ivBusinessRemote.length; ++i)
{
wrapperInterfaceName = ivBMD.ivBusinessRemoteInterfaceClasses[i].getName(); // depends on control dependency: [for], data = [i]
if (wrapperInterfaceName.equals(interfaceName))
{
// This is the correct wrapper.
remoteIndex = i; // depends on control dependency: [if], data = [none]
wrapper = ivBusinessRemote[remoteIndex]; // depends on control dependency: [if], data = [none]
wrapperId.ivInterfaceIndex = remoteIndex; // depends on control dependency: [if], data = [none]
break;
}
}
// d739542 Begin
if (wrapper == null) {
throw new IllegalStateException("Remote " + interfaceName + " interface not defined");
}
// d739542 End
}
registerServant(wrapper, remoteIndex);
return wrapper;
} } |
public class class_name {
public void marshall(StartContentModerationRequest startContentModerationRequest, ProtocolMarshaller protocolMarshaller) {
if (startContentModerationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startContentModerationRequest.getVideo(), VIDEO_BINDING);
protocolMarshaller.marshall(startContentModerationRequest.getMinConfidence(), MINCONFIDENCE_BINDING);
protocolMarshaller.marshall(startContentModerationRequest.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING);
protocolMarshaller.marshall(startContentModerationRequest.getNotificationChannel(), NOTIFICATIONCHANNEL_BINDING);
protocolMarshaller.marshall(startContentModerationRequest.getJobTag(), JOBTAG_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(StartContentModerationRequest startContentModerationRequest, ProtocolMarshaller protocolMarshaller) {
if (startContentModerationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startContentModerationRequest.getVideo(), VIDEO_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startContentModerationRequest.getMinConfidence(), MINCONFIDENCE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startContentModerationRequest.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startContentModerationRequest.getNotificationChannel(), NOTIFICATIONCHANNEL_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(startContentModerationRequest.getJobTag(), JOBTAG_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Position add( Position position ) {
if (this.getIndexInContent() < 0) {
return position.getIndexInContent() < 0 ? EMPTY_CONTENT_POSITION : position;
}
if (position.getIndexInContent() < 0) {
return this;
}
int index = this.getIndexInContent() + position.getIndexInContent();
int line = position.getLine() + this.getLine() - 1;
int column = this.getLine() == 1 ? this.getColumn() + position.getColumn() : this.getColumn();
return new Position(index, line, column);
} } | public class class_name {
public Position add( Position position ) {
if (this.getIndexInContent() < 0) {
return position.getIndexInContent() < 0 ? EMPTY_CONTENT_POSITION : position; // depends on control dependency: [if], data = [none]
}
if (position.getIndexInContent() < 0) {
return this; // depends on control dependency: [if], data = [none]
}
int index = this.getIndexInContent() + position.getIndexInContent();
int line = position.getLine() + this.getLine() - 1;
int column = this.getLine() == 1 ? this.getColumn() + position.getColumn() : this.getColumn();
return new Position(index, line, column);
} } |
public class class_name {
private static void loadConfig(String workingDirectory) {
String oldWorkingDirectory = System.getProperty(USER_DIR);
if (workingDirectory != null) {
System.setProperty(USER_DIR, workingDirectory);
}
try {
Config.loadConfig();
} finally {
System.setProperty(USER_DIR, oldWorkingDirectory);
}
} } | public class class_name {
private static void loadConfig(String workingDirectory) {
String oldWorkingDirectory = System.getProperty(USER_DIR);
if (workingDirectory != null) {
System.setProperty(USER_DIR, workingDirectory); // depends on control dependency: [if], data = [none]
}
try {
Config.loadConfig(); // depends on control dependency: [try], data = [none]
} finally {
System.setProperty(USER_DIR, oldWorkingDirectory);
}
} } |
public class class_name {
private static long timeFromQualifier(final byte[] qualifier,
final long base_time) {
final long offset;
if (qualifier.length == 3) {
offset = Bytes.getUnsignedShort(qualifier, 1);
return (base_time + offset) * 1000;
} else {
offset = Bytes.getUnsignedInt(qualifier, 1);
return (base_time * 1000) + offset;
}
} } | public class class_name {
private static long timeFromQualifier(final byte[] qualifier,
final long base_time) {
final long offset;
if (qualifier.length == 3) {
offset = Bytes.getUnsignedShort(qualifier, 1); // depends on control dependency: [if], data = [none]
return (base_time + offset) * 1000; // depends on control dependency: [if], data = [none]
} else {
offset = Bytes.getUnsignedInt(qualifier, 1); // depends on control dependency: [if], data = [none]
return (base_time * 1000) + offset; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public double score(DataSet data, boolean training) {
try{
return scoreHelper(data, training);
} catch (OutOfMemoryError e){
CrashReportingUtil.writeMemoryCrashDump(this, e);
throw e;
}
} } | public class class_name {
public double score(DataSet data, boolean training) {
try{
return scoreHelper(data, training); // depends on control dependency: [try], data = [none]
} catch (OutOfMemoryError e){
CrashReportingUtil.writeMemoryCrashDump(this, e);
throw e;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public boolean filter(Object entity) {
for (Filter filter : filters) {
if (filter.filter(entity)) {
return true;
}
}
return false;
} } | public class class_name {
@Override
public boolean filter(Object entity) {
for (Filter filter : filters) {
if (filter.filter(entity)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
@Generated(value = "com.sun.tools.xjc.Driver", date = "2018-10-12T02:50:55+02:00", comments = "JAXB RI v2.2.11")
public List<LandUndForstwirtschaft> getLandUndForstwirtschaft() {
if (landUndForstwirtschaft == null) {
landUndForstwirtschaft = new ArrayList<LandUndForstwirtschaft>();
}
return this.landUndForstwirtschaft;
} } | public class class_name {
@Generated(value = "com.sun.tools.xjc.Driver", date = "2018-10-12T02:50:55+02:00", comments = "JAXB RI v2.2.11")
public List<LandUndForstwirtschaft> getLandUndForstwirtschaft() {
if (landUndForstwirtschaft == null) {
landUndForstwirtschaft = new ArrayList<LandUndForstwirtschaft>(); // depends on control dependency: [if], data = [none]
}
return this.landUndForstwirtschaft;
} } |
public class class_name {
public boolean writeFile(File file, List<String> lines){
if(file.exists()){
file.delete();
}
try {
FileWriter out = new FileWriter(file);
for(String s : lines){
out.write(s);
out.write(System.getProperty("line.separator"));
}
out.close();
file.setExecutable(true);
}
catch (IOException ex) {
System.err.println(this.getAppName() + ": IO exception while writing to file - " + file + " with message: " + ex.getMessage());
return false;
}
return true;
} } | public class class_name {
public boolean writeFile(File file, List<String> lines){
if(file.exists()){
file.delete();
// depends on control dependency: [if], data = [none]
}
try {
FileWriter out = new FileWriter(file);
for(String s : lines){
out.write(s);
out.write(System.getProperty("line.separator"));
}
out.close();
file.setExecutable(true);
}
catch (IOException ex) {
System.err.println(this.getAppName() + ": IO exception while writing to file - " + file + " with message: " + ex.getMessage());
return false;
}
return true;
} } |
public class class_name {
public static void initEndpointDirectories(MuleContext muleContext, String[] serviceNames, String[] endpointNames) throws Exception {
// Stop all named services (either Flows or services
List<Lifecycle> services = new ArrayList<Lifecycle>();
for (String serviceName : serviceNames) {
try {
Lifecycle service = muleContext.getRegistry().lookupObject(serviceName);
// logServiceStatus(service);
// service.stop();
// logServiceStatus(service);
services.add(service);
} catch (Exception e) {
logger.error("Error '" + e.getMessage()
+ "' occured while stopping the service " + serviceName
+ ". Perhaps the service did not exist in the config?");
throw e;
}
}
// Now init the directory for each named endpoint, one by one
for (String endpointName : endpointNames) {
initEndpointDirectory(muleContext, endpointName);
}
// We are done, startup the services again so that the test can begin...
for (@SuppressWarnings("unused") Lifecycle service : services) {
// logServiceStatus(service);
// service.start();
// logServiceStatus(service);
}
} } | public class class_name {
public static void initEndpointDirectories(MuleContext muleContext, String[] serviceNames, String[] endpointNames) throws Exception {
// Stop all named services (either Flows or services
List<Lifecycle> services = new ArrayList<Lifecycle>();
for (String serviceName : serviceNames) {
try {
Lifecycle service = muleContext.getRegistry().lookupObject(serviceName);
// logServiceStatus(service);
// service.stop();
// logServiceStatus(service);
services.add(service); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("Error '" + e.getMessage()
+ "' occured while stopping the service " + serviceName
+ ". Perhaps the service did not exist in the config?");
throw e;
} // depends on control dependency: [catch], data = [none]
}
// Now init the directory for each named endpoint, one by one
for (String endpointName : endpointNames) {
initEndpointDirectory(muleContext, endpointName);
}
// We are done, startup the services again so that the test can begin...
for (@SuppressWarnings("unused") Lifecycle service : services) {
// logServiceStatus(service);
// service.start();
// logServiceStatus(service);
}
} } |
public class class_name {
public void add(int var, Type t) {
Set<Integer> tVars = t.getTypeVariables();
Set<Integer> intersection = Sets.intersection(tVars, bindings.keySet());
Preconditions.checkArgument(intersection.size() == 0,
"Tried to replace %s with %s, but already have bindings for %s", var, t, intersection);
Preconditions.checkArgument(!tVars.contains(var),
"Recursive replacement: tried to replace %s with %s", var, t);
Map<Integer, Type> newBinding = Maps.newHashMap();
newBinding.put(var, t);
for (int boundVar : bindings.keySet()) {
bindings.put(boundVar, bindings.get(boundVar).substitute(newBinding));
}
bindings.put(var, t);
} } | public class class_name {
public void add(int var, Type t) {
Set<Integer> tVars = t.getTypeVariables();
Set<Integer> intersection = Sets.intersection(tVars, bindings.keySet());
Preconditions.checkArgument(intersection.size() == 0,
"Tried to replace %s with %s, but already have bindings for %s", var, t, intersection);
Preconditions.checkArgument(!tVars.contains(var),
"Recursive replacement: tried to replace %s with %s", var, t);
Map<Integer, Type> newBinding = Maps.newHashMap();
newBinding.put(var, t);
for (int boundVar : bindings.keySet()) {
bindings.put(boundVar, bindings.get(boundVar).substitute(newBinding)); // depends on control dependency: [for], data = [boundVar]
}
bindings.put(var, t);
} } |
public class class_name {
public static String PUT(String path, String host, long length, boolean append) {
String newPath = null;
if (append) {
newPath = APPEND_URI + "/" + path;
} else {
newPath = "/" + path;
}
return HTTPProtocol.createPUTHeader(newPath, host, USER_AGENT,
TYPE, length, append);
} } | public class class_name {
public static String PUT(String path, String host, long length, boolean append) {
String newPath = null;
if (append) {
newPath = APPEND_URI + "/" + path; // depends on control dependency: [if], data = [none]
} else {
newPath = "/" + path; // depends on control dependency: [if], data = [none]
}
return HTTPProtocol.createPUTHeader(newPath, host, USER_AGENT,
TYPE, length, append);
} } |
public class class_name {
public void handlePending() {
if (this.throttleEngine) {
final TemplateFlowController controller = this.flowController;
if (controller.stopProcessing) {
controller.processorTemplateHandlerPending = true;
return;
}
// Execution of pending tasks will be done from the last one to be stopped to the newest one, so that
// all nested executions of the ProcessorTemplateHandler are correctly managed.
while (this.pendingProcessingsSize > 0) {
final boolean processed = this.pendingProcessings[this.pendingProcessingsSize - 1].process();
if (!processed) {
// Couldn't finish -- we were stopped again. This handlePending() will need to be called
// again the next time the throttling mechanism is asked to produce more output.
controller.processorTemplateHandlerPending = true;
return;
}
this.pendingProcessingsSize--;
}
// All pending jobs finished
controller.processorTemplateHandlerPending = false;
}
} } | public class class_name {
public void handlePending() {
if (this.throttleEngine) {
final TemplateFlowController controller = this.flowController;
if (controller.stopProcessing) {
controller.processorTemplateHandlerPending = true; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// Execution of pending tasks will be done from the last one to be stopped to the newest one, so that
// all nested executions of the ProcessorTemplateHandler are correctly managed.
while (this.pendingProcessingsSize > 0) {
final boolean processed = this.pendingProcessings[this.pendingProcessingsSize - 1].process();
if (!processed) {
// Couldn't finish -- we were stopped again. This handlePending() will need to be called
// again the next time the throttling mechanism is asked to produce more output.
controller.processorTemplateHandlerPending = true; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.pendingProcessingsSize--; // depends on control dependency: [while], data = [none]
}
// All pending jobs finished
controller.processorTemplateHandlerPending = false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setMimeType(MimeType mimeType) {
if (mimeType != null) {
getState().mimeType = mimeType.getMimeType();
} else {
getState().mimeType = null;
}
} } | public class class_name {
public void setMimeType(MimeType mimeType) {
if (mimeType != null) {
getState().mimeType = mimeType.getMimeType();
// depends on control dependency: [if], data = [none]
} else {
getState().mimeType = null;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public CommandLine setAtFileCommentChar(Character atFileCommentChar) {
getCommandSpec().parser().atFileCommentChar(atFileCommentChar);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setAtFileCommentChar(atFileCommentChar);
}
return this;
} } | public class class_name {
public CommandLine setAtFileCommentChar(Character atFileCommentChar) {
getCommandSpec().parser().atFileCommentChar(atFileCommentChar);
for (CommandLine command : getCommandSpec().subcommands().values()) {
command.setAtFileCommentChar(atFileCommentChar); // depends on control dependency: [for], data = [command]
}
return this;
} } |
public class class_name {
@Override
public MappedByteBuffer map(MapMode mode, long position, long size) throws IOException
{
ByteBuffer writeView;
if (MapMode.READ_WRITE == mode)
{
writeView = file.writeView(Casts.castInt(position), Casts.castInt(size));
}
else
{
if (MapMode.READ_ONLY == mode)
{
writeView = file.readView(Casts.castInt(position));
}
else
{
throw new UnsupportedOperationException(mode+" not supported");
}
}
if (writeView instanceof MappedByteBuffer)
{
ByteBuffer slice = writeView.slice();
return (MappedByteBuffer) slice;
}
else
{
throw new UnsupportedOperationException("Not supported yet.");
}
} } | public class class_name {
@Override
public MappedByteBuffer map(MapMode mode, long position, long size) throws IOException
{
ByteBuffer writeView;
if (MapMode.READ_WRITE == mode)
{
writeView = file.writeView(Casts.castInt(position), Casts.castInt(size));
}
else
{
if (MapMode.READ_ONLY == mode)
{
writeView = file.readView(Casts.castInt(position));
// depends on control dependency: [if], data = [none]
}
else
{
throw new UnsupportedOperationException(mode+" not supported");
}
}
if (writeView instanceof MappedByteBuffer)
{
ByteBuffer slice = writeView.slice();
return (MappedByteBuffer) slice;
}
else
{
throw new UnsupportedOperationException("Not supported yet.");
}
} } |
public class class_name {
public static PageFlowStack get( HttpServletRequest request, ServletContext servletContext, boolean createIfNotExist )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = PageFlowUtils.unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
String attrName = ScopedServletUtils.getScopedSessionAttrName( JPF_STACK_ATTR, unwrappedRequest );
PageFlowStack jpfStack = ( PageFlowStack ) sh.getAttribute( rc, attrName );
if ( jpfStack == null && createIfNotExist )
{
jpfStack = new PageFlowStack( servletContext );
jpfStack.save( request );
}
else if ( jpfStack != null )
{
jpfStack.setServletContext( servletContext );
}
return jpfStack;
} } | public class class_name {
public static PageFlowStack get( HttpServletRequest request, ServletContext servletContext, boolean createIfNotExist )
{
StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
HttpServletRequest unwrappedRequest = PageFlowUtils.unwrapMultipart( request );
RequestContext rc = new RequestContext( unwrappedRequest, null );
String attrName = ScopedServletUtils.getScopedSessionAttrName( JPF_STACK_ATTR, unwrappedRequest );
PageFlowStack jpfStack = ( PageFlowStack ) sh.getAttribute( rc, attrName );
if ( jpfStack == null && createIfNotExist )
{
jpfStack = new PageFlowStack( servletContext ); // depends on control dependency: [if], data = [none]
jpfStack.save( request ); // depends on control dependency: [if], data = [none]
}
else if ( jpfStack != null )
{
jpfStack.setServletContext( servletContext ); // depends on control dependency: [if], data = [none]
}
return jpfStack;
} } |
public class class_name {
public static String getVersion()
{
String rev = getBuildRevision();
Date date = getBuildDate();
StringBuilder result = new StringBuilder();
result.append(getReleaseName());
if (!"".equals(rev) || date != null)
{
result.append(" (");
boolean added = false;
if (!"".equals(rev))
{
result.append("rev. ");
result.append(rev);
added = true;
}
if (date != null)
{
result.append(added ? ", built " : "");
SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result.append(d.format(date));
}
result.append(")");
}
return result.toString();
} } | public class class_name {
public static String getVersion()
{
String rev = getBuildRevision();
Date date = getBuildDate();
StringBuilder result = new StringBuilder();
result.append(getReleaseName());
if (!"".equals(rev) || date != null)
{
result.append(" ("); // depends on control dependency: [if], data = [none]
boolean added = false;
if (!"".equals(rev))
{
result.append("rev. "); // depends on control dependency: [if], data = [none]
result.append(rev); // depends on control dependency: [if], data = [none]
added = true; // depends on control dependency: [if], data = [none]
}
if (date != null)
{
result.append(added ? ", built " : ""); // depends on control dependency: [if], data = [none]
SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result.append(d.format(date)); // depends on control dependency: [if], data = [(date]
}
result.append(")"); // depends on control dependency: [if], data = [none]
}
return result.toString();
} } |
public class class_name {
public void addTranslation(double[] v) {
assert (v.length == dim);
// reset inverse transformation - needs recomputation.
inv = null;
double[][] homTrans = unitMatrix(dim + 1);
for(int i = 0; i < dim; i++) {
homTrans[i][dim] = v[i];
}
trans = times(homTrans, trans);
} } | public class class_name {
public void addTranslation(double[] v) {
assert (v.length == dim);
// reset inverse transformation - needs recomputation.
inv = null;
double[][] homTrans = unitMatrix(dim + 1);
for(int i = 0; i < dim; i++) {
homTrans[i][dim] = v[i]; // depends on control dependency: [for], data = [i]
}
trans = times(homTrans, trans);
} } |
public class class_name {
private static String getCommaSeparatedStringForPathMapping(Collection<PathMapping> coll) {
StringBuilder buffer = new StringBuilder();
for (Iterator<PathMapping> eltIterator = coll.iterator(); eltIterator.hasNext();) {
PathMapping mapping = eltIterator.next();
buffer.append(mapping.getPath());
if (mapping.isRecursive()) {
buffer.append("**");
}
if (eltIterator.hasNext()) {
buffer.append(COMMA_SEPARATOR);
}
}
return buffer.toString();
} } | public class class_name {
private static String getCommaSeparatedStringForPathMapping(Collection<PathMapping> coll) {
StringBuilder buffer = new StringBuilder();
for (Iterator<PathMapping> eltIterator = coll.iterator(); eltIterator.hasNext();) {
PathMapping mapping = eltIterator.next();
buffer.append(mapping.getPath()); // depends on control dependency: [for], data = [none]
if (mapping.isRecursive()) {
buffer.append("**"); // depends on control dependency: [if], data = [none]
}
if (eltIterator.hasNext()) {
buffer.append(COMMA_SEPARATOR); // depends on control dependency: [if], data = [none]
}
}
return buffer.toString();
} } |
public class class_name {
private void checkOnClickListener(View view, AttributeSet attrs) {
final Context context = view.getContext();
if (!(context instanceof ContextWrapper) ||
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 && !ViewCompat.hasOnClickListeners(view))) {
// Skip our compat functionality if: the Context isn't a ContextWrapper, or
// the view doesn't have an OnClickListener (we can only rely on this on API 15+ so
// always use our compat code on older devices)
return;
}
final TypedArray a = context.obtainStyledAttributes(attrs, sOnClickAttrs);
final String handlerName = a.getString(0);
if (handlerName != null) {
view.setOnClickListener(new DeclaredOnClickListener(view, handlerName));
}
a.recycle();
} } | public class class_name {
private void checkOnClickListener(View view, AttributeSet attrs) {
final Context context = view.getContext();
if (!(context instanceof ContextWrapper) ||
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 && !ViewCompat.hasOnClickListeners(view))) {
// Skip our compat functionality if: the Context isn't a ContextWrapper, or
// the view doesn't have an OnClickListener (we can only rely on this on API 15+ so
// always use our compat code on older devices)
return; // depends on control dependency: [if], data = [none]
}
final TypedArray a = context.obtainStyledAttributes(attrs, sOnClickAttrs);
final String handlerName = a.getString(0);
if (handlerName != null) {
view.setOnClickListener(new DeclaredOnClickListener(view, handlerName)); // depends on control dependency: [if], data = [none]
}
a.recycle();
} } |
public class class_name {
public VoltTable sortByInput(String tableName)
{
List<ProcInputRow> sorted = new ArrayList<ProcInputRow>(m_rowsTable);
Collections.sort(sorted, new Comparator<ProcInputRow>() {
@Override
public int compare(ProcInputRow r1, ProcInputRow r2) {
return compareByInput(r2, r1); // sort descending
}
});
long totalInput = 0L;
for (ProcInputRow row : sorted) {
totalInput += (row.avgIN * row.invocations);
}
int kB = 1024;
int mB = 1024 * kB;
VoltTable result = TableShorthand.tableFromShorthand(
tableName +
"(TIMESTAMP:BIGINT," +
"PROCEDURE:VARCHAR," +
"WEIGHTED_PERC:BIGINT," +
"INVOCATIONS:BIGINT," +
"MIN_PARAMETER_SET_SIZE:BIGINT," +
"MAX_PARAMETER_SET_SIZE:BIGINT," +
"AVG_PARAMETER_SET_SIZE:BIGINT," +
"TOTAL_PARAMETER_SET_SIZE_MB:BIGINT)"
);
for (ProcInputRow row : sorted) {
result.addRow(
row.timestamp,
row.procedure,
calculatePercent((row.avgIN * row.invocations), totalInput), //% total in
row.invocations,
row.minIN,
row.maxIN,
row.avgIN,
(row.avgIN * row.invocations) / mB //total in
);
}
return result;
} } | public class class_name {
public VoltTable sortByInput(String tableName)
{
List<ProcInputRow> sorted = new ArrayList<ProcInputRow>(m_rowsTable);
Collections.sort(sorted, new Comparator<ProcInputRow>() {
@Override
public int compare(ProcInputRow r1, ProcInputRow r2) {
return compareByInput(r2, r1); // sort descending
}
});
long totalInput = 0L;
for (ProcInputRow row : sorted) {
totalInput += (row.avgIN * row.invocations); // depends on control dependency: [for], data = [row]
}
int kB = 1024;
int mB = 1024 * kB;
VoltTable result = TableShorthand.tableFromShorthand(
tableName +
"(TIMESTAMP:BIGINT," +
"PROCEDURE:VARCHAR," +
"WEIGHTED_PERC:BIGINT," +
"INVOCATIONS:BIGINT," +
"MIN_PARAMETER_SET_SIZE:BIGINT," +
"MAX_PARAMETER_SET_SIZE:BIGINT," +
"AVG_PARAMETER_SET_SIZE:BIGINT," +
"TOTAL_PARAMETER_SET_SIZE_MB:BIGINT)"
);
for (ProcInputRow row : sorted) {
result.addRow(
row.timestamp,
row.procedure,
calculatePercent((row.avgIN * row.invocations), totalInput), //% total in
row.invocations,
row.minIN,
row.maxIN,
row.avgIN,
(row.avgIN * row.invocations) / mB //total in
); // depends on control dependency: [for], data = [none]
}
return result;
} } |
public class class_name {
public static String getAccessToken(String clientId, String clientSecret, String code, String redirectUri) {
RequestBuilder call = new RequestBuilder(GRAPH_ENDPOINT + "oauth/access_token", HttpMethod.GET);
call.setTimeout(10 * 1000); // this is a somewhat crude hack but seems reasonable right now
call.addParam("client_id", clientId);
call.addParam("client_secret", clientSecret);
if (code != null || redirectUri != null) {
call.addParam("code", code);
call.addParam("redirect_uri", redirectUri);
} else
call.addParam("grant_type", "client_credentials");
try {
HttpResponse response = call.execute();
// Yet more Facebook API stupidity; if the response is OK then we parse as urlencoded params,
// otherwise we must parse as JSON and run through the error detector.
if (response.getResponseCode() == 200) {
return URLParser.parseQuery(StringUtils.read(response.getContentStream())).get("access_token");
} else {
Later<JsonNode> json = new Now<JsonNode>(new ObjectMapper().readTree(response.getContentStream()));
new ErrorDetectingWrapper(json).get(); // This should throw an exception
throw new IllegalStateException("Impossible, this should have been detected as an error: " + json);
}
} catch (IOException ex) {
throw new IOFacebookException(ex);
}
} } | public class class_name {
public static String getAccessToken(String clientId, String clientSecret, String code, String redirectUri) {
RequestBuilder call = new RequestBuilder(GRAPH_ENDPOINT + "oauth/access_token", HttpMethod.GET);
call.setTimeout(10 * 1000); // this is a somewhat crude hack but seems reasonable right now
call.addParam("client_id", clientId);
call.addParam("client_secret", clientSecret);
if (code != null || redirectUri != null) {
call.addParam("code", code);
// depends on control dependency: [if], data = [none]
call.addParam("redirect_uri", redirectUri);
// depends on control dependency: [if], data = [none]
} else
call.addParam("grant_type", "client_credentials");
try {
HttpResponse response = call.execute();
// Yet more Facebook API stupidity; if the response is OK then we parse as urlencoded params,
// otherwise we must parse as JSON and run through the error detector.
if (response.getResponseCode() == 200) {
return URLParser.parseQuery(StringUtils.read(response.getContentStream())).get("access_token");
// depends on control dependency: [if], data = [none]
} else {
Later<JsonNode> json = new Now<JsonNode>(new ObjectMapper().readTree(response.getContentStream()));
new ErrorDetectingWrapper(json).get(); // This should throw an exception
// depends on control dependency: [if], data = [none]
throw new IllegalStateException("Impossible, this should have been detected as an error: " + json);
}
} catch (IOException ex) {
throw new IOFacebookException(ex);
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public GroupedPropertyLoader splitKeyAndGroup(final String keyDelimiter) {
return group(new BiFunction<String, String, Tuple3<String, String, String>>() {
public Tuple3<String, String, String> apply(String key, String value) {
String[] keyTokens = key.split(keyDelimiter, 2);
if ( keyTokens.length == 1) {
keyTokens = new String[] {"", keyTokens[0]};
}
return Tuple3.tuple3(keyTokens[0], keyTokens[1], value);
}
});
} } | public class class_name {
public GroupedPropertyLoader splitKeyAndGroup(final String keyDelimiter) {
return group(new BiFunction<String, String, Tuple3<String, String, String>>() {
public Tuple3<String, String, String> apply(String key, String value) {
String[] keyTokens = key.split(keyDelimiter, 2);
if ( keyTokens.length == 1) {
keyTokens = new String[] {"", keyTokens[0]}; // depends on control dependency: [if], data = [none]
}
return Tuple3.tuple3(keyTokens[0], keyTokens[1], value);
}
});
} } |
public class class_name {
public Connection getConnection() throws SQLException {
Connection connection = this.pool.getConnection();
// set the Transaction Isolation if defined
try {
// set the Transaction Isolation if defined
if ((this.isolation != null) && (connection.getTransactionIsolation() != this.isolation.intValue())) {
connection.setTransactionIsolation (this.isolation.intValue());
}
// toggle autoCommit to false if set
if ( connection.getAutoCommit() != this.autocommit ){
connection.setAutoCommit(this.autocommit);
}
return connection;
} catch (SQLException e){
try {
connection.close();
} catch (Exception e2) {
logger.warn("Setting connection properties failed and closing this connection failed again", e);
}
throw e;
}
} } | public class class_name {
public Connection getConnection() throws SQLException {
Connection connection = this.pool.getConnection();
// set the Transaction Isolation if defined
try {
// set the Transaction Isolation if defined
if ((this.isolation != null) && (connection.getTransactionIsolation() != this.isolation.intValue())) {
connection.setTransactionIsolation (this.isolation.intValue());
// depends on control dependency: [if], data = [none]
}
// toggle autoCommit to false if set
if ( connection.getAutoCommit() != this.autocommit ){
connection.setAutoCommit(this.autocommit);
// depends on control dependency: [if], data = [none]
}
return connection;
} catch (SQLException e){
try {
connection.close();
// depends on control dependency: [try], data = [none]
} catch (Exception e2) {
logger.warn("Setting connection properties failed and closing this connection failed again", e);
}
// depends on control dependency: [catch], data = [none]
throw e;
}
} } |
public class class_name {
public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumType, String name) {
try {
return Optional.of(Enum.valueOf(enumType, name));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
} } | public class class_name {
public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumType, String name) {
try {
return Optional.of(Enum.valueOf(enumType, name)); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
return Optional.empty();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected boolean isArgumentSensitive(int index) {
if (methodInfo != null) {
return methodInfo.isArgSensitive(index);
}
Set<Type> parameterAnnotations = observedParameterAnnotations.get(index);
if (parameterAnnotations != null) {
return parameterAnnotations.contains(SENSITIVE_TYPE);
}
return false;
} } | public class class_name {
protected boolean isArgumentSensitive(int index) {
if (methodInfo != null) {
return methodInfo.isArgSensitive(index); // depends on control dependency: [if], data = [none]
}
Set<Type> parameterAnnotations = observedParameterAnnotations.get(index);
if (parameterAnnotations != null) {
return parameterAnnotations.contains(SENSITIVE_TYPE); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public static void loadLibrary(File extractedPath, List<String> candidates) {
for (String lib : candidates) {
File libPath = new File(extractedPath, lib);
String absPath = libPath.getAbsolutePath();
log.debug("Attempting to load dynamic library: " + absPath);
try {
System.load(absPath);
log.info("Loaded dynamic library: " + absPath);
return;
} catch (UnsatisfiedLinkError e) {
log.debug("Unable to load dynamic library: " + absPath, e);
}
}
throw new RuntimeException("Failed to load Aspera dynamic library from candidates " + candidates + " at location: " + extractedPath);
} } | public class class_name {
public static void loadLibrary(File extractedPath, List<String> candidates) {
for (String lib : candidates) {
File libPath = new File(extractedPath, lib);
String absPath = libPath.getAbsolutePath();
log.debug("Attempting to load dynamic library: " + absPath); // depends on control dependency: [for], data = [lib]
try {
System.load(absPath); // depends on control dependency: [try], data = [none]
log.info("Loaded dynamic library: " + absPath); // depends on control dependency: [try], data = [none]
return; // depends on control dependency: [try], data = [none]
} catch (UnsatisfiedLinkError e) {
log.debug("Unable to load dynamic library: " + absPath, e);
} // depends on control dependency: [catch], data = [none]
}
throw new RuntimeException("Failed to load Aspera dynamic library from candidates " + candidates + " at location: " + extractedPath);
} } |
public class class_name {
private Rectangle getVDropLineRect(JTable.DropLocation loc) {
if (!loc.isInsertColumn()) {
return null;
}
boolean ltr = table.getComponentOrientation().isLeftToRight();
int col = loc.getColumn();
Rectangle rect = table.getCellRect(loc.getRow(), col, true);
if (col >= table.getColumnCount()) {
col--;
rect = table.getCellRect(loc.getRow(), col, true);
if (ltr) {
rect.x = rect.x + rect.width;
}
} else if (!ltr) {
rect.x = rect.x + rect.width;
}
if (rect.x == 0) {
rect.x = -1;
} else {
rect.x -= 2;
}
rect.width = 3;
return rect;
} } | public class class_name {
private Rectangle getVDropLineRect(JTable.DropLocation loc) {
if (!loc.isInsertColumn()) {
return null; // depends on control dependency: [if], data = [none]
}
boolean ltr = table.getComponentOrientation().isLeftToRight();
int col = loc.getColumn();
Rectangle rect = table.getCellRect(loc.getRow(), col, true);
if (col >= table.getColumnCount()) {
col--; // depends on control dependency: [if], data = [none]
rect = table.getCellRect(loc.getRow(), col, true); // depends on control dependency: [if], data = [none]
if (ltr) {
rect.x = rect.x + rect.width; // depends on control dependency: [if], data = [none]
}
} else if (!ltr) {
rect.x = rect.x + rect.width; // depends on control dependency: [if], data = [none]
}
if (rect.x == 0) {
rect.x = -1; // depends on control dependency: [if], data = [none]
} else {
rect.x -= 2; // depends on control dependency: [if], data = [none]
}
rect.width = 3;
return rect;
} } |
public class class_name {
public CreateCommitRequest withPutFiles(PutFileEntry... putFiles) {
if (this.putFiles == null) {
setPutFiles(new java.util.ArrayList<PutFileEntry>(putFiles.length));
}
for (PutFileEntry ele : putFiles) {
this.putFiles.add(ele);
}
return this;
} } | public class class_name {
public CreateCommitRequest withPutFiles(PutFileEntry... putFiles) {
if (this.putFiles == null) {
setPutFiles(new java.util.ArrayList<PutFileEntry>(putFiles.length)); // depends on control dependency: [if], data = [none]
}
for (PutFileEntry ele : putFiles) {
this.putFiles.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private static void insertionSort(double[] keys, int[] vals, final int start, final int end) {
// Classic insertion sort.
for(int i = start + 1; i < end; i++) {
for(int j = i; j > start; j--) {
if(keys[j] >= keys[j - 1]) {
break;
}
swap(keys, vals, j, j - 1);
}
}
} } | public class class_name {
private static void insertionSort(double[] keys, int[] vals, final int start, final int end) {
// Classic insertion sort.
for(int i = start + 1; i < end; i++) {
for(int j = i; j > start; j--) {
if(keys[j] >= keys[j - 1]) {
break;
}
swap(keys, vals, j, j - 1); // depends on control dependency: [for], data = [j]
}
}
} } |
public class class_name {
private static PrintStream unbuffered(final PrintStream stream)
{
try
{
return new PrintStream(stream, true, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
return new PrintStream(stream, true);
}
} } | public class class_name {
private static PrintStream unbuffered(final PrintStream stream)
{
try
{
return new PrintStream(stream, true, "UTF-8"); // depends on control dependency: [try], data = [none]
}
catch (UnsupportedEncodingException e)
{
return new PrintStream(stream, true);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public ActionResult lookup(final ActionRequest actionRequest, final Object resultObject) {
ActionResult actionResultHandler = null;
// + read @RenderWith value on method
{
final ActionRuntime actionRuntime = actionRequest.getActionRuntime();
final Class<? extends ActionResult> actionResultClass = actionRuntime.getActionResult();
if (actionResultClass != null) {
actionResultHandler = lookupAndRegisterIfMissing(actionResultClass);
}
}
// + use @RenderWith value on resulting object if exist
if (actionResultHandler == null && resultObject != null) {
final RenderWith renderWith = resultObject.getClass().getAnnotation(RenderWith.class);
if (renderWith != null) {
actionResultHandler = lookupAndRegisterIfMissing(renderWith.value());
}
else if (resultObject instanceof ActionResult) {
// special case - returned value is already the ActionResult
actionResultHandler = (ActionResult) resultObject;
}
}
// + use action configuration
if (actionResultHandler == null) {
final ActionRuntime actionRuntime = actionRequest.getActionRuntime();
final Class<? extends ActionResult> actionResultClass = actionRuntime.getDefaultActionResult();
if (actionResultClass != null) {
actionResultHandler = lookupAndRegisterIfMissing(actionResultClass);
}
}
if (actionResultHandler == null) {
throw new MadvocException("ActionResult not found for: " + resultObject);
}
// set action result object into action request!
actionRequest.bindActionResult(resultObject);
return actionResultHandler;
} } | public class class_name {
public ActionResult lookup(final ActionRequest actionRequest, final Object resultObject) {
ActionResult actionResultHandler = null;
// + read @RenderWith value on method
{
final ActionRuntime actionRuntime = actionRequest.getActionRuntime();
final Class<? extends ActionResult> actionResultClass = actionRuntime.getActionResult();
if (actionResultClass != null) {
actionResultHandler = lookupAndRegisterIfMissing(actionResultClass); // depends on control dependency: [if], data = [(actionResultClass]
}
}
// + use @RenderWith value on resulting object if exist
if (actionResultHandler == null && resultObject != null) {
final RenderWith renderWith = resultObject.getClass().getAnnotation(RenderWith.class);
if (renderWith != null) {
actionResultHandler = lookupAndRegisterIfMissing(renderWith.value()); // depends on control dependency: [if], data = [(renderWith]
}
else if (resultObject instanceof ActionResult) {
// special case - returned value is already the ActionResult
actionResultHandler = (ActionResult) resultObject; // depends on control dependency: [if], data = [none]
}
}
// + use action configuration
if (actionResultHandler == null) {
final ActionRuntime actionRuntime = actionRequest.getActionRuntime();
final Class<? extends ActionResult> actionResultClass = actionRuntime.getDefaultActionResult();
if (actionResultClass != null) {
actionResultHandler = lookupAndRegisterIfMissing(actionResultClass); // depends on control dependency: [if], data = [(actionResultClass]
}
}
if (actionResultHandler == null) {
throw new MadvocException("ActionResult not found for: " + resultObject);
}
// set action result object into action request!
actionRequest.bindActionResult(resultObject);
return actionResultHandler;
} } |
public class class_name {
protected TypeReference<?> getBeanPropertyType(Class<?> clazz,
String propertyName, TypeReference<?> originalType) {
TypeReference<?> propertyDestinationType = null;
if (beanDestinationPropertyTypeProvider != null) {
propertyDestinationType = beanDestinationPropertyTypeProvider
.getPropertyType(clazz, propertyName, originalType);
}
if (propertyDestinationType == null) {
propertyDestinationType = originalType;
}
return propertyDestinationType;
} } | public class class_name {
protected TypeReference<?> getBeanPropertyType(Class<?> clazz,
String propertyName, TypeReference<?> originalType) {
TypeReference<?> propertyDestinationType = null;
if (beanDestinationPropertyTypeProvider != null) {
propertyDestinationType = beanDestinationPropertyTypeProvider
.getPropertyType(clazz, propertyName, originalType);
// depends on control dependency: [if], data = [none]
}
if (propertyDestinationType == null) {
propertyDestinationType = originalType;
// depends on control dependency: [if], data = [none]
}
return propertyDestinationType;
} } |
public class class_name {
public DataSet createDataSet(final Message response, final MessageType messageType) {
try {
if (response.getPayload() instanceof DataSet) {
return response.getPayload(DataSet.class);
} else if (isReadyToMarshal(response, messageType)) {
return marshalResponse(response, messageType);
} else {
return new DataSet();
}
} catch (final SQLException e) {
throw new CitrusRuntimeException("Failed to read dataSet from response message", e);
}
} } | public class class_name {
public DataSet createDataSet(final Message response, final MessageType messageType) {
try {
if (response.getPayload() instanceof DataSet) {
return response.getPayload(DataSet.class); // depends on control dependency: [if], data = [none]
} else if (isReadyToMarshal(response, messageType)) {
return marshalResponse(response, messageType); // depends on control dependency: [if], data = [none]
} else {
return new DataSet(); // depends on control dependency: [if], data = [none]
}
} catch (final SQLException e) {
throw new CitrusRuntimeException("Failed to read dataSet from response message", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Object evaluate()
{
if( !isCompileTimeConstant() )
{
return super.evaluate();
}
return (Boolean)getLHS().evaluate() || (Boolean)getRHS().evaluate();
} } | public class class_name {
public Object evaluate()
{
if( !isCompileTimeConstant() )
{
return super.evaluate(); // depends on control dependency: [if], data = [none]
}
return (Boolean)getLHS().evaluate() || (Boolean)getRHS().evaluate();
} } |
public class class_name {
protected void onHandshakeFinish(SSLEngine engine) {
// PK16095 - control the SSLSession cache inside the JSSE2 code
// security is creating the contexts, which should not change but might.
// we keep the last seen in an attempt to set these values only once
// per context. The alternative is to keep a list of each unique one
// seen but who knows how large that might grow to, so simply update
// based on last seen.
SSLSessionContext context = null;
try {
final SSLEngine localEngine = engine;
context = AccessController.doPrivileged(new PrivilegedExceptionAction<SSLSessionContext>() {
@Override
public SSLSessionContext run() throws Exception {
return localEngine.getSession().getSessionContext();
}
});
} catch (Exception e) {
FFDCFilter.processException(e,
getClass().getName() + ".onHandshakeFinish", "814");
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Exception querying sessioncontext; " + e);
}
return;
}
if (null == context || context.equals(this.sessionContext)) {
return;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Channel [" + this + "] saving context: " + context);
}
this.sessionContext = context;
context.setSessionCacheSize(getConfig().getSSLSessionCacheSize());
context.setSessionTimeout(getConfig().getSSLSessionTimeout());
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Session cache size set to " + context.getSessionCacheSize());
Tr.debug(tc, "Session timeout set to " + context.getSessionTimeout());
}
} } | public class class_name {
protected void onHandshakeFinish(SSLEngine engine) {
// PK16095 - control the SSLSession cache inside the JSSE2 code
// security is creating the contexts, which should not change but might.
// we keep the last seen in an attempt to set these values only once
// per context. The alternative is to keep a list of each unique one
// seen but who knows how large that might grow to, so simply update
// based on last seen.
SSLSessionContext context = null;
try {
final SSLEngine localEngine = engine;
context = AccessController.doPrivileged(new PrivilegedExceptionAction<SSLSessionContext>() {
@Override
public SSLSessionContext run() throws Exception {
return localEngine.getSession().getSessionContext();
}
}); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
FFDCFilter.processException(e,
getClass().getName() + ".onHandshakeFinish", "814");
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Exception querying sessioncontext; " + e); // depends on control dependency: [if], data = [none]
}
return;
} // depends on control dependency: [catch], data = [none]
if (null == context || context.equals(this.sessionContext)) {
return; // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Channel [" + this + "] saving context: " + context); // depends on control dependency: [if], data = [none]
}
this.sessionContext = context;
context.setSessionCacheSize(getConfig().getSSLSessionCacheSize());
context.setSessionTimeout(getConfig().getSSLSessionTimeout());
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Session cache size set to " + context.getSessionCacheSize()); // depends on control dependency: [if], data = [none]
Tr.debug(tc, "Session timeout set to " + context.getSessionTimeout()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void buildReplacementNodesFromTranslation(MsgNode msg, SoyMsg translation) {
currReplacementNodes = Lists.newArrayList();
for (SoyMsgPart msgPart : translation.getParts()) {
if (msgPart instanceof SoyMsgRawTextPart) {
// Append a new RawTextNode to the currReplacementNodes list.
String rawText = ((SoyMsgRawTextPart) msgPart).getRawText();
currReplacementNodes.add(
new RawTextNode(nodeIdGen.genId(), rawText, msg.getSourceLocation()));
} else if (msgPart instanceof SoyMsgPlaceholderPart) {
// Get the representative placeholder node and iterate through its contents.
String placeholderName = ((SoyMsgPlaceholderPart) msgPart).getPlaceholderName();
MsgPlaceholderNode placeholderNode = msg.getRepPlaceholderNode(placeholderName);
for (StandaloneNode contentNode : placeholderNode.getChildren()) {
// If the content node is a MsgHtmlTagNode, it needs to be replaced by a number of
// consecutive siblings. This is done by visiting the MsgHtmlTagNode. Otherwise, we
// simply add the content node to the currReplacementNodes list being built.
if (contentNode instanceof MsgHtmlTagNode) {
currReplacementNodes.addAll(((MsgHtmlTagNode) contentNode).getChildren());
} else {
currReplacementNodes.add(contentNode);
}
}
} else {
throw new AssertionError();
}
}
} } | public class class_name {
private void buildReplacementNodesFromTranslation(MsgNode msg, SoyMsg translation) {
currReplacementNodes = Lists.newArrayList();
for (SoyMsgPart msgPart : translation.getParts()) {
if (msgPart instanceof SoyMsgRawTextPart) {
// Append a new RawTextNode to the currReplacementNodes list.
String rawText = ((SoyMsgRawTextPart) msgPart).getRawText();
currReplacementNodes.add(
new RawTextNode(nodeIdGen.genId(), rawText, msg.getSourceLocation())); // depends on control dependency: [if], data = [none]
} else if (msgPart instanceof SoyMsgPlaceholderPart) {
// Get the representative placeholder node and iterate through its contents.
String placeholderName = ((SoyMsgPlaceholderPart) msgPart).getPlaceholderName();
MsgPlaceholderNode placeholderNode = msg.getRepPlaceholderNode(placeholderName);
for (StandaloneNode contentNode : placeholderNode.getChildren()) {
// If the content node is a MsgHtmlTagNode, it needs to be replaced by a number of
// consecutive siblings. This is done by visiting the MsgHtmlTagNode. Otherwise, we
// simply add the content node to the currReplacementNodes list being built.
if (contentNode instanceof MsgHtmlTagNode) {
currReplacementNodes.addAll(((MsgHtmlTagNode) contentNode).getChildren()); // depends on control dependency: [if], data = [none]
} else {
currReplacementNodes.add(contentNode); // depends on control dependency: [if], data = [none]
}
}
} else {
throw new AssertionError();
}
}
} } |
public class class_name {
public static String toAlpha(long i, boolean uppercase) {
final int A = (uppercase ? 'A' : 'a') - 1;
if (i < 0)
throw new IllegalArgumentException(
"Argument must be non-negative, was " + i);
if (i == Long.MAX_VALUE)
throw new IllegalArgumentException(
"Argument must be smaller than Long.MAX_VALUE");
i++;
StringBuilder sb = new StringBuilder();
while (i > 0) {
long d = i%26;
if (d == 0) d = 26;
sb.append((char)(A + d));
i = (i-d)/26;
}
return sb.reverse().toString();
} } | public class class_name {
public static String toAlpha(long i, boolean uppercase) {
final int A = (uppercase ? 'A' : 'a') - 1;
if (i < 0)
throw new IllegalArgumentException(
"Argument must be non-negative, was " + i);
if (i == Long.MAX_VALUE)
throw new IllegalArgumentException(
"Argument must be smaller than Long.MAX_VALUE");
i++;
StringBuilder sb = new StringBuilder();
while (i > 0) {
long d = i%26;
if (d == 0) d = 26;
sb.append((char)(A + d)); // depends on control dependency: [while], data = [none]
i = (i-d)/26; // depends on control dependency: [while], data = [(i]
}
return sb.reverse().toString();
} } |
public class class_name {
HystrixMetricsPublisherCommand getPublisherForCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandOwner, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) {
// attempt to retrieve from cache first
HystrixMetricsPublisherCommand publisher = commandPublishers.get(commandKey.name());
if (publisher != null) {
return publisher;
} else {
synchronized (this) {
HystrixMetricsPublisherCommand existingPublisher = commandPublishers.get(commandKey.name());
if (existingPublisher != null) {
return existingPublisher;
} else {
HystrixMetricsPublisherCommand newPublisher = HystrixPlugins.getInstance().getMetricsPublisher().getMetricsPublisherForCommand(commandKey, commandOwner, metrics, circuitBreaker, properties);
commandPublishers.putIfAbsent(commandKey.name(), newPublisher);
newPublisher.initialize();
return newPublisher;
}
}
}
} } | public class class_name {
HystrixMetricsPublisherCommand getPublisherForCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandOwner, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) {
// attempt to retrieve from cache first
HystrixMetricsPublisherCommand publisher = commandPublishers.get(commandKey.name());
if (publisher != null) {
return publisher; // depends on control dependency: [if], data = [none]
} else {
synchronized (this) { // depends on control dependency: [if], data = [none]
HystrixMetricsPublisherCommand existingPublisher = commandPublishers.get(commandKey.name());
if (existingPublisher != null) {
return existingPublisher; // depends on control dependency: [if], data = [none]
} else {
HystrixMetricsPublisherCommand newPublisher = HystrixPlugins.getInstance().getMetricsPublisher().getMetricsPublisherForCommand(commandKey, commandOwner, metrics, circuitBreaker, properties);
commandPublishers.putIfAbsent(commandKey.name(), newPublisher); // depends on control dependency: [if], data = [none]
newPublisher.initialize(); // depends on control dependency: [if], data = [none]
return newPublisher; // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public EEnum getImageResolutionYBase() {
if (imageResolutionYBaseEEnum == null) {
imageResolutionYBaseEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(176);
}
return imageResolutionYBaseEEnum;
} } | public class class_name {
public EEnum getImageResolutionYBase() {
if (imageResolutionYBaseEEnum == null) {
imageResolutionYBaseEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(176); // depends on control dependency: [if], data = [none]
}
return imageResolutionYBaseEEnum;
} } |
public class class_name {
public synchronized void onDataReceived() {
stopwatch.reset().start();
// We do not cancel the ping future here. This avoids constantly scheduling and cancellation in
// a busy transport. Instead, we update the status here and reschedule later. So we actually
// keep one sendPing task always in flight when there're active rpcs.
if (state == State.PING_SCHEDULED) {
state = State.PING_DELAYED;
} else if (state == State.PING_SENT || state == State.IDLE_AND_PING_SENT) {
// Ping acked or effectively ping acked. Cancel shutdown, and then if not idle,
// schedule a new keep-alive ping.
if (shutdownFuture != null) {
shutdownFuture.cancel(false);
}
if (state == State.IDLE_AND_PING_SENT) {
// not to schedule new pings until onTransportActive
state = State.IDLE;
return;
}
// schedule a new ping
state = State.PING_SCHEDULED;
checkState(pingFuture == null, "There should be no outstanding pingFuture");
pingFuture = scheduler.schedule(sendPing, keepAliveTimeInNanos, TimeUnit.NANOSECONDS);
}
} } | public class class_name {
public synchronized void onDataReceived() {
stopwatch.reset().start();
// We do not cancel the ping future here. This avoids constantly scheduling and cancellation in
// a busy transport. Instead, we update the status here and reschedule later. So we actually
// keep one sendPing task always in flight when there're active rpcs.
if (state == State.PING_SCHEDULED) {
state = State.PING_DELAYED; // depends on control dependency: [if], data = [none]
} else if (state == State.PING_SENT || state == State.IDLE_AND_PING_SENT) {
// Ping acked or effectively ping acked. Cancel shutdown, and then if not idle,
// schedule a new keep-alive ping.
if (shutdownFuture != null) {
shutdownFuture.cancel(false); // depends on control dependency: [if], data = [none]
}
if (state == State.IDLE_AND_PING_SENT) {
// not to schedule new pings until onTransportActive
state = State.IDLE; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// schedule a new ping
state = State.PING_SCHEDULED; // depends on control dependency: [if], data = [none]
checkState(pingFuture == null, "There should be no outstanding pingFuture"); // depends on control dependency: [if], data = [none]
pingFuture = scheduler.schedule(sendPing, keepAliveTimeInNanos, TimeUnit.NANOSECONDS); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public int prepare() throws ProtocolException, RollbackException, SeverePersistenceException, TransactionException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "prepare");
// Check the current transaction state (use state lock to ensure we see the latest value)
synchronized (_stateLock)
{
if (_state != TransactionState.STATE_ACTIVE)
{
ProtocolException pe = new ProtocolException("TRAN_PROTOCOL_ERROR_SIMS1001", new Object[]{});
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Cannot prepare Transaction. Transaction is complete or completing!", pe);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
throw pe;
}
// Transition our prepare sub-state immediately - before we call the callbacks
_preCommitSubstate = TransactionState.STATE_PREPARING;
}
// PK81848
// From this point on, we must perform a rollback if we fail to complete the prepare,
// or another thread requests a deferred rollback
try
{
// Call beforeCompletion on MP callback
for (int i = 0; i < _callbacks.size(); i++)
{
TransactionCallback callback = (TransactionCallback) _callbacks.get(i);
callback.beforeCompletion(this);
}
// Do we have work to do?
if (_workList != null)
{
_workList.preCommit(this);
synchronized (_stateLock)
{
// Need to change the overalll state after we have
// called the callbacks and preCommitted
// the workList as they may trigger
// an addWork call to add work to the
// transaction.
_state = TransactionState.STATE_PREPARING;
}
// The transaction is about to be in a state where any rollback must
// update the database. We cannot narrow the window any more than this
_rollbackChanges = true;
// Perform the prepare
_persistence.prepare(this);
// State check/change must be performed holding the state lock
synchronized (_stateLock)
{
// Another thread may have have received a rollback, while we were
// performing our prepare - if the database was extremely slow to respond
if (_preCommitSubstate == TransactionState.STATE_ROLLBACK_DEFERRED)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.event(this, tc, "Deferred rollback requested during prepare for TranId: "+_ptid);
// Throw an exception to trigger rollback processing.
throw new DeferredRollbackException();
}
else
{
_state = _preCommitSubstate = TransactionState.STATE_PREPARED;
}
}
}
else
{
// State change must be performed holding the state lock
synchronized (_stateLock)
{
// Defect 301480
// We don't have any work in our workList so in theory we should be
// able to vote READ_ONLY at this point. However in a particular case
// (Best Effort message being sent off server) a call back in an empty
// XAResource is used to trigger work on a remote server. In this case
// we need beforeCompletion AND afterCompletion to be called at the
// CORRECT time during transaction completion to ensure that the off
// server work stays part of the XA transaction and gets informed of
// the correct completion direction.
_state = _preCommitSubstate = TransactionState.STATE_PREPARED;
}
}
}
catch (SeverePersistenceException spe)
{
// SPE exceptions are handled with an RMFAIL return code by the caller,
// so unlike all other types of exception no attempt is made here to
// rollback the transaction. However, we report a local error - so
// the whole JVM will be coming down with a few minutes.
com.ibm.ws.ffdc.FFDCFilter.processException(spe, "com.ibm.ws.sib.msgstore.transactions.XidParticipant.prepare", "1:420:1.73", this);
// As we have thrown a severe exception we need to inform
// the ME that this instance is no longer able to continue.
if (_ms != null)
{
_ms.reportLocalError();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Unrecoverable persistence exception caught during prepare phase of transaction!", spe);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", spe);
throw spe;
}
// Catch and handle all exceptions but allow
// Errors to filter up without interference
catch (Exception e)
{
com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.sib.msgstore.transactions.XidParticipant.prepare", "1:436:1.73", this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Transaction will roll-back due to Exception in prepare!", e);
// Update our prepare state before calling rollback. If we are responding
// to a deferred rollback request this will have no affect but if this is
// due to some other failure it will lock out any other attempts to rollback
synchronized (_stateLock)
{
_preCommitSubstate = TransactionState.STATE_ROLLINGBACK;
}
// An error has occurred but we are able to keep the ME
// going so we just need to clean up this transaction.
try
{
// When we throw our RollbackException the TM is
// going to assume we are complete so we need to
// ensure we are rolled-back.
//
// PK81848.2
// We need to pass "true" in order to turn off the
// state checking which should block other threads
// from attempting a rollback when we are in the
// middle of internal rollback processing.
rollback(true);
}
// Catch and handle all exceptions but allow
// Errors to filter up without interference
catch (Exception e2)
{
com.ibm.ws.ffdc.FFDCFilter.processException(e2, "com.ibm.ws.sib.msgstore.transactions.XIDParticipant.prepare", "1:466:1.73", this);
// This is a problem because we now must RMFAIL this prepare call as we do not know the outcome.
// Transition to rollback expected state now even if we are in deferred rollback. This is the
// only thing we can do (problem is we said XA_OK to roll back in deferred case and now we
// cannot honour it). This case may still leave indoubts.
synchronized(_stateLock)
{
_state = _preCommitSubstate = TransactionState.STATE_ROLLBACK_EXPECTED;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", "Exception caught rolling-back transaction after preCommit failure! " + e2);
throw new TransactionException(e2);
}
// Mark ourselves as complete, regardless of the outcome of the attempt to rollback.
synchronized (_stateLock)
{
_state = _preCommitSubstate = TransactionState.STATE_ROLLEDBACK;
}
// Wrap any persistence exception, or an unexpected exception, in a rollback exception.
// This informs the TM that they can forget about this transaction.
RollbackException re = new RollbackException("COMPLETION_EXCEPTION_SIMS1002", new Object[]{e}, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", re);
throw re;
}
// Non-exception return path always returns XA_OK
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", "return="+XAResource.XA_OK);
return XAResource.XA_OK;
} } | public class class_name {
public int prepare() throws ProtocolException, RollbackException, SeverePersistenceException, TransactionException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "prepare");
// Check the current transaction state (use state lock to ensure we see the latest value)
synchronized (_stateLock)
{
if (_state != TransactionState.STATE_ACTIVE)
{
ProtocolException pe = new ProtocolException("TRAN_PROTOCOL_ERROR_SIMS1001", new Object[]{});
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Cannot prepare Transaction. Transaction is complete or completing!", pe);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
throw pe;
}
// Transition our prepare sub-state immediately - before we call the callbacks
_preCommitSubstate = TransactionState.STATE_PREPARING;
}
// PK81848
// From this point on, we must perform a rollback if we fail to complete the prepare,
// or another thread requests a deferred rollback
try
{
// Call beforeCompletion on MP callback
for (int i = 0; i < _callbacks.size(); i++)
{
TransactionCallback callback = (TransactionCallback) _callbacks.get(i);
callback.beforeCompletion(this); // depends on control dependency: [for], data = [none]
}
// Do we have work to do?
if (_workList != null)
{
_workList.preCommit(this); // depends on control dependency: [if], data = [none]
synchronized (_stateLock) // depends on control dependency: [if], data = [none]
{
// Need to change the overalll state after we have
// called the callbacks and preCommitted
// the workList as they may trigger
// an addWork call to add work to the
// transaction.
_state = TransactionState.STATE_PREPARING;
}
// The transaction is about to be in a state where any rollback must
// update the database. We cannot narrow the window any more than this
_rollbackChanges = true; // depends on control dependency: [if], data = [none]
// Perform the prepare
_persistence.prepare(this); // depends on control dependency: [if], data = [none]
// State check/change must be performed holding the state lock
synchronized (_stateLock) // depends on control dependency: [if], data = [none]
{
// Another thread may have have received a rollback, while we were
// performing our prepare - if the database was extremely slow to respond
if (_preCommitSubstate == TransactionState.STATE_ROLLBACK_DEFERRED)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.event(this, tc, "Deferred rollback requested during prepare for TranId: "+_ptid);
// Throw an exception to trigger rollback processing.
throw new DeferredRollbackException();
}
else
{
_state = _preCommitSubstate = TransactionState.STATE_PREPARED; // depends on control dependency: [if], data = [none]
}
}
}
else
{
// State change must be performed holding the state lock
synchronized (_stateLock) // depends on control dependency: [if], data = [none]
{
// Defect 301480
// We don't have any work in our workList so in theory we should be
// able to vote READ_ONLY at this point. However in a particular case
// (Best Effort message being sent off server) a call back in an empty
// XAResource is used to trigger work on a remote server. In this case
// we need beforeCompletion AND afterCompletion to be called at the
// CORRECT time during transaction completion to ensure that the off
// server work stays part of the XA transaction and gets informed of
// the correct completion direction.
_state = _preCommitSubstate = TransactionState.STATE_PREPARED;
}
}
}
catch (SeverePersistenceException spe)
{
// SPE exceptions are handled with an RMFAIL return code by the caller,
// so unlike all other types of exception no attempt is made here to
// rollback the transaction. However, we report a local error - so
// the whole JVM will be coming down with a few minutes.
com.ibm.ws.ffdc.FFDCFilter.processException(spe, "com.ibm.ws.sib.msgstore.transactions.XidParticipant.prepare", "1:420:1.73", this);
// As we have thrown a severe exception we need to inform
// the ME that this instance is no longer able to continue.
if (_ms != null)
{
_ms.reportLocalError(); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Unrecoverable persistence exception caught during prepare phase of transaction!", spe);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", spe);
throw spe;
}
// Catch and handle all exceptions but allow
// Errors to filter up without interference
catch (Exception e)
{
com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.sib.msgstore.transactions.XidParticipant.prepare", "1:436:1.73", this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Transaction will roll-back due to Exception in prepare!", e);
// Update our prepare state before calling rollback. If we are responding
// to a deferred rollback request this will have no affect but if this is
// due to some other failure it will lock out any other attempts to rollback
synchronized (_stateLock)
{
_preCommitSubstate = TransactionState.STATE_ROLLINGBACK;
}
// An error has occurred but we are able to keep the ME
// going so we just need to clean up this transaction.
try
{
// When we throw our RollbackException the TM is
// going to assume we are complete so we need to
// ensure we are rolled-back.
//
// PK81848.2
// We need to pass "true" in order to turn off the
// state checking which should block other threads
// from attempting a rollback when we are in the
// middle of internal rollback processing.
rollback(true); // depends on control dependency: [try], data = [none]
}
// Catch and handle all exceptions but allow
// Errors to filter up without interference
catch (Exception e2)
{
com.ibm.ws.ffdc.FFDCFilter.processException(e2, "com.ibm.ws.sib.msgstore.transactions.XIDParticipant.prepare", "1:466:1.73", this);
// This is a problem because we now must RMFAIL this prepare call as we do not know the outcome.
// Transition to rollback expected state now even if we are in deferred rollback. This is the
// only thing we can do (problem is we said XA_OK to roll back in deferred case and now we
// cannot honour it). This case may still leave indoubts.
synchronized(_stateLock)
{
_state = _preCommitSubstate = TransactionState.STATE_ROLLBACK_EXPECTED;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", "Exception caught rolling-back transaction after preCommit failure! " + e2);
throw new TransactionException(e2);
} // depends on control dependency: [catch], data = [none]
// Mark ourselves as complete, regardless of the outcome of the attempt to rollback.
synchronized (_stateLock)
{
_state = _preCommitSubstate = TransactionState.STATE_ROLLEDBACK;
}
// Wrap any persistence exception, or an unexpected exception, in a rollback exception.
// This informs the TM that they can forget about this transaction.
RollbackException re = new RollbackException("COMPLETION_EXCEPTION_SIMS1002", new Object[]{e}, e);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", re);
throw re;
}
// Non-exception return path always returns XA_OK
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare", "return="+XAResource.XA_OK);
return XAResource.XA_OK;
} } |
public class class_name {
boolean projectiveToMetric() {
// homography from projective to metric
DMatrixRMaj H = new DMatrixRMaj(4,4);
listPinhole.clear();
if( manualFocalLength <= 0 ) {
// Estimate calibration parameters
SelfCalibrationLinearDualQuadratic selfcalib = new SelfCalibrationLinearDualQuadratic(1.0);
selfcalib.addCameraMatrix(P1);
selfcalib.addCameraMatrix(P2);
selfcalib.addCameraMatrix(P3);
GeometricResult result = selfcalib.solve();
if (GeometricResult.SOLVE_FAILED != result && selfcalib.getSolutions().size() == 3) {
for (int i = 0; i < 3; i++) {
SelfCalibrationLinearDualQuadratic.Intrinsic c = selfcalib.getSolutions().get(i);
CameraPinhole p = new CameraPinhole(c.fx, c.fy, 0, 0, 0, width, height);
listPinhole.add(p);
}
} else {
// TODO Handle this better
System.out.println("Self calibration failed!");
for (int i = 0; i < 3; i++) {
CameraPinhole p = new CameraPinhole(width / 2, width / 2, 0, 0, 0, width, height);
listPinhole.add(p);
}
}
// convert camera matrix from projective to metric
if( !MultiViewOps.absoluteQuadraticToH(selfcalib.getQ(),H) ) {
if( verbose != null ) {
verbose.println("Projective to metric failed");
}
return false;
}
} else {
// Assume all cameras have a fixed known focal length
EstimatePlaneAtInfinityGivenK estimateV = new EstimatePlaneAtInfinityGivenK();
estimateV.setCamera1(manualFocalLength,manualFocalLength,0,0,0);
estimateV.setCamera2(manualFocalLength,manualFocalLength,0,0,0);
Vector3D_F64 v = new Vector3D_F64(); // plane at infinity
if( !estimateV.estimatePlaneAtInfinity(P2,v))
throw new RuntimeException("Failed!");
DMatrixRMaj K = PerspectiveOps.pinholeToMatrix(manualFocalLength,manualFocalLength,0,0,0);
MultiViewOps.createProjectiveToMetric(K,v.x,v.y,v.z,1,H);
for (int i = 0; i < 3; i++) {
CameraPinhole p = new CameraPinhole(manualFocalLength,manualFocalLength, 0, 0, 0, width, height);
listPinhole.add(p);
}
}
if( verbose != null ) {
for (int i = 0; i < 3; i++) {
CameraPinhole r = listPinhole.get(i);
verbose.println("fx=" + r.fx + " fy=" + r.fy + " skew=" + r.skew);
}
verbose.println("Projective to metric");
}
DMatrixRMaj K = new DMatrixRMaj(3,3);
// ignore K since we already have that
MultiViewOps.projectiveToMetric(P1,H,worldToView.get(0),K);
MultiViewOps.projectiveToMetric(P2,H,worldToView.get(1),K);
MultiViewOps.projectiveToMetric(P3,H,worldToView.get(2),K);
// scale is arbitrary. Set max translation to 1
double maxT = 0;
for( Se3_F64 p : worldToView ) {
maxT = Math.max(maxT,p.T.norm());
}
for( Se3_F64 p : worldToView ) {
p.T.scale(1.0/maxT);
if( verbose != null ) {
verbose.println(p);
}
}
return true;
} } | public class class_name {
boolean projectiveToMetric() {
// homography from projective to metric
DMatrixRMaj H = new DMatrixRMaj(4,4);
listPinhole.clear();
if( manualFocalLength <= 0 ) {
// Estimate calibration parameters
SelfCalibrationLinearDualQuadratic selfcalib = new SelfCalibrationLinearDualQuadratic(1.0);
selfcalib.addCameraMatrix(P1); // depends on control dependency: [if], data = [none]
selfcalib.addCameraMatrix(P2); // depends on control dependency: [if], data = [none]
selfcalib.addCameraMatrix(P3); // depends on control dependency: [if], data = [none]
GeometricResult result = selfcalib.solve();
if (GeometricResult.SOLVE_FAILED != result && selfcalib.getSolutions().size() == 3) {
for (int i = 0; i < 3; i++) {
SelfCalibrationLinearDualQuadratic.Intrinsic c = selfcalib.getSolutions().get(i);
CameraPinhole p = new CameraPinhole(c.fx, c.fy, 0, 0, 0, width, height);
listPinhole.add(p); // depends on control dependency: [for], data = [none]
}
} else {
// TODO Handle this better
System.out.println("Self calibration failed!"); // depends on control dependency: [if], data = [none]
for (int i = 0; i < 3; i++) {
CameraPinhole p = new CameraPinhole(width / 2, width / 2, 0, 0, 0, width, height);
listPinhole.add(p); // depends on control dependency: [for], data = [none]
}
}
// convert camera matrix from projective to metric
if( !MultiViewOps.absoluteQuadraticToH(selfcalib.getQ(),H) ) {
if( verbose != null ) {
verbose.println("Projective to metric failed"); // depends on control dependency: [if], data = [none]
}
return false; // depends on control dependency: [if], data = [none]
}
} else {
// Assume all cameras have a fixed known focal length
EstimatePlaneAtInfinityGivenK estimateV = new EstimatePlaneAtInfinityGivenK();
estimateV.setCamera1(manualFocalLength,manualFocalLength,0,0,0); // depends on control dependency: [if], data = [none]
estimateV.setCamera2(manualFocalLength,manualFocalLength,0,0,0); // depends on control dependency: [if], data = [none]
Vector3D_F64 v = new Vector3D_F64(); // plane at infinity
if( !estimateV.estimatePlaneAtInfinity(P2,v))
throw new RuntimeException("Failed!");
DMatrixRMaj K = PerspectiveOps.pinholeToMatrix(manualFocalLength,manualFocalLength,0,0,0);
MultiViewOps.createProjectiveToMetric(K,v.x,v.y,v.z,1,H); // depends on control dependency: [if], data = [none]
for (int i = 0; i < 3; i++) {
CameraPinhole p = new CameraPinhole(manualFocalLength,manualFocalLength, 0, 0, 0, width, height);
listPinhole.add(p); // depends on control dependency: [for], data = [none]
}
}
if( verbose != null ) {
for (int i = 0; i < 3; i++) {
CameraPinhole r = listPinhole.get(i);
verbose.println("fx=" + r.fx + " fy=" + r.fy + " skew=" + r.skew); // depends on control dependency: [for], data = [none]
}
verbose.println("Projective to metric"); // depends on control dependency: [if], data = [none]
}
DMatrixRMaj K = new DMatrixRMaj(3,3);
// ignore K since we already have that
MultiViewOps.projectiveToMetric(P1,H,worldToView.get(0),K);
MultiViewOps.projectiveToMetric(P2,H,worldToView.get(1),K);
MultiViewOps.projectiveToMetric(P3,H,worldToView.get(2),K);
// scale is arbitrary. Set max translation to 1
double maxT = 0;
for( Se3_F64 p : worldToView ) {
maxT = Math.max(maxT,p.T.norm()); // depends on control dependency: [for], data = [p]
}
for( Se3_F64 p : worldToView ) {
p.T.scale(1.0/maxT); // depends on control dependency: [for], data = [p]
if( verbose != null ) {
verbose.println(p); // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
private boolean isTitleAlreadyUsed(@NonNull final CharSequence title) {
for (NavigationPreference navigationPreference : getAllNavigationPreferences()) {
if (title.equals(navigationPreference.getTitle())) {
return true;
}
}
return false;
} } | public class class_name {
private boolean isTitleAlreadyUsed(@NonNull final CharSequence title) {
for (NavigationPreference navigationPreference : getAllNavigationPreferences()) {
if (title.equals(navigationPreference.getTitle())) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public static PubSubManager getInstanceFor(XMPPConnection connection, BareJid pubSubService) {
// CHECKSTYLE:ON:RegexpSingleline
if (pubSubService != null && connection.isAuthenticated() && connection.getUser().asBareJid().equals(pubSubService)) {
// PEP service.
pubSubService = null;
}
PubSubManager pubSubManager;
Map<BareJid, PubSubManager> managers;
synchronized (INSTANCES) {
managers = INSTANCES.get(connection);
if (managers == null) {
managers = new HashMap<>();
INSTANCES.put(connection, managers);
}
}
synchronized (managers) {
pubSubManager = managers.get(pubSubService);
if (pubSubManager == null) {
pubSubManager = new PubSubManager(connection, pubSubService);
managers.put(pubSubService, pubSubManager);
}
}
return pubSubManager;
} } | public class class_name {
public static PubSubManager getInstanceFor(XMPPConnection connection, BareJid pubSubService) {
// CHECKSTYLE:ON:RegexpSingleline
if (pubSubService != null && connection.isAuthenticated() && connection.getUser().asBareJid().equals(pubSubService)) {
// PEP service.
pubSubService = null; // depends on control dependency: [if], data = [none]
}
PubSubManager pubSubManager;
Map<BareJid, PubSubManager> managers;
synchronized (INSTANCES) {
managers = INSTANCES.get(connection);
if (managers == null) {
managers = new HashMap<>(); // depends on control dependency: [if], data = [none]
INSTANCES.put(connection, managers); // depends on control dependency: [if], data = [none]
}
}
synchronized (managers) {
pubSubManager = managers.get(pubSubService);
if (pubSubManager == null) {
pubSubManager = new PubSubManager(connection, pubSubService); // depends on control dependency: [if], data = [none]
managers.put(pubSubService, pubSubManager); // depends on control dependency: [if], data = [none]
}
}
return pubSubManager;
} } |
public class class_name {
private static WebDriver getDriver(final Builder builder) {
// this is the default value
DesiredCapabilities capabilities = getCapabilitiesBrowser(builder.browser);
WebDriver driver = null;
/**
* Setting the proxy
*/
LOG.info("Proxy seetings set");
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
if (builder.proxyHost != null && !builder.proxyHost.isEmpty()) {
if (!builder.proxyHost.equals("direct")) {
proxy.setAutodetect(false);
proxy.setHttpProxy(builder.proxyHost + ":" + builder.proxyPort)
.setFtpProxy(
builder.proxyHost + ":" + builder.proxyPort)
.setSslProxy(
builder.proxyHost + ":" + builder.proxyPort)
.setNoProxy(builder.noProxyFor);
} else {
proxy.setProxyType(ProxyType.DIRECT);
}
capabilities.setCapability(CapabilityType.PROXY, proxy);
}
/**
* the Driver will take screenshots
*/
LOG.info("Screenshot capability set");
capabilities.setCapability(CapabilityType.TAKES_SCREENSHOT, true);
/**
* setting the platform: LINUX, MAC or Windows. Remember that sometimes
* the browsers are linked to a platform like IE for example
*/
if (builder.platform != null) {
capabilities.setCapability(CapabilityType.PLATFORM,
builder.platform);
}
if (builder.browserVersion != null) {
capabilities.setCapability(CapabilityType.VERSION,
builder.browserVersion);
}
/**
* set if javascript is enabled
*/
capabilities.setJavascriptEnabled(builder.jsEnabled);
/**
* set if the browser will accept all certificates, including the
* self-signed ones
*/
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS,
builder.acceptAllCertificates);
/**
* this will actually create firefox profiles, chrome options and others
*/
LOG.info("Adding specific browser settings");
addSpecificBrowserSettings(capabilities, builder);
/**
* getting an actual WebDriver implementation now
*/
LOG.info("Detecting running mode");
if (builder.runMode.equalsIgnoreCase(Constants.RunMode.GRID)) {
LOG.info("Run mode GRID. Setting GRID properties");
try {
driver = new RemoteWebDriver(new URL(builder.gridUrl),
capabilities);
((RemoteWebDriver) driver).setLogLevel(Level.SEVERE);
} catch (Exception e) {
LOG.debug("Exception while initiating remote driver:", e);
}
} else {
LOG.info("Normal run mode. Getting driver instance");
driver = getDriverInstance(capabilities, builder);
}
LOG.info("Returning the following driver: " + driver);
LOG.info("With capabilities: " + capabilities);
return driver;
} } | public class class_name {
private static WebDriver getDriver(final Builder builder) {
// this is the default value
DesiredCapabilities capabilities = getCapabilitiesBrowser(builder.browser);
WebDriver driver = null;
/**
* Setting the proxy
*/
LOG.info("Proxy seetings set");
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
if (builder.proxyHost != null && !builder.proxyHost.isEmpty()) {
if (!builder.proxyHost.equals("direct")) {
proxy.setAutodetect(false); // depends on control dependency: [if], data = [none]
proxy.setHttpProxy(builder.proxyHost + ":" + builder.proxyPort)
.setFtpProxy(
builder.proxyHost + ":" + builder.proxyPort)
.setSslProxy(
builder.proxyHost + ":" + builder.proxyPort)
.setNoProxy(builder.noProxyFor); // depends on control dependency: [if], data = [none]
} else {
proxy.setProxyType(ProxyType.DIRECT); // depends on control dependency: [if], data = [none]
}
capabilities.setCapability(CapabilityType.PROXY, proxy); // depends on control dependency: [if], data = [none]
}
/**
* the Driver will take screenshots
*/
LOG.info("Screenshot capability set");
capabilities.setCapability(CapabilityType.TAKES_SCREENSHOT, true);
/**
* setting the platform: LINUX, MAC or Windows. Remember that sometimes
* the browsers are linked to a platform like IE for example
*/
if (builder.platform != null) {
capabilities.setCapability(CapabilityType.PLATFORM,
builder.platform); // depends on control dependency: [if], data = [none]
}
if (builder.browserVersion != null) {
capabilities.setCapability(CapabilityType.VERSION,
builder.browserVersion); // depends on control dependency: [if], data = [none]
}
/**
* set if javascript is enabled
*/
capabilities.setJavascriptEnabled(builder.jsEnabled);
/**
* set if the browser will accept all certificates, including the
* self-signed ones
*/
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS,
builder.acceptAllCertificates);
/**
* this will actually create firefox profiles, chrome options and others
*/
LOG.info("Adding specific browser settings");
addSpecificBrowserSettings(capabilities, builder);
/**
* getting an actual WebDriver implementation now
*/
LOG.info("Detecting running mode");
if (builder.runMode.equalsIgnoreCase(Constants.RunMode.GRID)) {
LOG.info("Run mode GRID. Setting GRID properties"); // depends on control dependency: [if], data = [none]
try {
driver = new RemoteWebDriver(new URL(builder.gridUrl),
capabilities); // depends on control dependency: [try], data = [none]
((RemoteWebDriver) driver).setLogLevel(Level.SEVERE); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
LOG.debug("Exception while initiating remote driver:", e);
} // depends on control dependency: [catch], data = [none]
} else {
LOG.info("Normal run mode. Getting driver instance"); // depends on control dependency: [if], data = [none]
driver = getDriverInstance(capabilities, builder); // depends on control dependency: [if], data = [none]
}
LOG.info("Returning the following driver: " + driver);
LOG.info("With capabilities: " + capabilities);
return driver;
} } |
public class class_name {
public E remove(Long x, Long y)
{
// Extract the region containing the coordinates from the hash table
Bucket<E> region = (Bucket<E>) regions.get(new Coordinates(div(x, bucketSize), div(y, bucketSize)));
// Check if the whole region is empty
if (region == null)
{
// Return null as nothing to remove
return null;
}
// Get the coordinates within the region
E removed = (region.array[mod(x, bucketSize)][mod(y, bucketSize)]);
// Clear the coordinate within the region
region.array[mod(x, bucketSize)][mod(y, bucketSize)] = null;
// Decrement the bucket and whole data strucutre item counts to reflect the true size
size--;
region.itemCount--;
// Return the removed data item
return removed;
} } | public class class_name {
public E remove(Long x, Long y)
{
// Extract the region containing the coordinates from the hash table
Bucket<E> region = (Bucket<E>) regions.get(new Coordinates(div(x, bucketSize), div(y, bucketSize)));
// Check if the whole region is empty
if (region == null)
{
// Return null as nothing to remove
return null; // depends on control dependency: [if], data = [none]
}
// Get the coordinates within the region
E removed = (region.array[mod(x, bucketSize)][mod(y, bucketSize)]);
// Clear the coordinate within the region
region.array[mod(x, bucketSize)][mod(y, bucketSize)] = null;
// Decrement the bucket and whole data strucutre item counts to reflect the true size
size--;
region.itemCount--;
// Return the removed data item
return removed;
} } |
public class class_name {
private final void write(byte dataType, int timestamp, ITag tag) {
if (tag != null) {
// only allow blank tags if they are of audio type
if (tag.getBodySize() > 0 || dataType == ITag.TYPE_AUDIO) {
try {
if (timestamp >= 0) {
if (!writer.writeTag(tag)) {
log.warn("Tag was not written");
}
} else {
log.warn("Skipping message with negative timestamp");
}
} catch (ClosedChannelException cce) {
// the channel we tried to write to is closed, we should not try again on that writer
log.error("The writer is no longer able to write to the file: {} writable: {}", path.getFileName(), path.toFile().canWrite());
} catch (IOException e) {
log.warn("Error writing tag", e);
if (e.getCause() instanceof ClosedChannelException) {
// the channel we tried to write to is closed, we should not try again on that writer
log.error("The writer is no longer able to write to the file: {} writable: {}", path.getFileName(), path.toFile().canWrite());
}
}
}
}
} } | public class class_name {
private final void write(byte dataType, int timestamp, ITag tag) {
if (tag != null) {
// only allow blank tags if they are of audio type
if (tag.getBodySize() > 0 || dataType == ITag.TYPE_AUDIO) {
try {
if (timestamp >= 0) {
if (!writer.writeTag(tag)) {
log.warn("Tag was not written");
// depends on control dependency: [if], data = [none]
}
} else {
log.warn("Skipping message with negative timestamp");
// depends on control dependency: [if], data = [none]
}
} catch (ClosedChannelException cce) {
// the channel we tried to write to is closed, we should not try again on that writer
log.error("The writer is no longer able to write to the file: {} writable: {}", path.getFileName(), path.toFile().canWrite());
} catch (IOException e) {
log.warn("Error writing tag", e);
if (e.getCause() instanceof ClosedChannelException) {
// the channel we tried to write to is closed, we should not try again on that writer
log.error("The writer is no longer able to write to the file: {} writable: {}", path.getFileName(), path.toFile().canWrite());
}
}
}
}
} } |
public class class_name {
private X509Certificate loadX509FromPEMFile(String filename) {
try {
return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(FileReader.openStreamToFileFromClassPathOrPath(filename));
} catch (Exception e) {
throw new RuntimeException("Exception reading X509 from PEM file", e);
}
} } | public class class_name {
private X509Certificate loadX509FromPEMFile(String filename) {
try {
return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(FileReader.openStreamToFileFromClassPathOrPath(filename)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new RuntimeException("Exception reading X509 from PEM file", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public Response init(ChaincodeStub stub) {
try {
// Get the args from the transaction proposal
List<String> args = stub.getParameters();
if (args.size() != 2) {
newErrorResponse("Incorrect arguments. Expecting a key and a value");
}
// Set up any variables or assets here by calling stub.putState()
// We store the key and the value on the ledger
stub.putStringState(args.get(0), args.get(1));
return newSuccessResponse();
} catch (Throwable e) {
return newErrorResponse("Failed to create asset");
}
} } | public class class_name {
@Override
public Response init(ChaincodeStub stub) {
try {
// Get the args from the transaction proposal
List<String> args = stub.getParameters();
if (args.size() != 2) {
newErrorResponse("Incorrect arguments. Expecting a key and a value"); // depends on control dependency: [if], data = [none]
}
// Set up any variables or assets here by calling stub.putState()
// We store the key and the value on the ledger
stub.putStringState(args.get(0), args.get(1)); // depends on control dependency: [try], data = [none]
return newSuccessResponse(); // depends on control dependency: [try], data = [none]
} catch (Throwable e) {
return newErrorResponse("Failed to create asset");
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void scheduleAlarm() {
if (wasCalledViaHTTP || retry >= maxNumberOfRetries) {
// No alarm necessary anymore.
LOG.log(Level.INFO,
"Not scheduling additional alarms after {0} out of max {1} retries. The HTTP handles was called: ",
new Object[] {retry, maxNumberOfRetries, wasCalledViaHTTP});
return;
}
// Scheduling an alarm will prevent the clock from going idle.
++retry;
clock.scheduleAlarm(alarmInterval, alarmHandler);
} } | public class class_name {
private void scheduleAlarm() {
if (wasCalledViaHTTP || retry >= maxNumberOfRetries) {
// No alarm necessary anymore.
LOG.log(Level.INFO,
"Not scheduling additional alarms after {0} out of max {1} retries. The HTTP handles was called: ",
new Object[] {retry, maxNumberOfRetries, wasCalledViaHTTP}); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// Scheduling an alarm will prevent the clock from going idle.
++retry;
clock.scheduleAlarm(alarmInterval, alarmHandler);
} } |
public class class_name {
public PageSnapshot blurExcept(WebElement element) {
try{
image = ImageProcessor.blurExceptArea(image, new Coordinates(element,devicePixelRatio));
}catch(RasterFormatException rfe){
throw new ElementOutsideViewportException(ELEMENT_OUT_OF_VIEWPORT_EX_MESSAGE,rfe);
}
return this;
} } | public class class_name {
public PageSnapshot blurExcept(WebElement element) {
try{
image = ImageProcessor.blurExceptArea(image, new Coordinates(element,devicePixelRatio)); // depends on control dependency: [try], data = [none]
}catch(RasterFormatException rfe){
throw new ElementOutsideViewportException(ELEMENT_OUT_OF_VIEWPORT_EX_MESSAGE,rfe);
} // depends on control dependency: [catch], data = [none]
return this;
} } |
public class class_name {
public final void setSourceText(final String text) {
if (SwingUtilities.isEventDispatchThread()) {
setSourceTextIntern(text);
} else {
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setSourceTextIntern(text);
}
});
} catch (final Exception ex) {
ignore();
}
}
} } | public class class_name {
public final void setSourceText(final String text) {
if (SwingUtilities.isEventDispatchThread()) {
setSourceTextIntern(text);
// depends on control dependency: [if], data = [none]
} else {
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setSourceTextIntern(text);
}
});
// depends on control dependency: [try], data = [none]
} catch (final Exception ex) {
ignore();
}
// depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private String destroyAs(String[] args) throws Exception {
if (args.length < 4) {
return M3UAOAMMessages.INVALID_COMMAND;
}
String asName = args[3];
if (asName == null) {
return M3UAOAMMessages.INVALID_COMMAND;
}
String m3uaStackName = null;
if (args.length > 4) {
if (!args[4].equals("stackname")) {
return M3UAOAMMessages.INVALID_COMMAND;
}
m3uaStackName = args[5];
M3UAManagementImpl m3uaManagementtmp = this.m3uaManagements.get(m3uaStackName);
if (m3uaManagementtmp == null) {
return String.format(M3UAOAMMessages.NO_M3UA_MANAGEMENT_BEAN_FOR_NAME, m3uaStackName);
}
this.m3uaManagement = m3uaManagementtmp;
} else {
this.setDefaultValue();
}
AsImpl asImpl = this.m3uaManagement.destroyAs(asName);
return String.format(M3UAOAMMessages.DESTROY_AS_SUCESSFULL, asName, this.m3uaManagement.getName());
} } | public class class_name {
private String destroyAs(String[] args) throws Exception {
if (args.length < 4) {
return M3UAOAMMessages.INVALID_COMMAND;
}
String asName = args[3];
if (asName == null) {
return M3UAOAMMessages.INVALID_COMMAND;
}
String m3uaStackName = null;
if (args.length > 4) {
if (!args[4].equals("stackname")) {
return M3UAOAMMessages.INVALID_COMMAND; // depends on control dependency: [if], data = [none]
}
m3uaStackName = args[5];
M3UAManagementImpl m3uaManagementtmp = this.m3uaManagements.get(m3uaStackName);
if (m3uaManagementtmp == null) {
return String.format(M3UAOAMMessages.NO_M3UA_MANAGEMENT_BEAN_FOR_NAME, m3uaStackName); // depends on control dependency: [if], data = [none]
}
this.m3uaManagement = m3uaManagementtmp;
} else {
this.setDefaultValue();
}
AsImpl asImpl = this.m3uaManagement.destroyAs(asName);
return String.format(M3UAOAMMessages.DESTROY_AS_SUCESSFULL, asName, this.m3uaManagement.getName());
} } |
public class class_name {
private boolean shiftRow() {
int su = rnd.nextInt(order); // Select the repeat
int rl = rnd.nextInt(2); // Select between moving right (0) or left (1)
int res = rnd.nextInt(length); // Residue as a pivot
// When the pivot residue is null try to add a residue from the freePool
if (block.get(su).get(res) == null) {
int right = res;
int left = res;
// Find the boundary to the right abd left
while (block.get(su).get(right) == null && right < length - 1) {
right++;
}
while (block.get(su).get(left) == null && left > 0) {
left--;
}
// If they both are null the whole block is null
if (block.get(su).get(left) == null
&& block.get(su).get(right) == null) {
return false;
} else if (block.get(su).get(left) == null) {
// Choose the sequentially previous residue of the known one
Integer residue = block.get(su).get(right) - 1;
if (freePool.contains(residue)) {
block.get(su).set(res, residue);
freePool.remove(residue);
} else
return false;
} else if (block.get(su).get(right) == null) {
// Choose the sequentially next residue of the known one
Integer residue = block.get(su).get(left) + 1;
if (freePool.contains(residue)) {
block.get(su).set(res, residue);
freePool.remove(residue);
} else
return false;
} else {
// If boundaries are consecutive swap null and position (R or L)
if (block.get(su).get(right) == block.get(su).get(left) + 1) {
switch (rl) {
case 0: // to the right
block.get(su).set(right - 1, block.get(su).get(right));
block.get(su).set(right, null);
break;
case 1: // to the left
block.get(su).set(left + 1, block.get(su).get(left));
block.get(su).set(left, null);
break;
}
} else {
// Choose randomly a residue in between left and right to
// add
Integer residue = rnd.nextInt(block.get(su).get(right)
- block.get(su).get(left) - 1)
+ block.get(su).get(left) + 1;
if (freePool.contains(residue)) {
block.get(su).set(res, residue);
freePool.remove(residue);
}
}
}
return true;
}
// When the residue is different than null
switch (rl) {
case 0: // Move to the right
int leftBoundary = res - 1;
int leftPrevRes = res;
while (true) {
if (leftBoundary < 0)
break;
else {
if (block.get(su).get(leftBoundary) == null) {
break; // gap
} else if (block.get(su).get(leftPrevRes) > block.get(su)
.get(leftBoundary) + 1) {
break; // discontinuity
}
}
leftPrevRes = leftBoundary;
leftBoundary--;
}
leftBoundary++;
int rightBoundary = res + 1;
int rightPrevRes = res;
while (true) {
if (rightBoundary == length)
break;
else {
if (block.get(su).get(rightBoundary) == null) {
break; // gap
} else if (block.get(su).get(rightPrevRes) + 1 < block.get(
su).get(rightBoundary)) {
break; // discontinuity
}
}
rightPrevRes = rightBoundary;
rightBoundary++;
}
rightBoundary--;
// Residues at the boundary
Integer residueR0 = block.get(su).get(rightBoundary);
Integer residueL0 = block.get(su).get(leftBoundary);
// Remove residue at the right of the block and add to the freePool
block.get(su).remove(rightBoundary);
if (residueR0 != null) {
freePool.add(residueR0);
Collections.sort(freePool);
}
// Add the residue at the left of the block
residueL0 -= 1; // cannot be null, throw exception if it is
if (freePool.contains(residueL0)) {
block.get(su).add(leftBoundary, residueL0);
freePool.remove(residueL0);
} else {
block.get(su).add(leftBoundary, null);
}
break;
case 1: // Move to the left
int leftBoundary1 = res - 1;
int leftPrevRes1 = res;
while (true) {
if (leftBoundary1 < 0)
break;
else {
if (block.get(su).get(leftBoundary1) == null) {
break; // gap
} else if (block.get(su).get(leftPrevRes1) > block.get(su)
.get(leftBoundary1) + 1) {
break; // discontinuity
}
}
leftPrevRes1 = leftBoundary1;
leftBoundary1--;
}
leftBoundary1++;
int rightBoundary1 = res + 1;
int rightPrevRes1 = res;
while (true) {
if (rightBoundary1 == length)
break;
else {
if (block.get(su).get(rightBoundary1) == null) {
break; // gap
} else if (block.get(su).get(rightPrevRes1) + 1 < block
.get(su).get(rightBoundary1)) {
break; // discontinuity
}
}
rightPrevRes1 = rightBoundary1;
rightBoundary1++;
}
rightBoundary1--;
// Residues at the boundary
Integer residueR1 = block.get(su).get(rightBoundary1);
Integer residueL1 = block.get(su).get(leftBoundary1);
// Add the residue at the right of the block
residueR1 += 1; // cannot be null
if (freePool.contains(residueR1)) {
if (rightBoundary1 == length - 1)
block.get(su).add(residueR1);
else
block.get(su).add(rightBoundary1 + 1, residueR1);
freePool.remove(residueR1);
} else {
block.get(su).add(rightBoundary1 + 1, null);
}
// Remove the residue at the left of the block
block.get(su).remove(leftBoundary1);
freePool.add(residueL1);
Collections.sort(freePool);
break;
}
checkGaps();
return true;
} } | public class class_name {
private boolean shiftRow() {
int su = rnd.nextInt(order); // Select the repeat
int rl = rnd.nextInt(2); // Select between moving right (0) or left (1)
int res = rnd.nextInt(length); // Residue as a pivot
// When the pivot residue is null try to add a residue from the freePool
if (block.get(su).get(res) == null) {
int right = res;
int left = res;
// Find the boundary to the right abd left
while (block.get(su).get(right) == null && right < length - 1) {
right++; // depends on control dependency: [while], data = [none]
}
while (block.get(su).get(left) == null && left > 0) {
left--; // depends on control dependency: [while], data = [none]
}
// If they both are null the whole block is null
if (block.get(su).get(left) == null
&& block.get(su).get(right) == null) {
return false; // depends on control dependency: [if], data = [none]
} else if (block.get(su).get(left) == null) {
// Choose the sequentially previous residue of the known one
Integer residue = block.get(su).get(right) - 1;
if (freePool.contains(residue)) {
block.get(su).set(res, residue); // depends on control dependency: [if], data = [none]
freePool.remove(residue); // depends on control dependency: [if], data = [none]
} else
return false;
} else if (block.get(su).get(right) == null) {
// Choose the sequentially next residue of the known one
Integer residue = block.get(su).get(left) + 1;
if (freePool.contains(residue)) {
block.get(su).set(res, residue); // depends on control dependency: [if], data = [none]
freePool.remove(residue); // depends on control dependency: [if], data = [none]
} else
return false;
} else {
// If boundaries are consecutive swap null and position (R or L)
if (block.get(su).get(right) == block.get(su).get(left) + 1) {
switch (rl) {
case 0: // to the right
block.get(su).set(right - 1, block.get(su).get(right));
block.get(su).set(right, null);
break;
case 1: // to the left
block.get(su).set(left + 1, block.get(su).get(left));
block.get(su).set(left, null);
break;
}
} else {
// Choose randomly a residue in between left and right to
// add
Integer residue = rnd.nextInt(block.get(su).get(right)
- block.get(su).get(left) - 1)
+ block.get(su).get(left) + 1;
if (freePool.contains(residue)) {
block.get(su).set(res, residue); // depends on control dependency: [if], data = [none]
freePool.remove(residue); // depends on control dependency: [if], data = [none]
}
}
}
return true; // depends on control dependency: [if], data = [none]
}
// When the residue is different than null
switch (rl) {
case 0: // Move to the right
int leftBoundary = res - 1;
int leftPrevRes = res;
while (true) {
if (leftBoundary < 0)
break;
else {
if (block.get(su).get(leftBoundary) == null) {
break; // gap
} else if (block.get(su).get(leftPrevRes) > block.get(su)
.get(leftBoundary) + 1) {
break; // discontinuity
}
}
leftPrevRes = leftBoundary; // depends on control dependency: [while], data = [none]
leftBoundary--; // depends on control dependency: [while], data = [none]
}
leftBoundary++;
int rightBoundary = res + 1;
int rightPrevRes = res;
while (true) {
if (rightBoundary == length)
break;
else {
if (block.get(su).get(rightBoundary) == null) {
break; // gap
} else if (block.get(su).get(rightPrevRes) + 1 < block.get(
su).get(rightBoundary)) {
break; // discontinuity
}
}
rightPrevRes = rightBoundary; // depends on control dependency: [while], data = [none]
rightBoundary++; // depends on control dependency: [while], data = [none]
}
rightBoundary--;
// Residues at the boundary
Integer residueR0 = block.get(su).get(rightBoundary);
Integer residueL0 = block.get(su).get(leftBoundary);
// Remove residue at the right of the block and add to the freePool
block.get(su).remove(rightBoundary);
if (residueR0 != null) {
freePool.add(residueR0); // depends on control dependency: [if], data = [(residueR0]
Collections.sort(freePool); // depends on control dependency: [if], data = [none]
}
// Add the residue at the left of the block
residueL0 -= 1; // cannot be null, throw exception if it is
if (freePool.contains(residueL0)) {
block.get(su).add(leftBoundary, residueL0); // depends on control dependency: [if], data = [none]
freePool.remove(residueL0); // depends on control dependency: [if], data = [none]
} else {
block.get(su).add(leftBoundary, null); // depends on control dependency: [if], data = [none]
}
break;
case 1: // Move to the left
int leftBoundary1 = res - 1;
int leftPrevRes1 = res;
while (true) {
if (leftBoundary1 < 0)
break;
else {
if (block.get(su).get(leftBoundary1) == null) {
break; // gap
} else if (block.get(su).get(leftPrevRes1) > block.get(su)
.get(leftBoundary1) + 1) {
break; // discontinuity
}
}
leftPrevRes1 = leftBoundary1; // depends on control dependency: [while], data = [none]
leftBoundary1--; // depends on control dependency: [while], data = [none]
}
leftBoundary1++;
int rightBoundary1 = res + 1;
int rightPrevRes1 = res;
while (true) {
if (rightBoundary1 == length)
break;
else {
if (block.get(su).get(rightBoundary1) == null) {
break; // gap
} else if (block.get(su).get(rightPrevRes1) + 1 < block
.get(su).get(rightBoundary1)) {
break; // discontinuity
}
}
rightPrevRes1 = rightBoundary1; // depends on control dependency: [while], data = [none]
rightBoundary1++; // depends on control dependency: [while], data = [none]
}
rightBoundary1--;
// Residues at the boundary
Integer residueR1 = block.get(su).get(rightBoundary1);
Integer residueL1 = block.get(su).get(leftBoundary1);
// Add the residue at the right of the block
residueR1 += 1; // cannot be null
if (freePool.contains(residueR1)) {
if (rightBoundary1 == length - 1)
block.get(su).add(residueR1);
else
block.get(su).add(rightBoundary1 + 1, residueR1);
freePool.remove(residueR1); // depends on control dependency: [if], data = [none]
} else {
block.get(su).add(rightBoundary1 + 1, null); // depends on control dependency: [if], data = [none]
}
// Remove the residue at the left of the block
block.get(su).remove(leftBoundary1);
freePool.add(residueL1);
Collections.sort(freePool);
break;
}
checkGaps();
return true;
} } |
public class class_name {
public CommandArgs<K, V> addKeys(Iterable<K> keys) {
LettuceAssert.notNull(keys, "Keys must not be null");
for (K key : keys) {
addKey(key);
}
return this;
} } | public class class_name {
public CommandArgs<K, V> addKeys(Iterable<K> keys) {
LettuceAssert.notNull(keys, "Keys must not be null");
for (K key : keys) {
addKey(key); // depends on control dependency: [for], data = [key]
}
return this;
} } |
public class class_name {
protected Object[] getKey(NodeId id) {
if (getStorageModel() == SM_BINARY_KEYS) {
return new Object[] { id.getRawBytes() };
} else {
return new Object[] {
id.getMostSignificantBits(), id.getLeastSignificantBits() };
}
} } | public class class_name {
protected Object[] getKey(NodeId id) {
if (getStorageModel() == SM_BINARY_KEYS) {
return new Object[] { id.getRawBytes() }; // depends on control dependency: [if], data = [none]
} else {
return new Object[] {
id.getMostSignificantBits(), id.getLeastSignificantBits() }; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void resolve(final ValueStack values) throws Exception
{
if (values.size() < 2)
throw new Exception("missing operands for " + toString());
try
{
final Object[] ops = values.ensureSameTypes();
if (ops[0] instanceof LocalDateTime)
{
values.push(new Boolean(((LocalDateTime) ops[1]).compareTo((LocalDateTime) ops[0]) < 0));
return;
}
if (ops[0] instanceof Double)
{
values.push(new Boolean((Double) ops[1] < (Double) ops[0]));
return;
}
if (ops[0] instanceof Long)
{
values.push(new Boolean((Long) ops[1] < (Long) ops[0]));
return;
}
throw new Exception(toString() + "; invalid type, found " + ops[0].getClass().getSimpleName());
} catch (final ParseException e)
{
e.fillInStackTrace();
throw new Exception(toString() + "; " + e.getMessage(), e);
}
} } | public class class_name {
@Override
public void resolve(final ValueStack values) throws Exception
{
if (values.size() < 2)
throw new Exception("missing operands for " + toString());
try
{
final Object[] ops = values.ensureSameTypes();
if (ops[0] instanceof LocalDateTime)
{
values.push(new Boolean(((LocalDateTime) ops[1]).compareTo((LocalDateTime) ops[0]) < 0)); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (ops[0] instanceof Double)
{
values.push(new Boolean((Double) ops[1] < (Double) ops[0])); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (ops[0] instanceof Long)
{
values.push(new Boolean((Long) ops[1] < (Long) ops[0])); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
throw new Exception(toString() + "; invalid type, found " + ops[0].getClass().getSimpleName());
} catch (final ParseException e)
{
e.fillInStackTrace();
throw new Exception(toString() + "; " + e.getMessage(), e);
}
} } |
public class class_name {
private static List<Annotation> selectMatching(CAS cas, final int begin,
final int end, AnnotationFS annotationCloseToTheRegion) {
final List<Annotation> list = new ArrayList<Annotation>();
final FSIterator<AnnotationFS> it = cas.getAnnotationIndex().iterator();
// Try to seek the insertion point.
it.moveTo(annotationCloseToTheRegion);
// If the insertion point is beyond the index, move back to the last.
if (!it.isValid()) {
it.moveToLast();
if (!it.isValid()) {
return list;
}
}
// Ignore type priorities by seeking to the first that has the same
// begin
boolean moved = false;
while (it.isValid() && (it.get()).getBegin() >= begin) {
it.moveToPrevious();
moved = true;
}
// If we moved, then we are now on one starting before the requested
// begin, so we have to
// move one ahead.
if (moved) {
it.moveToNext();
}
// If we managed to move outside the index, start at first.
if (!it.isValid()) {
it.moveToFirst();
}
// Skip annotations whose start is before the start parameter.
while (it.isValid() && (it.get()).getBegin() < begin) {
it.moveToNext();
}
while (it.isValid()) {
AnnotationFS a = it.get();
if (!(a instanceof Annotation))
continue;
// If the start of the current annotation is past the end parameter,
// we're done.
if (a.getBegin() > end) {
break;
}
it.moveToNext();
if (a.getBegin() == begin && a.getEnd() == end) {
list.add((Annotation) a);
}
}
return unmodifiableList(list);
} } | public class class_name {
private static List<Annotation> selectMatching(CAS cas, final int begin,
final int end, AnnotationFS annotationCloseToTheRegion) {
final List<Annotation> list = new ArrayList<Annotation>();
final FSIterator<AnnotationFS> it = cas.getAnnotationIndex().iterator();
// Try to seek the insertion point.
it.moveTo(annotationCloseToTheRegion);
// If the insertion point is beyond the index, move back to the last.
if (!it.isValid()) {
it.moveToLast(); // depends on control dependency: [if], data = [none]
if (!it.isValid()) {
return list; // depends on control dependency: [if], data = [none]
}
}
// Ignore type priorities by seeking to the first that has the same
// begin
boolean moved = false;
while (it.isValid() && (it.get()).getBegin() >= begin) {
it.moveToPrevious(); // depends on control dependency: [while], data = [none]
moved = true; // depends on control dependency: [while], data = [none]
}
// If we moved, then we are now on one starting before the requested
// begin, so we have to
// move one ahead.
if (moved) {
it.moveToNext(); // depends on control dependency: [if], data = [none]
}
// If we managed to move outside the index, start at first.
if (!it.isValid()) {
it.moveToFirst(); // depends on control dependency: [if], data = [none]
}
// Skip annotations whose start is before the start parameter.
while (it.isValid() && (it.get()).getBegin() < begin) {
it.moveToNext(); // depends on control dependency: [while], data = [none]
}
while (it.isValid()) {
AnnotationFS a = it.get();
if (!(a instanceof Annotation))
continue;
// If the start of the current annotation is past the end parameter,
// we're done.
if (a.getBegin() > end) {
break;
}
it.moveToNext(); // depends on control dependency: [while], data = [none]
if (a.getBegin() == begin && a.getEnd() == end) {
list.add((Annotation) a); // depends on control dependency: [if], data = [none]
}
}
return unmodifiableList(list);
} } |
public class class_name {
public void setPropertySortingComparator(Comparator comp) {
Comparator old = propertySortingComparator;
propertySortingComparator = comp;
if (propertySortingComparator != old) {
buildModel();
}
} } | public class class_name {
public void setPropertySortingComparator(Comparator comp) {
Comparator old = propertySortingComparator;
propertySortingComparator = comp;
if (propertySortingComparator != old) {
buildModel(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static List<String> readDataFromCVSFileToList(final File input, final int position,
final boolean putFirstLine, final String splitChar, final String encoding)
throws IOException
{
final List<String> output = new ArrayList<>();
try (BufferedReader reader = (BufferedReader)StreamExtensions.getReader(input, encoding,
false))
{
// the line.
String line = null;
// read all lines from the file
do
{
line = reader.readLine();
// if null break the loop
if (line == null)
{
break;
}
// Split the line
final String[] splittedData = line.split(splitChar);
// get the data with the index
if (position <= splittedData.length - 1)
{
final String s = StringExtensions.removeQuotationMarks(splittedData[position]);
output.add(s);
}
}
while (true);
}
catch (final IOException e)
{
throw e;
}
// return the list with all lines from the file.
if (!putFirstLine)
{
output.remove(0);
}
return output;
} } | public class class_name {
public static List<String> readDataFromCVSFileToList(final File input, final int position,
final boolean putFirstLine, final String splitChar, final String encoding)
throws IOException
{
final List<String> output = new ArrayList<>();
try (BufferedReader reader = (BufferedReader)StreamExtensions.getReader(input, encoding,
false))
{
// the line.
String line = null;
// read all lines from the file
do
{
line = reader.readLine();
// if null break the loop
if (line == null)
{
break;
}
// Split the line
final String[] splittedData = line.split(splitChar);
// get the data with the index
if (position <= splittedData.length - 1)
{
final String s = StringExtensions.removeQuotationMarks(splittedData[position]);
output.add(s); // depends on control dependency: [if], data = [none]
}
}
while (true);
}
catch (final IOException e)
{
throw e;
}
// return the list with all lines from the file.
if (!putFirstLine)
{
output.remove(0);
}
return output;
} } |
public class class_name {
private double calculateSurfaceTemperature( int[] conv, double Ts, double Tin, double Ta, double P, double V, double ea,
double Rsw, double Rlwin, double Qp, double rho, double cp, double Fcanopy, double K, double rho_sn, double Ks,
double eps, double Ts_min, double Ts_max ) {
double a, b, Ts0;
short cont;
// coefficienti non dipendenti dalla temperatura della superficie
a = Rsw + Rlwin + Qp + K * V * Ta * rho * cp + rho_sn * C_ice * Ks * Tin + 0.622 * K * V * Lv * rho * ea / P;
b = rho_sn * C_ice * Ks + K * V * rho * cp;
cont = 0;
do {
Ts0 = Ts;
Ts = (a - 0.622 * K * V * Lv * rho * (pVap(Ts0, P) - Ts * dpVap(Ts0, P)) / P + 3.0 * Fcanopy * sigma * eps
* pow(Ts0 + tk, 4.0))
/ (b + 0.622 * dpVap(Ts0, P) * K * V * Lv * rho / P + 4.0 * Fcanopy * eps * sigma * pow(Ts0 + tk, 3.0));
cont += 1;
} while( abs(Ts - Ts0) > defaultTollTs && cont <= defaultTsiter );
// controlli
if (abs(Ts - Ts0) > defaultTollTs) {
conv[0] = 0; // non converge
} else {
conv[0] = 1; // converge
}
if (Ts < Ts_min || Ts > Ts_max)
conv[0] = -1; // fuori dai limiti di ammissibilita'
Ts0 = Ts;
return Ts0;
} } | public class class_name {
private double calculateSurfaceTemperature( int[] conv, double Ts, double Tin, double Ta, double P, double V, double ea,
double Rsw, double Rlwin, double Qp, double rho, double cp, double Fcanopy, double K, double rho_sn, double Ks,
double eps, double Ts_min, double Ts_max ) {
double a, b, Ts0;
short cont;
// coefficienti non dipendenti dalla temperatura della superficie
a = Rsw + Rlwin + Qp + K * V * Ta * rho * cp + rho_sn * C_ice * Ks * Tin + 0.622 * K * V * Lv * rho * ea / P;
b = rho_sn * C_ice * Ks + K * V * rho * cp;
cont = 0;
do {
Ts0 = Ts;
Ts = (a - 0.622 * K * V * Lv * rho * (pVap(Ts0, P) - Ts * dpVap(Ts0, P)) / P + 3.0 * Fcanopy * sigma * eps
* pow(Ts0 + tk, 4.0))
/ (b + 0.622 * dpVap(Ts0, P) * K * V * Lv * rho / P + 4.0 * Fcanopy * eps * sigma * pow(Ts0 + tk, 3.0));
cont += 1;
} while( abs(Ts - Ts0) > defaultTollTs && cont <= defaultTsiter );
// controlli
if (abs(Ts - Ts0) > defaultTollTs) {
conv[0] = 0; // non converge // depends on control dependency: [if], data = [none]
} else {
conv[0] = 1; // converge // depends on control dependency: [if], data = [none]
}
if (Ts < Ts_min || Ts > Ts_max)
conv[0] = -1; // fuori dai limiti di ammissibilita'
Ts0 = Ts;
return Ts0;
} } |
public class class_name {
@Override
public boolean isBodyAllowed() {
if (super.isBodyAllowed()) {
// sending a body with the response is not valid for a HEAD request
if (getServiceContext().getRequestMethod().equals(MethodValues.HEAD)) {
return false;
}
// if that worked, then check the status code flag
return this.myStatusCode.isBodyAllowed();
}
// no body allowed on this message
return false;
} } | public class class_name {
@Override
public boolean isBodyAllowed() {
if (super.isBodyAllowed()) {
// sending a body with the response is not valid for a HEAD request
if (getServiceContext().getRequestMethod().equals(MethodValues.HEAD)) {
return false; // depends on control dependency: [if], data = [none]
}
// if that worked, then check the status code flag
return this.myStatusCode.isBodyAllowed(); // depends on control dependency: [if], data = [none]
}
// no body allowed on this message
return false;
} } |
public class class_name {
public static <K, V> HashMap<K, V> newHashMap(@NotNull final List<K> keys, @NotNull final List<V> values) {
Validate.isTrue(keys.size() == values.size(), "keys.length is %s but values.length is %s", keys.size(),
values.size());
HashMap<K, V> map = new HashMap<K, V>(keys.size() * 2);
Iterator<K> keyIt = keys.iterator();
Iterator<V> valueIt = values.iterator();
while (keyIt.hasNext()) {
map.put(keyIt.next(), valueIt.next());
}
return map;
} } | public class class_name {
public static <K, V> HashMap<K, V> newHashMap(@NotNull final List<K> keys, @NotNull final List<V> values) {
Validate.isTrue(keys.size() == values.size(), "keys.length is %s but values.length is %s", keys.size(),
values.size());
HashMap<K, V> map = new HashMap<K, V>(keys.size() * 2);
Iterator<K> keyIt = keys.iterator();
Iterator<V> valueIt = values.iterator();
while (keyIt.hasNext()) {
map.put(keyIt.next(), valueIt.next()); // depends on control dependency: [while], data = [none]
}
return map;
} } |
public class class_name {
@Deprecated
public void addArguments(String[] argList) throws DuplicateOptionException,
InvalidFormatException {
for (String arg : argList) {
Argument f = new Argument();
String[] breakdown = arg.split(",");
for (String s : breakdown) {
s = s.trim();
if (s.startsWith("--")) {
f.longOption = noDashes(s);
} else if (s.startsWith("-h")) {
f.helpText = s.substring(2);
} else if (s.startsWith("-")) {
f.option = noDashes(s);
} else if (s.equals("+")) {
f.takesValue = true;
f.valueRequired = true;
} else if (s.equals("?")) {
f.isParam = true;
f.takesValue = true;
params.add(f);
} else if (s.equals("*")) {
f.takesValue = true;
} else {
throw new InvalidFormatException(s + " in " + arg
+ " is not formatted correctly.");
}
}
addArgument(f);
}
} } | public class class_name {
@Deprecated
public void addArguments(String[] argList) throws DuplicateOptionException,
InvalidFormatException {
for (String arg : argList) {
Argument f = new Argument();
String[] breakdown = arg.split(",");
for (String s : breakdown) {
s = s.trim();
if (s.startsWith("--")) {
f.longOption = noDashes(s); // depends on control dependency: [if], data = [none]
} else if (s.startsWith("-h")) {
f.helpText = s.substring(2); // depends on control dependency: [if], data = [none]
} else if (s.startsWith("-")) {
f.option = noDashes(s); // depends on control dependency: [if], data = [none]
} else if (s.equals("+")) {
f.takesValue = true; // depends on control dependency: [if], data = [none]
f.valueRequired = true; // depends on control dependency: [if], data = [none]
} else if (s.equals("?")) {
f.isParam = true; // depends on control dependency: [if], data = [none]
f.takesValue = true; // depends on control dependency: [if], data = [none]
params.add(f); // depends on control dependency: [if], data = [none]
} else if (s.equals("*")) {
f.takesValue = true; // depends on control dependency: [if], data = [none]
} else {
throw new InvalidFormatException(s + " in " + arg
+ " is not formatted correctly.");
}
}
addArgument(f);
}
} } |
public class class_name {
synchronized void captureCheckpointManagedObjects()
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
"captureCheckpointManagedObjectsremove"
);
// Now that we are synchronized check that we have not captured the checkpoint sets already.
if (checkpointManagedObjectsToWrite == null) {
// Take the tokens to write first, if we miss a delete we will catch it next time.
// The managedObjectsToWrite and tokensToDelete sets are volatile so users of the store will move to them
// promptly.
checkpointManagedObjectsToWrite = managedObjectsToWrite;
managedObjectsToWrite = new ConcurrentHashMap(concurrency);
checkpointTokensToDelete = tokensToDelete;
tokensToDelete = new ConcurrentHashMap(concurrency);
}
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
"captureCheckpointManagedObjects");
} } | public class class_name {
synchronized void captureCheckpointManagedObjects()
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
"captureCheckpointManagedObjectsremove"
);
// Now that we are synchronized check that we have not captured the checkpoint sets already.
if (checkpointManagedObjectsToWrite == null) {
// Take the tokens to write first, if we miss a delete we will catch it next time.
// The managedObjectsToWrite and tokensToDelete sets are volatile so users of the store will move to them
// promptly.
checkpointManagedObjectsToWrite = managedObjectsToWrite; // depends on control dependency: [if], data = [none]
managedObjectsToWrite = new ConcurrentHashMap(concurrency); // depends on control dependency: [if], data = [none]
checkpointTokensToDelete = tokensToDelete; // depends on control dependency: [if], data = [none]
tokensToDelete = new ConcurrentHashMap(concurrency); // depends on control dependency: [if], data = [none]
}
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
"captureCheckpointManagedObjects");
} } |
public class class_name {
private boolean processAuthenticationResponse(final HttpMethod method) {
LOG.trace("enter HttpMethodBase.processAuthenticationResponse("
+ "HttpState, HttpConnection)");
try {
switch (method.getStatusCode()) {
case HttpStatus.SC_UNAUTHORIZED:
return processWWWAuthChallenge(method);
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
return processProxyAuthChallenge(method);
default:
return false;
}
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.getMessage(), e);
}
return false;
}
} } | public class class_name {
private boolean processAuthenticationResponse(final HttpMethod method) {
LOG.trace("enter HttpMethodBase.processAuthenticationResponse("
+ "HttpState, HttpConnection)");
try {
switch (method.getStatusCode()) {
case HttpStatus.SC_UNAUTHORIZED:
return processWWWAuthChallenge(method);
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
return processProxyAuthChallenge(method);
default:
return false;
}
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error(e.getMessage(), e); // depends on control dependency: [if], data = [none]
}
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Node<E> offerAndGetNode(E e) {
mPutLock.lock();
try {
Node newNode = mNodePool.borrowNode(e);
if (mSize.get() > 0)
newNode.mPrev = mTail;
mTail.mNext = newNode;
if (mSize.get() <= 1) {
mPollLock.lock();
try {
if (mSize.get() == 0)
mHead.mNext = newNode;
else
mHead.mNext = newNode.mPrev;
}
finally {
mPollLock.unlock();
}
}
mSize.incrementAndGet();
mTail = newNode;
return newNode;
}
finally {
mPutLock.unlock();
}
} } | public class class_name {
public Node<E> offerAndGetNode(E e) {
mPutLock.lock();
try {
Node newNode = mNodePool.borrowNode(e);
if (mSize.get() > 0)
newNode.mPrev = mTail;
mTail.mNext = newNode; // depends on control dependency: [try], data = [none]
if (mSize.get() <= 1) {
mPollLock.lock(); // depends on control dependency: [if], data = [none]
try {
if (mSize.get() == 0)
mHead.mNext = newNode;
else
mHead.mNext = newNode.mPrev;
}
finally {
mPollLock.unlock();
}
}
mSize.incrementAndGet(); // depends on control dependency: [try], data = [none]
mTail = newNode; // depends on control dependency: [try], data = [none]
return newNode; // depends on control dependency: [try], data = [none]
}
finally {
mPutLock.unlock();
}
} } |
public class class_name {
public String listCsv() {
StringBuffer csv = new StringBuffer(5120);
csv.append(m_metadata.csvHeader());
if (getContent().isEmpty()) {
csv.append(m_metadata.csvEmptyList());
} else {
Iterator<CmsListItem> itItems = getContent().iterator();
while (itItems.hasNext()) {
CmsListItem item = itItems.next();
csv.append(m_metadata.csvItem(item));
}
}
return getWp().resolveMacros(csv.toString());
} } | public class class_name {
public String listCsv() {
StringBuffer csv = new StringBuffer(5120);
csv.append(m_metadata.csvHeader());
if (getContent().isEmpty()) {
csv.append(m_metadata.csvEmptyList()); // depends on control dependency: [if], data = [none]
} else {
Iterator<CmsListItem> itItems = getContent().iterator();
while (itItems.hasNext()) {
CmsListItem item = itItems.next();
csv.append(m_metadata.csvItem(item)); // depends on control dependency: [while], data = [none]
}
}
return getWp().resolveMacros(csv.toString());
} } |
public class class_name {
public void updatePosition() {
setPosition(CmsPositionBean.getBoundingClientRect(m_element));
for (Widget widget : m_buttonPanel) {
if (widget instanceof CmsInlineEntityWidget) {
((CmsInlineEntityWidget)widget).positionWidget();
}
}
} } | public class class_name {
public void updatePosition() {
setPosition(CmsPositionBean.getBoundingClientRect(m_element));
for (Widget widget : m_buttonPanel) {
if (widget instanceof CmsInlineEntityWidget) {
((CmsInlineEntityWidget)widget).positionWidget();
// depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static int waitForExitProcess(Pointer hProcess) throws InterruptedException {
while (true) {
if (Thread.interrupted())
throw new InterruptedException();
Kernel32.INSTANCE.WaitForSingleObject(hProcess,1000);
IntByReference exitCode = new IntByReference();
exitCode.setValue(-1);
Kernel32.INSTANCE.GetExitCodeProcess(hProcess,exitCode);
int v = exitCode.getValue();
if (v !=Kernel32.STILL_ACTIVE) {
return v;
}
}
} } | public class class_name {
public static int waitForExitProcess(Pointer hProcess) throws InterruptedException {
while (true) {
if (Thread.interrupted())
throw new InterruptedException();
Kernel32.INSTANCE.WaitForSingleObject(hProcess,1000);
IntByReference exitCode = new IntByReference();
exitCode.setValue(-1);
Kernel32.INSTANCE.GetExitCodeProcess(hProcess,exitCode);
int v = exitCode.getValue();
if (v !=Kernel32.STILL_ACTIVE) {
return v; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private static void validateJndiLookup(String lookupString, Annotated annotated, Class<?> declaringClass, CDIArchive cdiArchive) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "validateJndiLookup", new Object[] { Util.identity(annotated), declaringClass, cdiArchive });
}
// We need to set a current component before doing anything to do with JNDI
CDIRuntime cdiRuntime = cdiArchive.getCDIRuntime();
try {
cdiRuntime.beginContext(cdiArchive);
InitialContext c = new InitialContext();
validateJndiLookup(c, lookupString, annotated, declaringClass, cdiArchive);
} catch (NamingException ex) {
// Failed to look up the object, just return without failing validation
} catch (CDIException e) {
throw new IllegalStateException(e);
} finally {
cdiRuntime.endContext();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "validateJndiLookup", new Object[] { Util.identity(annotated) });
}
} } | public class class_name {
private static void validateJndiLookup(String lookupString, Annotated annotated, Class<?> declaringClass, CDIArchive cdiArchive) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "validateJndiLookup", new Object[] { Util.identity(annotated), declaringClass, cdiArchive }); // depends on control dependency: [if], data = [none]
}
// We need to set a current component before doing anything to do with JNDI
CDIRuntime cdiRuntime = cdiArchive.getCDIRuntime();
try {
cdiRuntime.beginContext(cdiArchive); // depends on control dependency: [try], data = [none]
InitialContext c = new InitialContext();
validateJndiLookup(c, lookupString, annotated, declaringClass, cdiArchive); // depends on control dependency: [try], data = [none]
} catch (NamingException ex) {
// Failed to look up the object, just return without failing validation
} catch (CDIException e) { // depends on control dependency: [catch], data = [none]
throw new IllegalStateException(e);
} finally { // depends on control dependency: [catch], data = [none]
cdiRuntime.endContext();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "validateJndiLookup", new Object[] { Util.identity(annotated) }); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static AVIMClient getInstance(String clientId) {
if (StringUtil.isEmpty(clientId)) {
return null;
}
AVIMClient client = clients.get(clientId);
if (null == client) {
client = new AVIMClient(clientId);
AVIMClient elderClient = clients.putIfAbsent(clientId, client);
if (null != elderClient) {
client = elderClient;
}
}
return client;
} } | public class class_name {
public static AVIMClient getInstance(String clientId) {
if (StringUtil.isEmpty(clientId)) {
return null; // depends on control dependency: [if], data = [none]
}
AVIMClient client = clients.get(clientId);
if (null == client) {
client = new AVIMClient(clientId); // depends on control dependency: [if], data = [none]
AVIMClient elderClient = clients.putIfAbsent(clientId, client);
if (null != elderClient) {
client = elderClient; // depends on control dependency: [if], data = [none]
}
}
return client;
} } |
public class class_name {
@Expose
protected List<Exception> getExceptions() {
List<Exception> exceptions = new ArrayList<Exception>();
exceptions.add(exception);
Throwable currentThrowable = exception.getThrowable().getCause();
while (currentThrowable != null) {
exceptions.add(new Exception(config, currentThrowable));
currentThrowable = currentThrowable.getCause();
}
return exceptions;
} } | public class class_name {
@Expose
protected List<Exception> getExceptions() {
List<Exception> exceptions = new ArrayList<Exception>();
exceptions.add(exception);
Throwable currentThrowable = exception.getThrowable().getCause();
while (currentThrowable != null) {
exceptions.add(new Exception(config, currentThrowable)); // depends on control dependency: [while], data = [none]
currentThrowable = currentThrowable.getCause(); // depends on control dependency: [while], data = [none]
}
return exceptions;
} } |
public class class_name {
@Override
public EClass getIfcMaterialRelationship() {
if (ifcMaterialRelationshipEClass == null) {
ifcMaterialRelationshipEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(373);
}
return ifcMaterialRelationshipEClass;
} } | public class class_name {
@Override
public EClass getIfcMaterialRelationship() {
if (ifcMaterialRelationshipEClass == null) {
ifcMaterialRelationshipEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(373);
// depends on control dependency: [if], data = [none]
}
return ifcMaterialRelationshipEClass;
} } |
public class class_name {
public static int[] range(int length) {
int[] index = new int[length];
for (int i=0; i<index.length; i++) {
// TODO: This should maybe be a safe cast for the benefit of non-IntDouble classes.
index[i] = (int) i;
}
return index;
} } | public class class_name {
public static int[] range(int length) {
int[] index = new int[length];
for (int i=0; i<index.length; i++) {
// TODO: This should maybe be a safe cast for the benefit of non-IntDouble classes.
index[i] = (int) i; // depends on control dependency: [for], data = [i]
}
return index;
} } |
public class class_name {
@Override
protected boolean onLevelChange(int level) {
if (mIsRunning) {
// If the client called start on us, they expect us to run the animation. In that case,
// we ignore level changes.
return false;
}
if (mLastFrameAnimationTimeMs != level) {
mLastFrameAnimationTimeMs = level;
invalidateSelf();
return true;
}
return false;
} } | public class class_name {
@Override
protected boolean onLevelChange(int level) {
if (mIsRunning) {
// If the client called start on us, they expect us to run the animation. In that case,
// we ignore level changes.
return false; // depends on control dependency: [if], data = [none]
}
if (mLastFrameAnimationTimeMs != level) {
mLastFrameAnimationTimeMs = level; // depends on control dependency: [if], data = [none]
invalidateSelf(); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public static boolean isServiceNode(ChildData zNode) {
String path = zNode.getPath();
LOG.debug("正在检查节点路径: " + path);
LOG.debug("服务注册路径: " + getNodeBasePath());
if (!path.startsWith(getNodeBasePath()) || path.equals(getNodeBasePath())) {
return false;
}
String name = path.substring((getNodeBasePath() + "/").length());
String[] names = name.split("/");
if (names.length != 2) {
return false;
}
/*if (!SystemEnum.isServiceNodeName(names[0])) {
todo 由于去掉了systemEnum类,我们在watch到zk外部服务注册事件之前,根本不知道到底有哪些application
return false;
}*/
String zNodeDataStr = new String(zNode.getData());
JSONObject zNodeData;
try {
zNodeData = JSON.parseObject(zNodeDataStr);
} catch (JSONException notJsonString) {
LOG.debug(String.format("节点%s的data是%s,它不是我们要找的那个服务节点,排除掉! 这是我期待结果之一,不打印堆栈", path, zNodeDataStr));
return false;
}
try {
if (zNodeData.getJSONObject("payload") == null) {
LOG.debug(String.format("节点=%s,内容=%s,其内缺少payload属性,它不是我们预期的服务节点!", path, zNodeDataStr));
return false;
}
} catch (JSONException payloadIsNotJsonString) {
LOG.info(String.format("节点%s的data=%s,其内的payload属性是不是json格式,肯定是有非预期的节点混入,这里排除之", path, zNodeDataStr));
return false;
}
return true;
} } | public class class_name {
public static boolean isServiceNode(ChildData zNode) {
String path = zNode.getPath();
LOG.debug("正在检查节点路径: " + path);
LOG.debug("服务注册路径: " + getNodeBasePath());
if (!path.startsWith(getNodeBasePath()) || path.equals(getNodeBasePath())) {
return false; // depends on control dependency: [if], data = [none]
}
String name = path.substring((getNodeBasePath() + "/").length());
String[] names = name.split("/");
if (names.length != 2) {
return false; // depends on control dependency: [if], data = [none]
}
/*if (!SystemEnum.isServiceNodeName(names[0])) {
todo 由于去掉了systemEnum类,我们在watch到zk外部服务注册事件之前,根本不知道到底有哪些application
return false;
}*/
String zNodeDataStr = new String(zNode.getData());
JSONObject zNodeData;
try {
zNodeData = JSON.parseObject(zNodeDataStr); // depends on control dependency: [try], data = [none]
} catch (JSONException notJsonString) {
LOG.debug(String.format("节点%s的data是%s,它不是我们要找的那个服务节点,排除掉! 这是我期待结果之一,不打印堆栈", path, zNodeDataStr));
return false;
} // depends on control dependency: [catch], data = [none]
try {
if (zNodeData.getJSONObject("payload") == null) {
LOG.debug(String.format("节点=%s,内容=%s,其内缺少payload属性,它不是我们预期的服务节点!", path, zNodeDataStr)); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
} catch (JSONException payloadIsNotJsonString) {
LOG.info(String.format("节点%s的data=%s,其内的payload属性是不是json格式,肯定是有非预期的节点混入,这里排除之", path, zNodeDataStr));
return false;
} // depends on control dependency: [catch], data = [none]
return true;
} } |
public class class_name {
public static List<Element> getChildElementsByTagName(Element ele, String[] childEleNames) {
Assert.notNull(ele, "Element must not be null");
Assert.notNull(childEleNames, "Element names collection must not be null");
List<String> childEleNameList = Arrays.asList(childEleNames);
NodeList nl = ele.getChildNodes();
List<Element> childEles = new ArrayList<Element>();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && nodeNameMatch(node, childEleNameList)) {
childEles.add((Element) node);
}
}
return childEles;
} } | public class class_name {
public static List<Element> getChildElementsByTagName(Element ele, String[] childEleNames) {
Assert.notNull(ele, "Element must not be null");
Assert.notNull(childEleNames, "Element names collection must not be null");
List<String> childEleNameList = Arrays.asList(childEleNames);
NodeList nl = ele.getChildNodes();
List<Element> childEles = new ArrayList<Element>();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && nodeNameMatch(node, childEleNameList)) {
childEles.add((Element) node); // depends on control dependency: [if], data = [none]
}
}
return childEles;
} } |
public class class_name {
public static <T> String getUpdateAllSQL(Class<T> clazz, String setSql, String whereSql,
String extraWhereSql) {
StringBuilder sql = new StringBuilder();
sql.append("UPDATE ");
Table table = DOInfoReader.getTable(clazz);
List<Field> fields = DOInfoReader.getColumns(clazz);
sql.append(getTableName(table)).append(" ");
if(setSql.trim().toLowerCase().startsWith("set ")) {
sql.append(setSql);
} else {
sql.append("SET ").append(setSql);
}
// 加上更新时间
for(Field field : fields) {
Column column = field.getAnnotation(Column.class);
if(column.setTimeWhenUpdate() && Date.class.isAssignableFrom(field.getType())) {
sql.append(",").append(getColumnName(column))
.append("=").append(getDateString(new Date()));
}
}
sql.append(autoSetSoftDeleted(whereSql, clazz, extraWhereSql));
return sql.toString();
} } | public class class_name {
public static <T> String getUpdateAllSQL(Class<T> clazz, String setSql, String whereSql,
String extraWhereSql) {
StringBuilder sql = new StringBuilder();
sql.append("UPDATE ");
Table table = DOInfoReader.getTable(clazz);
List<Field> fields = DOInfoReader.getColumns(clazz);
sql.append(getTableName(table)).append(" ");
if(setSql.trim().toLowerCase().startsWith("set ")) {
sql.append(setSql); // depends on control dependency: [if], data = [none]
} else {
sql.append("SET ").append(setSql); // depends on control dependency: [if], data = [none]
}
// 加上更新时间
for(Field field : fields) {
Column column = field.getAnnotation(Column.class);
if(column.setTimeWhenUpdate() && Date.class.isAssignableFrom(field.getType())) {
sql.append(",").append(getColumnName(column))
.append("=").append(getDateString(new Date())); // depends on control dependency: [if], data = [none]
}
}
sql.append(autoSetSoftDeleted(whereSql, clazz, extraWhereSql));
return sql.toString();
} } |
public class class_name {
public Object getValue(final int pos) {
Object val = list.get(pos);
if (val instanceof Map) {
val = new JsonObject((Map) val);
}
else if (val instanceof List) {
val = new JsonArray((List) val);
}
return val;
} } | public class class_name {
public Object getValue(final int pos) {
Object val = list.get(pos);
if (val instanceof Map) {
val = new JsonObject((Map) val); // depends on control dependency: [if], data = [none]
}
else if (val instanceof List) {
val = new JsonArray((List) val); // depends on control dependency: [if], data = [none]
}
return val;
} } |
public class class_name {
@Override
public boolean start()
{
if (! _lifecycle.toStarting()) {
return false;
}
_fd = createNative();
if (_fd == 0) {
_lifecycle.toDestroy();
log.finer(this + " is not available on this system.");
return false;
}
String name = "resin-select-manager-" + _gId++;
_thread = new Thread(new SelectTask(), name);
_thread.setDaemon(true);
_thread.setPriority(Thread.MAX_PRIORITY);
_thread.start();
_lifecycle.waitForActive(2000);
if (log.isLoggable(Level.FINER))
log.finer(this + " active");
log.fine("Async/poll keepalive enabled with max sockets = "
+ _selectMax);
name = "resin-select-manager-timeout-" + _gId++;
Thread timeoutThread = new Thread(new TimeoutTask(), name);
timeoutThread.setDaemon(true);
timeoutThread.start();
return true;
} } | public class class_name {
@Override
public boolean start()
{
if (! _lifecycle.toStarting()) {
return false; // depends on control dependency: [if], data = [none]
}
_fd = createNative();
if (_fd == 0) {
_lifecycle.toDestroy(); // depends on control dependency: [if], data = [none]
log.finer(this + " is not available on this system."); // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
String name = "resin-select-manager-" + _gId++;
_thread = new Thread(new SelectTask(), name);
_thread.setDaemon(true);
_thread.setPriority(Thread.MAX_PRIORITY);
_thread.start();
_lifecycle.waitForActive(2000);
if (log.isLoggable(Level.FINER))
log.finer(this + " active");
log.fine("Async/poll keepalive enabled with max sockets = "
+ _selectMax);
name = "resin-select-manager-timeout-" + _gId++;
Thread timeoutThread = new Thread(new TimeoutTask(), name);
timeoutThread.setDaemon(true);
timeoutThread.start();
return true;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.