code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
private double initScore() {
double score = 0;
final int n = atoms.length;
for (int i = 0; i < n; i++) {
final Point2d p1 = atoms[i].getPoint2d();
for (int j = i + 1; j < n; j++) {
if (contribution[i][j] < 0) continue;
final Point2d p2 = atoms[j].getPoint2d();
final double x = p1.x - p2.x;
final double y = p1.y - p2.y;
final double len2 = x * x + y * y;
score += contribution[j][i] = contribution[i][j] = 1 / Math.max(len2, MIN_SCORE);
}
}
return score;
} } | public class class_name {
private double initScore() {
double score = 0;
final int n = atoms.length;
for (int i = 0; i < n; i++) {
final Point2d p1 = atoms[i].getPoint2d();
for (int j = i + 1; j < n; j++) {
if (contribution[i][j] < 0) continue;
final Point2d p2 = atoms[j].getPoint2d();
final double x = p1.x - p2.x;
final double y = p1.y - p2.y;
final double len2 = x * x + y * y;
score += contribution[j][i] = contribution[i][j] = 1 / Math.max(len2, MIN_SCORE); // depends on control dependency: [for], data = [j]
}
}
return score;
} } |
public class class_name {
protected void onSourceErrorOccurred(boolean isTerminating, Exception exception) {
for (TransformerSourceEventListener listener : transformerSourceEventListeners) {
fireErrorEvent(listener, new TransformerSourceErrorEvent(this, exception, isTerminating));
}
} } | public class class_name {
protected void onSourceErrorOccurred(boolean isTerminating, Exception exception) {
for (TransformerSourceEventListener listener : transformerSourceEventListeners) {
fireErrorEvent(listener, new TransformerSourceErrorEvent(this, exception, isTerminating)); // depends on control dependency: [for], data = [listener]
}
} } |
public class class_name {
private void persistCaches() {
for (Entry<CacheKey, Map<String, String>> cacheEntry : caches.entrySet()) {
persistCache(cacheEntry.getKey().projectName, cacheEntry.getKey().projectVersion, cacheEntry.getValue());
}
} } | public class class_name {
private void persistCaches() {
for (Entry<CacheKey, Map<String, String>> cacheEntry : caches.entrySet()) {
persistCache(cacheEntry.getKey().projectName, cacheEntry.getKey().projectVersion, cacheEntry.getValue()); // depends on control dependency: [for], data = [cacheEntry]
}
} } |
public class class_name {
@Override
public int compareTo(final WorkerInfo other) {
int retVal = 1;
if (other != null) {
if (this.status != null && other.status != null) {
if (this.status.getRunAt() != null && other.status.getRunAt() != null) {
retVal = this.status.getRunAt().compareTo(other.status.getRunAt());
} else if (this.status.getRunAt() == null) {
retVal = (other.status.getRunAt() == null) ? 0 : -1;
}
} else if (this.status == null) {
retVal = (other.status == null) ? 0 : -1;
}
}
return retVal;
} } | public class class_name {
@Override
public int compareTo(final WorkerInfo other) {
int retVal = 1;
if (other != null) {
if (this.status != null && other.status != null) {
if (this.status.getRunAt() != null && other.status.getRunAt() != null) {
retVal = this.status.getRunAt().compareTo(other.status.getRunAt()); // depends on control dependency: [if], data = [none]
} else if (this.status.getRunAt() == null) {
retVal = (other.status.getRunAt() == null) ? 0 : -1; // depends on control dependency: [if], data = [null)]
}
} else if (this.status == null) {
retVal = (other.status == null) ? 0 : -1; // depends on control dependency: [if], data = [null)]
}
}
return retVal;
} } |
public class class_name {
public <S> List<S> select(List<EvaluatedCandidate<S>> population,
boolean naturalFitnessScores,
int selectionSize,
Random rng)
{
List<EvaluatedCandidate<S>> rankedPopulation = new ArrayList<EvaluatedCandidate<S>>(population.size());
Iterator<EvaluatedCandidate<S>> iterator = population.iterator();
int index = -1;
while (iterator.hasNext())
{
S candidate = iterator.next().getCandidate();
rankedPopulation.add(new EvaluatedCandidate<S>(candidate,
mapRankToScore(++index,
population.size())));
}
return delegate.select(rankedPopulation, true, selectionSize, rng);
} } | public class class_name {
public <S> List<S> select(List<EvaluatedCandidate<S>> population,
boolean naturalFitnessScores,
int selectionSize,
Random rng)
{
List<EvaluatedCandidate<S>> rankedPopulation = new ArrayList<EvaluatedCandidate<S>>(population.size());
Iterator<EvaluatedCandidate<S>> iterator = population.iterator();
int index = -1;
while (iterator.hasNext())
{
S candidate = iterator.next().getCandidate();
rankedPopulation.add(new EvaluatedCandidate<S>(candidate,
mapRankToScore(++index,
population.size()))); // depends on control dependency: [while], data = [none]
}
return delegate.select(rankedPopulation, true, selectionSize, rng);
} } |
public class class_name {
public void writeToStdIn(String text, boolean newLine) {
if ( outputStream == null) {
outputStream = new BufferedOutputStream(process.getOutputStream());
outputWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
}
try {
outputWriter.write(text);
if ( newLine ) {
outputWriter.newLine();
}
outputWriter.flush();
outputStream.flush();
} catch (IOException e) {
getLog().debug("Error when writing to process in for " + this, e);
ChorusAssert.fail("IOException when writing line to process");
}
} } | public class class_name {
public void writeToStdIn(String text, boolean newLine) {
if ( outputStream == null) {
outputStream = new BufferedOutputStream(process.getOutputStream()); // depends on control dependency: [if], data = [none]
outputWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); // depends on control dependency: [if], data = [none]
}
try {
outputWriter.write(text); // depends on control dependency: [try], data = [none]
if ( newLine ) {
outputWriter.newLine(); // depends on control dependency: [if], data = [none]
}
outputWriter.flush(); // depends on control dependency: [try], data = [none]
outputStream.flush(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
getLog().debug("Error when writing to process in for " + this, e);
ChorusAssert.fail("IOException when writing line to process");
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private Instance getExistingKey(final String _key)
{
Instance ret = null;
try {
final QueryBuilder queryBldr = new QueryBuilder(Type.get(DBPropertiesUpdate.TYPE_PROPERTIES));
queryBldr.addWhereAttrEqValue("Key", _key);
queryBldr.addWhereAttrEqValue("BundleID", this.bundleInstance);
final InstanceQuery query = queryBldr.getQuery();
query.executeWithoutAccessCheck();
if (query.next()) {
ret = query.getCurrentValue();
}
} catch (final EFapsException e) {
DBPropertiesUpdate.LOG.error("getExisting()", e);
}
return ret;
} } | public class class_name {
private Instance getExistingKey(final String _key)
{
Instance ret = null;
try {
final QueryBuilder queryBldr = new QueryBuilder(Type.get(DBPropertiesUpdate.TYPE_PROPERTIES));
queryBldr.addWhereAttrEqValue("Key", _key); // depends on control dependency: [try], data = [none]
queryBldr.addWhereAttrEqValue("BundleID", this.bundleInstance); // depends on control dependency: [try], data = [none]
final InstanceQuery query = queryBldr.getQuery();
query.executeWithoutAccessCheck(); // depends on control dependency: [try], data = [none]
if (query.next()) {
ret = query.getCurrentValue(); // depends on control dependency: [if], data = [none]
}
} catch (final EFapsException e) {
DBPropertiesUpdate.LOG.error("getExisting()", e);
} // depends on control dependency: [catch], data = [none]
return ret;
} } |
public class class_name {
private static String serialize(final QueryParameter paramMetadata, final Object fieldValue, final String fieldName) {
String paramValue;
try {
paramValue = paramMetadata.serializer().newInstance().handle(fieldValue);
} catch (final InstantiationException e) {
LOGGER.error("Failure while serializing field {}", new Object[] { fieldName, e });
paramValue = new ToStringSerializer().handle(fieldValue);
} catch (final IllegalAccessException e) {
LOGGER.error("Failure while serializing field {}", new Object[] { fieldName, e });
paramValue = new ToStringSerializer().handle(fieldValue);
}
return paramValue;
} } | public class class_name {
private static String serialize(final QueryParameter paramMetadata, final Object fieldValue, final String fieldName) {
String paramValue;
try {
paramValue = paramMetadata.serializer().newInstance().handle(fieldValue); // depends on control dependency: [try], data = [none]
} catch (final InstantiationException e) {
LOGGER.error("Failure while serializing field {}", new Object[] { fieldName, e });
paramValue = new ToStringSerializer().handle(fieldValue);
} catch (final IllegalAccessException e) { // depends on control dependency: [catch], data = [none]
LOGGER.error("Failure while serializing field {}", new Object[] { fieldName, e });
paramValue = new ToStringSerializer().handle(fieldValue);
} // depends on control dependency: [catch], data = [none]
return paramValue;
} } |
public class class_name {
public void showAlertAddDialog(HttpMessage httpMessage, int historyType) {
if (dialogAlertAdd == null || !dialogAlertAdd.isVisible()) {
dialogAlertAdd = new AlertAddDialog(getView().getMainFrame(), false);
dialogAlertAdd.setHttpMessage(httpMessage, historyType);
dialogAlertAdd.setVisible(true);
}
} } | public class class_name {
public void showAlertAddDialog(HttpMessage httpMessage, int historyType) {
if (dialogAlertAdd == null || !dialogAlertAdd.isVisible()) {
dialogAlertAdd = new AlertAddDialog(getView().getMainFrame(), false);
// depends on control dependency: [if], data = [none]
dialogAlertAdd.setHttpMessage(httpMessage, historyType);
// depends on control dependency: [if], data = [none]
dialogAlertAdd.setVisible(true);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("PMD.UnusedLocalVariable")
public static <T> int size(Iterable<T> iter) {
if (iter instanceof ArrayTagSet) {
return ((ArrayTagSet) iter).size();
} else if (iter instanceof Collection<?>) {
return ((Collection<?>) iter).size();
} else {
int size = 0;
for (T v : iter) {
++size;
}
return size;
}
} } | public class class_name {
@SuppressWarnings("PMD.UnusedLocalVariable")
public static <T> int size(Iterable<T> iter) {
if (iter instanceof ArrayTagSet) {
return ((ArrayTagSet) iter).size(); // depends on control dependency: [if], data = [none]
} else if (iter instanceof Collection<?>) {
return ((Collection<?>) iter).size(); // depends on control dependency: [if], data = [)]
} else {
int size = 0;
for (T v : iter) {
++size; // depends on control dependency: [for], data = [none]
}
return size; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public String getText(final Object... stringParameters) {
String res = get().getMessage();
if (stringParameters.length > 0) {
try {
// Use the message formatter
res = MessageFormat.format(res, stringParameters);
if (res.startsWith("<") && res.endsWith(">")) {
res += " values: ";
final StringBuilder sb = new StringBuilder();
for (final Object param : stringParameters) {
if (param != null) {
sb.append(param.toString()).append("|");
}
}
res += sb.toString();
}
} catch (final IllegalArgumentException e) {
// Display special markups
res = "<!!" + builder().getParam(this).toString() + "!!>";
// In developer mode throw a runtime exception to stop the current task
if (CoreParameters.DEVELOPER_MODE.get()) {
throw new CoreRuntimeException("Bad formatted Message key : " + res, e);
}
}
}
return res;
} } | public class class_name {
@Override
public String getText(final Object... stringParameters) {
String res = get().getMessage();
if (stringParameters.length > 0) {
try {
// Use the message formatter
res = MessageFormat.format(res, stringParameters); // depends on control dependency: [try], data = [none]
if (res.startsWith("<") && res.endsWith(">")) {
res += " values: "; // depends on control dependency: [if], data = [none]
final StringBuilder sb = new StringBuilder();
for (final Object param : stringParameters) {
if (param != null) {
sb.append(param.toString()).append("|"); // depends on control dependency: [if], data = [(param]
}
}
res += sb.toString(); // depends on control dependency: [if], data = [none]
}
} catch (final IllegalArgumentException e) {
// Display special markups
res = "<!!" + builder().getParam(this).toString() + "!!>";
// In developer mode throw a runtime exception to stop the current task
if (CoreParameters.DEVELOPER_MODE.get()) {
throw new CoreRuntimeException("Bad formatted Message key : " + res, e);
}
} // depends on control dependency: [catch], data = [none]
}
return res;
} } |
public class class_name {
public boolean waitForActive(long timeout)
{
LifecycleState state = getState();
if (state.isActive()) {
return true;
}
else if (state.isAfterActive()) {
return false;
}
// server/1d2j
long waitEnd = CurrentTime.getCurrentTimeActual() + timeout;
synchronized (this) {
while ((state = _state).isBeforeActive()
&& CurrentTime.getCurrentTimeActual() < waitEnd) {
if (state.isActive()) {
return true;
}
else if (state.isAfterActive()) {
return false;
}
try {
long delta = waitEnd - CurrentTime.getCurrentTimeActual();
if (delta > 0) {
wait(delta);
}
} catch (InterruptedException e) {
}
}
}
return _state.isActive();
} } | public class class_name {
public boolean waitForActive(long timeout)
{
LifecycleState state = getState();
if (state.isActive()) {
return true; // depends on control dependency: [if], data = [none]
}
else if (state.isAfterActive()) {
return false; // depends on control dependency: [if], data = [none]
}
// server/1d2j
long waitEnd = CurrentTime.getCurrentTimeActual() + timeout;
synchronized (this) {
while ((state = _state).isBeforeActive()
&& CurrentTime.getCurrentTimeActual() < waitEnd) {
if (state.isActive()) {
return true; // depends on control dependency: [if], data = [none]
}
else if (state.isAfterActive()) {
return false; // depends on control dependency: [if], data = [none]
}
try {
long delta = waitEnd - CurrentTime.getCurrentTimeActual();
if (delta > 0) {
wait(delta); // depends on control dependency: [if], data = [(delta]
}
} catch (InterruptedException e) {
} // depends on control dependency: [catch], data = [none]
}
}
return _state.isActive();
} } |
public class class_name {
public static JsonWebKey fromAes(SecretKey secretKey) {
if (secretKey == null) {
return null;
}
return new JsonWebKey().withK(secretKey.getEncoded()).withKty(JsonWebKeyType.OCT);
} } | public class class_name {
public static JsonWebKey fromAes(SecretKey secretKey) {
if (secretKey == null) {
return null; // depends on control dependency: [if], data = [none]
}
return new JsonWebKey().withK(secretKey.getEncoded()).withKty(JsonWebKeyType.OCT);
} } |
public class class_name {
@Nullable
public <T> Cache<String, T> createCache(final ConcurrentLinkedDeque<T> out, Ticker ticker) {
Preconditions.checkNotNull(out, "The out deque cannot be null");
Preconditions.checkNotNull(ticker, "The ticker cannot be null");
if (numEntries <= 0) {
return null;
}
final RemovalListener<String, T> listener = new RemovalListener<String, T>() {
@Override
public void onRemoval(RemovalNotification<String, T> notification) {
out.addFirst(notification.getValue());
}
};
CacheBuilder<String, T> b = CacheBuilder.newBuilder().maximumSize(numEntries).ticker(ticker)
.removalListener(listener);
if (expirationMillis >= 0) {
b.expireAfterWrite(expirationMillis, TimeUnit.MILLISECONDS);
}
return b.build();
} } | public class class_name {
@Nullable
public <T> Cache<String, T> createCache(final ConcurrentLinkedDeque<T> out, Ticker ticker) {
Preconditions.checkNotNull(out, "The out deque cannot be null");
Preconditions.checkNotNull(ticker, "The ticker cannot be null");
if (numEntries <= 0) {
return null; // depends on control dependency: [if], data = [none]
}
final RemovalListener<String, T> listener = new RemovalListener<String, T>() {
@Override
public void onRemoval(RemovalNotification<String, T> notification) {
out.addFirst(notification.getValue());
}
};
CacheBuilder<String, T> b = CacheBuilder.newBuilder().maximumSize(numEntries).ticker(ticker)
.removalListener(listener);
if (expirationMillis >= 0) {
b.expireAfterWrite(expirationMillis, TimeUnit.MILLISECONDS); // depends on control dependency: [if], data = [(expirationMillis]
}
return b.build();
} } |
public class class_name {
public String getWmoId() {
String wmoID = "";
if (!(stnm == GempakConstants.IMISSD)) {
wmoID = String.valueOf((int) (stnm / 10));
}
return wmoID;
} } | public class class_name {
public String getWmoId() {
String wmoID = "";
if (!(stnm == GempakConstants.IMISSD)) {
wmoID = String.valueOf((int) (stnm / 10));
// depends on control dependency: [if], data = [none]
}
return wmoID;
} } |
public class class_name {
@SuppressWarnings("deprecation")
@Override
public int compareTo(Evidence o) {
if (o == null) {
throw new IllegalArgumentException("Unable to compare null evidence");
}
if (StringUtils.equalsIgnoreCase(source, o.source)) {
if (StringUtils.equalsIgnoreCase(name, o.name)) {
if (StringUtils.equalsIgnoreCase(value, o.value)) {
//TODO the call to ObjectUtils.equals needs to be replaced when we
//stop supporting Jenkins 1.6 requirement.
if (ObjectUtils.equals(confidence, o.confidence)) {
return 0; //they are equal
} else {
return ObjectUtils.compare(confidence, o.confidence);
}
} else {
return compareToIgnoreCaseWithNullCheck(value, o.value);
}
} else {
return compareToIgnoreCaseWithNullCheck(name, o.name);
}
} else {
return compareToIgnoreCaseWithNullCheck(source, o.source);
}
} } | public class class_name {
@SuppressWarnings("deprecation")
@Override
public int compareTo(Evidence o) {
if (o == null) {
throw new IllegalArgumentException("Unable to compare null evidence");
}
if (StringUtils.equalsIgnoreCase(source, o.source)) {
if (StringUtils.equalsIgnoreCase(name, o.name)) {
if (StringUtils.equalsIgnoreCase(value, o.value)) {
//TODO the call to ObjectUtils.equals needs to be replaced when we
//stop supporting Jenkins 1.6 requirement.
if (ObjectUtils.equals(confidence, o.confidence)) {
return 0; //they are equal // depends on control dependency: [if], data = [none]
} else {
return ObjectUtils.compare(confidence, o.confidence); // depends on control dependency: [if], data = [none]
}
} else {
return compareToIgnoreCaseWithNullCheck(value, o.value); // depends on control dependency: [if], data = [none]
}
} else {
return compareToIgnoreCaseWithNullCheck(name, o.name); // depends on control dependency: [if], data = [none]
}
} else {
return compareToIgnoreCaseWithNullCheck(source, o.source); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(DescribeDatasetRequest describeDatasetRequest, ProtocolMarshaller protocolMarshaller) {
if (describeDatasetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeDatasetRequest.getIdentityPoolId(), IDENTITYPOOLID_BINDING);
protocolMarshaller.marshall(describeDatasetRequest.getIdentityId(), IDENTITYID_BINDING);
protocolMarshaller.marshall(describeDatasetRequest.getDatasetName(), DATASETNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DescribeDatasetRequest describeDatasetRequest, ProtocolMarshaller protocolMarshaller) {
if (describeDatasetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeDatasetRequest.getIdentityPoolId(), IDENTITYPOOLID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(describeDatasetRequest.getIdentityId(), IDENTITYID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(describeDatasetRequest.getDatasetName(), DATASETNAME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static boolean isAssignable(final Type type, final Class<?> toClass) {
if (type == null) {
// consistency with ClassUtils.isAssignable() behavior
return toClass == null || !toClass.isPrimitive();
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toClass == null) {
return false;
}
// all types are assignable to themselves
if (toClass.equals(type)) {
return true;
}
if (type instanceof Class<?>) {
toClass.isAssignableFrom((Class<?>) type);
// just comparing two classes
return toClass.isAssignableFrom((Class<?>) type);
}
if (type instanceof ParameterizedType) {
// only have to compare the raw type to the class
return isAssignable(getRawType((ParameterizedType) type), toClass);
}
if (type instanceof TypeVariable<?>) {
// if any of the bounds are assignable to the class, then the
// type is assignable to the class.
for (final Type bound : ((TypeVariable<?>) type).getBounds()) {
if (isAssignable(bound, toClass)) {
return true;
}
}
return false;
}
// the only classes to which a generic array type can be assigned
// are class Object and array classes
if (type instanceof GenericArrayType) {
return toClass.equals(Object.class)
|| toClass.isArray()
&& isAssignable(((GenericArrayType) type).getGenericComponentType(), toClass
.getComponentType());
}
// wildcard types are not assignable to a class (though one would think
// "? super Object" would be assignable to Object)
if (type instanceof WildcardType) {
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
} } | public class class_name {
private static boolean isAssignable(final Type type, final Class<?> toClass) {
if (type == null) {
// consistency with ClassUtils.isAssignable() behavior
return toClass == null || !toClass.isPrimitive(); // depends on control dependency: [if], data = [none]
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toClass == null) {
return false; // depends on control dependency: [if], data = [none]
}
// all types are assignable to themselves
if (toClass.equals(type)) {
return true; // depends on control dependency: [if], data = [none]
}
if (type instanceof Class<?>) {
toClass.isAssignableFrom((Class<?>) type); // depends on control dependency: [if], data = [)]
// just comparing two classes
return toClass.isAssignableFrom((Class<?>) type); // depends on control dependency: [if], data = [)]
}
if (type instanceof ParameterizedType) {
// only have to compare the raw type to the class
return isAssignable(getRawType((ParameterizedType) type), toClass); // depends on control dependency: [if], data = [none]
}
if (type instanceof TypeVariable<?>) {
// if any of the bounds are assignable to the class, then the
// type is assignable to the class.
for (final Type bound : ((TypeVariable<?>) type).getBounds()) {
if (isAssignable(bound, toClass)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false; // depends on control dependency: [if], data = [none]
}
// the only classes to which a generic array type can be assigned
// are class Object and array classes
if (type instanceof GenericArrayType) {
return toClass.equals(Object.class)
|| toClass.isArray()
&& isAssignable(((GenericArrayType) type).getGenericComponentType(), toClass
.getComponentType()); // depends on control dependency: [if], data = [none]
}
// wildcard types are not assignable to a class (though one would think
// "? super Object" would be assignable to Object)
if (type instanceof WildcardType) {
return false; // depends on control dependency: [if], data = [none]
}
throw new IllegalStateException("found an unhandled type: " + type);
} } |
public class class_name {
protected void analysisSequence(Class<ENTITY> entityClass) {
Sequence sequence = entityClass.getAnnotation(Sequence.class);
if (sequence != null) {
this.sequenceName = sequence.name();
sequenceGenerator.initialSequence(sequenceName, sequence.size());
}
} } | public class class_name {
protected void analysisSequence(Class<ENTITY> entityClass) {
Sequence sequence = entityClass.getAnnotation(Sequence.class);
if (sequence != null) {
this.sequenceName = sequence.name(); // depends on control dependency: [if], data = [none]
sequenceGenerator.initialSequence(sequenceName, sequence.size()); // depends on control dependency: [if], data = [(sequence]
}
} } |
public class class_name {
public static Object repeat(Object arr, int times) {
Class<?> toType = Types.arrayElementType(arr.getClass());
if ( times < 1 )
return Array.newInstance(toType, 0);
int[] dims = dimensions(arr);
int length = dims[0];
dims[0] *= times;
int i = 0, total = dims[0];
Object toArray = Array.newInstance(toType, dims);
while ( i < total ) {
System.arraycopy(arr, 0, toArray, i, length);
i += length;
}
return toArray;
} } | public class class_name {
public static Object repeat(Object arr, int times) {
Class<?> toType = Types.arrayElementType(arr.getClass());
if ( times < 1 )
return Array.newInstance(toType, 0);
int[] dims = dimensions(arr);
int length = dims[0];
dims[0] *= times;
int i = 0, total = dims[0];
Object toArray = Array.newInstance(toType, dims);
while ( i < total ) {
System.arraycopy(arr, 0, toArray, i, length); // depends on control dependency: [while], data = [none]
i += length; // depends on control dependency: [while], data = [none]
}
return toArray;
} } |
public class class_name {
private CmsContainerElementBean generateDetailViewElement(
ServletRequest request,
CmsObject cms,
CmsResource detailContent,
CmsContainerBean container) {
CmsContainerElementBean element = null;
if (detailContent != null) {
// get the right formatter
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.getRequestContext().getRootUri());
CmsFormatterConfiguration formatters = config.getFormatters(cms, detailContent);
I_CmsFormatterBean formatter = formatters.getDetailFormatter(getType(), getContainerWidth());
if (formatter != null) {
// use structure id as the instance id to enable use of nested containers
Map<String, String> settings = new HashMap<String, String>();
if (!container.getElements().isEmpty()) {
// in case the first element in the container is of the same type as the detail content, transfer it's settings
CmsContainerElementBean el = container.getElements().get(0);
try {
el.initResource(cms);
if (el.getResource().getTypeId() == detailContent.getTypeId()) {
settings.putAll(el.getIndividualSettings());
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
String formatterKey = CmsFormatterConfig.getSettingsKeyForContainer(container.getName());
if (settings.containsKey(formatterKey)) {
String formatterConfigId = settings.get(formatterKey);
if (CmsUUID.isValidUUID(formatterConfigId)) {
I_CmsFormatterBean formatterBean = OpenCms.getADEManager().getCachedFormatters(
cms.getRequestContext().getCurrentProject().isOnlineProject()).getFormatters().get(
new CmsUUID(formatterConfigId));
if (formatterBean != null) {
formatter = formatterBean;
}
}
}
settings.put(formatterKey, formatter.getId());
settings.put(CmsContainerElement.ELEMENT_INSTANCE_ID, new CmsUUID().toString());
// create element bean
element = new CmsContainerElementBean(
detailContent.getStructureId(),
formatter.getJspStructureId(),
settings,
false);
String pageRootPath = cms.getRequestContext().addSiteRoot(cms.getRequestContext().getUri());
element = CmsTemplateMapper.get(request).transformDetailElement(cms, element, pageRootPath);
}
}
return element;
} } | public class class_name {
private CmsContainerElementBean generateDetailViewElement(
ServletRequest request,
CmsObject cms,
CmsResource detailContent,
CmsContainerBean container) {
CmsContainerElementBean element = null;
if (detailContent != null) {
// get the right formatter
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.getRequestContext().getRootUri());
CmsFormatterConfiguration formatters = config.getFormatters(cms, detailContent);
I_CmsFormatterBean formatter = formatters.getDetailFormatter(getType(), getContainerWidth());
if (formatter != null) {
// use structure id as the instance id to enable use of nested containers
Map<String, String> settings = new HashMap<String, String>();
if (!container.getElements().isEmpty()) {
// in case the first element in the container is of the same type as the detail content, transfer it's settings
CmsContainerElementBean el = container.getElements().get(0);
try {
el.initResource(cms); // depends on control dependency: [try], data = [none]
if (el.getResource().getTypeId() == detailContent.getTypeId()) {
settings.putAll(el.getIndividualSettings()); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
String formatterKey = CmsFormatterConfig.getSettingsKeyForContainer(container.getName());
if (settings.containsKey(formatterKey)) {
String formatterConfigId = settings.get(formatterKey);
if (CmsUUID.isValidUUID(formatterConfigId)) {
I_CmsFormatterBean formatterBean = OpenCms.getADEManager().getCachedFormatters(
cms.getRequestContext().getCurrentProject().isOnlineProject()).getFormatters().get(
new CmsUUID(formatterConfigId));
if (formatterBean != null) {
formatter = formatterBean; // depends on control dependency: [if], data = [none]
}
}
}
settings.put(formatterKey, formatter.getId()); // depends on control dependency: [if], data = [(formatter]
settings.put(CmsContainerElement.ELEMENT_INSTANCE_ID, new CmsUUID().toString()); // depends on control dependency: [if], data = [none]
// create element bean
element = new CmsContainerElementBean(
detailContent.getStructureId(),
formatter.getJspStructureId(),
settings,
false); // depends on control dependency: [if], data = [none]
String pageRootPath = cms.getRequestContext().addSiteRoot(cms.getRequestContext().getUri());
element = CmsTemplateMapper.get(request).transformDetailElement(cms, element, pageRootPath); // depends on control dependency: [if], data = [none]
}
}
return element;
} } |
public class class_name {
@SuppressWarnings("unchecked")
public T embed(HalRelation relation, ProcessEngine processEngine) {
List<HalResource<?>> resolvedLinks = linker.resolve(relation, processEngine);
if(resolvedLinks != null && resolvedLinks.size() > 0) {
addEmbedded(relation.relName, resolvedLinks);
}
return (T) this;
} } | public class class_name {
@SuppressWarnings("unchecked")
public T embed(HalRelation relation, ProcessEngine processEngine) {
List<HalResource<?>> resolvedLinks = linker.resolve(relation, processEngine);
if(resolvedLinks != null && resolvedLinks.size() > 0) {
addEmbedded(relation.relName, resolvedLinks); // depends on control dependency: [if], data = [none]
}
return (T) this;
} } |
public class class_name {
@Override
public T convertFromString(Class<? extends T> cls, String str) {
try {
return fromString.newInstance(str);
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Constructor is not accessible: " + fromString);
} catch (InstantiationException ex) {
throw new IllegalStateException("Constructor is not valid: " + fromString);
} catch (InvocationTargetException ex) {
if (ex.getCause() instanceof RuntimeException) {
throw (RuntimeException) ex.getCause();
}
throw new RuntimeException(ex.getMessage(), ex.getCause());
}
} } | public class class_name {
@Override
public T convertFromString(Class<? extends T> cls, String str) {
try {
return fromString.newInstance(str);
// depends on control dependency: [try], data = [none]
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Constructor is not accessible: " + fromString);
} catch (InstantiationException ex) {
// depends on control dependency: [catch], data = [none]
throw new IllegalStateException("Constructor is not valid: " + fromString);
} catch (InvocationTargetException ex) {
// depends on control dependency: [catch], data = [none]
if (ex.getCause() instanceof RuntimeException) {
throw (RuntimeException) ex.getCause();
}
throw new RuntimeException(ex.getMessage(), ex.getCause());
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Pure
public static boolean getDirectionSymbolInPreferredStringRepresentation() {
final Preferences prefs = Preferences.userNodeForPackage(GeodesicPosition.class);
if (prefs != null) {
return prefs.getBoolean("SYMBOL_IN_STRING_REPRESENTATION", DEFAULT_SYMBOL_IN_STRING_REPRESENTATION); //$NON-NLS-1$
}
return DEFAULT_SYMBOL_IN_STRING_REPRESENTATION;
} } | public class class_name {
@Pure
public static boolean getDirectionSymbolInPreferredStringRepresentation() {
final Preferences prefs = Preferences.userNodeForPackage(GeodesicPosition.class);
if (prefs != null) {
return prefs.getBoolean("SYMBOL_IN_STRING_REPRESENTATION", DEFAULT_SYMBOL_IN_STRING_REPRESENTATION); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
return DEFAULT_SYMBOL_IN_STRING_REPRESENTATION;
} } |
public class class_name {
public AttributeList getAttributes(String[] attributes /* cannot be null */) {
final AttributeList ret = new AttributeList(attributes.length);
for (String attrName : attributes) {
try {
final Object attrValue = getAttribute(attrName);
ret.add(new Attribute(attrName, attrValue));
} catch (Exception e) {
// Ignore this attribute. As specified in the JMX Spec
}
}
return ret;
} } | public class class_name {
public AttributeList getAttributes(String[] attributes /* cannot be null */) {
final AttributeList ret = new AttributeList(attributes.length);
for (String attrName : attributes) {
try {
final Object attrValue = getAttribute(attrName);
ret.add(new Attribute(attrName, attrValue)); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// Ignore this attribute. As specified in the JMX Spec
} // depends on control dependency: [catch], data = [none]
}
return ret;
} } |
public class class_name {
public static final QName buildQName(final String paramUri, final String paramName) {
QName qname;
if (paramName.contains(":")) {
qname = new QName(paramUri, paramName.split(":")[1], paramName.split(":")[0]);
} else {
qname = new QName(paramUri, paramName);
}
return qname;
} } | public class class_name {
public static final QName buildQName(final String paramUri, final String paramName) {
QName qname;
if (paramName.contains(":")) {
qname = new QName(paramUri, paramName.split(":")[1], paramName.split(":")[0]); // depends on control dependency: [if], data = [none]
} else {
qname = new QName(paramUri, paramName); // depends on control dependency: [if], data = [none]
}
return qname;
} } |
public class class_name {
void addUnchecked(final BaseDownloadTask.IRunningTask task) {
if (task.isMarkedAdded2List()) {
return;
}
synchronized (mList) {
if (mList.contains(task)) {
FileDownloadLog.w(this, "already has %s", task);
} else {
task.markAdded2List();
mList.add(task);
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.v(this, "add list in all %s %d %d", task,
task.getOrigin().getStatus(), mList.size());
}
}
}
} } | public class class_name {
void addUnchecked(final BaseDownloadTask.IRunningTask task) {
if (task.isMarkedAdded2List()) {
return; // depends on control dependency: [if], data = [none]
}
synchronized (mList) {
if (mList.contains(task)) {
FileDownloadLog.w(this, "already has %s", task); // depends on control dependency: [if], data = [none]
} else {
task.markAdded2List(); // depends on control dependency: [if], data = [none]
mList.add(task); // depends on control dependency: [if], data = [none]
if (FileDownloadLog.NEED_LOG) {
FileDownloadLog.v(this, "add list in all %s %d %d", task,
task.getOrigin().getStatus(), mList.size()); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
protected void createVolatileImage ()
{
// release any previous volatile image we might hold
if (_image != null) {
_image.flush();
}
// create a new, compatible, volatile image
// _image = _imgr.createVolatileImage(
// _bounds.width, _bounds.height, getTransparency());
_image = _imgr.createImage(
_bounds.width, _bounds.height, getTransparency());
// render our source image into the volatile image
refreshVolatileImage();
} } | public class class_name {
protected void createVolatileImage ()
{
// release any previous volatile image we might hold
if (_image != null) {
_image.flush(); // depends on control dependency: [if], data = [none]
}
// create a new, compatible, volatile image
// _image = _imgr.createVolatileImage(
// _bounds.width, _bounds.height, getTransparency());
_image = _imgr.createImage(
_bounds.width, _bounds.height, getTransparency());
// render our source image into the volatile image
refreshVolatileImage();
} } |
public class class_name {
public void addFkToItemClass(String column)
{
if (fksToItemClass == null)
{
fksToItemClass = new Vector();
}
fksToItemClass.add(column);
fksToItemClassAry = null;
} } | public class class_name {
public void addFkToItemClass(String column)
{
if (fksToItemClass == null)
{
fksToItemClass = new Vector();
// depends on control dependency: [if], data = [none]
}
fksToItemClass.add(column);
fksToItemClassAry = null;
} } |
public class class_name {
public static boolean removeOccurrences(
Multiset<?> multisetToModify, Iterable<?> occurrencesToRemove) {
if (occurrencesToRemove instanceof Multiset) {
return removeOccurrencesImpl(
multisetToModify, (Multiset<?>) occurrencesToRemove);
} else {
return removeOccurrencesImpl(multisetToModify, occurrencesToRemove);
}
} } | public class class_name {
public static boolean removeOccurrences(
Multiset<?> multisetToModify, Iterable<?> occurrencesToRemove) {
if (occurrencesToRemove instanceof Multiset) {
return removeOccurrencesImpl(
multisetToModify, (Multiset<?>) occurrencesToRemove); // depends on control dependency: [if], data = [none]
} else {
return removeOccurrencesImpl(multisetToModify, occurrencesToRemove); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void format(Mode mode, AlluxioConfiguration alluxioConf) throws IOException {
switch (mode) {
case MASTER:
URI journalLocation = JournalUtils.getJournalLocation();
LOG.info("Formatting master journal: {}", journalLocation);
JournalSystem journalSystem = new JournalSystem.Builder()
.setLocation(journalLocation).build(CommonUtils.ProcessType.MASTER);
for (String masterServiceName : ServiceUtils.getMasterServiceNames()) {
journalSystem.createJournal(new NoopMaster(masterServiceName));
}
journalSystem.format();
break;
case WORKER:
String workerDataFolder = ServerConfiguration.get(PropertyKey.WORKER_DATA_FOLDER);
LOG.info("Formatting worker data folder: {}", workerDataFolder);
int storageLevels = ServerConfiguration.getInt(PropertyKey.WORKER_TIERED_STORE_LEVELS);
for (int level = 0; level < storageLevels; level++) {
PropertyKey tierLevelDirPath =
PropertyKey.Template.WORKER_TIERED_STORE_LEVEL_DIRS_PATH.format(level);
String[] dirPaths = ServerConfiguration.get(tierLevelDirPath).split(",");
String name = "Data path for tier " + level;
for (String dirPath : dirPaths) {
String dirWorkerDataFolder = CommonUtils.getWorkerDataDirectory(dirPath, alluxioConf);
LOG.info("Formatting {}:{}", name, dirWorkerDataFolder);
formatWorkerDataFolder(dirWorkerDataFolder);
}
}
break;
default:
throw new RuntimeException(String.format("Unrecognized format mode: %s", mode));
}
} } | public class class_name {
public static void format(Mode mode, AlluxioConfiguration alluxioConf) throws IOException {
switch (mode) {
case MASTER:
URI journalLocation = JournalUtils.getJournalLocation();
LOG.info("Formatting master journal: {}", journalLocation);
JournalSystem journalSystem = new JournalSystem.Builder()
.setLocation(journalLocation).build(CommonUtils.ProcessType.MASTER);
for (String masterServiceName : ServiceUtils.getMasterServiceNames()) {
journalSystem.createJournal(new NoopMaster(masterServiceName)); // depends on control dependency: [for], data = [masterServiceName]
}
journalSystem.format();
break;
case WORKER:
String workerDataFolder = ServerConfiguration.get(PropertyKey.WORKER_DATA_FOLDER);
LOG.info("Formatting worker data folder: {}", workerDataFolder);
int storageLevels = ServerConfiguration.getInt(PropertyKey.WORKER_TIERED_STORE_LEVELS);
for (int level = 0; level < storageLevels; level++) {
PropertyKey tierLevelDirPath =
PropertyKey.Template.WORKER_TIERED_STORE_LEVEL_DIRS_PATH.format(level);
String[] dirPaths = ServerConfiguration.get(tierLevelDirPath).split(",");
String name = "Data path for tier " + level;
for (String dirPath : dirPaths) {
String dirWorkerDataFolder = CommonUtils.getWorkerDataDirectory(dirPath, alluxioConf);
LOG.info("Formatting {}:{}", name, dirWorkerDataFolder); // depends on control dependency: [for], data = [none]
formatWorkerDataFolder(dirWorkerDataFolder); // depends on control dependency: [for], data = [none]
}
}
break;
default:
throw new RuntimeException(String.format("Unrecognized format mode: %s", mode));
}
} } |
public class class_name {
public static ServletRequest convertRequest(Object input) {
ServletRequest req = null;
if (input instanceof ServletRequest) {
req = (ServletRequest)input;
} else if (input instanceof PageContext) {
req = ((PageContext)input).getRequest();
}
return req;
} } | public class class_name {
public static ServletRequest convertRequest(Object input) {
ServletRequest req = null;
if (input instanceof ServletRequest) {
req = (ServletRequest)input; // depends on control dependency: [if], data = [none]
} else if (input instanceof PageContext) {
req = ((PageContext)input).getRequest(); // depends on control dependency: [if], data = [none]
}
return req;
} } |
public class class_name {
public DrawerView removeItemById(long id) {
for (DrawerItem item : mAdapter.getItems()) {
if (item.getId() == id) {
mAdapter.remove(item);
updateList();
return this;
}
}
return this;
} } | public class class_name {
public DrawerView removeItemById(long id) {
for (DrawerItem item : mAdapter.getItems()) {
if (item.getId() == id) {
mAdapter.remove(item); // depends on control dependency: [if], data = [none]
updateList(); // depends on control dependency: [if], data = [none]
return this; // depends on control dependency: [if], data = [none]
}
}
return this;
} } |
public class class_name {
public Observable<ServiceResponse<Page<SiteInner>>> beginResumeNextWithServiceResponseAsync(final String nextPageLink) {
return beginResumeNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<SiteInner>>, Observable<ServiceResponse<Page<SiteInner>>>>() {
@Override
public Observable<ServiceResponse<Page<SiteInner>>> call(ServiceResponse<Page<SiteInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(beginResumeNextWithServiceResponseAsync(nextPageLink));
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<SiteInner>>> beginResumeNextWithServiceResponseAsync(final String nextPageLink) {
return beginResumeNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<SiteInner>>, Observable<ServiceResponse<Page<SiteInner>>>>() {
@Override
public Observable<ServiceResponse<Page<SiteInner>>> call(ServiceResponse<Page<SiteInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page); // depends on control dependency: [if], data = [none]
}
return Observable.just(page).concatWith(beginResumeNextWithServiceResponseAsync(nextPageLink));
}
});
} } |
public class class_name {
private LocalDate calculate3rdWednesday(final LocalDate original) {
final LocalDate firstOfMonth = original.withDayOfMonth(1);
LocalDate firstWed = firstOfMonth.withDayOfWeek(MONTHS_IN_QUARTER);
if (firstWed.isBefore(firstOfMonth)) {
firstWed = firstWed.plusWeeks(1);
}
return firstWed.plusWeeks(2);
} } | public class class_name {
private LocalDate calculate3rdWednesday(final LocalDate original) {
final LocalDate firstOfMonth = original.withDayOfMonth(1);
LocalDate firstWed = firstOfMonth.withDayOfWeek(MONTHS_IN_QUARTER);
if (firstWed.isBefore(firstOfMonth)) {
firstWed = firstWed.plusWeeks(1);
// depends on control dependency: [if], data = [none]
}
return firstWed.plusWeeks(2);
} } |
public class class_name {
@Override
public Map<String, Object> toSource() {
Map<String, Object> sourceMap = new HashMap<>();
if (crawlingInfoId != null) {
addFieldToSource(sourceMap, "crawlingInfoId", crawlingInfoId);
}
if (createdTime != null) {
addFieldToSource(sourceMap, "createdTime", createdTime);
}
if (key != null) {
addFieldToSource(sourceMap, "key", key);
}
if (value != null) {
addFieldToSource(sourceMap, "value", value);
}
return sourceMap;
} } | public class class_name {
@Override
public Map<String, Object> toSource() {
Map<String, Object> sourceMap = new HashMap<>();
if (crawlingInfoId != null) {
addFieldToSource(sourceMap, "crawlingInfoId", crawlingInfoId); // depends on control dependency: [if], data = [none]
}
if (createdTime != null) {
addFieldToSource(sourceMap, "createdTime", createdTime); // depends on control dependency: [if], data = [none]
}
if (key != null) {
addFieldToSource(sourceMap, "key", key); // depends on control dependency: [if], data = [none]
}
if (value != null) {
addFieldToSource(sourceMap, "value", value); // depends on control dependency: [if], data = [none]
}
return sourceMap;
} } |
public class class_name {
public void logError(final Level level, final String message, final Error e)
{
try {
Logger errors = LoggingFactory
.getLogger(LoggingFactory.NAME_ERROR_LOGGER);
errors.logThrowable(level, message, e);
}
catch (LoggingException ex) {
ex.printStackTrace();
}
if (logLevel.toInt() > level.toInt()) {
return;
}
logThrowable(level, message, e);
} } | public class class_name {
public void logError(final Level level, final String message, final Error e)
{
try {
Logger errors = LoggingFactory
.getLogger(LoggingFactory.NAME_ERROR_LOGGER);
errors.logThrowable(level, message, e); // depends on control dependency: [try], data = [none]
}
catch (LoggingException ex) {
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
if (logLevel.toInt() > level.toInt()) {
return; // depends on control dependency: [if], data = [none]
}
logThrowable(level, message, e);
} } |
public class class_name {
private boolean propagationAllowed(final AbstractNode thisNode, final RelationshipInterface rel, final SchemaRelationshipNode.Direction propagationDirection, final boolean doLog) {
// early exit
if (propagationDirection.equals(SchemaRelationshipNode.Direction.Both)) {
return true;
}
// early exit
if (propagationDirection.equals(SchemaRelationshipNode.Direction.None)) {
return false;
}
final String sourceNodeId = rel.getSourceNode().getUuid();
final String thisNodeId = thisNode.getUuid();
if (sourceNodeId.equals(thisNodeId)) {
// evaluation WITH the relationship direction
switch (propagationDirection) {
case Out:
return false;
case In:
return true;
}
} else {
// evaluation AGAINST the relationship direction
switch (propagationDirection) {
case Out:
return true;
case In:
return false;
}
}
return false;
} } | public class class_name {
private boolean propagationAllowed(final AbstractNode thisNode, final RelationshipInterface rel, final SchemaRelationshipNode.Direction propagationDirection, final boolean doLog) {
// early exit
if (propagationDirection.equals(SchemaRelationshipNode.Direction.Both)) {
return true; // depends on control dependency: [if], data = [none]
}
// early exit
if (propagationDirection.equals(SchemaRelationshipNode.Direction.None)) {
return false; // depends on control dependency: [if], data = [none]
}
final String sourceNodeId = rel.getSourceNode().getUuid();
final String thisNodeId = thisNode.getUuid();
if (sourceNodeId.equals(thisNodeId)) {
// evaluation WITH the relationship direction
switch (propagationDirection) {
case Out:
return false;
case In:
return true;
}
} else {
// evaluation AGAINST the relationship direction
switch (propagationDirection) {
case Out:
return true;
case In:
return false;
}
}
return false;
} } |
public class class_name {
private UndergraduateStudents getUndergraduateStudents(
OtherPersonnelDto otherPersonnel) {
UndergraduateStudents undergraduate = UndergraduateStudents.Factory
.newInstance();
if (otherPersonnel != null) {
undergraduate.setNumberOfPersonnel(otherPersonnel
.getNumberPersonnel());
undergraduate.setProjectRole(otherPersonnel.getRole());
CompensationDto sectBCompType = otherPersonnel.getCompensation();
undergraduate.setRequestedSalary(sectBCompType.getRequestedSalary().bigDecimalValue());
undergraduate.setFringeBenefits(sectBCompType.getFringe().bigDecimalValue());
undergraduate.setAcademicMonths(sectBCompType.getAcademicMonths().bigDecimalValue());
undergraduate.setCalendarMonths(sectBCompType.getCalendarMonths().bigDecimalValue());
undergraduate.setFundsRequested(sectBCompType.getFundsRequested().bigDecimalValue());
undergraduate.setSummerMonths(sectBCompType.getSummerMonths().bigDecimalValue());
}
return undergraduate;
} } | public class class_name {
private UndergraduateStudents getUndergraduateStudents(
OtherPersonnelDto otherPersonnel) {
UndergraduateStudents undergraduate = UndergraduateStudents.Factory
.newInstance();
if (otherPersonnel != null) {
undergraduate.setNumberOfPersonnel(otherPersonnel
.getNumberPersonnel()); // depends on control dependency: [if], data = [none]
undergraduate.setProjectRole(otherPersonnel.getRole()); // depends on control dependency: [if], data = [(otherPersonnel]
CompensationDto sectBCompType = otherPersonnel.getCompensation();
undergraduate.setRequestedSalary(sectBCompType.getRequestedSalary().bigDecimalValue()); // depends on control dependency: [if], data = [none]
undergraduate.setFringeBenefits(sectBCompType.getFringe().bigDecimalValue()); // depends on control dependency: [if], data = [none]
undergraduate.setAcademicMonths(sectBCompType.getAcademicMonths().bigDecimalValue()); // depends on control dependency: [if], data = [none]
undergraduate.setCalendarMonths(sectBCompType.getCalendarMonths().bigDecimalValue()); // depends on control dependency: [if], data = [none]
undergraduate.setFundsRequested(sectBCompType.getFundsRequested().bigDecimalValue()); // depends on control dependency: [if], data = [none]
undergraduate.setSummerMonths(sectBCompType.getSummerMonths().bigDecimalValue()); // depends on control dependency: [if], data = [none]
}
return undergraduate;
} } |
public class class_name {
@Override
public EEnum getIfcBSplineCurveForm() {
if (ifcBSplineCurveFormEEnum == null) {
ifcBSplineCurveFormEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(918);
}
return ifcBSplineCurveFormEEnum;
} } | public class class_name {
@Override
public EEnum getIfcBSplineCurveForm() {
if (ifcBSplineCurveFormEEnum == null) {
ifcBSplineCurveFormEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(918);
// depends on control dependency: [if], data = [none]
}
return ifcBSplineCurveFormEEnum;
} } |
public class class_name {
public boolean isChild(final UIMenuItem _childItem,
final UIMenuItem _parentItem)
{
boolean ret = _parentItem.getChildren().contains(_childItem);
if (!ret) {
for (final UIMenuItem child : _parentItem.getChildren()) {
if (child.hasChildren()) {
ret = isChild(_childItem, child);
}
if (ret) {
break;
}
}
}
return ret;
} } | public class class_name {
public boolean isChild(final UIMenuItem _childItem,
final UIMenuItem _parentItem)
{
boolean ret = _parentItem.getChildren().contains(_childItem);
if (!ret) {
for (final UIMenuItem child : _parentItem.getChildren()) {
if (child.hasChildren()) {
ret = isChild(_childItem, child); // depends on control dependency: [if], data = [none]
}
if (ret) {
break;
}
}
}
return ret;
} } |
public class class_name {
protected void parseAsynchronousContinuationForActivity(Element activityElement, ActivityImpl activity) {
// can't use #getMultiInstanceScope here to determine whether the task is multi-instance,
// since the property hasn't been set yet (cf parseActivity)
ActivityImpl parentFlowScopeActivity = activity.getParentFlowScopeActivity();
if (parentFlowScopeActivity != null && parentFlowScopeActivity.getActivityBehavior() instanceof MultiInstanceActivityBehavior
&& !activity.isCompensationHandler()) {
parseAsynchronousContinuation(activityElement, parentFlowScopeActivity);
Element miLoopCharacteristics = activityElement.element("multiInstanceLoopCharacteristics");
parseAsynchronousContinuation(miLoopCharacteristics, activity);
} else {
parseAsynchronousContinuation(activityElement, activity);
}
} } | public class class_name {
protected void parseAsynchronousContinuationForActivity(Element activityElement, ActivityImpl activity) {
// can't use #getMultiInstanceScope here to determine whether the task is multi-instance,
// since the property hasn't been set yet (cf parseActivity)
ActivityImpl parentFlowScopeActivity = activity.getParentFlowScopeActivity();
if (parentFlowScopeActivity != null && parentFlowScopeActivity.getActivityBehavior() instanceof MultiInstanceActivityBehavior
&& !activity.isCompensationHandler()) {
parseAsynchronousContinuation(activityElement, parentFlowScopeActivity); // depends on control dependency: [if], data = [none]
Element miLoopCharacteristics = activityElement.element("multiInstanceLoopCharacteristics");
parseAsynchronousContinuation(miLoopCharacteristics, activity); // depends on control dependency: [if], data = [none]
} else {
parseAsynchronousContinuation(activityElement, activity); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static long getNextRefresh(long tokenValiditySec) {
long interval = Config.JWT_REFRESH_INTERVAL_SEC;
// estimate when the next token refresh should be
// usually every hour, or halfway until the time it expires
if (tokenValiditySec < (2 * interval)) {
interval = (tokenValiditySec / 2);
}
return System.currentTimeMillis() + (interval * 1000);
} } | public class class_name {
private static long getNextRefresh(long tokenValiditySec) {
long interval = Config.JWT_REFRESH_INTERVAL_SEC;
// estimate when the next token refresh should be
// usually every hour, or halfway until the time it expires
if (tokenValiditySec < (2 * interval)) {
interval = (tokenValiditySec / 2); // depends on control dependency: [if], data = [(tokenValiditySec]
}
return System.currentTimeMillis() + (interval * 1000);
} } |
public class class_name {
public void pauseRecording(){
if (currentAudioState.get()==RECORDING_STATE){
currentAudioState.getAndSet(PAUSED_STATE);
onTimeCompletedTimer.cancel();
remainingMaxTimeInMillis=remainingMaxTimeInMillis-(System.currentTimeMillis()-recordingStartTimeMillis);
}
else{
Log.w(TAG,"Audio recording is not recording");
}
} } | public class class_name {
public void pauseRecording(){
if (currentAudioState.get()==RECORDING_STATE){
currentAudioState.getAndSet(PAUSED_STATE); // depends on control dependency: [if], data = [none]
onTimeCompletedTimer.cancel(); // depends on control dependency: [if], data = [none]
remainingMaxTimeInMillis=remainingMaxTimeInMillis-(System.currentTimeMillis()-recordingStartTimeMillis); // depends on control dependency: [if], data = [none]
}
else{
Log.w(TAG,"Audio recording is not recording"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String createKey(String keyWithoutBranch, @Nullable String branch) {
if (StringUtils.isNotBlank(branch)) {
return String.format(KEY_WITH_BRANCH_FORMAT, keyWithoutBranch, branch);
} else {
return keyWithoutBranch;
}
} } | public class class_name {
public static String createKey(String keyWithoutBranch, @Nullable String branch) {
if (StringUtils.isNotBlank(branch)) {
return String.format(KEY_WITH_BRANCH_FORMAT, keyWithoutBranch, branch); // depends on control dependency: [if], data = [none]
} else {
return keyWithoutBranch; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private HttpPipeKey saveDbBatch(DbBatch dbBatch) {
RowBatch rowBatch = dbBatch.getRowBatch();
// 转化为proto对象
BatchProto.RowBatch.Builder rowBatchBuilder = BatchProto.RowBatch.newBuilder();
rowBatchBuilder.setIdentity(build(rowBatch.getIdentity()));
// 处理具体的字段rowData
for (EventData eventData : rowBatch.getDatas()) {
BatchProto.RowData.Builder rowDataBuilder = BatchProto.RowData.newBuilder();
rowDataBuilder.setPairId(eventData.getPairId());
rowDataBuilder.setTableId(eventData.getTableId());
if (eventData.getSchemaName() != null) {
rowDataBuilder.setSchemaName(eventData.getSchemaName());
}
rowDataBuilder.setTableName(eventData.getTableName());
rowDataBuilder.setEventType(eventData.getEventType().getValue());
rowDataBuilder.setExecuteTime(eventData.getExecuteTime());
// add by ljh at 2012-10-31
if (eventData.getSyncMode() != null) {
rowDataBuilder.setSyncMode(eventData.getSyncMode().getValue());
}
if (eventData.getSyncConsistency() != null) {
rowDataBuilder.setSyncConsistency(eventData.getSyncConsistency().getValue());
}
// 构造key column
for (EventColumn keyColumn : eventData.getKeys()) {
rowDataBuilder.addKeys(buildColumn(keyColumn));
}
// 构造old key column
if (CollectionUtils.isEmpty(eventData.getOldKeys()) == false) {
for (EventColumn keyColumn : eventData.getOldKeys()) {
rowDataBuilder.addOldKeys(buildColumn(keyColumn));
}
}
// 构造其他 column
for (EventColumn column : eventData.getColumns()) {
rowDataBuilder.addColumns(buildColumn(column));
}
rowDataBuilder.setRemedy(eventData.isRemedy());
rowDataBuilder.setSize(eventData.getSize());
if (StringUtils.isNotEmpty(eventData.getSql())) {
rowDataBuilder.setSql(eventData.getSql());
}
if (StringUtils.isNotEmpty(eventData.getDdlSchemaName())) {
rowDataBuilder.setDdlSchemaName(eventData.getDdlSchemaName());
}
if (StringUtils.isNotEmpty(eventData.getHint())) {
rowDataBuilder.setHint(eventData.getHint());
}
rowDataBuilder.setWithoutSchema(eventData.isWithoutSchema());
rowBatchBuilder.addRows(rowDataBuilder.build());// 添加一条rowData记录
}
// 处理下FileBatch
FileBatch fileBatch = dbBatch.getFileBatch();
BatchProto.FileBatch.Builder fileBatchBuilder = null;
fileBatchBuilder = BatchProto.FileBatch.newBuilder();
fileBatchBuilder.setIdentity(build(fileBatch.getIdentity()));
// 构造对应的proto对象
for (FileData fileData : fileBatch.getFiles()) {
BatchProto.FileData.Builder fileDataBuilder = BatchProto.FileData.newBuilder();
fileDataBuilder.setPairId(fileData.getPairId());
fileDataBuilder.setTableId(fileData.getTableId());
if (fileData.getNameSpace() != null) {
fileDataBuilder.setNamespace(fileData.getNameSpace());
}
if (fileData.getPath() != null) {
fileDataBuilder.setPath(fileData.getPath());
}
fileDataBuilder.setEventType(fileData.getEventType().getValue());
fileDataBuilder.setSize(fileData.getSize());
fileDataBuilder.setLastModifiedTime(fileData.getLastModifiedTime());
fileBatchBuilder.addFiles(fileDataBuilder.build());// 添加一条fileData记录
}
// 处理构造对应的文件url
String filename = buildFileName(rowBatch.getIdentity(), ClassUtils.getShortClassName(dbBatch.getClass()));
// 写入数据
File file = new File(htdocsDir, filename);
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(file));
com.alibaba.otter.node.etl.model.protobuf.BatchProto.RowBatch rowBatchProto = rowBatchBuilder.build();
output.write(ByteUtils.int2bytes(rowBatchProto.getSerializedSize()));// 输出大小
rowBatchProto.writeTo(output);// 输出row batch
com.alibaba.otter.node.etl.model.protobuf.BatchProto.FileBatch fileBatchProto = fileBatchBuilder.build();
output.write(ByteUtils.int2bytes(fileBatchProto.getSerializedSize()));// 输出大小
fileBatchProto.writeTo(output); // 输出file batch
output.flush();
} catch (IOException e) {
throw new PipeException("write_byte_error", e);
} finally {
IOUtils.closeQuietly(output);
}
HttpPipeKey key = new HttpPipeKey();
key.setUrl(remoteUrlBuilder.getUrl(rowBatch.getIdentity().getPipelineId(), filename));
key.setDataType(PipeDataType.DB_BATCH);
key.setIdentity(rowBatch.getIdentity());
Pipeline pipeline = configClientService.findPipeline(rowBatch.getIdentity().getPipelineId());
if (pipeline.getParameters().getUseFileEncrypt()) {
// 加密处理
EncryptedData encryptedData = encryptFile(file);
key.setKey(encryptedData.getKey());
key.setCrc(encryptedData.getCrc());
}
return key;
} } | public class class_name {
private HttpPipeKey saveDbBatch(DbBatch dbBatch) {
RowBatch rowBatch = dbBatch.getRowBatch();
// 转化为proto对象
BatchProto.RowBatch.Builder rowBatchBuilder = BatchProto.RowBatch.newBuilder();
rowBatchBuilder.setIdentity(build(rowBatch.getIdentity()));
// 处理具体的字段rowData
for (EventData eventData : rowBatch.getDatas()) {
BatchProto.RowData.Builder rowDataBuilder = BatchProto.RowData.newBuilder();
rowDataBuilder.setPairId(eventData.getPairId()); // depends on control dependency: [for], data = [eventData]
rowDataBuilder.setTableId(eventData.getTableId()); // depends on control dependency: [for], data = [eventData]
if (eventData.getSchemaName() != null) {
rowDataBuilder.setSchemaName(eventData.getSchemaName()); // depends on control dependency: [if], data = [(eventData.getSchemaName()]
}
rowDataBuilder.setTableName(eventData.getTableName()); // depends on control dependency: [for], data = [eventData]
rowDataBuilder.setEventType(eventData.getEventType().getValue()); // depends on control dependency: [for], data = [eventData]
rowDataBuilder.setExecuteTime(eventData.getExecuteTime()); // depends on control dependency: [for], data = [eventData]
// add by ljh at 2012-10-31
if (eventData.getSyncMode() != null) {
rowDataBuilder.setSyncMode(eventData.getSyncMode().getValue()); // depends on control dependency: [if], data = [(eventData.getSyncMode()]
}
if (eventData.getSyncConsistency() != null) {
rowDataBuilder.setSyncConsistency(eventData.getSyncConsistency().getValue()); // depends on control dependency: [if], data = [(eventData.getSyncConsistency()]
}
// 构造key column
for (EventColumn keyColumn : eventData.getKeys()) {
rowDataBuilder.addKeys(buildColumn(keyColumn)); // depends on control dependency: [for], data = [keyColumn]
}
// 构造old key column
if (CollectionUtils.isEmpty(eventData.getOldKeys()) == false) {
for (EventColumn keyColumn : eventData.getOldKeys()) {
rowDataBuilder.addOldKeys(buildColumn(keyColumn)); // depends on control dependency: [for], data = [keyColumn]
}
}
// 构造其他 column
for (EventColumn column : eventData.getColumns()) {
rowDataBuilder.addColumns(buildColumn(column)); // depends on control dependency: [for], data = [column]
}
rowDataBuilder.setRemedy(eventData.isRemedy()); // depends on control dependency: [for], data = [eventData]
rowDataBuilder.setSize(eventData.getSize()); // depends on control dependency: [for], data = [eventData]
if (StringUtils.isNotEmpty(eventData.getSql())) {
rowDataBuilder.setSql(eventData.getSql()); // depends on control dependency: [if], data = [none]
}
if (StringUtils.isNotEmpty(eventData.getDdlSchemaName())) {
rowDataBuilder.setDdlSchemaName(eventData.getDdlSchemaName()); // depends on control dependency: [if], data = [none]
}
if (StringUtils.isNotEmpty(eventData.getHint())) {
rowDataBuilder.setHint(eventData.getHint()); // depends on control dependency: [if], data = [none]
}
rowDataBuilder.setWithoutSchema(eventData.isWithoutSchema()); // depends on control dependency: [for], data = [eventData]
rowBatchBuilder.addRows(rowDataBuilder.build());// 添加一条rowData记录 // depends on control dependency: [for], data = [none]
}
// 处理下FileBatch
FileBatch fileBatch = dbBatch.getFileBatch();
BatchProto.FileBatch.Builder fileBatchBuilder = null;
fileBatchBuilder = BatchProto.FileBatch.newBuilder();
fileBatchBuilder.setIdentity(build(fileBatch.getIdentity()));
// 构造对应的proto对象
for (FileData fileData : fileBatch.getFiles()) {
BatchProto.FileData.Builder fileDataBuilder = BatchProto.FileData.newBuilder();
fileDataBuilder.setPairId(fileData.getPairId()); // depends on control dependency: [for], data = [fileData]
fileDataBuilder.setTableId(fileData.getTableId()); // depends on control dependency: [for], data = [fileData]
if (fileData.getNameSpace() != null) {
fileDataBuilder.setNamespace(fileData.getNameSpace()); // depends on control dependency: [if], data = [(fileData.getNameSpace()]
}
if (fileData.getPath() != null) {
fileDataBuilder.setPath(fileData.getPath()); // depends on control dependency: [if], data = [(fileData.getPath()]
}
fileDataBuilder.setEventType(fileData.getEventType().getValue()); // depends on control dependency: [for], data = [fileData]
fileDataBuilder.setSize(fileData.getSize()); // depends on control dependency: [for], data = [fileData]
fileDataBuilder.setLastModifiedTime(fileData.getLastModifiedTime()); // depends on control dependency: [for], data = [fileData]
fileBatchBuilder.addFiles(fileDataBuilder.build());// 添加一条fileData记录 // depends on control dependency: [for], data = [fileData]
}
// 处理构造对应的文件url
String filename = buildFileName(rowBatch.getIdentity(), ClassUtils.getShortClassName(dbBatch.getClass()));
// 写入数据
File file = new File(htdocsDir, filename);
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(file)); // depends on control dependency: [try], data = [none]
com.alibaba.otter.node.etl.model.protobuf.BatchProto.RowBatch rowBatchProto = rowBatchBuilder.build();
output.write(ByteUtils.int2bytes(rowBatchProto.getSerializedSize()));// 输出大小 // depends on control dependency: [try], data = [none]
rowBatchProto.writeTo(output);// 输出row batch // depends on control dependency: [try], data = [none]
com.alibaba.otter.node.etl.model.protobuf.BatchProto.FileBatch fileBatchProto = fileBatchBuilder.build();
output.write(ByteUtils.int2bytes(fileBatchProto.getSerializedSize()));// 输出大小 // depends on control dependency: [try], data = [none]
fileBatchProto.writeTo(output); // 输出file batch // depends on control dependency: [try], data = [none]
output.flush(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new PipeException("write_byte_error", e);
} finally { // depends on control dependency: [catch], data = [none]
IOUtils.closeQuietly(output);
}
HttpPipeKey key = new HttpPipeKey();
key.setUrl(remoteUrlBuilder.getUrl(rowBatch.getIdentity().getPipelineId(), filename));
key.setDataType(PipeDataType.DB_BATCH);
key.setIdentity(rowBatch.getIdentity());
Pipeline pipeline = configClientService.findPipeline(rowBatch.getIdentity().getPipelineId());
if (pipeline.getParameters().getUseFileEncrypt()) {
// 加密处理
EncryptedData encryptedData = encryptFile(file);
key.setKey(encryptedData.getKey()); // depends on control dependency: [if], data = [none]
key.setCrc(encryptedData.getCrc()); // depends on control dependency: [if], data = [none]
}
return key;
} } |
public class class_name {
public Bundle withSupportedPlatforms(String... supportedPlatforms) {
if (this.supportedPlatforms == null) {
setSupportedPlatforms(new java.util.ArrayList<String>(supportedPlatforms.length));
}
for (String ele : supportedPlatforms) {
this.supportedPlatforms.add(ele);
}
return this;
} } | public class class_name {
public Bundle withSupportedPlatforms(String... supportedPlatforms) {
if (this.supportedPlatforms == null) {
setSupportedPlatforms(new java.util.ArrayList<String>(supportedPlatforms.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : supportedPlatforms) {
this.supportedPlatforms.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void fillContent(CmsImageInfoBean imageInfo) {
//checking for enhanced image options
m_form.hideEnhancedOptions(
(getDialogMode() != GalleryMode.editor) || !CmsPreviewUtil.hasEnhancedImageOptions());
CmsJSONMap imageAttributes = CmsPreviewUtil.getImageAttributes();
boolean inititalFill = false;
// checking if selected image resource is the same as previewed resource
if ((imageAttributes.containsKey(Attribute.emptySelection.name()))
|| (imageAttributes.containsKey(Attribute.hash.name())
&& !imageAttributes.getString(Attribute.hash.name()).equals(
String.valueOf(m_handler.getImageIdHash())))) {
imageAttributes = CmsJSONMap.createJSONMap();
inititalFill = true;
}
m_form.fillContent(imageInfo, imageAttributes, inititalFill);
} } | public class class_name {
public void fillContent(CmsImageInfoBean imageInfo) {
//checking for enhanced image options
m_form.hideEnhancedOptions(
(getDialogMode() != GalleryMode.editor) || !CmsPreviewUtil.hasEnhancedImageOptions());
CmsJSONMap imageAttributes = CmsPreviewUtil.getImageAttributes();
boolean inititalFill = false;
// checking if selected image resource is the same as previewed resource
if ((imageAttributes.containsKey(Attribute.emptySelection.name()))
|| (imageAttributes.containsKey(Attribute.hash.name())
&& !imageAttributes.getString(Attribute.hash.name()).equals(
String.valueOf(m_handler.getImageIdHash())))) {
imageAttributes = CmsJSONMap.createJSONMap(); // depends on control dependency: [if], data = [none]
inititalFill = true; // depends on control dependency: [if], data = [none]
}
m_form.fillContent(imageInfo, imageAttributes, inititalFill);
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static <C> C parameterizeOrAbort(Class<?> c, Parameterization config) {
try {
C ret = tryInstantiate((Class<C>) c, c, config);
if(ret == null) {
throw new AbortException("Could not instantiate class. Check parameters.");
}
return ret;
}
catch(Exception e) {
if(config.hasErrors()) {
for(ParameterException err : config.getErrors()) {
LOG.warning(err.toString());
}
}
throw e instanceof AbortException ? (AbortException) e : new AbortException("Instantiation failed", e);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public static <C> C parameterizeOrAbort(Class<?> c, Parameterization config) {
try {
C ret = tryInstantiate((Class<C>) c, c, config);
if(ret == null) {
throw new AbortException("Could not instantiate class. Check parameters.");
}
return ret; // depends on control dependency: [try], data = [none]
}
catch(Exception e) {
if(config.hasErrors()) {
for(ParameterException err : config.getErrors()) {
LOG.warning(err.toString()); // depends on control dependency: [for], data = [err]
}
}
throw e instanceof AbortException ? (AbortException) e : new AbortException("Instantiation failed", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public boolean simpleEvaluation(Agent agent) {
//System.out.println("********************************** EVENT CONDITION ***********************************");
PHATEventManager em = agent.getEventManager();
if (em != null) {
List<EventRecord> events = em.getLastEvents(5000, agent.getAgentsAppState().getPHAInterface().getSimTime().getMillisecond());
//System.out.println("Events = "+events.size());
return em.contains(events, idEvent);
} else {
logger.log(Level.WARNING, "Agent {0} hasn't got EventManager!", new Object[]{agent.getId()});
}
return false;
} } | public class class_name {
@Override
public boolean simpleEvaluation(Agent agent) {
//System.out.println("********************************** EVENT CONDITION ***********************************");
PHATEventManager em = agent.getEventManager();
if (em != null) {
List<EventRecord> events = em.getLastEvents(5000, agent.getAgentsAppState().getPHAInterface().getSimTime().getMillisecond());
//System.out.println("Events = "+events.size());
return em.contains(events, idEvent); // depends on control dependency: [if], data = [none]
} else {
logger.log(Level.WARNING, "Agent {0} hasn't got EventManager!", new Object[]{agent.getId()}); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
private void failTasksWithMaxRssMemory(
long rssMemoryInUsage, long availableRssMemory) {
List<TaskAttemptID> tasksToKill = new ArrayList<TaskAttemptID>();
List<TaskAttemptID> allTasks = new ArrayList<TaskAttemptID>();
allTasks.addAll(processTreeInfoMap.keySet());
// Sort the tasks descendingly according to RSS memory usage
Collections.sort(allTasks, new Comparator<TaskAttemptID>() {
@Override
public int compare(TaskAttemptID tid1, TaskAttemptID tid2) {
return getTaskCumulativeRssmem(tid2) > getTaskCumulativeRssmem(tid1) ?
1 : -1;
}});
long rssMemoryStillInUsage = rssMemoryInUsage;
long availableRssMemoryAfterKilling = availableRssMemory;
// Fail the tasks one by one until the memory requirement is met
while ((rssMemoryStillInUsage > maxRssMemoryAllowedForAllTasks ||
availableRssMemoryAfterKilling < reservedRssMemory) &&
!allTasks.isEmpty()) {
TaskAttemptID tid = allTasks.remove(0);
if (!isKillable(tid)) {
continue;
}
long rssmem = getTaskCumulativeRssmem(tid);
if (rssmem == 0) {
break; // Skip tasks without process tree information currently
}
tasksToKill.add(tid);
rssMemoryStillInUsage -= rssmem;
availableRssMemoryAfterKilling += rssmem;
}
// Now kill the tasks.
if (!tasksToKill.isEmpty()) {
for (TaskAttemptID tid : tasksToKill) {
long taskMemoryLimit = getTaskMemoryLimit(tid);
long taskMemory = getTaskCumulativeRssmem(tid);
String pid = processTreeInfoMap.get(tid).getPID();
String msg = HIGH_MEMORY_KEYWORD + " task:" + tid +
" pid:" + pid +
" taskMemory:" + taskMemory +
" taskMemoryLimit:" + taskMemoryLimit +
" availableMemory:" + availableRssMemory +
" totalMemory:" + rssMemoryInUsage +
" totalMemoryLimit:" + maxRssMemoryAllowedForAllTasks;
if (taskMemory > taskMemoryLimit) {
msg = "Failing " + msg;
LOG.warn(msg);
killTask(tid, msg, true);
} else {
msg = "Killing " + msg;
LOG.warn(msg);
killTask(tid, msg, false);
}
}
} else {
LOG.error("The total physical memory usage is overflowing TTs limits. "
+ "But found no alive task to kill for freeing memory.");
}
} } | public class class_name {
private void failTasksWithMaxRssMemory(
long rssMemoryInUsage, long availableRssMemory) {
List<TaskAttemptID> tasksToKill = new ArrayList<TaskAttemptID>();
List<TaskAttemptID> allTasks = new ArrayList<TaskAttemptID>();
allTasks.addAll(processTreeInfoMap.keySet());
// Sort the tasks descendingly according to RSS memory usage
Collections.sort(allTasks, new Comparator<TaskAttemptID>() {
@Override
public int compare(TaskAttemptID tid1, TaskAttemptID tid2) {
return getTaskCumulativeRssmem(tid2) > getTaskCumulativeRssmem(tid1) ?
1 : -1;
}});
long rssMemoryStillInUsage = rssMemoryInUsage;
long availableRssMemoryAfterKilling = availableRssMemory;
// Fail the tasks one by one until the memory requirement is met
while ((rssMemoryStillInUsage > maxRssMemoryAllowedForAllTasks ||
availableRssMemoryAfterKilling < reservedRssMemory) &&
!allTasks.isEmpty()) {
TaskAttemptID tid = allTasks.remove(0);
if (!isKillable(tid)) {
continue;
}
long rssmem = getTaskCumulativeRssmem(tid);
if (rssmem == 0) {
break; // Skip tasks without process tree information currently
}
tasksToKill.add(tid); // depends on control dependency: [while], data = [none]
rssMemoryStillInUsage -= rssmem; // depends on control dependency: [while], data = [none]
availableRssMemoryAfterKilling += rssmem; // depends on control dependency: [while], data = [none]
}
// Now kill the tasks.
if (!tasksToKill.isEmpty()) {
for (TaskAttemptID tid : tasksToKill) {
long taskMemoryLimit = getTaskMemoryLimit(tid);
long taskMemory = getTaskCumulativeRssmem(tid);
String pid = processTreeInfoMap.get(tid).getPID();
String msg = HIGH_MEMORY_KEYWORD + " task:" + tid +
" pid:" + pid +
" taskMemory:" + taskMemory +
" taskMemoryLimit:" + taskMemoryLimit +
" availableMemory:" + availableRssMemory +
" totalMemory:" + rssMemoryInUsage +
" totalMemoryLimit:" + maxRssMemoryAllowedForAllTasks;
if (taskMemory > taskMemoryLimit) {
msg = "Failing " + msg; // depends on control dependency: [if], data = [none]
LOG.warn(msg); // depends on control dependency: [if], data = [none]
killTask(tid, msg, true); // depends on control dependency: [if], data = [none]
} else {
msg = "Killing " + msg; // depends on control dependency: [if], data = [none]
LOG.warn(msg); // depends on control dependency: [if], data = [none]
killTask(tid, msg, false); // depends on control dependency: [if], data = [none]
}
}
} else {
LOG.error("The total physical memory usage is overflowing TTs limits. "
+ "But found no alive task to kill for freeing memory."); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException {
Preconditions.checkArgument(uploader == null);
Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET));
String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod;
final HttpRequest httpRequest = getAbstractGoogleClient()
.getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent);
new MethodOverride().intercept(httpRequest);
httpRequest.setParser(getAbstractGoogleClient().getObjectParser());
// custom methods may use POST with no content but require a Content-Length header
if (httpContent == null && (requestMethod.equals(HttpMethods.POST)
|| requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) {
httpRequest.setContent(new EmptyContent());
}
httpRequest.getHeaders().putAll(requestHeaders);
if (!disableGZipContent) {
httpRequest.setEncoding(new GZipEncoding());
}
final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor();
httpRequest.setResponseInterceptor(new HttpResponseInterceptor() {
public void interceptResponse(HttpResponse response) throws IOException {
if (responseInterceptor != null) {
responseInterceptor.interceptResponse(response);
}
if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) {
throw newExceptionOnError(response);
}
}
});
return httpRequest;
} } | public class class_name {
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException {
Preconditions.checkArgument(uploader == null);
Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET));
String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod;
final HttpRequest httpRequest = getAbstractGoogleClient()
.getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent);
new MethodOverride().intercept(httpRequest);
httpRequest.setParser(getAbstractGoogleClient().getObjectParser());
// custom methods may use POST with no content but require a Content-Length header
if (httpContent == null && (requestMethod.equals(HttpMethods.POST)
|| requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) {
httpRequest.setContent(new EmptyContent());
}
httpRequest.getHeaders().putAll(requestHeaders);
if (!disableGZipContent) {
httpRequest.setEncoding(new GZipEncoding());
}
final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor();
httpRequest.setResponseInterceptor(new HttpResponseInterceptor() {
public void interceptResponse(HttpResponse response) throws IOException {
if (responseInterceptor != null) {
responseInterceptor.interceptResponse(response); // depends on control dependency: [if], data = [none]
}
if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) {
throw newExceptionOnError(response);
}
}
});
return httpRequest;
} } |
public class class_name {
private static List<Integer> initializeEligible(Map<Integer, Integer> alignment,
Map<Integer, Double> scores, List<Integer> eligible, int k, NavigableSet<Integer> forwardLoops, NavigableSet<Integer> backwardLoops) {
// Eligible if:
// 1. score(x)>0
// 2. f^K-1(x) is defined
// 3. score(f^K-1(x))>0
// 4. For all y, score(y)==0 implies sign(f^K-1(x)-y) == sign(x-f(y) )
// 5. Not in a loop of length less than k
// Assume all residues are eligible to start
if(eligible == null) {
eligible = new LinkedList<Integer>(alignment.keySet());
}
// Precalculate f^K-1(x)
// Map<Integer, Integer> alignK1 = AlignmentTools.applyAlignment(alignment, k-1);
Map<Integer, Integer> alignK1 = applyAlignmentAndCheckCycles(alignment, k - 1, eligible);
// Remove ineligible residues
Iterator<Integer> eligibleIt = eligible.iterator();
while(eligibleIt.hasNext()) {
Integer res = eligibleIt.next();
// 2. f^K-1(x) is defined
if(!alignK1.containsKey(res)) {
eligibleIt.remove();
continue;
}
Integer k1 = alignK1.get(res);
if(k1 == null) {
eligibleIt.remove();
continue;
}
// 1. score(x)>0
Double score = scores.get(res);
if(score == null || score <= 0.0) {
eligibleIt.remove();
// res is in a loop. Add it to the proper set
if(res <= alignment.get(res)) {
//forward
forwardLoops.add(res);
} else {
//backward
backwardLoops.add(res);
}
continue;
}
// 3. score(f^K-1(x))>0
Double scoreK1 = scores.get(k1);
if(scoreK1 == null || scoreK1 <= 0.0) {
eligibleIt.remove();
continue;
}
}
// Now that loops are up-to-date, check for loop crossings
eligibleIt = eligible.iterator();
while(eligibleIt.hasNext()) {
Integer res = eligibleIt.next();
//4. For all y, score(y)==0 implies sign(f^K-1(x)-y) == sign(x-f(y) )
//Test equivalent: All loop edges should be properly ordered wrt edge f^k-1(x) -> x
Integer src = alignK1.get(res);
if( src < res ) {
//forward
// get interval [a,b) containing res
Integer a = forwardLoops.floor(src);
Integer b = forwardLoops.higher(src);
// Ineligible unless f(a) < res < f(b)
if(a != null && alignment.get(a) > res ) {
eligibleIt.remove();
continue;
}
if(b != null && alignment.get(b) < res ) {
eligibleIt.remove();
continue;
}
}
}
return eligible;
} } | public class class_name {
private static List<Integer> initializeEligible(Map<Integer, Integer> alignment,
Map<Integer, Double> scores, List<Integer> eligible, int k, NavigableSet<Integer> forwardLoops, NavigableSet<Integer> backwardLoops) {
// Eligible if:
// 1. score(x)>0
// 2. f^K-1(x) is defined
// 3. score(f^K-1(x))>0
// 4. For all y, score(y)==0 implies sign(f^K-1(x)-y) == sign(x-f(y) )
// 5. Not in a loop of length less than k
// Assume all residues are eligible to start
if(eligible == null) {
eligible = new LinkedList<Integer>(alignment.keySet()); // depends on control dependency: [if], data = [none]
}
// Precalculate f^K-1(x)
// Map<Integer, Integer> alignK1 = AlignmentTools.applyAlignment(alignment, k-1);
Map<Integer, Integer> alignK1 = applyAlignmentAndCheckCycles(alignment, k - 1, eligible);
// Remove ineligible residues
Iterator<Integer> eligibleIt = eligible.iterator();
while(eligibleIt.hasNext()) {
Integer res = eligibleIt.next();
// 2. f^K-1(x) is defined
if(!alignK1.containsKey(res)) {
eligibleIt.remove(); // depends on control dependency: [if], data = [none]
continue;
}
Integer k1 = alignK1.get(res);
if(k1 == null) {
eligibleIt.remove(); // depends on control dependency: [if], data = [none]
continue;
}
// 1. score(x)>0
Double score = scores.get(res);
if(score == null || score <= 0.0) {
eligibleIt.remove(); // depends on control dependency: [if], data = [none]
// res is in a loop. Add it to the proper set
if(res <= alignment.get(res)) {
//forward
forwardLoops.add(res); // depends on control dependency: [if], data = [(res]
} else {
//backward
backwardLoops.add(res); // depends on control dependency: [if], data = [(res]
}
continue;
}
// 3. score(f^K-1(x))>0
Double scoreK1 = scores.get(k1);
if(scoreK1 == null || scoreK1 <= 0.0) {
eligibleIt.remove(); // depends on control dependency: [if], data = [none]
continue;
}
}
// Now that loops are up-to-date, check for loop crossings
eligibleIt = eligible.iterator();
while(eligibleIt.hasNext()) {
Integer res = eligibleIt.next();
//4. For all y, score(y)==0 implies sign(f^K-1(x)-y) == sign(x-f(y) )
//Test equivalent: All loop edges should be properly ordered wrt edge f^k-1(x) -> x
Integer src = alignK1.get(res);
if( src < res ) {
//forward
// get interval [a,b) containing res
Integer a = forwardLoops.floor(src);
Integer b = forwardLoops.higher(src);
// Ineligible unless f(a) < res < f(b)
if(a != null && alignment.get(a) > res ) {
eligibleIt.remove(); // depends on control dependency: [if], data = [none]
continue;
}
if(b != null && alignment.get(b) < res ) {
eligibleIt.remove(); // depends on control dependency: [if], data = [none]
continue;
}
}
}
return eligible;
} } |
public class class_name {
private static void collectTerminals(AbstractExpression expr, Set<AbstractExpression> accum) {
if (expr != null) {
collectTerminals(expr.getLeft(), accum);
collectTerminals(expr.getRight(), accum);
if (expr.getArgs() != null) {
expr.getArgs().forEach(e -> collectTerminals(e, accum));
} else if (expr.getLeft() == null && expr.getRight() == null) {
accum.add(expr);
}
}
} } | public class class_name {
private static void collectTerminals(AbstractExpression expr, Set<AbstractExpression> accum) {
if (expr != null) {
collectTerminals(expr.getLeft(), accum); // depends on control dependency: [if], data = [(expr]
collectTerminals(expr.getRight(), accum); // depends on control dependency: [if], data = [(expr]
if (expr.getArgs() != null) {
expr.getArgs().forEach(e -> collectTerminals(e, accum)); // depends on control dependency: [if], data = [none]
} else if (expr.getLeft() == null && expr.getRight() == null) {
accum.add(expr); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
protected Object findValue(String expr, Class<?> toType) {
if (altSyntax() && toType == String.class) {
return TextParseUtil.translateVariables('%', expr, stack);
} else {
expr = stripExpressionIfAltSyntax(expr);
return stack.findValue(expr, toType, false);
}
} } | public class class_name {
protected Object findValue(String expr, Class<?> toType) {
if (altSyntax() && toType == String.class) {
return TextParseUtil.translateVariables('%', expr, stack); // depends on control dependency: [if], data = [none]
} else {
expr = stripExpressionIfAltSyntax(expr); // depends on control dependency: [if], data = [none]
return stack.findValue(expr, toType, false); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Address[] getAddresses() {
if (addresses != null)
return addresses;
if (hosts != null) {
addresses = new Address[hosts.length];
for (int i = 0; i < hosts.length; i++)
addresses[i] = new Address(hosts[i], factory.getPort());
return addresses;
}
Address address = factory == null ? new Address("localhost", -1) : new Address(
factory.getHost(), factory.getPort());
return new Address[] { address };
} } | public class class_name {
public Address[] getAddresses() {
if (addresses != null)
return addresses;
if (hosts != null) {
addresses = new Address[hosts.length]; // depends on control dependency: [if], data = [none]
for (int i = 0; i < hosts.length; i++)
addresses[i] = new Address(hosts[i], factory.getPort());
return addresses; // depends on control dependency: [if], data = [none]
}
Address address = factory == null ? new Address("localhost", -1) : new Address(
factory.getHost(), factory.getPort());
return new Address[] { address };
} } |
public class class_name {
private void initEmbedded(String[] args, String[] services) {
if (m_bInitialized) {
m_logger.warn("initEmbedded: Already initialized -- ignoring");
return;
}
m_logger.info("Initializing embedded mode");
initConfig(args);
initEmbeddedServices(services);
RESTService.instance().registerCommands(CMD_CLASSES);
m_bInitialized = true;
} } | public class class_name {
private void initEmbedded(String[] args, String[] services) {
if (m_bInitialized) {
m_logger.warn("initEmbedded: Already initialized -- ignoring");
// depends on control dependency: [if], data = [none]
return;
// depends on control dependency: [if], data = [none]
}
m_logger.info("Initializing embedded mode");
initConfig(args);
initEmbeddedServices(services);
RESTService.instance().registerCommands(CMD_CLASSES);
m_bInitialized = true;
} } |
public class class_name {
public Observable<ServiceResponse<StorageBundle>> regenerateStorageAccountKeyWithServiceResponseAsync(String vaultBaseUrl, String storageAccountName, String keyName) {
if (vaultBaseUrl == null) {
throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null.");
}
if (storageAccountName == null) {
throw new IllegalArgumentException("Parameter storageAccountName is required and cannot be null.");
}
if (this.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null.");
}
if (keyName == null) {
throw new IllegalArgumentException("Parameter keyName is required and cannot be null.");
}
StorageAccountRegenerteKeyParameters parameters = new StorageAccountRegenerteKeyParameters();
parameters.withKeyName(keyName);
String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl);
return service.regenerateStorageAccountKey(storageAccountName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<StorageBundle>>>() {
@Override
public Observable<ServiceResponse<StorageBundle>> call(Response<ResponseBody> response) {
try {
ServiceResponse<StorageBundle> clientResponse = regenerateStorageAccountKeyDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<StorageBundle>> regenerateStorageAccountKeyWithServiceResponseAsync(String vaultBaseUrl, String storageAccountName, String keyName) {
if (vaultBaseUrl == null) {
throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null.");
}
if (storageAccountName == null) {
throw new IllegalArgumentException("Parameter storageAccountName is required and cannot be null.");
}
if (this.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.apiVersion() is required and cannot be null.");
}
if (keyName == null) {
throw new IllegalArgumentException("Parameter keyName is required and cannot be null.");
}
StorageAccountRegenerteKeyParameters parameters = new StorageAccountRegenerteKeyParameters();
parameters.withKeyName(keyName);
String parameterizedHost = Joiner.on(", ").join("{vaultBaseUrl}", vaultBaseUrl);
return service.regenerateStorageAccountKey(storageAccountName, this.apiVersion(), this.acceptLanguage(), parameters, parameterizedHost, this.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<StorageBundle>>>() {
@Override
public Observable<ServiceResponse<StorageBundle>> call(Response<ResponseBody> response) {
try {
ServiceResponse<StorageBundle> clientResponse = regenerateStorageAccountKeyDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public void marshall(ImageDetail imageDetail, ProtocolMarshaller protocolMarshaller) {
if (imageDetail == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(imageDetail.getRegistryId(), REGISTRYID_BINDING);
protocolMarshaller.marshall(imageDetail.getRepositoryName(), REPOSITORYNAME_BINDING);
protocolMarshaller.marshall(imageDetail.getImageDigest(), IMAGEDIGEST_BINDING);
protocolMarshaller.marshall(imageDetail.getImageTags(), IMAGETAGS_BINDING);
protocolMarshaller.marshall(imageDetail.getImageSizeInBytes(), IMAGESIZEINBYTES_BINDING);
protocolMarshaller.marshall(imageDetail.getImagePushedAt(), IMAGEPUSHEDAT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ImageDetail imageDetail, ProtocolMarshaller protocolMarshaller) {
if (imageDetail == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(imageDetail.getRegistryId(), REGISTRYID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(imageDetail.getRepositoryName(), REPOSITORYNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(imageDetail.getImageDigest(), IMAGEDIGEST_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(imageDetail.getImageTags(), IMAGETAGS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(imageDetail.getImageSizeInBytes(), IMAGESIZEINBYTES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(imageDetail.getImagePushedAt(), IMAGEPUSHEDAT_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 HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException {
HttpMethod httpMethod = null;
String method = header.getMethod();
URI uri = header.getURI();
String version = header.getVersion();
httpMethod = new GenericMethod(method);
httpMethod.setURI(uri);
HttpMethodParams httpParams = httpMethod.getParams();
// default to use HTTP 1.0
httpParams.setVersion(HttpVersion.HTTP_1_0);
if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
httpParams.setVersion(HttpVersion.HTTP_1_1);
}
// set various headers
int pos = 0;
// ZAP: FindBugs fix - always initialise pattern
Pattern pattern = patternCRLF;
String msg = header.getHeadersAsString();
if ((pos = msg.indexOf(CRLF)) < 0) {
if ((pos = msg.indexOf(LF)) < 0) {
pattern = patternLF;
}
} else {
pattern = patternCRLF;
}
String[] split = pattern.split(msg);
String token = null;
String name = null;
String value = null;
for (int i=0; i<split.length; i++) {
token = split[i];
if (token.equals("")) {
continue;
}
if ((pos = token.indexOf(":")) < 0) {
return null;
}
name = token.substring(0, pos).trim();
value = token.substring(pos +1).trim();
httpMethod.addRequestHeader(name, value);
}
// set body if post method or put method
if (body != null && body.length() > 0) {
EntityEnclosingMethod generic = (EntityEnclosingMethod) httpMethod;
generic.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
}
httpMethod.setFollowRedirects(false);
return httpMethod;
} } | public class class_name {
public HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException {
HttpMethod httpMethod = null;
String method = header.getMethod();
URI uri = header.getURI();
String version = header.getVersion();
httpMethod = new GenericMethod(method);
httpMethod.setURI(uri);
HttpMethodParams httpParams = httpMethod.getParams();
// default to use HTTP 1.0
httpParams.setVersion(HttpVersion.HTTP_1_0);
if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
httpParams.setVersion(HttpVersion.HTTP_1_1);
}
// set various headers
int pos = 0;
// ZAP: FindBugs fix - always initialise pattern
Pattern pattern = patternCRLF;
String msg = header.getHeadersAsString();
if ((pos = msg.indexOf(CRLF)) < 0) {
if ((pos = msg.indexOf(LF)) < 0) {
pattern = patternLF;
// depends on control dependency: [if], data = [none]
}
} else {
pattern = patternCRLF;
}
String[] split = pattern.split(msg);
String token = null;
String name = null;
String value = null;
for (int i=0; i<split.length; i++) {
token = split[i];
if (token.equals("")) {
continue;
}
if ((pos = token.indexOf(":")) < 0) {
return null;
}
name = token.substring(0, pos).trim();
value = token.substring(pos +1).trim();
httpMethod.addRequestHeader(name, value);
}
// set body if post method or put method
if (body != null && body.length() > 0) {
EntityEnclosingMethod generic = (EntityEnclosingMethod) httpMethod;
generic.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
}
httpMethod.setFollowRedirects(false);
return httpMethod;
} } |
public class class_name {
@SuppressWarnings("deprecation")
private CmsResourceTypeBean createTypeBean(
I_CmsResourceType type,
I_CmsPreviewProvider preview,
boolean creatable) {
CmsResourceTypeBean result = new CmsResourceTypeBean();
result.setResourceType(type.getTypeName());
result.setTypeId(type.getTypeId());
Locale wpLocale = getWorkplaceLocale();
// type title and subtitle
result.setTitle(CmsWorkplaceMessages.getResourceTypeName(wpLocale, type.getTypeName()));
result.setSubTitle(CmsWorkplaceMessages.getResourceTypeDescription(wpLocale, type.getTypeName()));
result.setBigIconClasses(CmsIconUtil.getIconClasses(type.getTypeName(), null, false));
// gallery id of corresponding galleries
ArrayList<String> galleryNames = new ArrayList<String>();
Iterator<I_CmsResourceType> galleryTypes = type.getGalleryTypes().iterator();
while (galleryTypes.hasNext()) {
I_CmsResourceType galleryType = galleryTypes.next();
galleryNames.add(galleryType.getTypeName());
}
result.setGalleryTypeNames(galleryNames);
if (preview != null) {
result.setPreviewProviderName(preview.getPreviewName());
}
if (type.isFolder()) {
result.setVisibility(TypeVisibility.hidden);
}
result.setCreatableType(creatable);
return result;
} } | public class class_name {
@SuppressWarnings("deprecation")
private CmsResourceTypeBean createTypeBean(
I_CmsResourceType type,
I_CmsPreviewProvider preview,
boolean creatable) {
CmsResourceTypeBean result = new CmsResourceTypeBean();
result.setResourceType(type.getTypeName());
result.setTypeId(type.getTypeId());
Locale wpLocale = getWorkplaceLocale();
// type title and subtitle
result.setTitle(CmsWorkplaceMessages.getResourceTypeName(wpLocale, type.getTypeName()));
result.setSubTitle(CmsWorkplaceMessages.getResourceTypeDescription(wpLocale, type.getTypeName()));
result.setBigIconClasses(CmsIconUtil.getIconClasses(type.getTypeName(), null, false));
// gallery id of corresponding galleries
ArrayList<String> galleryNames = new ArrayList<String>();
Iterator<I_CmsResourceType> galleryTypes = type.getGalleryTypes().iterator();
while (galleryTypes.hasNext()) {
I_CmsResourceType galleryType = galleryTypes.next();
galleryNames.add(galleryType.getTypeName()); // depends on control dependency: [while], data = [none]
}
result.setGalleryTypeNames(galleryNames);
if (preview != null) {
result.setPreviewProviderName(preview.getPreviewName()); // depends on control dependency: [if], data = [(preview]
}
if (type.isFolder()) {
result.setVisibility(TypeVisibility.hidden); // depends on control dependency: [if], data = [none]
}
result.setCreatableType(creatable);
return result;
} } |
public class class_name {
public static void initLookAndFeel(final String className) {
if (SwingUtilities.isEventDispatchThread()) {
initLookAndFeelIntern(className);
} else {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
initLookAndFeelIntern(className);
}
});
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
} } | public class class_name {
public static void initLookAndFeel(final String className) {
if (SwingUtilities.isEventDispatchThread()) {
initLookAndFeelIntern(className);
// depends on control dependency: [if], data = [none]
} else {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
initLookAndFeelIntern(className);
}
});
// depends on control dependency: [try], data = [none]
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
// depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public void activate() {
// if no handlers are currently running, start one now
if (this.numHandlersInFlight.getInt() == 0) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Activating result handler: " + this.completionPort);
}
startHandler();
}
} } | public class class_name {
public void activate() {
// if no handlers are currently running, start one now
if (this.numHandlersInFlight.getInt() == 0) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Activating result handler: " + this.completionPort); // depends on control dependency: [if], data = [none]
}
startHandler(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static final long getNegDivMod(int number, int factor)
{
int modulo = number % factor;
long result = number / factor;
if (modulo < 0) {
-- result;
modulo += factor;
}
return (result << 32) | modulo;
} } | public class class_name {
private static final long getNegDivMod(int number, int factor)
{
int modulo = number % factor;
long result = number / factor;
if (modulo < 0) {
-- result; // depends on control dependency: [if], data = [none]
modulo += factor; // depends on control dependency: [if], data = [none]
}
return (result << 32) | modulo;
} } |
public class class_name {
private boolean evalFormElement(final AjaxRequestTarget _target,
final StringBuilder _html,
final UIForm _uiform)
throws EFapsException
{
AjaxSubmitCloseButton.LOG.trace("entering evalFormElement");
boolean ret = true;
for (final Element element : _uiform.getElements()) {
if (element.getType().equals(ElementType.FORM)) {
final FormElement formElement = (FormElement) element.getElement();
for (final Iterator<FormRow> uiRowIter = formElement.getRowModels(); uiRowIter.hasNext();) {
for (final IUIElement object : uiRowIter.next().getValues()) {
}
}
} else if (element.getType().equals(ElementType.SUBFORM)) {
final UIFieldForm uiFieldForm = (UIFieldForm) element.getElement();
final boolean tmp = evalFormElement(_target, _html, uiFieldForm);
ret = ret ? tmp : ret;
} else if (element.getType().equals(ElementType.TABLE)) {
final UIFieldTable uiFieldTable = (UIFieldTable) element.getElement();
final List<UITableHeader> headers = uiFieldTable.getHeaders();
for (final UIRow uiRow : uiFieldTable.getValues()) {
uiRow.getUserinterfaceId();
final Iterator<UITableHeader> headerIter = headers.iterator();
for (final IFilterable filterable : uiRow.getCells()) {
headerIter.next();
}
}
}
}
return ret;
} } | public class class_name {
private boolean evalFormElement(final AjaxRequestTarget _target,
final StringBuilder _html,
final UIForm _uiform)
throws EFapsException
{
AjaxSubmitCloseButton.LOG.trace("entering evalFormElement");
boolean ret = true;
for (final Element element : _uiform.getElements()) {
if (element.getType().equals(ElementType.FORM)) {
final FormElement formElement = (FormElement) element.getElement();
for (final Iterator<FormRow> uiRowIter = formElement.getRowModels(); uiRowIter.hasNext();) {
for (final IUIElement object : uiRowIter.next().getValues()) {
}
}
} else if (element.getType().equals(ElementType.SUBFORM)) {
final UIFieldForm uiFieldForm = (UIFieldForm) element.getElement();
final boolean tmp = evalFormElement(_target, _html, uiFieldForm);
ret = ret ? tmp : ret;
} else if (element.getType().equals(ElementType.TABLE)) {
final UIFieldTable uiFieldTable = (UIFieldTable) element.getElement();
final List<UITableHeader> headers = uiFieldTable.getHeaders();
for (final UIRow uiRow : uiFieldTable.getValues()) {
uiRow.getUserinterfaceId(); // depends on control dependency: [for], data = [uiRow]
final Iterator<UITableHeader> headerIter = headers.iterator();
for (final IFilterable filterable : uiRow.getCells()) {
headerIter.next(); // depends on control dependency: [for], data = [none]
}
}
}
}
return ret;
} } |
public class class_name {
public EClass getIfcMetric() {
if (ifcMetricEClass == null) {
ifcMetricEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(322);
}
return ifcMetricEClass;
} } | public class class_name {
public EClass getIfcMetric() {
if (ifcMetricEClass == null) {
ifcMetricEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(322);
// depends on control dependency: [if], data = [none]
}
return ifcMetricEClass;
} } |
public class class_name {
private String fetchCsrfToken() {
try {
return connection.fetchToken("csrf");
} catch (IOException | MediaWikiApiErrorException e) {
logger.error("Error when trying to fetch csrf token: "
+ e.toString());
}
return null;
} } | public class class_name {
private String fetchCsrfToken() {
try {
return connection.fetchToken("csrf"); // depends on control dependency: [try], data = [none]
} catch (IOException | MediaWikiApiErrorException e) {
logger.error("Error when trying to fetch csrf token: "
+ e.toString());
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
public Object lookupLink(Name name) throws NamingException {
check(name, JndiPermission.ACTION_LOOKUP);
if (name.isEmpty()) {
return lookup(name);
}
try {
final Name absoluteName = getAbsoluteName(name);
Object link = namingStore.lookup(absoluteName);
if (!(link instanceof LinkRef) && link instanceof Reference) {
link = getObjectInstance(link, name, null);
}
return link;
} catch (Exception e) {
throw namingException(NamingLogger.ROOT_LOGGER.cannotLookupLink(), e, name);
}
} } | public class class_name {
public Object lookupLink(Name name) throws NamingException {
check(name, JndiPermission.ACTION_LOOKUP);
if (name.isEmpty()) {
return lookup(name);
}
try {
final Name absoluteName = getAbsoluteName(name);
Object link = namingStore.lookup(absoluteName);
if (!(link instanceof LinkRef) && link instanceof Reference) {
link = getObjectInstance(link, name, null); // depends on control dependency: [if], data = [none]
}
return link;
} catch (Exception e) {
throw namingException(NamingLogger.ROOT_LOGGER.cannotLookupLink(), e, name);
}
} } |
public class class_name {
protected boolean
contractR(DapStructure dstruct, Set<DapStructure> contracted)
{
if(contracted.contains(dstruct))
return true;
int processed = 0;
List<DapVariable> fields = dstruct.getFields();
for(DapVariable field : fields) {
if(findVariableIndex(field) < 0)
break; // this compound cannot be contracted
DapType base = field.getBaseType();
if(base.getTypeSort().isCompound()
&& !contracted.contains((field))) {
if(!contractR((DapStructure)base, contracted))
break; // this compound cannot be contracted
}
processed++;
}
if(processed < fields.size())
return false;
contracted.add(dstruct); // all compound fields were successfully contracted.
return true;
} } | public class class_name {
protected boolean
contractR(DapStructure dstruct, Set<DapStructure> contracted)
{
if(contracted.contains(dstruct))
return true;
int processed = 0;
List<DapVariable> fields = dstruct.getFields();
for(DapVariable field : fields) {
if(findVariableIndex(field) < 0)
break; // this compound cannot be contracted
DapType base = field.getBaseType();
if(base.getTypeSort().isCompound()
&& !contracted.contains((field))) {
if(!contractR((DapStructure)base, contracted))
break; // this compound cannot be contracted
}
processed++; // depends on control dependency: [for], data = [none]
}
if(processed < fields.size())
return false;
contracted.add(dstruct); // all compound fields were successfully contracted.
return true;
} } |
public class class_name {
@Override
public void setPriority(int newPriority) {
if (newPriority >= Thread.MIN_PRIORITY
&& newPriority <= Thread.MAX_PRIORITY) {
thread.setPriority(newPriority);
}
} } | public class class_name {
@Override
public void setPriority(int newPriority) {
if (newPriority >= Thread.MIN_PRIORITY
&& newPriority <= Thread.MAX_PRIORITY) {
thread.setPriority(newPriority); // depends on control dependency: [if], data = [(newPriority]
}
} } |
public class class_name {
public static Field getField(Class<?> clazz, String fieldName)
throws IllegalStateException {
Assert.notNull(clazz, "Class required");
Assert.hasText(fieldName, "Field name required");
try {
return clazz.getDeclaredField(fieldName);
}
catch (NoSuchFieldException nsf) {
// Try superclass
if (clazz.getSuperclass() != null) {
return getField(clazz.getSuperclass(), fieldName);
}
throw new IllegalStateException("Could not locate field '" + fieldName
+ "' on class " + clazz);
}
} } | public class class_name {
public static Field getField(Class<?> clazz, String fieldName)
throws IllegalStateException {
Assert.notNull(clazz, "Class required");
Assert.hasText(fieldName, "Field name required");
try {
return clazz.getDeclaredField(fieldName);
}
catch (NoSuchFieldException nsf) {
// Try superclass
if (clazz.getSuperclass() != null) {
return getField(clazz.getSuperclass(), fieldName); // depends on control dependency: [if], data = [(clazz.getSuperclass()]
}
throw new IllegalStateException("Could not locate field '" + fieldName
+ "' on class " + clazz);
}
} } |
public class class_name {
public void setExpirationTime(long expirationTime) {
if (expirationTime == NO_EXPIRE) {
updateExpirationTime(NO_EXPIRE);
} else if (expirationTime < 0) {
throw new IllegalArgumentException("invalid expiration time: " + expirationTime);
} else {
updateExpirationTime(expirationTime);
}
} } | public class class_name {
public void setExpirationTime(long expirationTime) {
if (expirationTime == NO_EXPIRE) {
updateExpirationTime(NO_EXPIRE); // depends on control dependency: [if], data = [NO_EXPIRE)]
} else if (expirationTime < 0) {
throw new IllegalArgumentException("invalid expiration time: " + expirationTime);
} else {
updateExpirationTime(expirationTime); // depends on control dependency: [if], data = [(expirationTime]
}
} } |
public class class_name {
private Map<String, String> propertiesToMap(Properties properties) {
Map<String, String> map = new HashMap<>();
for(Map.Entry<Object, Object> entry : properties.entrySet()) {
map.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
return map;
} } | public class class_name {
private Map<String, String> propertiesToMap(Properties properties) {
Map<String, String> map = new HashMap<>();
for(Map.Entry<Object, Object> entry : properties.entrySet()) {
map.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); // depends on control dependency: [for], data = [entry]
}
return map;
} } |
public class class_name {
@Override
public String getOperationReplyDescription(String operationName, Locale locale, ResourceBundle bundle) {
try {
return bundle.getString(getBundleKey(operationName, REPLY));
} catch (MissingResourceException e) {
return null;
}
} } | public class class_name {
@Override
public String getOperationReplyDescription(String operationName, Locale locale, ResourceBundle bundle) {
try {
return bundle.getString(getBundleKey(operationName, REPLY)); // depends on control dependency: [try], data = [none]
} catch (MissingResourceException e) {
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static List<Object> parseCSVLine(String line, String separatorRegex) {
List<Object> matches = new ArrayList<>();
int currentPosition = 0;
Matcher separatorMatcher = Pattern.compile("^" + separatorRegex).matcher(line);
Matcher stringMatcher = Pattern.compile("^" + QUOTED_STRING_REGEX).matcher(line);
Matcher doubleMatcher = Pattern.compile("^" + DOUBLE_REGEX).matcher(line);
while (currentPosition < line.length()) {
if (stringMatcher.region(currentPosition, line.length()).useAnchoringBounds(true).find()) {
// Found String match
String token = line.substring(currentPosition + 1, stringMatcher.end() - 1);
matches.add(unescapeString(token));
currentPosition = stringMatcher.end();
} else if (doubleMatcher.region(currentPosition, line.length()).useAnchoringBounds(true).find()) {
// Found Double match
Double token = Double.parseDouble(line.substring(currentPosition, doubleMatcher.end()));
matches.add(token);
currentPosition = doubleMatcher.end();
} else {
throw new IllegalArgumentException("Can't parse line: expected token at " + currentPosition + " (" + line + ")");
}
if (currentPosition < line.length()) {
if (!separatorMatcher.region(currentPosition, line.length()).useAnchoringBounds(true).find()) {
throw new IllegalArgumentException("Can't parse line: expected separator at " + currentPosition + " (" + line + ")");
}
currentPosition = separatorMatcher.end();
}
}
return matches;
} } | public class class_name {
public static List<Object> parseCSVLine(String line, String separatorRegex) {
List<Object> matches = new ArrayList<>();
int currentPosition = 0;
Matcher separatorMatcher = Pattern.compile("^" + separatorRegex).matcher(line);
Matcher stringMatcher = Pattern.compile("^" + QUOTED_STRING_REGEX).matcher(line);
Matcher doubleMatcher = Pattern.compile("^" + DOUBLE_REGEX).matcher(line);
while (currentPosition < line.length()) {
if (stringMatcher.region(currentPosition, line.length()).useAnchoringBounds(true).find()) {
// Found String match
String token = line.substring(currentPosition + 1, stringMatcher.end() - 1);
matches.add(unescapeString(token));
// depends on control dependency: [if], data = [none]
currentPosition = stringMatcher.end();
// depends on control dependency: [if], data = [none]
} else if (doubleMatcher.region(currentPosition, line.length()).useAnchoringBounds(true).find()) {
// Found Double match
Double token = Double.parseDouble(line.substring(currentPosition, doubleMatcher.end()));
matches.add(token);
// depends on control dependency: [if], data = [none]
currentPosition = doubleMatcher.end();
// depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Can't parse line: expected token at " + currentPosition + " (" + line + ")");
}
if (currentPosition < line.length()) {
if (!separatorMatcher.region(currentPosition, line.length()).useAnchoringBounds(true).find()) {
throw new IllegalArgumentException("Can't parse line: expected separator at " + currentPosition + " (" + line + ")");
}
currentPosition = separatorMatcher.end();
}
}
return matches;
} } |
public class class_name {
public void stopLoadingExcept(URL url) {
if (sourcePicture != null) {
boolean isCurrentlyLoading = sourcePicture.stopLoadingExcept(url);
if (!isCurrentlyLoading) {
// sourcePicture.removeListener( this );
}
PictureCache.stopBackgroundLoadingExcept(url);
}
} } | public class class_name {
public void stopLoadingExcept(URL url) {
if (sourcePicture != null) {
boolean isCurrentlyLoading = sourcePicture.stopLoadingExcept(url);
if (!isCurrentlyLoading) {
// sourcePicture.removeListener( this );
}
PictureCache.stopBackgroundLoadingExcept(url);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private String getDefaultTagReplaceID() {
if (m_tags2replacementTags.size() == 0) {
return ""; // to know that no replacements were set before and the ID will still have
// to be computed later
} else {
StringBuffer result = new StringBuffer();
Map.Entry entry;
Iterator itEntries = m_tags2replacementTags.entrySet().iterator();
while (itEntries.hasNext()) {
entry = (Map.Entry)itEntries.next();
result.append(entry.getKey()).append('=').append(entry.getValue());
if (itEntries.hasNext()) {
result.append(',');
}
}
return result.toString();
}
} } | public class class_name {
private String getDefaultTagReplaceID() {
if (m_tags2replacementTags.size() == 0) {
return ""; // to know that no replacements were set before and the ID will still have // depends on control dependency: [if], data = [none]
// to be computed later
} else {
StringBuffer result = new StringBuffer();
Map.Entry entry;
Iterator itEntries = m_tags2replacementTags.entrySet().iterator();
while (itEntries.hasNext()) {
entry = (Map.Entry)itEntries.next(); // depends on control dependency: [while], data = [none]
result.append(entry.getKey()).append('=').append(entry.getValue()); // depends on control dependency: [while], data = [none]
if (itEntries.hasNext()) {
result.append(','); // depends on control dependency: [if], data = [none]
}
}
return result.toString(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static ClassName bestGuess(String classNameString) {
// Add the package name, like "java.util.concurrent", or "" for no package.
int p = 0;
while (p < classNameString.length() && Character.isLowerCase(classNameString.codePointAt(p))) {
p = classNameString.indexOf('.', p) + 1;
checkArgument(p != 0, "couldn't make a guess for %s", classNameString);
}
String packageName = p == 0 ? "" : classNameString.substring(0, p - 1);
// Add class names like "Map" and "Entry".
ClassName className = null;
for (String simpleName : classNameString.substring(p).split("\\.", -1)) {
checkArgument(!simpleName.isEmpty() && Character.isUpperCase(simpleName.codePointAt(0)),
"couldn't make a guess for %s", classNameString);
className = new ClassName(packageName, className, simpleName);
}
return className;
} } | public class class_name {
public static ClassName bestGuess(String classNameString) {
// Add the package name, like "java.util.concurrent", or "" for no package.
int p = 0;
while (p < classNameString.length() && Character.isLowerCase(classNameString.codePointAt(p))) {
p = classNameString.indexOf('.', p) + 1; // depends on control dependency: [while], data = [none]
checkArgument(p != 0, "couldn't make a guess for %s", classNameString);
}
String packageName = p == 0 ? "" : classNameString.substring(0, p - 1);
// Add class names like "Map" and "Entry".
ClassName className = null;
for (String simpleName : classNameString.substring(p).split("\\.", -1)) {
checkArgument(!simpleName.isEmpty() && Character.isUpperCase(simpleName.codePointAt(0)),
"couldn't make a guess for %s", classNameString); // depends on control dependency: [while], data = [(p]
className = new ClassName(packageName, className, simpleName); // depends on control dependency: [while], data = [(p]
}
return className;
} } |
public class class_name {
public TaskEntity getParentTask() {
if ( parentTask == null && parentTaskId != null) {
this.parentTask = Context.getCommandContext()
.getTaskManager()
.findTaskById(parentTaskId);
}
return parentTask;
} } | public class class_name {
public TaskEntity getParentTask() {
if ( parentTask == null && parentTaskId != null) {
this.parentTask = Context.getCommandContext()
.getTaskManager()
.findTaskById(parentTaskId); // depends on control dependency: [if], data = [none]
}
return parentTask;
} } |
public class class_name {
private static boolean isLogicalMapType(Type groupType)
{
OriginalType ot = groupType.getOriginalType();
if (groupType.isPrimitive() || ot == null || groupType.isRepetition(Type.Repetition.REPEATED)) {
return false;
}
if (groupType.getOriginalType().equals(OriginalType.MAP) ||
groupType.getOriginalType().equals(OriginalType.MAP_KEY_VALUE)) {
GroupType myMapType = groupType.asGroupType();
if (myMapType.getFieldCount() != 1 || myMapType.getFields().get(0).isPrimitive()) {
return false;
}
GroupType mapItemType = myMapType.getFields().get(0).asGroupType();
return mapItemType.isRepetition(Type.Repetition.REPEATED) &&
mapItemType.getFieldCount() == 2 &&
mapItemType.getFields().get(0).getName().equalsIgnoreCase("key") &&
mapItemType.getFields().get(0).isPrimitive() &&
mapItemType.getFields().get(1).getName().equalsIgnoreCase("value");
}
return false;
} } | public class class_name {
private static boolean isLogicalMapType(Type groupType)
{
OriginalType ot = groupType.getOriginalType();
if (groupType.isPrimitive() || ot == null || groupType.isRepetition(Type.Repetition.REPEATED)) {
return false; // depends on control dependency: [if], data = [none]
}
if (groupType.getOriginalType().equals(OriginalType.MAP) ||
groupType.getOriginalType().equals(OriginalType.MAP_KEY_VALUE)) {
GroupType myMapType = groupType.asGroupType();
if (myMapType.getFieldCount() != 1 || myMapType.getFields().get(0).isPrimitive()) {
return false; // depends on control dependency: [if], data = [none]
}
GroupType mapItemType = myMapType.getFields().get(0).asGroupType();
return mapItemType.isRepetition(Type.Repetition.REPEATED) &&
mapItemType.getFieldCount() == 2 &&
mapItemType.getFields().get(0).getName().equalsIgnoreCase("key") &&
mapItemType.getFields().get(0).isPrimitive() &&
mapItemType.getFields().get(1).getName().equalsIgnoreCase("value"); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Override
public void stop() {
if (stopRequested) {
return;
}
super.stop();
if (jobMonitor != null) jobMonitor.running = false;
if (jobMonitorThread != null) jobMonitorThread.interrupt();
} } | public class class_name {
@Override
public void stop() {
if (stopRequested) {
return; // depends on control dependency: [if], data = [none]
}
super.stop();
if (jobMonitor != null) jobMonitor.running = false;
if (jobMonitorThread != null) jobMonitorThread.interrupt();
} } |
public class class_name {
protected void initParameters(Element root) {
m_parameters.clear();
for (Element paramElement : root.elements(APPINFO_PARAM)) {
String name = paramElement.attributeValue(APPINFO_ATTR_NAME);
String value = paramElement.getText();
m_parameters.put(name, value);
}
} } | public class class_name {
protected void initParameters(Element root) {
m_parameters.clear();
for (Element paramElement : root.elements(APPINFO_PARAM)) {
String name = paramElement.attributeValue(APPINFO_ATTR_NAME);
String value = paramElement.getText();
m_parameters.put(name, value); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
private static String decodeFragment(WsByteBuffer buffer) throws CompressionException {
String decodedResult = null;
try {
byte currentByte = buffer.get();
//Reset back position to decode the integer length of this segment.
buffer.position(buffer.position() - 1);
boolean huffman = (HpackUtils.getBit(currentByte, 7) == 1);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Decoding using huffman encoding: " + huffman);
}
//HUFFMAN and NOHUFFMAN ByteFormatTypes have the same
//integer decoding bits (N=7). Therefore, either enum value
//is valid for the integer representation decoder.
int fragmentLength = IntegerRepresentation.decode(buffer, ByteFormatType.HUFFMAN);
byte[] bytes = new byte[fragmentLength];
//Transfer bytes from the buffer into byte array.
buffer.get(bytes);
if (huffman && bytes.length > 0) {
HuffmanDecoder decoder = new HuffmanDecoder();
bytes = decoder.convertHuffmanToAscii(bytes);
}
decodedResult = new String(bytes, Charset.forName(HpackConstants.HPACK_CHAR_SET));
} catch (Exception e) {
throw new CompressionException("Received an invalid header block fragment");
}
return decodedResult;
} } | public class class_name {
private static String decodeFragment(WsByteBuffer buffer) throws CompressionException {
String decodedResult = null;
try {
byte currentByte = buffer.get();
//Reset back position to decode the integer length of this segment.
buffer.position(buffer.position() - 1);
boolean huffman = (HpackUtils.getBit(currentByte, 7) == 1);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Decoding using huffman encoding: " + huffman); // depends on control dependency: [if], data = [none]
}
//HUFFMAN and NOHUFFMAN ByteFormatTypes have the same
//integer decoding bits (N=7). Therefore, either enum value
//is valid for the integer representation decoder.
int fragmentLength = IntegerRepresentation.decode(buffer, ByteFormatType.HUFFMAN);
byte[] bytes = new byte[fragmentLength];
//Transfer bytes from the buffer into byte array.
buffer.get(bytes);
if (huffman && bytes.length > 0) {
HuffmanDecoder decoder = new HuffmanDecoder();
bytes = decoder.convertHuffmanToAscii(bytes); // depends on control dependency: [if], data = [none]
}
decodedResult = new String(bytes, Charset.forName(HpackConstants.HPACK_CHAR_SET));
} catch (Exception e) {
throw new CompressionException("Received an invalid header block fragment");
}
return decodedResult;
} } |
public class class_name {
public static void assertNotNull(Object object, String message) {
if (imp != null && object == null) {
imp.assertFailed(message);
}
} } | public class class_name {
public static void assertNotNull(Object object, String message) {
if (imp != null && object == null) {
imp.assertFailed(message); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public GetLifecyclePolicyPreviewResult withPreviewResults(LifecyclePolicyPreviewResult... previewResults) {
if (this.previewResults == null) {
setPreviewResults(new java.util.ArrayList<LifecyclePolicyPreviewResult>(previewResults.length));
}
for (LifecyclePolicyPreviewResult ele : previewResults) {
this.previewResults.add(ele);
}
return this;
} } | public class class_name {
public GetLifecyclePolicyPreviewResult withPreviewResults(LifecyclePolicyPreviewResult... previewResults) {
if (this.previewResults == null) {
setPreviewResults(new java.util.ArrayList<LifecyclePolicyPreviewResult>(previewResults.length)); // depends on control dependency: [if], data = [none]
}
for (LifecyclePolicyPreviewResult ele : previewResults) {
this.previewResults.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static boolean isCastableToImage(PageContext pc, Object obj) {
try {
Class clazz = ImageUtil.getImageClass();
if (clazz != null) {
Method m = clazz.getMethod("isCastableToImage", new Class[] { PageContext.class, Object.class });
return (boolean) m.invoke(null, new Object[] { pc, obj });
}
}
catch (Exception e) {}
return false;
} } | public class class_name {
public static boolean isCastableToImage(PageContext pc, Object obj) {
try {
Class clazz = ImageUtil.getImageClass();
if (clazz != null) {
Method m = clazz.getMethod("isCastableToImage", new Class[] { PageContext.class, Object.class });
return (boolean) m.invoke(null, new Object[] { pc, obj }); // depends on control dependency: [if], data = [none]
}
}
catch (Exception e) {} // depends on control dependency: [catch], data = [none]
return false;
} } |
public class class_name {
public EClass getFNNRG() {
if (fnnrgEClass == null) {
fnnrgEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(434);
}
return fnnrgEClass;
} } | public class class_name {
public EClass getFNNRG() {
if (fnnrgEClass == null) {
fnnrgEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(434); // depends on control dependency: [if], data = [none]
}
return fnnrgEClass;
} } |
public class class_name {
@Override
public String interpret(String property)
{
try
{
property = Cryption.interpret(property);
if(property != null && property.indexOf(Styles.DEFAULT_PREFIX) > -1)
{
property = Text.format(property,this.getProperties());
}
}
catch (FormatException e)
{
throw new ConfigException("Format exception for \""+property+"\"",e);
}
return Cryption.interpret(property);
} } | public class class_name {
@Override
public String interpret(String property)
{
try
{
property = Cryption.interpret(property);
// depends on control dependency: [try], data = [none]
if(property != null && property.indexOf(Styles.DEFAULT_PREFIX) > -1)
{
property = Text.format(property,this.getProperties());
// depends on control dependency: [if], data = [(property]
}
}
catch (FormatException e)
{
throw new ConfigException("Format exception for \""+property+"\"",e);
}
// depends on control dependency: [catch], data = [none]
return Cryption.interpret(property);
} } |
public class class_name {
protected void appendTimeAllowed(SolrQuery solrQuery, @Nullable Integer timeAllowed) {
if (timeAllowed != null) {
solrQuery.setTimeAllowed(timeAllowed);
}
} } | public class class_name {
protected void appendTimeAllowed(SolrQuery solrQuery, @Nullable Integer timeAllowed) {
if (timeAllowed != null) {
solrQuery.setTimeAllowed(timeAllowed); // depends on control dependency: [if], data = [(timeAllowed]
}
} } |
public class class_name {
public void marshall(Endpoint endpoint, ProtocolMarshaller protocolMarshaller) {
if (endpoint == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(endpoint.getUrl(), URL_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(Endpoint endpoint, ProtocolMarshaller protocolMarshaller) {
if (endpoint == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(endpoint.getUrl(), URL_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private List<Pair<Long, Long>> getTransferSections(CompressionMetadata.Chunk[] chunks)
{
List<Pair<Long, Long>> transferSections = new ArrayList<>();
Pair<Long, Long> lastSection = null;
for (CompressionMetadata.Chunk chunk : chunks)
{
if (lastSection != null)
{
if (chunk.offset == lastSection.right)
{
// extend previous section to end of this chunk
lastSection = Pair.create(lastSection.left, chunk.offset + chunk.length + 4); // 4 bytes for CRC
}
else
{
transferSections.add(lastSection);
lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4);
}
}
else
{
lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4);
}
}
if (lastSection != null)
transferSections.add(lastSection);
return transferSections;
} } | public class class_name {
private List<Pair<Long, Long>> getTransferSections(CompressionMetadata.Chunk[] chunks)
{
List<Pair<Long, Long>> transferSections = new ArrayList<>();
Pair<Long, Long> lastSection = null;
for (CompressionMetadata.Chunk chunk : chunks)
{
if (lastSection != null)
{
if (chunk.offset == lastSection.right)
{
// extend previous section to end of this chunk
lastSection = Pair.create(lastSection.left, chunk.offset + chunk.length + 4); // 4 bytes for CRC // depends on control dependency: [if], data = [none]
}
else
{
transferSections.add(lastSection); // depends on control dependency: [if], data = [none]
lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4); // depends on control dependency: [if], data = [(chunk.offset]
}
}
else
{
lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4); // depends on control dependency: [if], data = [none]
}
}
if (lastSection != null)
transferSections.add(lastSection);
return transferSections;
} } |
public class class_name {
private void destroySingletons() {
if (log.isDebugEnabled()) {
log.debug("Destroying singletons in " + this);
}
int failedDestroyes = 0;
for (BeanRule beanRule : beanRuleRegistry.getIdBasedBeanRules()) {
failedDestroyes += doDestroySingleton(beanRule);
}
for (Set<BeanRule> beanRuleSet : beanRuleRegistry.getTypeBasedBeanRules()) {
for (BeanRule beanRule : beanRuleSet) {
failedDestroyes += doDestroySingleton(beanRule);
}
}
for (BeanRule beanRule : beanRuleRegistry.getConfigurableBeanRules()) {
failedDestroyes += doDestroySingleton(beanRule);
}
if (failedDestroyes > 0) {
log.warn("Singletons has not been destroyed cleanly (Failure Count: " + failedDestroyes + ")");
} else {
log.debug("Destroyed all cached singletons in " + this);
}
} } | public class class_name {
private void destroySingletons() {
if (log.isDebugEnabled()) {
log.debug("Destroying singletons in " + this); // depends on control dependency: [if], data = [none]
}
int failedDestroyes = 0;
for (BeanRule beanRule : beanRuleRegistry.getIdBasedBeanRules()) {
failedDestroyes += doDestroySingleton(beanRule); // depends on control dependency: [for], data = [beanRule]
}
for (Set<BeanRule> beanRuleSet : beanRuleRegistry.getTypeBasedBeanRules()) {
for (BeanRule beanRule : beanRuleSet) {
failedDestroyes += doDestroySingleton(beanRule); // depends on control dependency: [for], data = [beanRule]
}
}
for (BeanRule beanRule : beanRuleRegistry.getConfigurableBeanRules()) {
failedDestroyes += doDestroySingleton(beanRule); // depends on control dependency: [for], data = [beanRule]
}
if (failedDestroyes > 0) {
log.warn("Singletons has not been destroyed cleanly (Failure Count: " + failedDestroyes + ")"); // depends on control dependency: [if], data = [none]
} else {
log.debug("Destroyed all cached singletons in " + this); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Set<InetSocketAddress> getUniqueBinaryTransportHostsAsInetSocketAddresses() {
Set<String> hosts = getUniqueBinaryTransportHosts();
Set<InetSocketAddress> inetAddresses = new HashSet<InetSocketAddress>();
for (String host: hosts) {
String[] parts = host.split(":");
InetSocketAddress inetSocketAddress;
if ( parts.length == 1 ) {
inetSocketAddress = new InetSocketAddress(parts[0], config.getIntegerProperty(CoreConfig.CASSANDRA_BINXPORT_PORT));
} else {
inetSocketAddress = new InetSocketAddress(parts[0], Integer.parseInt(parts[1]));
}
inetAddresses.add(inetSocketAddress);
}
return inetAddresses;
} } | public class class_name {
public Set<InetSocketAddress> getUniqueBinaryTransportHostsAsInetSocketAddresses() {
Set<String> hosts = getUniqueBinaryTransportHosts();
Set<InetSocketAddress> inetAddresses = new HashSet<InetSocketAddress>();
for (String host: hosts) {
String[] parts = host.split(":");
InetSocketAddress inetSocketAddress;
if ( parts.length == 1 ) {
inetSocketAddress = new InetSocketAddress(parts[0], config.getIntegerProperty(CoreConfig.CASSANDRA_BINXPORT_PORT)); // depends on control dependency: [if], data = [none]
} else {
inetSocketAddress = new InetSocketAddress(parts[0], Integer.parseInt(parts[1])); // depends on control dependency: [if], data = [none]
}
inetAddresses.add(inetSocketAddress); // depends on control dependency: [for], data = [none]
}
return inetAddresses;
} } |
public class class_name {
@Nullable
public String getLoggerLevel(@Nullable String loggerName) {
try {
loggerName = loggerName == null ? "" : loggerName;
if (loggerName.isEmpty()) {
return LogManager.getRootLogger().getLevel().toString();
}
Logger logger = LogManager.exists(loggerName);
if (logger == null) {
return null;
} else {
Level level = logger.getLevel();
if (level == null) {
return null;
}
return level.toString();
}
} catch (RuntimeException e) {
logger.warn("Exception getting effective logger level " + loggerName, e);
throw e;
}
} } | public class class_name {
@Nullable
public String getLoggerLevel(@Nullable String loggerName) {
try {
loggerName = loggerName == null ? "" : loggerName; // depends on control dependency: [try], data = [none]
if (loggerName.isEmpty()) {
return LogManager.getRootLogger().getLevel().toString(); // depends on control dependency: [if], data = [none]
}
Logger logger = LogManager.exists(loggerName);
if (logger == null) {
return null; // depends on control dependency: [if], data = [none]
} else {
Level level = logger.getLevel();
if (level == null) {
return null; // depends on control dependency: [if], data = [none]
}
return level.toString(); // depends on control dependency: [if], data = [none]
}
} catch (RuntimeException e) {
logger.warn("Exception getting effective logger level " + loggerName, e);
throw e;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public void removeByG_S(long groupId, int status) {
for (CPDefinition cpDefinition : findByG_S(groupId, status,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(cpDefinition);
}
} } | public class class_name {
@Override
public void removeByG_S(long groupId, int status) {
for (CPDefinition cpDefinition : findByG_S(groupId, status,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(cpDefinition); // depends on control dependency: [for], data = [cpDefinition]
}
} } |
public class class_name {
@Override
public void _randomOrdering(String seed) {
assertNoRawQuery();
if (StringUtils.isBlank(seed)) {
_randomOrdering();
return;
}
_noCaching();
orderByTokens.add(OrderByToken.createRandom(seed));
} } | public class class_name {
@Override
public void _randomOrdering(String seed) {
assertNoRawQuery();
if (StringUtils.isBlank(seed)) {
_randomOrdering(); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
_noCaching();
orderByTokens.add(OrderByToken.createRandom(seed));
} } |
public class class_name {
private String getValueWithDefault(String value, String manifestKey) {
if (StringUtils.isEmpty(value) && manifest != null) {
value = manifest.getMainAttributes().getValue(manifestKey);
}
return value;
} } | public class class_name {
private String getValueWithDefault(String value, String manifestKey) {
if (StringUtils.isEmpty(value) && manifest != null) {
value = manifest.getMainAttributes().getValue(manifestKey); // depends on control dependency: [if], data = [none]
}
return value;
} } |
public class class_name {
public void marshall(UpdateSmsChannelRequest updateSmsChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (updateSmsChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateSmsChannelRequest.getApplicationId(), APPLICATIONID_BINDING);
protocolMarshaller.marshall(updateSmsChannelRequest.getSMSChannelRequest(), SMSCHANNELREQUEST_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(UpdateSmsChannelRequest updateSmsChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (updateSmsChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateSmsChannelRequest.getApplicationId(), APPLICATIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(updateSmsChannelRequest.getSMSChannelRequest(), SMSCHANNELREQUEST_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 boolean removeChild(final AbstractHtml child) {
boolean listenerInvoked = false;
final Lock lock = sharedObject.getLock(ACCESS_OBJECT).writeLock();
boolean removed = false;
try {
lock.lock();
removed = children.remove(child);
if (removed) {
// making child.parent = null inside the below method.
initNewSharedObjectInAllNestedTagsAndSetSuperParentNull(child);
final ChildTagRemoveListener listener = sharedObject
.getChildTagRemoveListener(ACCESS_OBJECT);
if (listener != null) {
listener.childRemoved(
new ChildTagRemoveListener.Event(this, child));
listenerInvoked = true;
}
}
} finally {
lock.unlock();
}
if (listenerInvoked) {
final PushQueue pushQueue = sharedObject
.getPushQueue(ACCESS_OBJECT);
if (pushQueue != null) {
pushQueue.push();
}
}
return removed;
} } | public class class_name {
public boolean removeChild(final AbstractHtml child) {
boolean listenerInvoked = false;
final Lock lock = sharedObject.getLock(ACCESS_OBJECT).writeLock();
boolean removed = false;
try {
lock.lock(); // depends on control dependency: [try], data = [none]
removed = children.remove(child); // depends on control dependency: [try], data = [none]
if (removed) {
// making child.parent = null inside the below method.
initNewSharedObjectInAllNestedTagsAndSetSuperParentNull(child); // depends on control dependency: [if], data = [none]
final ChildTagRemoveListener listener = sharedObject
.getChildTagRemoveListener(ACCESS_OBJECT);
if (listener != null) {
listener.childRemoved(
new ChildTagRemoveListener.Event(this, child)); // depends on control dependency: [if], data = [none]
listenerInvoked = true; // depends on control dependency: [if], data = [none]
}
}
} finally {
lock.unlock();
}
if (listenerInvoked) {
final PushQueue pushQueue = sharedObject
.getPushQueue(ACCESS_OBJECT);
if (pushQueue != null) {
pushQueue.push(); // depends on control dependency: [if], data = [none]
}
}
return removed;
} } |
public class class_name {
public String generate(final int bad) {
int[] sizes = new int[nodes.size()];
for (int i = 0; i < sizes.length; i++) {
Range r = nodes.get(i).getRange();
sizes[i] = r.getMin() + r.getRange() / 2;
}
return generate(sizes, bad);
} } | public class class_name {
public String generate(final int bad) {
int[] sizes = new int[nodes.size()];
for (int i = 0; i < sizes.length; i++) {
Range r = nodes.get(i).getRange();
sizes[i] = r.getMin() + r.getRange() / 2;
// depends on control dependency: [for], data = [i]
}
return generate(sizes, bad);
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.