code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
static Jar create(PathImpl backing)
{
if (_jarCache == null) {
int size = 256;
Integer iSize = _jarSize.get();
if (iSize != null)
size = iSize.intValue();
_jarCache = new LruCache<PathImpl,Jar>(size);
}
Jar jar = _jarCache.get(backing);
if (jar != null) {
jar.updateBacking();
}
else if (backing.getScheme().equals("file")) {
jar = new JarWithFile(backing);
jar = _jarCache.putIfNew(backing, jar);
}
else {
jar = new JarWithStream(backing);
jar = _jarCache.putIfNew(backing, jar);
}
return jar;
} } | public class class_name {
static Jar create(PathImpl backing)
{
if (_jarCache == null) {
int size = 256;
Integer iSize = _jarSize.get();
if (iSize != null)
size = iSize.intValue();
_jarCache = new LruCache<PathImpl,Jar>(size); // depends on control dependency: [if], data = [none]
}
Jar jar = _jarCache.get(backing);
if (jar != null) {
jar.updateBacking(); // depends on control dependency: [if], data = [none]
}
else if (backing.getScheme().equals("file")) {
jar = new JarWithFile(backing); // depends on control dependency: [if], data = [none]
jar = _jarCache.putIfNew(backing, jar); // depends on control dependency: [if], data = [none]
}
else {
jar = new JarWithStream(backing); // depends on control dependency: [if], data = [none]
jar = _jarCache.putIfNew(backing, jar); // depends on control dependency: [if], data = [none]
}
return jar;
} } |
public class class_name {
protected void logVarstat(DoubleStatistic varstat, double[] varsum) {
if(varstat != null) {
double s = sum(varsum);
getLogger().statistics(varstat.setDouble(s));
}
} } | public class class_name {
protected void logVarstat(DoubleStatistic varstat, double[] varsum) {
if(varstat != null) {
double s = sum(varsum);
getLogger().statistics(varstat.setDouble(s)); // depends on control dependency: [if], data = [(varstat]
}
} } |
public class class_name {
private static <T> ParTask<T> vapar(final Task<?>... tasks) {
final List<Task<T>> taskList = new ArrayList<Task<T>>(tasks.length);
for (Task<?> task : tasks) {
@SuppressWarnings("unchecked")
final Task<T> typedTask = (Task<T>) task;
taskList.add(typedTask);
}
return par(taskList);
} } | public class class_name {
private static <T> ParTask<T> vapar(final Task<?>... tasks) {
final List<Task<T>> taskList = new ArrayList<Task<T>>(tasks.length);
for (Task<?> task : tasks) {
@SuppressWarnings("unchecked")
final Task<T> typedTask = (Task<T>) task;
taskList.add(typedTask); // depends on control dependency: [for], data = [task]
}
return par(taskList);
} } |
public class class_name {
public boolean isOutputOrdered (List<AbstractExpression> sortExpressions, List<SortDirectionType> sortDirections) {
assert(sortExpressions.size() == sortDirections.size());
if (m_children.size() == 1) {
return m_children.get(0).isOutputOrdered(sortExpressions, sortDirections);
}
return false;
} } | public class class_name {
public boolean isOutputOrdered (List<AbstractExpression> sortExpressions, List<SortDirectionType> sortDirections) {
assert(sortExpressions.size() == sortDirections.size());
if (m_children.size() == 1) {
return m_children.get(0).isOutputOrdered(sortExpressions, sortDirections); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Override
public CommerceAccountOrganizationRel fetchByPrimaryKey(
Serializable primaryKey) {
Serializable serializable = entityCache.getResult(CommerceAccountOrganizationRelModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountOrganizationRelImpl.class, primaryKey);
if (serializable == nullModel) {
return null;
}
CommerceAccountOrganizationRel commerceAccountOrganizationRel = (CommerceAccountOrganizationRel)serializable;
if (commerceAccountOrganizationRel == null) {
Session session = null;
try {
session = openSession();
commerceAccountOrganizationRel = (CommerceAccountOrganizationRel)session.get(CommerceAccountOrganizationRelImpl.class,
primaryKey);
if (commerceAccountOrganizationRel != null) {
cacheResult(commerceAccountOrganizationRel);
}
else {
entityCache.putResult(CommerceAccountOrganizationRelModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountOrganizationRelImpl.class, primaryKey,
nullModel);
}
}
catch (Exception e) {
entityCache.removeResult(CommerceAccountOrganizationRelModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountOrganizationRelImpl.class, primaryKey);
throw processException(e);
}
finally {
closeSession(session);
}
}
return commerceAccountOrganizationRel;
} } | public class class_name {
@Override
public CommerceAccountOrganizationRel fetchByPrimaryKey(
Serializable primaryKey) {
Serializable serializable = entityCache.getResult(CommerceAccountOrganizationRelModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountOrganizationRelImpl.class, primaryKey);
if (serializable == nullModel) {
return null; // depends on control dependency: [if], data = [none]
}
CommerceAccountOrganizationRel commerceAccountOrganizationRel = (CommerceAccountOrganizationRel)serializable;
if (commerceAccountOrganizationRel == null) {
Session session = null;
try {
session = openSession(); // depends on control dependency: [try], data = [none]
commerceAccountOrganizationRel = (CommerceAccountOrganizationRel)session.get(CommerceAccountOrganizationRelImpl.class,
primaryKey); // depends on control dependency: [try], data = [none]
if (commerceAccountOrganizationRel != null) {
cacheResult(commerceAccountOrganizationRel); // depends on control dependency: [if], data = [(commerceAccountOrganizationRel]
}
else {
entityCache.putResult(CommerceAccountOrganizationRelModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountOrganizationRelImpl.class, primaryKey,
nullModel); // depends on control dependency: [if], data = [none]
}
}
catch (Exception e) {
entityCache.removeResult(CommerceAccountOrganizationRelModelImpl.ENTITY_CACHE_ENABLED,
CommerceAccountOrganizationRelImpl.class, primaryKey);
throw processException(e);
} // depends on control dependency: [catch], data = [none]
finally {
closeSession(session);
}
}
return commerceAccountOrganizationRel;
} } |
public class class_name {
public static void runExample(
AdManagerServices adManagerServices, AdManagerSession session, long labelId)
throws RemoteException {
// Get the LabelService.
LabelServiceInterface labelService =
adManagerServices.get(session, LabelServiceInterface.class);
// Create a statement to select a label.
StatementBuilder statementBuilder =
new StatementBuilder()
.where("WHERE id = :id")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("id", labelId);
// Default for total result set size.
int totalResultSetSize = 0;
do {
// Get labels by statement.
LabelPage page = labelService.getLabelsByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (Label label : page.getResults()) {
System.out.printf("%d) Label with ID %d will be deactivated.%n", i++, label.getId());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of labels to be deactivated: %d%n", totalResultSetSize);
if (totalResultSetSize > 0) {
// Remove limit and offset from statement.
statementBuilder.removeLimitAndOffset();
// Create action.
com.google.api.ads.admanager.axis.v201811.DeactivateLabels action =
new com.google.api.ads.admanager.axis.v201811.DeactivateLabels();
// Perform action.
UpdateResult result = labelService.performLabelAction(action, statementBuilder.toStatement());
if (result != null && result.getNumChanges() > 0) {
System.out.printf("Number of labels deactivated: %d%n", result.getNumChanges());
} else {
System.out.println("No labels were deactivated.");
}
}
} } | public class class_name {
public static void runExample(
AdManagerServices adManagerServices, AdManagerSession session, long labelId)
throws RemoteException {
// Get the LabelService.
LabelServiceInterface labelService =
adManagerServices.get(session, LabelServiceInterface.class);
// Create a statement to select a label.
StatementBuilder statementBuilder =
new StatementBuilder()
.where("WHERE id = :id")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("id", labelId);
// Default for total result set size.
int totalResultSetSize = 0;
do {
// Get labels by statement.
LabelPage page = labelService.getLabelsByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
totalResultSetSize = page.getTotalResultSetSize(); // depends on control dependency: [if], data = [none]
int i = page.getStartIndex();
for (Label label : page.getResults()) {
System.out.printf("%d) Label with ID %d will be deactivated.%n", i++, label.getId()); // depends on control dependency: [for], data = [none] // depends on control dependency: [for], data = [none] // depends on control dependency: [for], data = [label]
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of labels to be deactivated: %d%n", totalResultSetSize);
if (totalResultSetSize > 0) {
// Remove limit and offset from statement.
statementBuilder.removeLimitAndOffset();
// Create action.
com.google.api.ads.admanager.axis.v201811.DeactivateLabels action =
new com.google.api.ads.admanager.axis.v201811.DeactivateLabels();
// Perform action.
UpdateResult result = labelService.performLabelAction(action, statementBuilder.toStatement());
if (result != null && result.getNumChanges() > 0) {
System.out.printf("Number of labels deactivated: %d%n", result.getNumChanges());
} else {
System.out.println("No labels were deactivated.");
}
}
} } |
public class class_name {
public CloseableHttpClient getHttpClient() {
CloseableHttpClient result = httpClient;
if (result == null) {
synchronized (DocumentLoader.class) {
result = httpClient;
if (result == null) {
result = httpClient = JsonUtils.getDefaultHttpClient();
}
}
}
return result;
} } | public class class_name {
public CloseableHttpClient getHttpClient() {
CloseableHttpClient result = httpClient;
if (result == null) {
synchronized (DocumentLoader.class) { // depends on control dependency: [if], data = [none]
result = httpClient;
if (result == null) {
result = httpClient = JsonUtils.getDefaultHttpClient(); // depends on control dependency: [if], data = [none]
}
}
}
return result;
} } |
public class class_name {
@Override
protected void deltaStartWorkAccepted()
{
if (trace)
log.trace("deltaStartWorkAccepted");
super.deltaStartWorkAccepted();
if (distributedStatisticsEnabled && distributedStatistics != null && transport != null)
{
try
{
checkTransport();
distributedStatistics.sendDeltaStartWorkAccepted();
}
catch (WorkException we)
{
log.debugf("deltaStartWorkAccepted: %s", we.getMessage(), we);
}
}
} } | public class class_name {
@Override
protected void deltaStartWorkAccepted()
{
if (trace)
log.trace("deltaStartWorkAccepted");
super.deltaStartWorkAccepted();
if (distributedStatisticsEnabled && distributedStatistics != null && transport != null)
{
try
{
checkTransport(); // depends on control dependency: [try], data = [none]
distributedStatistics.sendDeltaStartWorkAccepted(); // depends on control dependency: [try], data = [none]
}
catch (WorkException we)
{
log.debugf("deltaStartWorkAccepted: %s", we.getMessage(), we);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public static InterceptorClassDescription merge(InterceptorClassDescription existing, InterceptorClassDescription override) {
if (existing == null && override == null) {
return EMPTY_INSTANCE;
}
if (override == null) {
return existing;
}
if (existing == null) {
return override;
}
final Builder builder = builder(existing);
if (override.getAroundInvoke() != null) {
builder.setAroundInvoke(override.getAroundInvoke());
}
if (override.getAroundTimeout() != null) {
builder.setAroundTimeout(override.getAroundTimeout());
}
if (override.getAroundConstruct() != null) {
builder.setAroundConstruct(override.getAroundConstruct());
}
if (override.getPostConstruct() != null) {
builder.setPostConstruct(override.getPostConstruct());
}
if (override.getPreDestroy() != null) {
builder.setPreDestroy(override.getPreDestroy());
}
if (override.getPrePassivate() != null) {
builder.setPrePassivate(override.getPrePassivate());
}
if (override.getPostActivate() != null) {
builder.setPostActivate(override.getPostActivate());
}
return builder.build();
} } | public class class_name {
public static InterceptorClassDescription merge(InterceptorClassDescription existing, InterceptorClassDescription override) {
if (existing == null && override == null) {
return EMPTY_INSTANCE; // depends on control dependency: [if], data = [none]
}
if (override == null) {
return existing; // depends on control dependency: [if], data = [none]
}
if (existing == null) {
return override; // depends on control dependency: [if], data = [none]
}
final Builder builder = builder(existing);
if (override.getAroundInvoke() != null) {
builder.setAroundInvoke(override.getAroundInvoke()); // depends on control dependency: [if], data = [(override.getAroundInvoke()]
}
if (override.getAroundTimeout() != null) {
builder.setAroundTimeout(override.getAroundTimeout()); // depends on control dependency: [if], data = [(override.getAroundTimeout()]
}
if (override.getAroundConstruct() != null) {
builder.setAroundConstruct(override.getAroundConstruct()); // depends on control dependency: [if], data = [(override.getAroundConstruct()]
}
if (override.getPostConstruct() != null) {
builder.setPostConstruct(override.getPostConstruct()); // depends on control dependency: [if], data = [(override.getPostConstruct()]
}
if (override.getPreDestroy() != null) {
builder.setPreDestroy(override.getPreDestroy()); // depends on control dependency: [if], data = [(override.getPreDestroy()]
}
if (override.getPrePassivate() != null) {
builder.setPrePassivate(override.getPrePassivate()); // depends on control dependency: [if], data = [(override.getPrePassivate()]
}
if (override.getPostActivate() != null) {
builder.setPostActivate(override.getPostActivate()); // depends on control dependency: [if], data = [(override.getPostActivate()]
}
return builder.build();
} } |
public class class_name {
public Observable<ServiceResponse<List<SimilarFace>>> findSimilarWithServiceResponseAsync(UUID faceId, String faceListId, List<UUID> faceIds, Integer maxNumOfCandidatesReturned, FindSimilarMatchMode mode) {
if (this.client.azureRegion() == null) {
throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null.");
}
if (faceId == null) {
throw new IllegalArgumentException("Parameter faceId is required and cannot be null.");
}
Validator.validate(faceIds);
FindSimilarRequest bodyParameter = new FindSimilarRequest();
bodyParameter.withFaceId(faceId);
bodyParameter.withFaceListId(faceListId);
bodyParameter.withFaceIds(faceIds);
bodyParameter.withMaxNumOfCandidatesReturned(maxNumOfCandidatesReturned);
bodyParameter.withMode(mode);
String parameterizedHost = Joiner.on(", ").join("{AzureRegion}", this.client.azureRegion());
return service.findSimilar(this.client.acceptLanguage(), bodyParameter, parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<SimilarFace>>>>() {
@Override
public Observable<ServiceResponse<List<SimilarFace>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<SimilarFace>> clientResponse = findSimilarDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<List<SimilarFace>>> findSimilarWithServiceResponseAsync(UUID faceId, String faceListId, List<UUID> faceIds, Integer maxNumOfCandidatesReturned, FindSimilarMatchMode mode) {
if (this.client.azureRegion() == null) {
throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null.");
}
if (faceId == null) {
throw new IllegalArgumentException("Parameter faceId is required and cannot be null.");
}
Validator.validate(faceIds);
FindSimilarRequest bodyParameter = new FindSimilarRequest();
bodyParameter.withFaceId(faceId);
bodyParameter.withFaceListId(faceListId);
bodyParameter.withFaceIds(faceIds);
bodyParameter.withMaxNumOfCandidatesReturned(maxNumOfCandidatesReturned);
bodyParameter.withMode(mode);
String parameterizedHost = Joiner.on(", ").join("{AzureRegion}", this.client.azureRegion());
return service.findSimilar(this.client.acceptLanguage(), bodyParameter, parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<SimilarFace>>>>() {
@Override
public Observable<ServiceResponse<List<SimilarFace>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<SimilarFace>> clientResponse = findSimilarDelegate(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 {
private void configureFlowLevelMetrics(final FlowRunner flowRunner) {
logger.info("Configuring Azkaban metrics tracking for flow runner object");
if (MetricReportManager.isAvailable()) {
final MetricReportManager metricManager = MetricReportManager.getInstance();
// Adding NumFailedFlow Metric listener
flowRunner.addListener((NumFailedFlowMetric) metricManager
.getMetricFromName(NumFailedFlowMetric.NUM_FAILED_FLOW_METRIC_NAME));
}
} } | public class class_name {
private void configureFlowLevelMetrics(final FlowRunner flowRunner) {
logger.info("Configuring Azkaban metrics tracking for flow runner object");
if (MetricReportManager.isAvailable()) {
final MetricReportManager metricManager = MetricReportManager.getInstance();
// Adding NumFailedFlow Metric listener
flowRunner.addListener((NumFailedFlowMetric) metricManager
.getMetricFromName(NumFailedFlowMetric.NUM_FAILED_FLOW_METRIC_NAME)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
List<Object> alignResults(List<QueryResult> results, String epoch) {
Object[] alignedResults = new Object[results.size() + 1];
List<String> headerList = Arrays.asList(header);
alignedResults[0] = epoch;
for (QueryResult result : results) {
alignedResults[headerList.indexOf(result.getName())] = result.getValue();
}
return Arrays.asList(alignedResults);
} } | public class class_name {
List<Object> alignResults(List<QueryResult> results, String epoch) {
Object[] alignedResults = new Object[results.size() + 1];
List<String> headerList = Arrays.asList(header);
alignedResults[0] = epoch;
for (QueryResult result : results) {
alignedResults[headerList.indexOf(result.getName())] = result.getValue(); // depends on control dependency: [for], data = [result]
}
return Arrays.asList(alignedResults);
} } |
public class class_name {
public <T> T fromJson(@Nullable String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
} } | public class class_name {
public <T> T fromJson(@Nullable String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString)) {
return null; // depends on control dependency: [if], data = [none]
}
try {
return mapper.readValue(jsonString, clazz); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <V extends Value> ValueList<V> getInstance(V... value) {
ValueList<V> result = new ValueList<>(value.length);
for (V val : value) {
result.add(val);
}
return result;
} } | public class class_name {
public static <V extends Value> ValueList<V> getInstance(V... value) {
ValueList<V> result = new ValueList<>(value.length);
for (V val : value) {
result.add(val); // depends on control dependency: [for], data = [val]
}
return result;
} } |
public class class_name {
@SneakyThrows(IOException.class)
public static String decompressFromBase64(final String base64CompressedString) {
Exceptions.checkNotNullOrEmpty(base64CompressedString, "base64CompressedString");
try {
@Cleanup
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64CompressedString.getBytes(UTF_8));
@Cleanup
final InputStream base64InputStream = Base64.getDecoder().wrap(byteArrayInputStream);
@Cleanup
final GZIPInputStream gzipInputStream = new GZIPInputStream(base64InputStream);
return IOUtils.toString(gzipInputStream, UTF_8);
} catch (ZipException | EOFException e) { // exceptions thrown for invalid encoding and partial data.
throw new IllegalArgumentException("Invalid base64 input.", e);
}
} } | public class class_name {
@SneakyThrows(IOException.class)
public static String decompressFromBase64(final String base64CompressedString) {
Exceptions.checkNotNullOrEmpty(base64CompressedString, "base64CompressedString");
try {
@Cleanup
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64CompressedString.getBytes(UTF_8));
@Cleanup
final InputStream base64InputStream = Base64.getDecoder().wrap(byteArrayInputStream);
@Cleanup
final GZIPInputStream gzipInputStream = new GZIPInputStream(base64InputStream);
return IOUtils.toString(gzipInputStream, UTF_8); // depends on control dependency: [try], data = [none]
} catch (ZipException | EOFException e) { // exceptions thrown for invalid encoding and partial data.
throw new IllegalArgumentException("Invalid base64 input.", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public boolean isReadonlyDisplay(final TargetMode _mode)
{
boolean ret = false;
if (this.mode2display.containsKey(_mode)) {
ret = this.mode2display.get(_mode).equals(Field.Display.READONLY);
} else if (_mode.equals(TargetMode.CONNECT) || _mode.equals(TargetMode.VIEW)
|| _mode.equals(TargetMode.EDIT) || _mode.equals(TargetMode.PRINT)) {
ret = true;
}
return ret;
} } | public class class_name {
public boolean isReadonlyDisplay(final TargetMode _mode)
{
boolean ret = false;
if (this.mode2display.containsKey(_mode)) {
ret = this.mode2display.get(_mode).equals(Field.Display.READONLY); // depends on control dependency: [if], data = [none]
} else if (_mode.equals(TargetMode.CONNECT) || _mode.equals(TargetMode.VIEW)
|| _mode.equals(TargetMode.EDIT) || _mode.equals(TargetMode.PRINT)) {
ret = true; // depends on control dependency: [if], data = [none]
}
return ret;
} } |
public class class_name {
public CmsContainerPageBean readModelGroups(CmsContainerPageBean page) {
List<CmsContainerBean> resultContainers = new ArrayList<CmsContainerBean>();
for (CmsContainerBean container : page.getContainers().values()) {
boolean hasModels = false;
List<CmsContainerElementBean> elements = new ArrayList<CmsContainerElementBean>();
for (CmsContainerElementBean element : container.getElements()) {
try {
element.initResource(m_cms);
if (isModelGroupResource(element.getResource())) {
hasModels = true;
CmsContainerPageBean modelGroupPage = getContainerPageBean(element.getResource());
CmsContainerElementBean baseElement = getModelBaseElement(
modelGroupPage,
element.getResource());
if (baseElement == null) {
LOG.error(
"Error rendering model group '"
+ element.getResource().getRootPath()
+ "', base element could not be determind.");
continue;
}
String baseInstanceId = baseElement.getInstanceId();
CmsContainerElementBean replaceElement = getModelReplacementElement(
element,
baseElement,
false);
if (m_sessionCache != null) {
m_sessionCache.setCacheContainerElement(replaceElement.editorHash(), replaceElement);
}
elements.add(replaceElement);
resultContainers.addAll(
readModelContainers(
baseInstanceId,
element.getInstanceId(),
modelGroupPage,
baseElement.isCopyModel()));
} else {
elements.add(element);
}
} catch (CmsException e) {
LOG.info(e.getLocalizedMessage(), e);
}
}
if (hasModels) {
resultContainers.add(
new CmsContainerBean(
container.getName(),
container.getType(),
container.getParentInstanceId(),
container.isRootContainer(),
container.getMaxElements(),
elements));
} else {
resultContainers.add(container);
}
}
return new CmsContainerPageBean(resultContainers);
} } | public class class_name {
public CmsContainerPageBean readModelGroups(CmsContainerPageBean page) {
List<CmsContainerBean> resultContainers = new ArrayList<CmsContainerBean>();
for (CmsContainerBean container : page.getContainers().values()) {
boolean hasModels = false;
List<CmsContainerElementBean> elements = new ArrayList<CmsContainerElementBean>();
for (CmsContainerElementBean element : container.getElements()) {
try {
element.initResource(m_cms); // depends on control dependency: [try], data = [none]
if (isModelGroupResource(element.getResource())) {
hasModels = true; // depends on control dependency: [if], data = [none]
CmsContainerPageBean modelGroupPage = getContainerPageBean(element.getResource());
CmsContainerElementBean baseElement = getModelBaseElement(
modelGroupPage,
element.getResource());
if (baseElement == null) {
LOG.error(
"Error rendering model group '"
+ element.getResource().getRootPath()
+ "', base element could not be determind."); // depends on control dependency: [if], data = [none]
continue;
}
String baseInstanceId = baseElement.getInstanceId();
CmsContainerElementBean replaceElement = getModelReplacementElement(
element,
baseElement,
false);
if (m_sessionCache != null) {
m_sessionCache.setCacheContainerElement(replaceElement.editorHash(), replaceElement); // depends on control dependency: [if], data = [none]
}
elements.add(replaceElement); // depends on control dependency: [if], data = [none]
resultContainers.addAll(
readModelContainers(
baseInstanceId,
element.getInstanceId(),
modelGroupPage,
baseElement.isCopyModel())); // depends on control dependency: [if], data = [none]
} else {
elements.add(element); // depends on control dependency: [if], data = [none]
}
} catch (CmsException e) {
LOG.info(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
if (hasModels) {
resultContainers.add(
new CmsContainerBean(
container.getName(),
container.getType(),
container.getParentInstanceId(),
container.isRootContainer(),
container.getMaxElements(),
elements)); // depends on control dependency: [if], data = [none]
} else {
resultContainers.add(container); // depends on control dependency: [if], data = [none]
}
}
return new CmsContainerPageBean(resultContainers);
} } |
public class class_name {
public boolean checkedRemove(final int x) {
final short hb = Util.highbits(x);
final int i = highLowContainer.getIndex(hb);
if (i < 0) {
return false;
}
Container C = highLowContainer.getContainerAtIndex(i);
int oldcard = C.getCardinality();
C.remove(Util.lowbits(x));
int newcard = C.getCardinality();
if (newcard == oldcard) {
return false;
}
if (newcard > 0) {
highLowContainer.setContainerAtIndex(i, C);
} else {
highLowContainer.removeAtIndex(i);
}
return true;
} } | public class class_name {
public boolean checkedRemove(final int x) {
final short hb = Util.highbits(x);
final int i = highLowContainer.getIndex(hb);
if (i < 0) {
return false; // depends on control dependency: [if], data = [none]
}
Container C = highLowContainer.getContainerAtIndex(i);
int oldcard = C.getCardinality();
C.remove(Util.lowbits(x));
int newcard = C.getCardinality();
if (newcard == oldcard) {
return false; // depends on control dependency: [if], data = [none]
}
if (newcard > 0) {
highLowContainer.setContainerAtIndex(i, C); // depends on control dependency: [if], data = [none]
} else {
highLowContainer.removeAtIndex(i); // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public static String getString(String key, String valueIfNull) {
String value = System.getProperty(key);
if (Strings.isNullOrEmpty(value)) {
return valueIfNull;
}
return value;
} } | public class class_name {
public static String getString(String key, String valueIfNull) {
String value = System.getProperty(key);
if (Strings.isNullOrEmpty(value)) {
return valueIfNull; // depends on control dependency: [if], data = [none]
}
return value;
} } |
public class class_name {
public static void enc(char[] in, int start, int length, StringBuffer out) {
for (int i = start; i < length + start; i++) {
enc(in[i], out);
}
} } | public class class_name {
public static void enc(char[] in, int start, int length, StringBuffer out) {
for (int i = start; i < length + start; i++) {
enc(in[i], out); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
public static TreePath getPath(TreePath path, Tree target) {
path.getClass();
target.getClass();
class Result extends Error {
static final long serialVersionUID = -5942088234594905625L;
TreePath path;
Result(TreePath path) {
this.path = path;
}
}
class PathFinder extends TreePathScanner<TreePath,Tree> {
public TreePath scan(Tree tree, Tree target) {
if (tree == target) {
throw new Result(new TreePath(getCurrentPath(), target));
}
return super.scan(tree, target);
}
}
if (path.getLeaf() == target) {
return path;
}
try {
new PathFinder().scan(path, target);
} catch (Result result) {
return result.path;
}
return null;
} } | public class class_name {
public static TreePath getPath(TreePath path, Tree target) {
path.getClass();
target.getClass();
class Result extends Error {
static final long serialVersionUID = -5942088234594905625L;
TreePath path;
Result(TreePath path) {
this.path = path;
}
}
class PathFinder extends TreePathScanner<TreePath,Tree> {
public TreePath scan(Tree tree, Tree target) {
if (tree == target) {
throw new Result(new TreePath(getCurrentPath(), target));
}
return super.scan(tree, target);
}
}
if (path.getLeaf() == target) {
return path; // depends on control dependency: [if], data = [none]
}
try {
new PathFinder().scan(path, target); // depends on control dependency: [try], data = [none]
} catch (Result result) {
return result.path;
} // depends on control dependency: [catch], data = [none]
return null;
} } |
public class class_name {
public EClass getIfcRegularTimeSeries() {
if (ifcRegularTimeSeriesEClass == null) {
ifcRegularTimeSeriesEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(431);
}
return ifcRegularTimeSeriesEClass;
} } | public class class_name {
public EClass getIfcRegularTimeSeries() {
if (ifcRegularTimeSeriesEClass == null) {
ifcRegularTimeSeriesEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(431);
// depends on control dependency: [if], data = [none]
}
return ifcRegularTimeSeriesEClass;
} } |
public class class_name {
public static <T> ElementDescriptor<T> register(QualifiedName qname, IObjectBuilder<T> builder, XmlContext context)
{
if (context == null)
{
context = DEFAULT_CONTEXT;
}
synchronized (context)
{
Map<QualifiedName, ElementDescriptor<?>> descriptorMap = context.DESCRIPTOR_MAP;
if (descriptorMap.containsKey(qname))
{
throw new IllegalStateException("descriptor for " + qname + " already exists, use 'overload' to override the definition");
}
ElementDescriptor<T> descriptor = new ElementDescriptor<T>(qname, builder, context);
descriptorMap.put(qname, descriptor);
return descriptor;
}
} } | public class class_name {
public static <T> ElementDescriptor<T> register(QualifiedName qname, IObjectBuilder<T> builder, XmlContext context)
{
if (context == null)
{
context = DEFAULT_CONTEXT; // depends on control dependency: [if], data = [none]
}
synchronized (context)
{
Map<QualifiedName, ElementDescriptor<?>> descriptorMap = context.DESCRIPTOR_MAP;
if (descriptorMap.containsKey(qname))
{
throw new IllegalStateException("descriptor for " + qname + " already exists, use 'overload' to override the definition");
}
ElementDescriptor<T> descriptor = new ElementDescriptor<T>(qname, builder, context);
descriptorMap.put(qname, descriptor);
return descriptor;
}
} } |
public class class_name {
public void setElementView(String elementView) {
m_elementView = elementView;
if (LOG.isDebugEnabled()) {
LOG.debug("Setting element view to " + elementView);
}
} } | public class class_name {
public void setElementView(String elementView) {
m_elementView = elementView;
if (LOG.isDebugEnabled()) {
LOG.debug("Setting element view to " + elementView); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@VisibleForTesting
static byte[] ascii8To6bitBin(byte[] toDecBytes) {
byte[] convertedBytes = new byte[toDecBytes.length];
int sum = 0;
int _6bitBin = 0;
for (int i = 0; i < toDecBytes.length; i++) {
sum = 0;
_6bitBin = 0;
if (toDecBytes[i] < 48) {
throw new AisParseException(AisParseException.INVALID_CHARACTER + " "
+ (char) toDecBytes[i]);
} else {
if (toDecBytes[i] > 119) {
throw new AisParseException(AisParseException.INVALID_CHARACTER + " "
+ (char) toDecBytes[i]);
} else {
if (toDecBytes[i] > 87) {
if (toDecBytes[i] < 96) {
throw new AisParseException(AisParseException.INVALID_CHARACTER + " "
+ (char) toDecBytes[i]);
} else {
sum = toDecBytes[i] + 40;
}
} else {
sum = toDecBytes[i] + 40;
}
if (sum != 0) {
if (sum > 128) {
sum += 32;
} else {
sum += 40;
}
_6bitBin = sum & 0x3F;
convertedBytes[i] = (byte) _6bitBin;
}
}
}
}
return convertedBytes;
} } | public class class_name {
@VisibleForTesting
static byte[] ascii8To6bitBin(byte[] toDecBytes) {
byte[] convertedBytes = new byte[toDecBytes.length];
int sum = 0;
int _6bitBin = 0;
for (int i = 0; i < toDecBytes.length; i++) {
sum = 0; // depends on control dependency: [for], data = [none]
_6bitBin = 0; // depends on control dependency: [for], data = [none]
if (toDecBytes[i] < 48) {
throw new AisParseException(AisParseException.INVALID_CHARACTER + " "
+ (char) toDecBytes[i]);
} else {
if (toDecBytes[i] > 119) {
throw new AisParseException(AisParseException.INVALID_CHARACTER + " "
+ (char) toDecBytes[i]);
} else {
if (toDecBytes[i] > 87) {
if (toDecBytes[i] < 96) {
throw new AisParseException(AisParseException.INVALID_CHARACTER + " "
+ (char) toDecBytes[i]);
} else {
sum = toDecBytes[i] + 40; // depends on control dependency: [if], data = [none]
}
} else {
sum = toDecBytes[i] + 40; // depends on control dependency: [if], data = [none]
}
if (sum != 0) {
if (sum > 128) {
sum += 32; // depends on control dependency: [if], data = [none]
} else {
sum += 40; // depends on control dependency: [if], data = [none]
}
_6bitBin = sum & 0x3F; // depends on control dependency: [if], data = [none]
convertedBytes[i] = (byte) _6bitBin; // depends on control dependency: [if], data = [none]
}
}
}
}
return convertedBytes;
} } |
public class class_name {
public void process(Clustering<?> result1, Clustering<?> result2) {
// Get the clusters
final List<? extends Cluster<?>> cs1 = result1.getAllClusters();
final List<? extends Cluster<?>> cs2 = result2.getAllClusters();
// Initialize
size1 = cs1.size();
size2 = cs2.size();
contingency = new int[size1 + 2][size2 + 2];
noise1 = BitsUtil.zero(size1);
noise2 = BitsUtil.zero(size2);
// Fill main part of matrix
{
final Iterator<? extends Cluster<?>> it2 = cs2.iterator();
for(int i2 = 0; it2.hasNext(); i2++) {
final Cluster<?> c2 = it2.next();
if(c2.isNoise()) {
BitsUtil.setI(noise2, i2);
}
contingency[size1 + 1][i2] = c2.size();
contingency[size1 + 1][size2] += c2.size();
}
}
final Iterator<? extends Cluster<?>> it1 = cs1.iterator();
for(int i1 = 0; it1.hasNext(); i1++) {
final Cluster<?> c1 = it1.next();
if(c1.isNoise()) {
BitsUtil.setI(noise1, i1);
}
final DBIDs ids = DBIDUtil.ensureSet(c1.getIDs());
contingency[i1][size2 + 1] = c1.size();
contingency[size1][size2 + 1] += c1.size();
final Iterator<? extends Cluster<?>> it2 = cs2.iterator();
for(int i2 = 0; it2.hasNext(); i2++) {
final Cluster<?> c2 = it2.next();
int count = DBIDUtil.intersectionSize(ids, c2.getIDs());
contingency[i1][i2] = count;
contingency[i1][size2] += count;
contingency[size1][i2] += count;
contingency[size1][size2] += count;
}
}
} } | public class class_name {
public void process(Clustering<?> result1, Clustering<?> result2) {
// Get the clusters
final List<? extends Cluster<?>> cs1 = result1.getAllClusters();
final List<? extends Cluster<?>> cs2 = result2.getAllClusters();
// Initialize
size1 = cs1.size();
size2 = cs2.size();
contingency = new int[size1 + 2][size2 + 2];
noise1 = BitsUtil.zero(size1);
noise2 = BitsUtil.zero(size2);
// Fill main part of matrix
{
final Iterator<? extends Cluster<?>> it2 = cs2.iterator();
for(int i2 = 0; it2.hasNext(); i2++) {
final Cluster<?> c2 = it2.next();
if(c2.isNoise()) {
BitsUtil.setI(noise2, i2); // depends on control dependency: [if], data = [none]
}
contingency[size1 + 1][i2] = c2.size(); // depends on control dependency: [for], data = [i2]
contingency[size1 + 1][size2] += c2.size(); // depends on control dependency: [for], data = [none]
}
}
final Iterator<? extends Cluster<?>> it1 = cs1.iterator();
for(int i1 = 0; it1.hasNext(); i1++) {
final Cluster<?> c1 = it1.next();
if(c1.isNoise()) {
BitsUtil.setI(noise1, i1); // depends on control dependency: [if], data = [none]
}
final DBIDs ids = DBIDUtil.ensureSet(c1.getIDs());
contingency[i1][size2 + 1] = c1.size(); // depends on control dependency: [for], data = [i1]
contingency[size1][size2 + 1] += c1.size(); // depends on control dependency: [for], data = [none]
final Iterator<? extends Cluster<?>> it2 = cs2.iterator();
for(int i2 = 0; it2.hasNext(); i2++) {
final Cluster<?> c2 = it2.next();
int count = DBIDUtil.intersectionSize(ids, c2.getIDs());
contingency[i1][i2] = count; // depends on control dependency: [for], data = [i2]
contingency[i1][size2] += count; // depends on control dependency: [for], data = [none]
contingency[size1][i2] += count; // depends on control dependency: [for], data = [i2]
contingency[size1][size2] += count; // depends on control dependency: [for], data = [none]
}
}
} } |
public class class_name {
protected void addSimpleSearchSetting(CmsXmlContentDefinition contentDef, String name, String value)
throws CmsXmlException {
if ("false".equalsIgnoreCase(value)) {
addSearchSetting(contentDef, name, Boolean.FALSE);
} else if ("true".equalsIgnoreCase(value)) {
addSearchSetting(contentDef, name, Boolean.TRUE);
} else {
StringTemplate template = m_searchTemplateGroup.getInstanceOf(value);
if ((template != null) && (template.getFormalArgument("name") != null)) {
template.setAttribute("name", CmsEncoder.escapeXml(name));
String xml = template.toString();
try {
Document doc = DocumentHelper.parseText(xml);
initSearchSettings(doc.getRootElement(), contentDef);
} catch (DocumentException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
} } | public class class_name {
protected void addSimpleSearchSetting(CmsXmlContentDefinition contentDef, String name, String value)
throws CmsXmlException {
if ("false".equalsIgnoreCase(value)) {
addSearchSetting(contentDef, name, Boolean.FALSE);
} else if ("true".equalsIgnoreCase(value)) {
addSearchSetting(contentDef, name, Boolean.TRUE);
} else {
StringTemplate template = m_searchTemplateGroup.getInstanceOf(value);
if ((template != null) && (template.getFormalArgument("name") != null)) {
template.setAttribute("name", CmsEncoder.escapeXml(name)); // depends on control dependency: [if], data = [none]
String xml = template.toString();
try {
Document doc = DocumentHelper.parseText(xml);
initSearchSettings(doc.getRootElement(), contentDef); // depends on control dependency: [try], data = [none]
} catch (DocumentException e) {
LOG.error(e.getLocalizedMessage(), e);
} // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
public void filterTable(String filter) {
m_container.removeAllContainerFilters();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(filter)) {
m_container.addContainerFilter(
new Or(
new SimpleStringFilter(PROP_NAME, filter, true, false),
new SimpleStringFilter(PROP_DESCRIPTION, filter, true, false)));
}
if ((getValue() != null) & !((Set<CmsUUID>)getValue()).isEmpty()) {
setCurrentPageFirstItemId(((Set<CmsUUID>)getValue()).iterator().next());
}
} } | public class class_name {
public void filterTable(String filter) {
m_container.removeAllContainerFilters();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(filter)) {
m_container.addContainerFilter(
new Or(
new SimpleStringFilter(PROP_NAME, filter, true, false),
new SimpleStringFilter(PROP_DESCRIPTION, filter, true, false))); // depends on control dependency: [if], data = [none]
}
if ((getValue() != null) & !((Set<CmsUUID>)getValue()).isEmpty()) {
setCurrentPageFirstItemId(((Set<CmsUUID>)getValue()).iterator().next()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static final String id(String id) {
if (StringUtils.startsWith(id, PREFIX)) {
return PREFIX.concat(Utils.noSpaces(Utils.stripAndTrim(id.replaceAll(PREFIX, ""), " "), "-"));
} else if (id != null) {
return PREFIX.concat(Utils.noSpaces(Utils.stripAndTrim(id, " "), "-"));
} else {
return null;
}
} } | public class class_name {
public static final String id(String id) {
if (StringUtils.startsWith(id, PREFIX)) {
return PREFIX.concat(Utils.noSpaces(Utils.stripAndTrim(id.replaceAll(PREFIX, ""), " "), "-")); // depends on control dependency: [if], data = [none]
} else if (id != null) {
return PREFIX.concat(Utils.noSpaces(Utils.stripAndTrim(id, " "), "-")); // depends on control dependency: [if], data = [(id]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(PutAccountSendingAttributesRequest putAccountSendingAttributesRequest, ProtocolMarshaller protocolMarshaller) {
if (putAccountSendingAttributesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(putAccountSendingAttributesRequest.getSendingEnabled(), SENDINGENABLED_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(PutAccountSendingAttributesRequest putAccountSendingAttributesRequest, ProtocolMarshaller protocolMarshaller) {
if (putAccountSendingAttributesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(putAccountSendingAttributesRequest.getSendingEnabled(), SENDINGENABLED_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 static String[] listAllCowfiles() {
String[] resultAsArray;
String[] bundled = null;
String cowfileExtRe = "\\" + COWFILE_EXT + "$";
InputStream bundleStream = Cowloader.class.getResourceAsStream("/cowfile-list.csv");
if (bundleStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(bundleStream));
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
String bundleList = sb.toString();
bundled = bundleList.split(",");
} catch (IOException ex) {
Logger.getLogger(Cowloader.class.getName()).log(Level.WARNING, null, ex);
} finally {
try {
bundleStream.close();
} catch (IOException ex) {
Logger.getLogger(Cowloader.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Set<String> result = new HashSet<String>();
if (bundled != null) {
for (String cowfile : bundled) {
if (cowfile.endsWith(COWFILE_EXT)) { // mech-and-cow for example is not a cowfile and should be excluded
result.add(cowfile.replaceAll(cowfileExtRe, ""));
}
}
}
String cowPath = System.getenv("COWPATH");
if (cowPath != null) {
String[] paths = cowPath.split(File.pathSeparator);
if (paths != null) {
for (String path : paths) {
File[] cowfiles = getCowFiles(path);
if (cowfiles != null) {
for (File cowfile : cowfiles) {
result.add(cowfile.getName().replaceAll(cowfileExtRe, ""));
}
}
}
}
}
resultAsArray = result.toArray(new String[result.size()]);
Arrays.sort(resultAsArray);
return resultAsArray;
} } | public class class_name {
public static String[] listAllCowfiles() {
String[] resultAsArray;
String[] bundled = null;
String cowfileExtRe = "\\" + COWFILE_EXT + "$";
InputStream bundleStream = Cowloader.class.getResourceAsStream("/cowfile-list.csv");
if (bundleStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(bundleStream));
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line); // depends on control dependency: [while], data = [none]
}
reader.close(); // depends on control dependency: [try], data = [none]
String bundleList = sb.toString();
bundled = bundleList.split(","); // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
Logger.getLogger(Cowloader.class.getName()).log(Level.WARNING, null, ex);
} finally { // depends on control dependency: [catch], data = [none]
try {
bundleStream.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
Logger.getLogger(Cowloader.class.getName()).log(Level.SEVERE, null, ex);
} // depends on control dependency: [catch], data = [none]
}
}
Set<String> result = new HashSet<String>();
if (bundled != null) {
for (String cowfile : bundled) {
if (cowfile.endsWith(COWFILE_EXT)) { // mech-and-cow for example is not a cowfile and should be excluded
result.add(cowfile.replaceAll(cowfileExtRe, "")); // depends on control dependency: [if], data = [none]
}
}
}
String cowPath = System.getenv("COWPATH");
if (cowPath != null) {
String[] paths = cowPath.split(File.pathSeparator);
if (paths != null) {
for (String path : paths) {
File[] cowfiles = getCowFiles(path);
if (cowfiles != null) {
for (File cowfile : cowfiles) {
result.add(cowfile.getName().replaceAll(cowfileExtRe, "")); // depends on control dependency: [for], data = [cowfile]
}
}
}
}
}
resultAsArray = result.toArray(new String[result.size()]);
Arrays.sort(resultAsArray);
return resultAsArray;
} } |
public class class_name {
@SuppressWarnings("Duplicates")
public static Optional<Charset> resolveCharset(HttpMessage<?> request) {
try {
Optional<Charset> contentTypeCharset = request
.getContentType()
.flatMap(contentType ->
contentType.getParameters()
.get(MediaType.CHARSET_PARAMETER)
.map(Charset::forName)
);
if (contentTypeCharset.isPresent()) {
return contentTypeCharset;
} else {
return request
.getHeaders()
.findFirst(HttpHeaders.ACCEPT_CHARSET)
.map(text -> {
int len = text.length();
if (len == 0 || (len == 1 && text.charAt(0) == '*')) {
return StandardCharsets.UTF_8;
}
if (text.indexOf(';') > -1) {
text = text.split(";")[0];
}
if (text.indexOf(',') > -1) {
text = text.split(",")[0];
}
try {
return Charset.forName(text);
} catch (Exception e) {
// unsupported charset, default to UTF-8
return StandardCharsets.UTF_8;
}
});
}
} catch (UnsupportedCharsetException e) {
return Optional.empty();
}
} } | public class class_name {
@SuppressWarnings("Duplicates")
public static Optional<Charset> resolveCharset(HttpMessage<?> request) {
try {
Optional<Charset> contentTypeCharset = request
.getContentType()
.flatMap(contentType ->
contentType.getParameters()
.get(MediaType.CHARSET_PARAMETER)
.map(Charset::forName)
);
if (contentTypeCharset.isPresent()) {
return contentTypeCharset; // depends on control dependency: [if], data = [none]
} else {
return request
.getHeaders()
.findFirst(HttpHeaders.ACCEPT_CHARSET)
.map(text -> {
int len = text.length(); // depends on control dependency: [if], data = [none]
if (len == 0 || (len == 1 && text.charAt(0) == '*')) {
return StandardCharsets.UTF_8; // depends on control dependency: [if], data = [none]
}
if (text.indexOf(';') > -1) {
text = text.split(";")[0]; // depends on control dependency: [if], data = [none]
}
if (text.indexOf(',') > -1) {
text = text.split(",")[0]; // depends on control dependency: [if], data = [none]
}
try {
return Charset.forName(text); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
// unsupported charset, default to UTF-8
return StandardCharsets.UTF_8;
} // depends on control dependency: [catch], data = [none]
});
}
} catch (UnsupportedCharsetException e) {
return Optional.empty();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public DependencyId[] getDependencyIds(){
DependencyId[] depIds = new DependencyId[configEntry.dependencyIds.length];
for ( int i=0; i<configEntry.dependencyIds.length; i++ ){
depIds[i] = new DependencyId(configEntry.dependencyIds[i]);
}
return depIds;
} } | public class class_name {
public DependencyId[] getDependencyIds(){
DependencyId[] depIds = new DependencyId[configEntry.dependencyIds.length];
for ( int i=0; i<configEntry.dependencyIds.length; i++ ){
depIds[i] = new DependencyId(configEntry.dependencyIds[i]); // depends on control dependency: [for], data = [i]
}
return depIds;
} } |
public class class_name {
public static void editPropertiesForLocaleCompareMode(
final CmsLocaleComparePropertyData data,
final CmsUUID ownId,
final CmsUUID defaultFileId,
final String noEditReason) {
final CmsUUID infoId;
infoId = defaultFileId;
Set<CmsUUID> idsForPropertyConfig = new HashSet<CmsUUID>();
idsForPropertyConfig.add(defaultFileId);
idsForPropertyConfig.add(ownId);
final List<CmsUUID> propertyConfigIds = new ArrayList<CmsUUID>(idsForPropertyConfig);
CmsRpcAction<CmsListInfoBean> action = new CmsRpcAction<CmsListInfoBean>() {
@Override
public void execute() {
start(0, true);
CmsCoreProvider.getVfsService().getPageInfo(infoId, this);
}
@Override
protected void onResponse(CmsListInfoBean infoResult) {
stop(false);
final CmsLocaleComparePropertyHandler handler = new CmsLocaleComparePropertyHandler(data);
handler.setPageInfo(infoResult);
CmsRpcAction<Map<CmsUUID, Map<String, CmsXmlContentProperty>>> propertyAction = new CmsRpcAction<Map<CmsUUID, Map<String, CmsXmlContentProperty>>>() {
@Override
public void execute() {
start(0, true);
CmsCoreProvider.getVfsService().getDefaultProperties(propertyConfigIds, this);
}
@Override
protected void onResponse(Map<CmsUUID, Map<String, CmsXmlContentProperty>> propertyResult) {
stop(false);
Map<String, CmsXmlContentProperty> propConfig = new LinkedHashMap<String, CmsXmlContentProperty>();
for (Map<String, CmsXmlContentProperty> defaultProps : propertyResult.values()) {
propConfig.putAll(defaultProps);
}
propConfig.putAll(CmsSitemapView.getInstance().getController().getData().getProperties());
A_CmsPropertyEditor editor = new CmsNavModePropertyEditor(propConfig, handler);
editor.setPropertyNames(
CmsSitemapView.getInstance().getController().getData().getAllPropertyNames());
final CmsFormDialog dialog = new CmsFormDialog(handler.getDialogTitle(), editor.getForm());
CmsPropertyDefinitionButton defButton = new CmsPropertyDefinitionButton() {
/**
* @see org.opencms.gwt.client.property.definition.CmsPropertyDefinitionButton#onBeforeEditPropertyDefinition()
*/
@Override
public void onBeforeEditPropertyDefinition() {
dialog.hide();
}
};
defButton.getElement().getStyle().setFloat(Style.Float.LEFT);
defButton.installOnDialog(dialog);
CmsDialogFormHandler formHandler = new CmsDialogFormHandler();
formHandler.setDialog(dialog);
I_CmsFormSubmitHandler submitHandler = new CmsPropertySubmitHandler(handler);
formHandler.setSubmitHandler(submitHandler);
dialog.setFormHandler(formHandler);
editor.initializeWidgets(dialog);
dialog.centerHorizontally(50);
dialog.catchNotifications();
if (noEditReason != null) {
editor.disableInput(noEditReason);
dialog.getOkButton().disable(noEditReason);
}
}
};
propertyAction.execute();
}
};
action.execute();
} } | public class class_name {
public static void editPropertiesForLocaleCompareMode(
final CmsLocaleComparePropertyData data,
final CmsUUID ownId,
final CmsUUID defaultFileId,
final String noEditReason) {
final CmsUUID infoId;
infoId = defaultFileId;
Set<CmsUUID> idsForPropertyConfig = new HashSet<CmsUUID>();
idsForPropertyConfig.add(defaultFileId);
idsForPropertyConfig.add(ownId);
final List<CmsUUID> propertyConfigIds = new ArrayList<CmsUUID>(idsForPropertyConfig);
CmsRpcAction<CmsListInfoBean> action = new CmsRpcAction<CmsListInfoBean>() {
@Override
public void execute() {
start(0, true);
CmsCoreProvider.getVfsService().getPageInfo(infoId, this);
}
@Override
protected void onResponse(CmsListInfoBean infoResult) {
stop(false);
final CmsLocaleComparePropertyHandler handler = new CmsLocaleComparePropertyHandler(data);
handler.setPageInfo(infoResult);
CmsRpcAction<Map<CmsUUID, Map<String, CmsXmlContentProperty>>> propertyAction = new CmsRpcAction<Map<CmsUUID, Map<String, CmsXmlContentProperty>>>() {
@Override
public void execute() {
start(0, true);
CmsCoreProvider.getVfsService().getDefaultProperties(propertyConfigIds, this);
}
@Override
protected void onResponse(Map<CmsUUID, Map<String, CmsXmlContentProperty>> propertyResult) {
stop(false);
Map<String, CmsXmlContentProperty> propConfig = new LinkedHashMap<String, CmsXmlContentProperty>();
for (Map<String, CmsXmlContentProperty> defaultProps : propertyResult.values()) {
propConfig.putAll(defaultProps); // depends on control dependency: [for], data = [defaultProps]
}
propConfig.putAll(CmsSitemapView.getInstance().getController().getData().getProperties());
A_CmsPropertyEditor editor = new CmsNavModePropertyEditor(propConfig, handler);
editor.setPropertyNames(
CmsSitemapView.getInstance().getController().getData().getAllPropertyNames());
final CmsFormDialog dialog = new CmsFormDialog(handler.getDialogTitle(), editor.getForm());
CmsPropertyDefinitionButton defButton = new CmsPropertyDefinitionButton() {
/**
* @see org.opencms.gwt.client.property.definition.CmsPropertyDefinitionButton#onBeforeEditPropertyDefinition()
*/
@Override
public void onBeforeEditPropertyDefinition() {
dialog.hide();
}
};
defButton.getElement().getStyle().setFloat(Style.Float.LEFT);
defButton.installOnDialog(dialog);
CmsDialogFormHandler formHandler = new CmsDialogFormHandler();
formHandler.setDialog(dialog);
I_CmsFormSubmitHandler submitHandler = new CmsPropertySubmitHandler(handler);
formHandler.setSubmitHandler(submitHandler);
dialog.setFormHandler(formHandler);
editor.initializeWidgets(dialog);
dialog.centerHorizontally(50);
dialog.catchNotifications();
if (noEditReason != null) {
editor.disableInput(noEditReason); // depends on control dependency: [if], data = [(noEditReason]
dialog.getOkButton().disable(noEditReason); // depends on control dependency: [if], data = [(noEditReason]
}
}
};
propertyAction.execute();
}
};
action.execute();
} } |
public class class_name {
@Override
public EClass getIfcNormalisedRatioMeasure() {
if (ifcNormalisedRatioMeasureEClass == null) {
ifcNormalisedRatioMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(899);
}
return ifcNormalisedRatioMeasureEClass;
} } | public class class_name {
@Override
public EClass getIfcNormalisedRatioMeasure() {
if (ifcNormalisedRatioMeasureEClass == null) {
ifcNormalisedRatioMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(899);
// depends on control dependency: [if], data = [none]
}
return ifcNormalisedRatioMeasureEClass;
} } |
public class class_name {
@Override
public void destroy() {
if (!isDestroyed.compareAndSet(false, true)) {
return;
}
deregisterLifecycleListener();
for (ICacheInternal cache : caches.values()) {
cache.destroy();
}
caches.clear();
isClosed.set(true);
postDestroy();
} } | public class class_name {
@Override
public void destroy() {
if (!isDestroyed.compareAndSet(false, true)) {
return; // depends on control dependency: [if], data = [none]
}
deregisterLifecycleListener();
for (ICacheInternal cache : caches.values()) {
cache.destroy(); // depends on control dependency: [for], data = [cache]
}
caches.clear();
isClosed.set(true);
postDestroy();
} } |
public class class_name {
@Override
public void dispatchConfigurationChanged(Configuration newConfig) {
if (ActionBarSherlock.DEBUG) Log.d(TAG, "[dispatchConfigurationChanged] newConfig: " + newConfig);
if (aActionBar != null) {
aActionBar.onConfigurationChanged(newConfig);
}
} } | public class class_name {
@Override
public void dispatchConfigurationChanged(Configuration newConfig) {
if (ActionBarSherlock.DEBUG) Log.d(TAG, "[dispatchConfigurationChanged] newConfig: " + newConfig);
if (aActionBar != null) {
aActionBar.onConfigurationChanged(newConfig); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
void putAll(BitArray array) {
assert data.length == array.data.length : "BitArrays must be of equal length when merging";
long bitCount = 0;
for (int i = 0; i < data.length; i++) {
data[i] |= array.data[i];
bitCount += Long.bitCount(data[i]);
}
this.bitCount = bitCount;
} } | public class class_name {
void putAll(BitArray array) {
assert data.length == array.data.length : "BitArrays must be of equal length when merging";
long bitCount = 0;
for (int i = 0; i < data.length; i++) {
data[i] |= array.data[i]; // depends on control dependency: [for], data = [i]
bitCount += Long.bitCount(data[i]); // depends on control dependency: [for], data = [i]
}
this.bitCount = bitCount;
} } |
public class class_name {
public String generateSqlSelectAll(String tableName) {
try {
return cacheSQLs.get("SELECT-ALL:" + tableName, () -> {
return MessageFormat.format("SELECT {2} FROM {0} ORDER BY {1}", tableName,
strPkColumns, strAllColumns);
});
} catch (ExecutionException e) {
throw new DaoException(e);
}
} } | public class class_name {
public String generateSqlSelectAll(String tableName) {
try {
return cacheSQLs.get("SELECT-ALL:" + tableName, () -> {
return MessageFormat.format("SELECT {2} FROM {0} ORDER BY {1}", tableName,
strPkColumns, strAllColumns);
}); // depends on control dependency: [try], data = [none]
} catch (ExecutionException e) {
throw new DaoException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static String cleanODataPath(String path, HandleParametersOption handleParameters) {
String cleanedPath = path;
if (HandleParametersOption.USE_ALL.equals(handleParameters) ) {
cleanedPath = path;
} else {
// check for single ID (unnamed)
Matcher matcher = patternResourceIdentifierUnquoted.matcher(path);
if (matcher.find()) {
String resourceName = matcher.group(1);
String resourceID = matcher.group(2);
String subString = resourceName + "(" + resourceID + ")";
int begin = path.indexOf(subString);
int end = begin + subString.length();
String beforeSubstring = path.substring(0,begin);
String afterSubstring = path.substring(end);
if (HandleParametersOption.IGNORE_COMPLETELY.equals(handleParameters) ||
HandleParametersOption.IGNORE_VALUE.equals(handleParameters) ) {
StringBuilder sb = new StringBuilder(beforeSubstring);
sb.append(resourceName).append("()").append(afterSubstring);
cleanedPath = sb.toString();
}
} else {
matcher = patternResourceMultipleIdentifier.matcher(path);
if (matcher.find()) {
// We've found a composite identifier. i.e: /Resource(field1=a,field2=3)
String multipleIdentifierSection = matcher.group(1);
int begin = path.indexOf(multipleIdentifierSection);
int end = begin + multipleIdentifierSection.length();
String beforeSubstring = path.substring(0,begin);
String afterSubstring = path.substring(end);
if (HandleParametersOption.IGNORE_COMPLETELY.equals(handleParameters) ) {
cleanedPath = beforeSubstring + afterSubstring;
} else {
StringBuilder sb = new StringBuilder(beforeSubstring);
matcher = patternResourceMultipleIdentifierDetail.matcher(multipleIdentifierSection);
int i = 1;
while (matcher.find()) {
if (i > 1) {
sb.append(',');
}
String paramName = matcher.group(1);
sb.append(paramName);
i++;
}
sb.append(afterSubstring);
cleanedPath = sb.toString();
}
}
}
}
return cleanedPath;
} } | public class class_name {
private static String cleanODataPath(String path, HandleParametersOption handleParameters) {
String cleanedPath = path;
if (HandleParametersOption.USE_ALL.equals(handleParameters) ) {
cleanedPath = path; // depends on control dependency: [if], data = [none]
} else {
// check for single ID (unnamed)
Matcher matcher = patternResourceIdentifierUnquoted.matcher(path);
if (matcher.find()) {
String resourceName = matcher.group(1);
String resourceID = matcher.group(2);
String subString = resourceName + "(" + resourceID + ")";
int begin = path.indexOf(subString);
int end = begin + subString.length();
String beforeSubstring = path.substring(0,begin);
String afterSubstring = path.substring(end);
if (HandleParametersOption.IGNORE_COMPLETELY.equals(handleParameters) ||
HandleParametersOption.IGNORE_VALUE.equals(handleParameters) ) {
StringBuilder sb = new StringBuilder(beforeSubstring);
sb.append(resourceName).append("()").append(afterSubstring); // depends on control dependency: [if], data = [none]
cleanedPath = sb.toString(); // depends on control dependency: [if], data = [none]
}
} else {
matcher = patternResourceMultipleIdentifier.matcher(path); // depends on control dependency: [if], data = [none]
if (matcher.find()) {
// We've found a composite identifier. i.e: /Resource(field1=a,field2=3)
String multipleIdentifierSection = matcher.group(1);
int begin = path.indexOf(multipleIdentifierSection);
int end = begin + multipleIdentifierSection.length();
String beforeSubstring = path.substring(0,begin);
String afterSubstring = path.substring(end);
if (HandleParametersOption.IGNORE_COMPLETELY.equals(handleParameters) ) {
cleanedPath = beforeSubstring + afterSubstring; // depends on control dependency: [if], data = [none]
} else {
StringBuilder sb = new StringBuilder(beforeSubstring);
matcher = patternResourceMultipleIdentifierDetail.matcher(multipleIdentifierSection); // depends on control dependency: [if], data = [none]
int i = 1;
while (matcher.find()) {
if (i > 1) {
sb.append(','); // depends on control dependency: [if], data = [none]
}
String paramName = matcher.group(1);
sb.append(paramName); // depends on control dependency: [while], data = [none]
i++; // depends on control dependency: [while], data = [none]
}
sb.append(afterSubstring); // depends on control dependency: [if], data = [none]
cleanedPath = sb.toString(); // depends on control dependency: [if], data = [none]
}
}
}
}
return cleanedPath;
} } |
public class class_name {
protected void checkpoint(InternalTransaction internalTransaction,
ObjectManagerByteArrayOutputStream serializedBytes,
long savedSequenceNumber)
throws ObjectManagerException
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
"checkpoint",
new Object[] { internalTransaction,
serializedBytes,
new Long(savedSequenceNumber) });
if (lockedBy(internalTransaction)) { // Locking update?
switch (state) {
case stateAdded:
synchronized (forcedUpdateSequenceLock) {
// Now give the ManagedObnject to the ObjectStore, if we have a newer version.
if (savedSequenceNumber > forcedUpdateSequence) {
forcedUpdateSequence = savedSequenceNumber;
latestSerializedBytes = serializedBytes;
// TODO It is possible that nothing has changed since the last time we checkpointed this
// if the transaction is long running so the addition of the same thing to the Object
// store might be pointless.
owningToken.objectStore.add(this, true);
} // if (savedSequenceNumber > forcedUpdateSequence).
} // synchronized (forcedUpdateSequenceLock).
break;
case stateReplaced:
// The replaced image is written as part of the TransactionCheckpointLogRecord and must
// not be given to the ObjectStore because we dont yet know whether it will commit.
break;
case stateToBeDeleted:
case stateMustBeDeleted:
synchronized (forcedUpdateSequenceLock) {
if (savedSequenceNumber > forcedUpdateSequence) {
if (serializedBytes != null) {
// We have to consider including toBeDeleted Objects because they have not yet been deleted.
// The forcedSerializedBytes passed in may not be null if another OptimisticReplace happened to this
// ManagedObject after Delete had been logged. This happens when two links are deleted in a LinkedList
// under one transaction. If the serialized bytes are null we leave the ObjectStore version alone and
// let another transaction place its version in the store. We will only delete them when the
// transaction commits.
forcedUpdateSequence = savedSequenceNumber;
latestSerializedBytes = serializedBytes;
owningToken.objectStore.add(this, true);
} // if (serializedBytes != null).
} // if (savedSequenceNumber > forcedUpdateSequence).
} // synchronized (forcedUpdateSequenceLock).
break;
} // switch.
} else { // OptimisticReplace update.
synchronized (forcedUpdateSequenceLock) {
if (savedSequenceNumber > forcedUpdateSequence) {
forcedUpdateSequence = savedSequenceNumber;
// Did we checkpoint an OptimisticReplace after some other transaction has subsequently deleted us.
if (state != stateDeleted) {
latestSerializedBytes = serializedBytes;
owningToken.objectStore.add(this, true);
} // if (state != stateDeleted).
} // if (savedSequenceNumber > forcedUpdateSequence).
} // synchronized (forcedUpdateSequenceLock).
} // if (lockedBy(transaction)).
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
"checkpoint");
} } | public class class_name {
protected void checkpoint(InternalTransaction internalTransaction,
ObjectManagerByteArrayOutputStream serializedBytes,
long savedSequenceNumber)
throws ObjectManagerException
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
"checkpoint",
new Object[] { internalTransaction,
serializedBytes,
new Long(savedSequenceNumber) });
if (lockedBy(internalTransaction)) { // Locking update?
switch (state) {
case stateAdded:
synchronized (forcedUpdateSequenceLock) {
// Now give the ManagedObnject to the ObjectStore, if we have a newer version.
if (savedSequenceNumber > forcedUpdateSequence) {
forcedUpdateSequence = savedSequenceNumber; // depends on control dependency: [if], data = [none]
latestSerializedBytes = serializedBytes; // depends on control dependency: [if], data = [none]
// TODO It is possible that nothing has changed since the last time we checkpointed this
// if the transaction is long running so the addition of the same thing to the Object
// store might be pointless.
owningToken.objectStore.add(this, true); // depends on control dependency: [if], data = [none]
} // if (savedSequenceNumber > forcedUpdateSequence).
} // synchronized (forcedUpdateSequenceLock).
break;
case stateReplaced:
// The replaced image is written as part of the TransactionCheckpointLogRecord and must
// not be given to the ObjectStore because we dont yet know whether it will commit.
break;
case stateToBeDeleted:
case stateMustBeDeleted:
synchronized (forcedUpdateSequenceLock) {
if (savedSequenceNumber > forcedUpdateSequence) {
if (serializedBytes != null) {
// We have to consider including toBeDeleted Objects because they have not yet been deleted.
// The forcedSerializedBytes passed in may not be null if another OptimisticReplace happened to this
// ManagedObject after Delete had been logged. This happens when two links are deleted in a LinkedList
// under one transaction. If the serialized bytes are null we leave the ObjectStore version alone and
// let another transaction place its version in the store. We will only delete them when the
// transaction commits.
forcedUpdateSequence = savedSequenceNumber; // depends on control dependency: [if], data = [none]
latestSerializedBytes = serializedBytes; // depends on control dependency: [if], data = [none]
owningToken.objectStore.add(this, true); // depends on control dependency: [if], data = [none]
} // if (serializedBytes != null).
} // if (savedSequenceNumber > forcedUpdateSequence).
} // synchronized (forcedUpdateSequenceLock).
break;
} // switch.
} else { // OptimisticReplace update.
synchronized (forcedUpdateSequenceLock) {
if (savedSequenceNumber > forcedUpdateSequence) {
forcedUpdateSequence = savedSequenceNumber; // depends on control dependency: [if], data = [none]
// Did we checkpoint an OptimisticReplace after some other transaction has subsequently deleted us.
if (state != stateDeleted) {
latestSerializedBytes = serializedBytes; // depends on control dependency: [if], data = [none]
owningToken.objectStore.add(this, true); // depends on control dependency: [if], data = [none]
} // if (state != stateDeleted).
} // if (savedSequenceNumber > forcedUpdateSequence).
} // synchronized (forcedUpdateSequenceLock).
} // if (lockedBy(transaction)).
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
"checkpoint");
} } |
public class class_name {
@NonNull
public Searcher search(@Nullable final Intent intent) {
String query = null;
Object origin = null;
if (intent != null) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.hasExtra(SearchManager.QUERY) ?
intent.getStringExtra(SearchManager.QUERY) : intent.getDataString();
origin = intent;
}
}
return search(query, origin);
} } | public class class_name {
@NonNull
public Searcher search(@Nullable final Intent intent) {
String query = null;
Object origin = null;
if (intent != null) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.hasExtra(SearchManager.QUERY) ?
intent.getStringExtra(SearchManager.QUERY) : intent.getDataString(); // depends on control dependency: [if], data = [none]
origin = intent; // depends on control dependency: [if], data = [none]
}
}
return search(query, origin);
} } |
public class class_name {
private static final String unescape(String str) {
StringBuilder sb = new StringBuilder(str.length() * 2);
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if ((c == '\\') && (i < len - 1)) {
char d = str.charAt(i + 1);
if (!((d == USER_DATA_DELIM) || (d == USER_ATTRIB_DELIM) || (d == TOKEN_DELIM))) {
// if next char is delim, skip this escape char
sb.append(c);
}
} else {
sb.append(c);
}
}
return sb.toString();
} } | public class class_name {
private static final String unescape(String str) {
StringBuilder sb = new StringBuilder(str.length() * 2);
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if ((c == '\\') && (i < len - 1)) {
char d = str.charAt(i + 1);
if (!((d == USER_DATA_DELIM) || (d == USER_ATTRIB_DELIM) || (d == TOKEN_DELIM))) {
// if next char is delim, skip this escape char
sb.append(c); // depends on control dependency: [if], data = [none]
}
} else {
sb.append(c); // depends on control dependency: [if], data = [none]
}
}
return sb.toString();
} } |
public class class_name {
private static MemoryManager createMemoryManager(
TaskManagerServicesConfiguration taskManagerServicesConfiguration,
long freeHeapMemoryWithDefrag,
long maxJvmHeapMemory) throws Exception {
// computing the amount of memory to use depends on how much memory is available
// it strictly needs to happen AFTER the network stack has been initialized
// check if a value has been configured
long configuredMemory = taskManagerServicesConfiguration.getConfiguredMemory();
MemoryType memType = taskManagerServicesConfiguration.getMemoryType();
final long memorySize;
boolean preAllocateMemory = taskManagerServicesConfiguration.isPreAllocateMemory();
if (configuredMemory > 0) {
if (preAllocateMemory) {
LOG.info("Using {} MB for managed memory." , configuredMemory);
} else {
LOG.info("Limiting managed memory to {} MB, memory will be allocated lazily." , configuredMemory);
}
memorySize = configuredMemory << 20; // megabytes to bytes
} else {
// similar to #calculateNetworkBufferMemory(TaskManagerServicesConfiguration tmConfig)
float memoryFraction = taskManagerServicesConfiguration.getMemoryFraction();
if (memType == MemoryType.HEAP) {
// network buffers allocated off-heap -> use memoryFraction of the available heap:
long relativeMemSize = (long) (freeHeapMemoryWithDefrag * memoryFraction);
if (preAllocateMemory) {
LOG.info("Using {} of the currently free heap space for managed heap memory ({} MB)." ,
memoryFraction , relativeMemSize >> 20);
} else {
LOG.info("Limiting managed memory to {} of the currently free heap space ({} MB), " +
"memory will be allocated lazily." , memoryFraction , relativeMemSize >> 20);
}
memorySize = relativeMemSize;
} else if (memType == MemoryType.OFF_HEAP) {
// The maximum heap memory has been adjusted according to the fraction (see
// calculateHeapSizeMB(long totalJavaMemorySizeMB, Configuration config)), i.e.
// maxJvmHeap = jvmTotalNoNet - jvmTotalNoNet * memoryFraction = jvmTotalNoNet * (1 - memoryFraction)
// directMemorySize = jvmTotalNoNet * memoryFraction
long directMemorySize = (long) (maxJvmHeapMemory / (1.0 - memoryFraction) * memoryFraction);
if (preAllocateMemory) {
LOG.info("Using {} of the maximum memory size for managed off-heap memory ({} MB)." ,
memoryFraction, directMemorySize >> 20);
} else {
LOG.info("Limiting managed memory to {} of the maximum memory size ({} MB)," +
" memory will be allocated lazily.", memoryFraction, directMemorySize >> 20);
}
memorySize = directMemorySize;
} else {
throw new RuntimeException("No supported memory type detected.");
}
}
// now start the memory manager
final MemoryManager memoryManager;
try {
memoryManager = new MemoryManager(
memorySize,
taskManagerServicesConfiguration.getNumberOfSlots(),
taskManagerServicesConfiguration.getNetworkConfig().networkBufferSize(),
memType,
preAllocateMemory);
} catch (OutOfMemoryError e) {
if (memType == MemoryType.HEAP) {
throw new Exception("OutOfMemory error (" + e.getMessage() +
") while allocating the TaskManager heap memory (" + memorySize + " bytes).", e);
} else if (memType == MemoryType.OFF_HEAP) {
throw new Exception("OutOfMemory error (" + e.getMessage() +
") while allocating the TaskManager off-heap memory (" + memorySize +
" bytes).Try increasing the maximum direct memory (-XX:MaxDirectMemorySize)", e);
} else {
throw e;
}
}
return memoryManager;
} } | public class class_name {
private static MemoryManager createMemoryManager(
TaskManagerServicesConfiguration taskManagerServicesConfiguration,
long freeHeapMemoryWithDefrag,
long maxJvmHeapMemory) throws Exception {
// computing the amount of memory to use depends on how much memory is available
// it strictly needs to happen AFTER the network stack has been initialized
// check if a value has been configured
long configuredMemory = taskManagerServicesConfiguration.getConfiguredMemory();
MemoryType memType = taskManagerServicesConfiguration.getMemoryType();
final long memorySize;
boolean preAllocateMemory = taskManagerServicesConfiguration.isPreAllocateMemory();
if (configuredMemory > 0) {
if (preAllocateMemory) {
LOG.info("Using {} MB for managed memory." , configuredMemory); // depends on control dependency: [if], data = [none]
} else {
LOG.info("Limiting managed memory to {} MB, memory will be allocated lazily." , configuredMemory); // depends on control dependency: [if], data = [none]
}
memorySize = configuredMemory << 20; // megabytes to bytes
} else {
// similar to #calculateNetworkBufferMemory(TaskManagerServicesConfiguration tmConfig)
float memoryFraction = taskManagerServicesConfiguration.getMemoryFraction();
if (memType == MemoryType.HEAP) {
// network buffers allocated off-heap -> use memoryFraction of the available heap:
long relativeMemSize = (long) (freeHeapMemoryWithDefrag * memoryFraction);
if (preAllocateMemory) {
LOG.info("Using {} of the currently free heap space for managed heap memory ({} MB)." ,
memoryFraction , relativeMemSize >> 20); // depends on control dependency: [if], data = [none]
} else {
LOG.info("Limiting managed memory to {} of the currently free heap space ({} MB), " +
"memory will be allocated lazily." , memoryFraction , relativeMemSize >> 20); // depends on control dependency: [if], data = [none]
}
memorySize = relativeMemSize; // depends on control dependency: [if], data = [none]
} else if (memType == MemoryType.OFF_HEAP) {
// The maximum heap memory has been adjusted according to the fraction (see
// calculateHeapSizeMB(long totalJavaMemorySizeMB, Configuration config)), i.e.
// maxJvmHeap = jvmTotalNoNet - jvmTotalNoNet * memoryFraction = jvmTotalNoNet * (1 - memoryFraction)
// directMemorySize = jvmTotalNoNet * memoryFraction
long directMemorySize = (long) (maxJvmHeapMemory / (1.0 - memoryFraction) * memoryFraction);
if (preAllocateMemory) {
LOG.info("Using {} of the maximum memory size for managed off-heap memory ({} MB)." ,
memoryFraction, directMemorySize >> 20); // depends on control dependency: [if], data = [none]
} else {
LOG.info("Limiting managed memory to {} of the maximum memory size ({} MB)," +
" memory will be allocated lazily.", memoryFraction, directMemorySize >> 20); // depends on control dependency: [if], data = [none]
}
memorySize = directMemorySize; // depends on control dependency: [if], data = [none]
} else {
throw new RuntimeException("No supported memory type detected.");
}
}
// now start the memory manager
final MemoryManager memoryManager;
try {
memoryManager = new MemoryManager(
memorySize,
taskManagerServicesConfiguration.getNumberOfSlots(),
taskManagerServicesConfiguration.getNetworkConfig().networkBufferSize(),
memType,
preAllocateMemory);
} catch (OutOfMemoryError e) {
if (memType == MemoryType.HEAP) {
throw new Exception("OutOfMemory error (" + e.getMessage() +
") while allocating the TaskManager heap memory (" + memorySize + " bytes).", e);
} else if (memType == MemoryType.OFF_HEAP) {
throw new Exception("OutOfMemory error (" + e.getMessage() +
") while allocating the TaskManager off-heap memory (" + memorySize +
" bytes).Try increasing the maximum direct memory (-XX:MaxDirectMemorySize)", e);
} else {
throw e;
}
}
return memoryManager;
} } |
public class class_name {
public void onSelectFilterFunction() {
int selectedIdx = view.getSelectedFunctionIndex();
if (selectedIdx >= 0) {
CoreFunctionFilter coreFilter = getCoreFilter();
CoreFunctionType functionType = getAvailableFunctions(coreFilter).get(selectedIdx);
ColumnType columnType = metadata.getColumnType(coreFilter.getColumnId());
List params = FilterFactory.createParameters(columnType, functionType);
coreFilter.setType(functionType);
coreFilter.setParameters(params);
initFilterSelector();
fireFilterChanged();
if (!initFilterConfig().isEmpty()) {
view.showFilterConfig();
}
}
} } | public class class_name {
public void onSelectFilterFunction() {
int selectedIdx = view.getSelectedFunctionIndex();
if (selectedIdx >= 0) {
CoreFunctionFilter coreFilter = getCoreFilter();
CoreFunctionType functionType = getAvailableFunctions(coreFilter).get(selectedIdx);
ColumnType columnType = metadata.getColumnType(coreFilter.getColumnId());
List params = FilterFactory.createParameters(columnType, functionType);
coreFilter.setType(functionType); // depends on control dependency: [if], data = [none]
coreFilter.setParameters(params); // depends on control dependency: [if], data = [none]
initFilterSelector(); // depends on control dependency: [if], data = [none]
fireFilterChanged(); // depends on control dependency: [if], data = [none]
if (!initFilterConfig().isEmpty()) {
view.showFilterConfig(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public static LocalizationContext getLocalizationContext(PageContext pc, String basename) {
LocalizationContext locCtxt = null;
ResourceBundle bundle = null;
if ((basename == null) || basename.equals("")) {
return new LocalizationContext();
}
// Try preferred locales
Locale pref = getLocale(pc, javax.servlet.jsp.jstl.core.Config.FMT_LOCALE);
if (pref != null) {
// Preferred locale is application-based
bundle = findMatch(basename, pref);
if (bundle != null) {
locCtxt = new LocalizationContext(bundle, pref);
}
}
if (locCtxt == null) {
// No match found with preferred locales, try using fallback locale
locCtxt = BundleSupport.getLocalizationContext(pc, basename);
} else {
// set response locale
if (locCtxt.getLocale() != null) {
setResponseLocale(pc, locCtxt.getLocale());
}
}
return locCtxt;
} } | public class class_name {
public static LocalizationContext getLocalizationContext(PageContext pc, String basename) {
LocalizationContext locCtxt = null;
ResourceBundle bundle = null;
if ((basename == null) || basename.equals("")) {
return new LocalizationContext();
// depends on control dependency: [if], data = [none]
}
// Try preferred locales
Locale pref = getLocale(pc, javax.servlet.jsp.jstl.core.Config.FMT_LOCALE);
if (pref != null) {
// Preferred locale is application-based
bundle = findMatch(basename, pref);
// depends on control dependency: [if], data = [none]
if (bundle != null) {
locCtxt = new LocalizationContext(bundle, pref);
// depends on control dependency: [if], data = [(bundle]
}
}
if (locCtxt == null) {
// No match found with preferred locales, try using fallback locale
locCtxt = BundleSupport.getLocalizationContext(pc, basename);
// depends on control dependency: [if], data = [none]
} else {
// set response locale
if (locCtxt.getLocale() != null) {
setResponseLocale(pc, locCtxt.getLocale());
// depends on control dependency: [if], data = [none]
}
}
return locCtxt;
} } |
public class class_name {
public UrlBuilder addPath(String path) {
if (path.charAt(0) == '/' && baseUrl.endsWith("/")) {
baseUrl = baseUrl + path.substring(1);
} else {
baseUrl = baseUrl + path;
}
return this;
} } | public class class_name {
public UrlBuilder addPath(String path) {
if (path.charAt(0) == '/' && baseUrl.endsWith("/")) {
baseUrl = baseUrl + path.substring(1); // depends on control dependency: [if], data = [none]
} else {
baseUrl = baseUrl + path; // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
public void cluster (ArrayList<Instance> insts) {
System.out.println("Initial centers");
for(int i=0;i<k;i++){
assignedClusters[i] = new ArrayList<Instance>();
}
for(int i=0;i<insts.size();i++){
assignedClusters[i%k].add(insts.get(i));
}
for(int i=0;i<k;i++){
centroids[i] = calculateCentroid(assignedClusters[i]);
clusterQualities[i] = calculateClusterQuality(assignedClusters[i], centroids[i]);
}
for (int numChanged = 0, itr = 0; (numChanged > 0) || (itr == 0); ++itr) {
numChanged = 0;
while (true) {
int numReassigned = doBatchKmeans();
System.out.println("After an iteration of Batch K-Means, " +
numReassigned + " documents were moved.");
double oldQuality = 0.0;
double newQuality = 0.0;
for (int b = 0; b < this.centroids.length; ++b) {
oldQuality += this.clusterQualities[b];
newQuality += this.newQualities[b];
}
double qualityDelta = oldQuality - newQuality;
System.out.println("Change in quality is: " + qualityDelta);
if (qualityDelta < this.TOL) {
System.out.println(
"Benefit of change is below tolerance... Switching to incremental...\n");
break;
}
if (numReassigned == 0) {
System.out.println(
"Batch K-Means has made no changes! Switching to incremental...\n");
break;
}
// We like the new results. Let's make them authoritative
for (int kk = 0; kk < this.assignedClusters.length; ++kk) {
this.assignedClusters[kk] = this.newClusters[kk];
this.centroids[kk] = this.newCentroids[kk];
this.clusterQualities[kk] = this.newQualities[kk];
}
numChanged = numReassigned; // Record the fact we made a change!
}
double qual = 0.0;
for (int i = 0; i < this.clusterQualities.length; ++i) {
qual += this.clusterQualities[i];
}
System.out.println("Quality of partition generated by Batch K-Means: " +
qual);
}
System.out.println("Batch K-Means Complete!\n");
} } | public class class_name {
public void cluster (ArrayList<Instance> insts) {
System.out.println("Initial centers");
for(int i=0;i<k;i++){
assignedClusters[i] = new ArrayList<Instance>();
// depends on control dependency: [for], data = [i]
}
for(int i=0;i<insts.size();i++){
assignedClusters[i%k].add(insts.get(i));
// depends on control dependency: [for], data = [i]
}
for(int i=0;i<k;i++){
centroids[i] = calculateCentroid(assignedClusters[i]);
// depends on control dependency: [for], data = [i]
clusterQualities[i] = calculateClusterQuality(assignedClusters[i], centroids[i]);
// depends on control dependency: [for], data = [i]
}
for (int numChanged = 0, itr = 0; (numChanged > 0) || (itr == 0); ++itr) {
numChanged = 0;
// depends on control dependency: [for], data = [numChanged]
while (true) {
int numReassigned = doBatchKmeans();
System.out.println("After an iteration of Batch K-Means, " +
numReassigned + " documents were moved.");
// depends on control dependency: [while], data = [none]
double oldQuality = 0.0;
double newQuality = 0.0;
for (int b = 0; b < this.centroids.length; ++b) {
oldQuality += this.clusterQualities[b];
// depends on control dependency: [for], data = [b]
newQuality += this.newQualities[b];
// depends on control dependency: [for], data = [b]
}
double qualityDelta = oldQuality - newQuality;
System.out.println("Change in quality is: " + qualityDelta);
// depends on control dependency: [while], data = [none]
if (qualityDelta < this.TOL) {
System.out.println(
"Benefit of change is below tolerance... Switching to incremental...\n");
// depends on control dependency: [if], data = [none]
break;
}
if (numReassigned == 0) {
System.out.println(
"Batch K-Means has made no changes! Switching to incremental...\n");
// depends on control dependency: [if], data = [none]
break;
}
// We like the new results. Let's make them authoritative
for (int kk = 0; kk < this.assignedClusters.length; ++kk) {
this.assignedClusters[kk] = this.newClusters[kk];
// depends on control dependency: [for], data = [kk]
this.centroids[kk] = this.newCentroids[kk];
// depends on control dependency: [for], data = [kk]
this.clusterQualities[kk] = this.newQualities[kk];
// depends on control dependency: [for], data = [kk]
}
numChanged = numReassigned; // Record the fact we made a change!
// depends on control dependency: [while], data = [none]
}
double qual = 0.0;
for (int i = 0; i < this.clusterQualities.length; ++i) {
qual += this.clusterQualities[i];
// depends on control dependency: [for], data = [i]
}
System.out.println("Quality of partition generated by Batch K-Means: " +
qual);
// depends on control dependency: [for], data = [none]
}
System.out.println("Batch K-Means Complete!\n");
} } |
public class class_name {
public void setDatasets(java.util.Collection<Dataset> datasets) {
if (datasets == null) {
this.datasets = null;
return;
}
this.datasets = new com.amazonaws.internal.SdkInternalList<Dataset>(datasets);
} } | public class class_name {
public void setDatasets(java.util.Collection<Dataset> datasets) {
if (datasets == null) {
this.datasets = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.datasets = new com.amazonaws.internal.SdkInternalList<Dataset>(datasets);
} } |
public class class_name {
public static TranslatedContentSpecWrapper getTranslatedContentSpecById(final DataProviderFactory providerFactory, final Integer id,
final Integer rev) {
final CollectionWrapper<TranslatedContentSpecWrapper> translatedContentSpecs = providerFactory.getProvider(
ContentSpecProvider.class).getContentSpecTranslations(id, rev);
if (translatedContentSpecs != null) {
final List<TranslatedContentSpecWrapper> translatedContentSpecItems = translatedContentSpecs.getItems();
for (final TranslatedContentSpecWrapper translatedContentSpec : translatedContentSpecItems) {
if (rev != null && translatedContentSpec.getContentSpecRevision().equals(rev)) {
return translatedContentSpec;
} else if (rev == null) {
return translatedContentSpec;
}
}
}
return null;
} } | public class class_name {
public static TranslatedContentSpecWrapper getTranslatedContentSpecById(final DataProviderFactory providerFactory, final Integer id,
final Integer rev) {
final CollectionWrapper<TranslatedContentSpecWrapper> translatedContentSpecs = providerFactory.getProvider(
ContentSpecProvider.class).getContentSpecTranslations(id, rev);
if (translatedContentSpecs != null) {
final List<TranslatedContentSpecWrapper> translatedContentSpecItems = translatedContentSpecs.getItems();
for (final TranslatedContentSpecWrapper translatedContentSpec : translatedContentSpecItems) {
if (rev != null && translatedContentSpec.getContentSpecRevision().equals(rev)) {
return translatedContentSpec; // depends on control dependency: [if], data = [none]
} else if (rev == null) {
return translatedContentSpec; // depends on control dependency: [if], data = [none]
}
}
}
return null;
} } |
public class class_name {
public void onBuyGasButtonClicked(View arg0) {
Log.d(TAG, "Buy gas button clicked.");
if (mSubscribedToInfiniteGas) {
complain("No need! You're subscribed to infinite gas. Isn't that awesome?");
return;
}
if (mTank >= TANK_MAX) {
complain("Your tank is full. Drive around a bit!");
return;
}
if (setupDone == null) {
complain("Billing Setup is not completed yet");
return;
}
if (!setupDone) {
complain("Billing Setup failed");
return;
}
// launch the gas purchase UI flow.
// We will be notified of completion via mPurchaseFinishedListener
setWaitScreen(true);
Log.d(TAG, "Launching purchase flow for gas.");
/* TODO: for security, generate your payload here for verification. See the comments on
* verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use
* an empty string, but on a production app you should carefully generate this. */
String payload = "";
mHelper.launchPurchaseFlow(this, InAppConfig.SKU_GAS, RC_REQUEST, mPurchaseFinishedListener, payload);
} } | public class class_name {
public void onBuyGasButtonClicked(View arg0) {
Log.d(TAG, "Buy gas button clicked.");
if (mSubscribedToInfiniteGas) {
complain("No need! You're subscribed to infinite gas. Isn't that awesome?"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (mTank >= TANK_MAX) {
complain("Your tank is full. Drive around a bit!"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (setupDone == null) {
complain("Billing Setup is not completed yet"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
if (!setupDone) {
complain("Billing Setup failed"); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// launch the gas purchase UI flow.
// We will be notified of completion via mPurchaseFinishedListener
setWaitScreen(true);
Log.d(TAG, "Launching purchase flow for gas.");
/* TODO: for security, generate your payload here for verification. See the comments on
* verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use
* an empty string, but on a production app you should carefully generate this. */
String payload = "";
mHelper.launchPurchaseFlow(this, InAppConfig.SKU_GAS, RC_REQUEST, mPurchaseFinishedListener, payload);
} } |
public class class_name {
public MethodHandle getFieldQuiet(MethodHandles.Lookup lookup, String name) {
try {
return getField(lookup, name);
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new InvalidTransformException(e);
}
} } | public class class_name {
public MethodHandle getFieldQuiet(MethodHandles.Lookup lookup, String name) {
try {
return getField(lookup, name); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new InvalidTransformException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public final byte[] decompress(byte[] compressed) {
Assert.notNull(compressed, "compressed bytes cannot be null.");
try {
return doDecompress(compressed);
} catch (IOException e) {
throw new CompressionException("Unable to decompress bytes.", e);
}
} } | public class class_name {
@Override
public final byte[] decompress(byte[] compressed) {
Assert.notNull(compressed, "compressed bytes cannot be null.");
try {
return doDecompress(compressed); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new CompressionException("Unable to decompress bytes.", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static BigDecimal div(BigDecimal v1, BigDecimal v2, int scale, RoundingMode roundingMode) {
Assert.notNull(v2, "Divisor must be not null !");
if (null == v1) {
return BigDecimal.ZERO;
}
if (scale < 0) {
scale = -scale;
}
return v1.divide(v2, scale, roundingMode);
} } | public class class_name {
public static BigDecimal div(BigDecimal v1, BigDecimal v2, int scale, RoundingMode roundingMode) {
Assert.notNull(v2, "Divisor must be not null !");
if (null == v1) {
return BigDecimal.ZERO;
// depends on control dependency: [if], data = [none]
}
if (scale < 0) {
scale = -scale;
// depends on control dependency: [if], data = [none]
}
return v1.divide(v2, scale, roundingMode);
} } |
public class class_name {
private void setTree(ComponentTree tree) {
synchronized (this) {
this.tree = tree;
for (ComponentVertex child : children) {
child.setTree(tree);
}
}
} } | public class class_name {
private void setTree(ComponentTree tree) {
synchronized (this) {
this.tree = tree;
for (ComponentVertex child : children) {
child.setTree(tree); // depends on control dependency: [for], data = [child]
}
}
} } |
public class class_name {
public static boolean canSwapRows(Matrix matrix, int row1, int row2, int col1) {
boolean response = true;
for (int col = 0; col < col1; ++col) {
if (0 == matrix.getAsDouble(row1, col)) {
if (0 != matrix.getAsDouble(row2, col)) {
response = false;
break;
}
}
}
return response;
} } | public class class_name {
public static boolean canSwapRows(Matrix matrix, int row1, int row2, int col1) {
boolean response = true;
for (int col = 0; col < col1; ++col) {
if (0 == matrix.getAsDouble(row1, col)) {
if (0 != matrix.getAsDouble(row2, col)) {
response = false; // depends on control dependency: [if], data = [none]
break;
}
}
}
return response;
} } |
public class class_name {
public ListProtectedResourcesResult withResults(ProtectedResource... results) {
if (this.results == null) {
setResults(new java.util.ArrayList<ProtectedResource>(results.length));
}
for (ProtectedResource ele : results) {
this.results.add(ele);
}
return this;
} } | public class class_name {
public ListProtectedResourcesResult withResults(ProtectedResource... results) {
if (this.results == null) {
setResults(new java.util.ArrayList<ProtectedResource>(results.length)); // depends on control dependency: [if], data = [none]
}
for (ProtectedResource ele : results) {
this.results.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void marshall(NotifyWhenUploadedRequest notifyWhenUploadedRequest, ProtocolMarshaller protocolMarshaller) {
if (notifyWhenUploadedRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(notifyWhenUploadedRequest.getFileShareARN(), FILESHAREARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(NotifyWhenUploadedRequest notifyWhenUploadedRequest, ProtocolMarshaller protocolMarshaller) {
if (notifyWhenUploadedRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(notifyWhenUploadedRequest.getFileShareARN(), FILESHAREARN_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 SubMenuItem findParent(MenuItem toFind) {
synchronized (subMenuItems) {
SubMenuItem parent = MenuTree.ROOT;
for (Map.Entry<MenuItem, ArrayList<MenuItem>> entry : subMenuItems.entrySet()) {
for (MenuItem item : entry.getValue()) {
if (item.getId() == toFind.getId()) {
parent = asSubMenu(entry.getKey());
}
}
}
return parent;
}
} } | public class class_name {
public SubMenuItem findParent(MenuItem toFind) {
synchronized (subMenuItems) {
SubMenuItem parent = MenuTree.ROOT;
for (Map.Entry<MenuItem, ArrayList<MenuItem>> entry : subMenuItems.entrySet()) {
for (MenuItem item : entry.getValue()) {
if (item.getId() == toFind.getId()) {
parent = asSubMenu(entry.getKey()); // depends on control dependency: [if], data = [none]
}
}
}
return parent;
}
} } |
public class class_name {
private TreeMap<Integer, Integer> createResourceMap(FieldMap fieldMap, FixedMeta rscFixedMeta, FixedData rscFixedData)
{
TreeMap<Integer, Integer> resourceMap = new TreeMap<Integer, Integer>();
int itemCount = rscFixedMeta.getAdjustedItemCount();
for (int loop = 0; loop < itemCount; loop++)
{
byte[] data = rscFixedData.getByteArrayValue(loop);
if (data == null || data.length < fieldMap.getMaxFixedDataSize(0))
{
continue;
}
Integer uniqueID = Integer.valueOf(MPPUtility.getShort(data, 0));
resourceMap.put(uniqueID, Integer.valueOf(loop));
}
return (resourceMap);
} } | public class class_name {
private TreeMap<Integer, Integer> createResourceMap(FieldMap fieldMap, FixedMeta rscFixedMeta, FixedData rscFixedData)
{
TreeMap<Integer, Integer> resourceMap = new TreeMap<Integer, Integer>();
int itemCount = rscFixedMeta.getAdjustedItemCount();
for (int loop = 0; loop < itemCount; loop++)
{
byte[] data = rscFixedData.getByteArrayValue(loop);
if (data == null || data.length < fieldMap.getMaxFixedDataSize(0))
{
continue;
}
Integer uniqueID = Integer.valueOf(MPPUtility.getShort(data, 0));
resourceMap.put(uniqueID, Integer.valueOf(loop)); // depends on control dependency: [for], data = [loop]
}
return (resourceMap);
} } |
public class class_name {
private List<CmsSearchResult> getSearchResults(Map<String, String> params) {
if (m_searchResults == null) {
m_searchResults = getSearchBean(params).getSearchResult();
}
return m_searchResults;
} } | public class class_name {
private List<CmsSearchResult> getSearchResults(Map<String, String> params) {
if (m_searchResults == null) {
m_searchResults = getSearchBean(params).getSearchResult(); // depends on control dependency: [if], data = [none]
}
return m_searchResults;
} } |
public class class_name {
public void fieldToData(ComponentCache componentCache, int iRowIndex, int iColumnIndex)
{
if (componentCache.m_rgcompoments[iColumnIndex] != null)
{
Object object = this.getModel().getValueAt(iRowIndex, iColumnIndex);
String string = "";
if (object != null)
string = object.toString();
if (componentCache.m_rgcompoments[iColumnIndex] instanceof JTextComponent)
((JTextComponent)componentCache.m_rgcompoments[iColumnIndex]).setText(string);
else if (componentCache.m_rgcompoments[iColumnIndex] instanceof JCheckBox)
{
boolean bIsSelected = false;
if (string != null) if (string.equals("1"))
bIsSelected = true;
((JCheckBox)componentCache.m_rgcompoments[iColumnIndex]).setSelected(bIsSelected);
}
}
} } | public class class_name {
public void fieldToData(ComponentCache componentCache, int iRowIndex, int iColumnIndex)
{
if (componentCache.m_rgcompoments[iColumnIndex] != null)
{
Object object = this.getModel().getValueAt(iRowIndex, iColumnIndex);
String string = "";
if (object != null)
string = object.toString();
if (componentCache.m_rgcompoments[iColumnIndex] instanceof JTextComponent)
((JTextComponent)componentCache.m_rgcompoments[iColumnIndex]).setText(string);
else if (componentCache.m_rgcompoments[iColumnIndex] instanceof JCheckBox)
{
boolean bIsSelected = false;
if (string != null) if (string.equals("1"))
bIsSelected = true;
((JCheckBox)componentCache.m_rgcompoments[iColumnIndex]).setSelected(bIsSelected); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public void pushDistribCfg2Clients(final ODocument iConfig) {
if (iConfig == null)
return;
final Set<String> pushed = new HashSet<String>();
for (OClientConnection c : connections.values()) {
if (!c.getData().supportsLegacyPushMessages)
continue;
try {
final String remoteAddress = c.getRemoteAddress();
if (pushed.contains(remoteAddress))
// ALREADY SENT: JUMP IT
continue;
} catch (Exception e) {
// SOCKET EXCEPTION SKIP IT
continue;
}
if (!(c.getProtocol() instanceof ONetworkProtocolBinary) || c.getData().getSerializationImpl() == null)
// INVOLVE ONLY BINARY PROTOCOLS
continue;
final ONetworkProtocolBinary p = (ONetworkProtocolBinary) c.getProtocol();
final OChannelBinary channel = p.getChannel();
final ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(c.getData().getSerializationImpl());
if (ser == null)
return;
final byte[] content = ser.toStream(iConfig, false);
try {
// TRY ACQUIRING THE LOCK FOR MAXIMUM 3 SECS TO AVOID TO FREEZE CURRENT THREAD
if (channel.tryAcquireWriteLock(TIMEOUT_PUSH)) {
try {
channel.writeByte(OChannelBinaryProtocol.PUSH_DATA);
channel.writeInt(Integer.MIN_VALUE);
channel.writeByte(OChannelBinaryProtocol.REQUEST_PUSH_DISTRIB_CONFIG);
channel.writeBytes(content);
channel.flush();
pushed.add(c.getRemoteAddress());
OLogManager.instance().debug(this, "Sent updated cluster configuration to the remote client %s", c.getRemoteAddress());
} finally {
channel.releaseWriteLock();
}
} else {
OLogManager.instance()
.info(this, "Timeout on sending updated cluster configuration to the remote client %s", c.getRemoteAddress());
}
} catch (Exception e) {
OLogManager.instance().warn(this, "Cannot push cluster configuration to the client %s", e, c.getRemoteAddress());
}
}
} } | public class class_name {
public void pushDistribCfg2Clients(final ODocument iConfig) {
if (iConfig == null)
return;
final Set<String> pushed = new HashSet<String>();
for (OClientConnection c : connections.values()) {
if (!c.getData().supportsLegacyPushMessages)
continue;
try {
final String remoteAddress = c.getRemoteAddress();
if (pushed.contains(remoteAddress))
// ALREADY SENT: JUMP IT
continue;
} catch (Exception e) {
// SOCKET EXCEPTION SKIP IT
continue;
} // depends on control dependency: [catch], data = [none]
if (!(c.getProtocol() instanceof ONetworkProtocolBinary) || c.getData().getSerializationImpl() == null)
// INVOLVE ONLY BINARY PROTOCOLS
continue;
final ONetworkProtocolBinary p = (ONetworkProtocolBinary) c.getProtocol();
final OChannelBinary channel = p.getChannel();
final ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(c.getData().getSerializationImpl());
if (ser == null)
return;
final byte[] content = ser.toStream(iConfig, false);
try {
// TRY ACQUIRING THE LOCK FOR MAXIMUM 3 SECS TO AVOID TO FREEZE CURRENT THREAD
if (channel.tryAcquireWriteLock(TIMEOUT_PUSH)) {
try {
channel.writeByte(OChannelBinaryProtocol.PUSH_DATA); // depends on control dependency: [try], data = [none]
channel.writeInt(Integer.MIN_VALUE); // depends on control dependency: [try], data = [none]
channel.writeByte(OChannelBinaryProtocol.REQUEST_PUSH_DISTRIB_CONFIG); // depends on control dependency: [try], data = [none]
channel.writeBytes(content); // depends on control dependency: [try], data = [none]
channel.flush(); // depends on control dependency: [try], data = [none]
pushed.add(c.getRemoteAddress()); // depends on control dependency: [try], data = [none]
OLogManager.instance().debug(this, "Sent updated cluster configuration to the remote client %s", c.getRemoteAddress()); // depends on control dependency: [try], data = [none]
} finally {
channel.releaseWriteLock();
}
} else {
OLogManager.instance()
.info(this, "Timeout on sending updated cluster configuration to the remote client %s", c.getRemoteAddress()); // depends on control dependency: [if], data = [none]
}
} catch (Exception e) {
OLogManager.instance().warn(this, "Cannot push cluster configuration to the client %s", e, c.getRemoteAddress());
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
void formatDayOfYear(StringBuilder b, ZonedDateTime d, int width) {
int day = d.getDayOfYear();
int digits = day < 10 ? 1 : day < 100 ? 2 : 3;
switch (digits) {
case 1:
if (width > 1) {
b.append('0');
}
// fall through
case 2:
if (width > 2) {
b.append('0');
}
// fall through
case 3:
b.append(day);
break;
}
} } | public class class_name {
void formatDayOfYear(StringBuilder b, ZonedDateTime d, int width) {
int day = d.getDayOfYear();
int digits = day < 10 ? 1 : day < 100 ? 2 : 3;
switch (digits) {
case 1:
if (width > 1) {
b.append('0'); // depends on control dependency: [if], data = [none]
}
// fall through
case 2:
if (width > 2) {
b.append('0'); // depends on control dependency: [if], data = [none]
}
// fall through
case 3:
b.append(day);
break;
}
} } |
public class class_name {
private void cleanup() {
if ((++counter & 0xFF) != 0) { // (++counter % 256) != 0
return;
}
final long currentTimeNanos = System.nanoTime();
if (currentTimeNanos - lastCleanupTimeNanos < CLEANUP_INTERVAL_NANOS) {
return;
}
for (final Iterator<State> i = map.values().iterator(); i.hasNext();) {
final State state = i.next();
final boolean remove;
synchronized (state) {
remove = state.allActiveRequests == 0 &&
currentTimeNanos - state.lastActivityTimeNanos >= CLEANUP_INTERVAL_NANOS;
}
if (remove) {
i.remove();
}
}
lastCleanupTimeNanos = System.nanoTime();
} } | public class class_name {
private void cleanup() {
if ((++counter & 0xFF) != 0) { // (++counter % 256) != 0
return; // depends on control dependency: [if], data = [none]
}
final long currentTimeNanos = System.nanoTime();
if (currentTimeNanos - lastCleanupTimeNanos < CLEANUP_INTERVAL_NANOS) {
return; // depends on control dependency: [if], data = [none]
}
for (final Iterator<State> i = map.values().iterator(); i.hasNext();) {
final State state = i.next();
final boolean remove;
synchronized (state) { // depends on control dependency: [for], data = [none]
remove = state.allActiveRequests == 0 &&
currentTimeNanos - state.lastActivityTimeNanos >= CLEANUP_INTERVAL_NANOS;
}
if (remove) {
i.remove(); // depends on control dependency: [if], data = [none]
}
}
lastCleanupTimeNanos = System.nanoTime();
} } |
public class class_name {
public void closeFile() {
if (getZipFile() != null) {
try {
getZipFile().close();
} catch (IOException e) {
CmsMessageContainer message = Messages.get().container(
Messages.ERR_IMPORTEXPORT_ERROR_CLOSING_ZIP_ARCHIVE_1,
getZipFile().getName());
if (LOG.isDebugEnabled()) {
LOG.debug(message.key(), e);
}
}
}
} } | public class class_name {
public void closeFile() {
if (getZipFile() != null) {
try {
getZipFile().close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
CmsMessageContainer message = Messages.get().container(
Messages.ERR_IMPORTEXPORT_ERROR_CLOSING_ZIP_ARCHIVE_1,
getZipFile().getName());
if (LOG.isDebugEnabled()) {
LOG.debug(message.key(), e); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
private Variable scope(Data data, Identifier id, Position line) throws TemplateException {
String idStr = id.getUpper();
if (idStr.equals("ARGUMENTS")) return data.factory.createVariable(Scope.SCOPE_ARGUMENTS, line, data.srcCode.getPosition());
else if (idStr.equals("LOCAL")) return data.factory.createVariable(Scope.SCOPE_LOCAL, line, data.srcCode.getPosition());
else if (idStr.equals("VAR")) {
Identifier _id = identifier(data, false, true);
if (_id != null) {
comments(data);
Variable local = data.factory.createVariable(ScopeSupport.SCOPE_VAR, line, data.srcCode.getPosition());
if (!"LOCAL".equalsIgnoreCase(_id.getString())) local.addMember(data.factory.createDataMember(_id));
else {
local.ignoredFirstMember(true);
}
return local;
}
}
else if (idStr.equals("VARIABLES")) return data.factory.createVariable(Scope.SCOPE_VARIABLES, line, data.srcCode.getPosition());
else if (idStr.equals("REQUEST")) return data.factory.createVariable(Scope.SCOPE_REQUEST, line, data.srcCode.getPosition());
else if (idStr.equals("SERVER")) return data.factory.createVariable(Scope.SCOPE_SERVER, line, data.srcCode.getPosition());
if (data.settings.ignoreScopes) return null;
if (idStr.equals("CGI")) return data.factory.createVariable(Scope.SCOPE_CGI, line, data.srcCode.getPosition());
else if (idStr.equals("SESSION")) return data.factory.createVariable(Scope.SCOPE_SESSION, line, data.srcCode.getPosition());
else if (idStr.equals("APPLICATION")) return data.factory.createVariable(Scope.SCOPE_APPLICATION, line, data.srcCode.getPosition());
else if (idStr.equals("FORM")) return data.factory.createVariable(Scope.SCOPE_FORM, line, data.srcCode.getPosition());
else if (idStr.equals("URL")) return data.factory.createVariable(Scope.SCOPE_URL, line, data.srcCode.getPosition());
else if (idStr.equals("CLIENT")) return data.factory.createVariable(Scope.SCOPE_CLIENT, line, data.srcCode.getPosition());
else if (idStr.equals("COOKIE")) return data.factory.createVariable(Scope.SCOPE_COOKIE, line, data.srcCode.getPosition());
else if (idStr.equals("CLUSTER")) return data.factory.createVariable(Scope.SCOPE_CLUSTER, line, data.srcCode.getPosition());
return null;
} } | public class class_name {
private Variable scope(Data data, Identifier id, Position line) throws TemplateException {
String idStr = id.getUpper();
if (idStr.equals("ARGUMENTS")) return data.factory.createVariable(Scope.SCOPE_ARGUMENTS, line, data.srcCode.getPosition());
else if (idStr.equals("LOCAL")) return data.factory.createVariable(Scope.SCOPE_LOCAL, line, data.srcCode.getPosition());
else if (idStr.equals("VAR")) {
Identifier _id = identifier(data, false, true);
if (_id != null) {
comments(data); // depends on control dependency: [if], data = [none]
Variable local = data.factory.createVariable(ScopeSupport.SCOPE_VAR, line, data.srcCode.getPosition());
if (!"LOCAL".equalsIgnoreCase(_id.getString())) local.addMember(data.factory.createDataMember(_id));
else {
local.ignoredFirstMember(true); // depends on control dependency: [if], data = [none]
}
return local; // depends on control dependency: [if], data = [none]
}
}
else if (idStr.equals("VARIABLES")) return data.factory.createVariable(Scope.SCOPE_VARIABLES, line, data.srcCode.getPosition());
else if (idStr.equals("REQUEST")) return data.factory.createVariable(Scope.SCOPE_REQUEST, line, data.srcCode.getPosition());
else if (idStr.equals("SERVER")) return data.factory.createVariable(Scope.SCOPE_SERVER, line, data.srcCode.getPosition());
if (data.settings.ignoreScopes) return null;
if (idStr.equals("CGI")) return data.factory.createVariable(Scope.SCOPE_CGI, line, data.srcCode.getPosition());
else if (idStr.equals("SESSION")) return data.factory.createVariable(Scope.SCOPE_SESSION, line, data.srcCode.getPosition());
else if (idStr.equals("APPLICATION")) return data.factory.createVariable(Scope.SCOPE_APPLICATION, line, data.srcCode.getPosition());
else if (idStr.equals("FORM")) return data.factory.createVariable(Scope.SCOPE_FORM, line, data.srcCode.getPosition());
else if (idStr.equals("URL")) return data.factory.createVariable(Scope.SCOPE_URL, line, data.srcCode.getPosition());
else if (idStr.equals("CLIENT")) return data.factory.createVariable(Scope.SCOPE_CLIENT, line, data.srcCode.getPosition());
else if (idStr.equals("COOKIE")) return data.factory.createVariable(Scope.SCOPE_COOKIE, line, data.srcCode.getPosition());
else if (idStr.equals("CLUSTER")) return data.factory.createVariable(Scope.SCOPE_CLUSTER, line, data.srcCode.getPosition());
return null;
} } |
public class class_name {
public Region withRelationalDatabaseAvailabilityZones(AvailabilityZone... relationalDatabaseAvailabilityZones) {
if (this.relationalDatabaseAvailabilityZones == null) {
setRelationalDatabaseAvailabilityZones(new java.util.ArrayList<AvailabilityZone>(relationalDatabaseAvailabilityZones.length));
}
for (AvailabilityZone ele : relationalDatabaseAvailabilityZones) {
this.relationalDatabaseAvailabilityZones.add(ele);
}
return this;
} } | public class class_name {
public Region withRelationalDatabaseAvailabilityZones(AvailabilityZone... relationalDatabaseAvailabilityZones) {
if (this.relationalDatabaseAvailabilityZones == null) {
setRelationalDatabaseAvailabilityZones(new java.util.ArrayList<AvailabilityZone>(relationalDatabaseAvailabilityZones.length)); // depends on control dependency: [if], data = [none]
}
for (AvailabilityZone ele : relationalDatabaseAvailabilityZones) {
this.relationalDatabaseAvailabilityZones.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static void traceStateChanged(final TraceComponent traceComponent) {
if (instrumentation == null) {
return;
}
if (!injectAtTransform && traceComponent.isEntryEnabled()) {
final Class<?> traceClass = traceComponent.getTraceClass();
if ((traceClass != null) && (traceClass != LibertyRuntimeTransformer.class)) {
LibertyRuntimeTransformer.addTransformer();
traceComponentByClass.put(traceClass, new WeakReference<TraceComponent>(traceComponent));
//if (retransformExecutor == null) {
retransformClass(traceClass);
// } else {
// // IBM Hot Code Replace Bug:
// // Run async on another thread so this thread can return from <clinit>
// retransformExecutor.execute(new Runnable() {
// @Override
// public void run() {
// retransformClass(traceClass);
// }
// });
// }
}
}
} } | public class class_name {
public static void traceStateChanged(final TraceComponent traceComponent) {
if (instrumentation == null) {
return; // depends on control dependency: [if], data = [none]
}
if (!injectAtTransform && traceComponent.isEntryEnabled()) {
final Class<?> traceClass = traceComponent.getTraceClass();
if ((traceClass != null) && (traceClass != LibertyRuntimeTransformer.class)) {
LibertyRuntimeTransformer.addTransformer(); // depends on control dependency: [if], data = [none]
traceComponentByClass.put(traceClass, new WeakReference<TraceComponent>(traceComponent)); // depends on control dependency: [if], data = [none]
//if (retransformExecutor == null) {
retransformClass(traceClass); // depends on control dependency: [if], data = [none]
// } else {
// // IBM Hot Code Replace Bug:
// // Run async on another thread so this thread can return from <clinit>
// retransformExecutor.execute(new Runnable() {
// @Override
// public void run() {
// retransformClass(traceClass);
// }
// });
// }
}
}
} } |
public class class_name {
private void initGraphics() {
// Set initial size
if (Double.compare(gauge.getPrefWidth(), 0.0) <= 0 || Double.compare(gauge.getPrefHeight(), 0.0) <= 0 ||
Double.compare(gauge.getWidth(), 0.0) <= 0 || Double.compare(gauge.getHeight(), 0.0) <= 0) {
if (gauge.getPrefWidth() > 0 && gauge.getPrefHeight() > 0) {
gauge.setPrefSize(gauge.getPrefWidth(), gauge.getPrefHeight());
} else {
gauge.setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT);
}
}
barBackground = new Arc(PREFERRED_WIDTH * 0.5, PREFERRED_HEIGHT * 0.696, PREFERRED_WIDTH * 0.275, PREFERRED_WIDTH * 0.275, angleRange * 0.5 + 90, -angleRange);
barBackground.setType(ArcType.OPEN);
barBackground.setStroke(gauge.getBarBackgroundColor());
barBackground.setStrokeWidth(PREFERRED_WIDTH * 0.02819549 * 2);
barBackground.setStrokeLineCap(StrokeLineCap.BUTT);
barBackground.setFill(null);
sectionLayer = new Pane();
sectionLayer.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY)));
bar = new Arc(PREFERRED_WIDTH * 0.5, PREFERRED_HEIGHT * 0.696, PREFERRED_WIDTH * 0.275, PREFERRED_WIDTH * 0.275, angleRange * 0.5 + 90, 0);
bar.setType(ArcType.OPEN);
bar.setStroke(gauge.getBarColor());
bar.setStrokeWidth(PREFERRED_WIDTH * 0.02819549 * 2);
bar.setStrokeLineCap(StrokeLineCap.BUTT);
bar.setFill(null);
//bar.setMouseTransparent(sectionsAlwaysVisible ? true : false);
bar.setVisible(!sectionsAlwaysVisible);
needleRotate = new Rotate((gauge.getValue() - oldValue - minValue) * angleStep);
needleMoveTo1 = new MoveTo();
needleCubicCurveTo2 = new CubicCurveTo();
needleCubicCurveTo3 = new CubicCurveTo();
needleCubicCurveTo4 = new CubicCurveTo();
needleCubicCurveTo5 = new CubicCurveTo();
needleCubicCurveTo6 = new CubicCurveTo();
needleCubicCurveTo7 = new CubicCurveTo();
needleClosePath8 = new ClosePath();
needle = new Path(needleMoveTo1, needleCubicCurveTo2, needleCubicCurveTo3, needleCubicCurveTo4, needleCubicCurveTo5, needleCubicCurveTo6, needleCubicCurveTo7, needleClosePath8);
needle.setFillRule(FillRule.EVEN_ODD);
needle.getTransforms().setAll(needleRotate);
needle.setFill(gauge.getNeedleColor());
needle.setPickOnBounds(false);
needle.setStrokeType(StrokeType.INSIDE);
needle.setStrokeWidth(1);
needle.setStroke(gauge.getBackgroundPaint());
needleTooltip = new Tooltip(String.format(locale, formatString, gauge.getValue()));
needleTooltip.setTextAlignment(TextAlignment.CENTER);
Tooltip.install(needle, needleTooltip);
minValueText = new Text(String.format(locale, "%." + gauge.getTickLabelDecimals() + "f", gauge.getMinValue()));
minValueText.setFill(gauge.getTitleColor());
Helper.enableNode(minValueText, gauge.getTickLabelsVisible());
maxValueText = new Text(String.format(locale, "%." + gauge.getTickLabelDecimals() + "f", gauge.getMaxValue()));
maxValueText.setFill(gauge.getTitleColor());
Helper.enableNode(maxValueText, gauge.getTickLabelsVisible());
titleText = new Text(gauge.getTitle());
titleText.setFill(gauge.getTitleColor());
Helper.enableNode(titleText, !gauge.getTitle().isEmpty());
if (!sections.isEmpty() && sectionsVisible && !sectionsAlwaysVisible) {
barTooltip = new Tooltip();
barTooltip.setTextAlignment(TextAlignment.CENTER);
Tooltip.install(bar, barTooltip);
}
pane = new Pane(barBackground, sectionLayer, bar, needle, minValueText, maxValueText, titleText);
pane.setBorder(new Border(new BorderStroke(gauge.getBorderPaint(), BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(gauge.getBorderWidth()))));
pane.setBackground(new Background(new BackgroundFill(gauge.getBackgroundPaint(), CornerRadii.EMPTY, Insets.EMPTY)));
getChildren().setAll(pane);
} } | public class class_name {
private void initGraphics() {
// Set initial size
if (Double.compare(gauge.getPrefWidth(), 0.0) <= 0 || Double.compare(gauge.getPrefHeight(), 0.0) <= 0 ||
Double.compare(gauge.getWidth(), 0.0) <= 0 || Double.compare(gauge.getHeight(), 0.0) <= 0) {
if (gauge.getPrefWidth() > 0 && gauge.getPrefHeight() > 0) {
gauge.setPrefSize(gauge.getPrefWidth(), gauge.getPrefHeight()); // depends on control dependency: [if], data = [(gauge.getPrefWidth()]
} else {
gauge.setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); // depends on control dependency: [if], data = [none]
}
}
barBackground = new Arc(PREFERRED_WIDTH * 0.5, PREFERRED_HEIGHT * 0.696, PREFERRED_WIDTH * 0.275, PREFERRED_WIDTH * 0.275, angleRange * 0.5 + 90, -angleRange);
barBackground.setType(ArcType.OPEN);
barBackground.setStroke(gauge.getBarBackgroundColor());
barBackground.setStrokeWidth(PREFERRED_WIDTH * 0.02819549 * 2);
barBackground.setStrokeLineCap(StrokeLineCap.BUTT);
barBackground.setFill(null);
sectionLayer = new Pane();
sectionLayer.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY)));
bar = new Arc(PREFERRED_WIDTH * 0.5, PREFERRED_HEIGHT * 0.696, PREFERRED_WIDTH * 0.275, PREFERRED_WIDTH * 0.275, angleRange * 0.5 + 90, 0);
bar.setType(ArcType.OPEN);
bar.setStroke(gauge.getBarColor());
bar.setStrokeWidth(PREFERRED_WIDTH * 0.02819549 * 2);
bar.setStrokeLineCap(StrokeLineCap.BUTT);
bar.setFill(null);
//bar.setMouseTransparent(sectionsAlwaysVisible ? true : false);
bar.setVisible(!sectionsAlwaysVisible);
needleRotate = new Rotate((gauge.getValue() - oldValue - minValue) * angleStep);
needleMoveTo1 = new MoveTo();
needleCubicCurveTo2 = new CubicCurveTo();
needleCubicCurveTo3 = new CubicCurveTo();
needleCubicCurveTo4 = new CubicCurveTo();
needleCubicCurveTo5 = new CubicCurveTo();
needleCubicCurveTo6 = new CubicCurveTo();
needleCubicCurveTo7 = new CubicCurveTo();
needleClosePath8 = new ClosePath();
needle = new Path(needleMoveTo1, needleCubicCurveTo2, needleCubicCurveTo3, needleCubicCurveTo4, needleCubicCurveTo5, needleCubicCurveTo6, needleCubicCurveTo7, needleClosePath8);
needle.setFillRule(FillRule.EVEN_ODD);
needle.getTransforms().setAll(needleRotate);
needle.setFill(gauge.getNeedleColor());
needle.setPickOnBounds(false);
needle.setStrokeType(StrokeType.INSIDE);
needle.setStrokeWidth(1);
needle.setStroke(gauge.getBackgroundPaint());
needleTooltip = new Tooltip(String.format(locale, formatString, gauge.getValue()));
needleTooltip.setTextAlignment(TextAlignment.CENTER);
Tooltip.install(needle, needleTooltip);
minValueText = new Text(String.format(locale, "%." + gauge.getTickLabelDecimals() + "f", gauge.getMinValue()));
minValueText.setFill(gauge.getTitleColor());
Helper.enableNode(minValueText, gauge.getTickLabelsVisible());
maxValueText = new Text(String.format(locale, "%." + gauge.getTickLabelDecimals() + "f", gauge.getMaxValue()));
maxValueText.setFill(gauge.getTitleColor());
Helper.enableNode(maxValueText, gauge.getTickLabelsVisible());
titleText = new Text(gauge.getTitle());
titleText.setFill(gauge.getTitleColor());
Helper.enableNode(titleText, !gauge.getTitle().isEmpty());
if (!sections.isEmpty() && sectionsVisible && !sectionsAlwaysVisible) {
barTooltip = new Tooltip(); // depends on control dependency: [if], data = [none]
barTooltip.setTextAlignment(TextAlignment.CENTER); // depends on control dependency: [if], data = [none]
Tooltip.install(bar, barTooltip); // depends on control dependency: [if], data = [none]
}
pane = new Pane(barBackground, sectionLayer, bar, needle, minValueText, maxValueText, titleText);
pane.setBorder(new Border(new BorderStroke(gauge.getBorderPaint(), BorderStrokeStyle.SOLID, CornerRadii.EMPTY, new BorderWidths(gauge.getBorderWidth()))));
pane.setBackground(new Background(new BackgroundFill(gauge.getBackgroundPaint(), CornerRadii.EMPTY, Insets.EMPTY)));
getChildren().setAll(pane);
} } |
public class class_name {
public final boolean declare(String label, BtrpOperand t) {
if (isDeclared(label) && level.get(label) < 0) { //Disallow immutable value
return false;
}
if (!isDeclared(label)) {
level.put(label, currentLevel);
}
type.put(label, t);
return true;
} } | public class class_name {
public final boolean declare(String label, BtrpOperand t) {
if (isDeclared(label) && level.get(label) < 0) { //Disallow immutable value
return false; // depends on control dependency: [if], data = [none]
}
if (!isDeclared(label)) {
level.put(label, currentLevel); // depends on control dependency: [if], data = [none]
}
type.put(label, t);
return true;
} } |
public class class_name {
@Override
public void stopPlayback()
{
if (isNotStoppingNorStopped())
{
setIsStopping();
while (!isStopped())
{
try { Thread.sleep(1); } catch (InterruptedException ex) { /*noop*/ }
}
stopLine();
}
} } | public class class_name {
@Override
public void stopPlayback()
{
if (isNotStoppingNorStopped())
{
setIsStopping(); // depends on control dependency: [if], data = [none]
while (!isStopped())
{
try { Thread.sleep(1); } catch (InterruptedException ex) { /*noop*/ } // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none]
}
stopLine(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public InterceptorBean createInterceptor(
StageLibraryTask stageLib,
InterceptorDefinition definition,
StageConfiguration stageConfiguration,
StageDefinition stageDefinition,
InterceptorCreatorContextBuilder contextBuilder,
InterceptorCreator.InterceptorType interceptorType,
List<Issue> issues
) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InterceptorCreator.Context context = contextBuilder.buildFor(
definition.getLibraryDefinition().getName(),
definition.getKlass().getName(),
stageConfiguration,
stageDefinition,
interceptorType
);
try {
Thread.currentThread().setContextClassLoader(definition.getStageClassLoader());
InterceptorCreator creator = definition.getDefaultCreator().newInstance();
Interceptor interceptor = creator.create(context);
if(interceptor == null) {
return null;
}
return new InterceptorBean(
definition,
interceptor,
stageLib
);
} catch (IllegalAccessException|InstantiationException e) {
LOG.debug("Can't instantiate interceptor: {}", e.toString(), e);
IssueCreator issueCreator = IssueCreator.getStage(stageDefinition.getName());
issues.add(issueCreator.create(
CreationError.CREATION_000, "interceptor", definition.getKlass().getName(), e.toString()
));
} finally {
Thread.currentThread().setContextClassLoader(classLoader);
}
return null;
} } | public class class_name {
public InterceptorBean createInterceptor(
StageLibraryTask stageLib,
InterceptorDefinition definition,
StageConfiguration stageConfiguration,
StageDefinition stageDefinition,
InterceptorCreatorContextBuilder contextBuilder,
InterceptorCreator.InterceptorType interceptorType,
List<Issue> issues
) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InterceptorCreator.Context context = contextBuilder.buildFor(
definition.getLibraryDefinition().getName(),
definition.getKlass().getName(),
stageConfiguration,
stageDefinition,
interceptorType
);
try {
Thread.currentThread().setContextClassLoader(definition.getStageClassLoader()); // depends on control dependency: [try], data = [none]
InterceptorCreator creator = definition.getDefaultCreator().newInstance();
Interceptor interceptor = creator.create(context);
if(interceptor == null) {
return null; // depends on control dependency: [if], data = [none]
}
return new InterceptorBean(
definition,
interceptor,
stageLib
); // depends on control dependency: [try], data = [none]
} catch (IllegalAccessException|InstantiationException e) {
LOG.debug("Can't instantiate interceptor: {}", e.toString(), e);
IssueCreator issueCreator = IssueCreator.getStage(stageDefinition.getName());
issues.add(issueCreator.create(
CreationError.CREATION_000, "interceptor", definition.getKlass().getName(), e.toString()
));
} finally { // depends on control dependency: [catch], data = [none]
Thread.currentThread().setContextClassLoader(classLoader);
}
return null;
} } |
public class class_name {
public SeqnoList getMissing(int max_msgs) {
lock.lock();
try {
if(size == 0)
return null;
long start_seqno=getHighestDeliverable() +1;
int capacity=(int)(hr - start_seqno);
int max_size=max_msgs > 0? Math.min(max_msgs, capacity) : capacity;
if(max_size <= 0)
return null;
Missing missing=new Missing(start_seqno, max_size);
long to=max_size > 0? Math.min(start_seqno + max_size-1, hr-1) : hr-1;
forEach(start_seqno, to, missing);
return missing.getMissingElements();
}
finally {
lock.unlock();
}
} } | public class class_name {
public SeqnoList getMissing(int max_msgs) {
lock.lock();
try {
if(size == 0)
return null;
long start_seqno=getHighestDeliverable() +1;
int capacity=(int)(hr - start_seqno);
int max_size=max_msgs > 0? Math.min(max_msgs, capacity) : capacity;
if(max_size <= 0)
return null;
Missing missing=new Missing(start_seqno, max_size);
long to=max_size > 0? Math.min(start_seqno + max_size-1, hr-1) : hr-1;
forEach(start_seqno, to, missing); // depends on control dependency: [try], data = [none]
return missing.getMissingElements(); // depends on control dependency: [try], data = [none]
}
finally {
lock.unlock();
}
} } |
public class class_name {
public void addChildNodes(NodeData parent, List<NodeData> childs)
{
boolean inTransaction = cache.isTransactionActive();
try
{
if (!inTransaction)
{
cache.beginTransaction();
}
cache.setLocal(true);
Set<Object> set = new HashSet<Object>();
for (NodeData child : childs)
{
putNode(child, ModifyChildOption.NOT_MODIFY);
set.add(child.getIdentifier());
}
cache.putIfAbsent(new CacheNodesId(getOwnerId(), parent.getIdentifier()), set);
}
finally
{
cache.setLocal(false);
if (!inTransaction)
{
dedicatedTxCommit();
}
}
} } | public class class_name {
public void addChildNodes(NodeData parent, List<NodeData> childs)
{
boolean inTransaction = cache.isTransactionActive();
try
{
if (!inTransaction)
{
cache.beginTransaction();
// depends on control dependency: [if], data = [none]
}
cache.setLocal(true);
// depends on control dependency: [try], data = [none]
Set<Object> set = new HashSet<Object>();
for (NodeData child : childs)
{
putNode(child, ModifyChildOption.NOT_MODIFY);
// depends on control dependency: [for], data = [child]
set.add(child.getIdentifier());
// depends on control dependency: [for], data = [child]
}
cache.putIfAbsent(new CacheNodesId(getOwnerId(), parent.getIdentifier()), set);
// depends on control dependency: [try], data = [none]
}
finally
{
cache.setLocal(false);
if (!inTransaction)
{
dedicatedTxCommit();
// depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private void configureSaxonExtensions(SaxonTransformerFactory tfi) {
final net.sf.saxon.Configuration conf = tfi.getConfiguration();
for (ExtensionFunctionDefinition def : ServiceLoader.load(ExtensionFunctionDefinition.class)) {
try {
conf.registerExtensionFunction(def.getClass().newInstance());
} catch (InstantiationException e) {
throw new RuntimeException("Failed to register " + def.getFunctionQName().getDisplayName()
+ ". Cannot create instance of " + def.getClass().getName() + ": " + e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
} } | public class class_name {
private void configureSaxonExtensions(SaxonTransformerFactory tfi) {
final net.sf.saxon.Configuration conf = tfi.getConfiguration();
for (ExtensionFunctionDefinition def : ServiceLoader.load(ExtensionFunctionDefinition.class)) {
try {
conf.registerExtensionFunction(def.getClass().newInstance()); // depends on control dependency: [try], data = [none]
} catch (InstantiationException e) {
throw new RuntimeException("Failed to register " + def.getFunctionQName().getDisplayName()
+ ". Cannot create instance of " + def.getClass().getName() + ": " + e.getMessage(), e);
} catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none]
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
public void setPrivateIpAddressConfigs(java.util.Collection<ScheduledInstancesPrivateIpAddressConfig> privateIpAddressConfigs) {
if (privateIpAddressConfigs == null) {
this.privateIpAddressConfigs = null;
return;
}
this.privateIpAddressConfigs = new com.amazonaws.internal.SdkInternalList<ScheduledInstancesPrivateIpAddressConfig>(privateIpAddressConfigs);
} } | public class class_name {
public void setPrivateIpAddressConfigs(java.util.Collection<ScheduledInstancesPrivateIpAddressConfig> privateIpAddressConfigs) {
if (privateIpAddressConfigs == null) {
this.privateIpAddressConfigs = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.privateIpAddressConfigs = new com.amazonaws.internal.SdkInternalList<ScheduledInstancesPrivateIpAddressConfig>(privateIpAddressConfigs);
} } |
public class class_name {
public static File getServerOutputDir(String serverName, boolean isClient) {
if (serverName == null) {
throw new IllegalArgumentException("Parameter serverName can not be 'null'");
}
File outputDir = Utils.getOutputDir(isClient);
if (outputDir != null) {
return new File(outputDir, serverName);
}
return getServerConfigDir(serverName);
} } | public class class_name {
public static File getServerOutputDir(String serverName, boolean isClient) {
if (serverName == null) {
throw new IllegalArgumentException("Parameter serverName can not be 'null'");
}
File outputDir = Utils.getOutputDir(isClient);
if (outputDir != null) {
return new File(outputDir, serverName); // depends on control dependency: [if], data = [(outputDir]
}
return getServerConfigDir(serverName);
} } |
public class class_name {
public final void setTimeRange (final String rangeStartingTimeString, final String rangeEndingTimeString)
{
String [] rangeStartingTime;
int rStartingHourOfDay;
int rStartingMinute;
int rStartingSecond;
int rStartingMillis;
String [] rEndingTime;
int rEndingHourOfDay;
int rEndingMinute;
int rEndingSecond;
int rEndingMillis;
rangeStartingTime = split (rangeStartingTimeString, colon);
if ((rangeStartingTime.length < 2) || (rangeStartingTime.length > 4))
{
throw new IllegalArgumentException ("Invalid time string '" + rangeStartingTimeString + "'");
}
rStartingHourOfDay = Integer.parseInt (rangeStartingTime[0]);
rStartingMinute = Integer.parseInt (rangeStartingTime[1]);
if (rangeStartingTime.length > 2)
{
rStartingSecond = Integer.parseInt (rangeStartingTime[2]);
}
else
{
rStartingSecond = 0;
}
if (rangeStartingTime.length == 4)
{
rStartingMillis = Integer.parseInt (rangeStartingTime[3]);
}
else
{
rStartingMillis = 0;
}
rEndingTime = split (rangeEndingTimeString, colon);
if ((rEndingTime.length < 2) || (rEndingTime.length > 4))
{
throw new IllegalArgumentException ("Invalid time string '" + rangeEndingTimeString + "'");
}
rEndingHourOfDay = Integer.parseInt (rEndingTime[0]);
rEndingMinute = Integer.parseInt (rEndingTime[1]);
if (rEndingTime.length > 2)
{
rEndingSecond = Integer.parseInt (rEndingTime[2]);
}
else
{
rEndingSecond = 0;
}
if (rEndingTime.length == 4)
{
rEndingMillis = Integer.parseInt (rEndingTime[3]);
}
else
{
rEndingMillis = 0;
}
setTimeRange (rStartingHourOfDay,
rStartingMinute,
rStartingSecond,
rStartingMillis,
rEndingHourOfDay,
rEndingMinute,
rEndingSecond,
rEndingMillis);
} } | public class class_name {
public final void setTimeRange (final String rangeStartingTimeString, final String rangeEndingTimeString)
{
String [] rangeStartingTime;
int rStartingHourOfDay;
int rStartingMinute;
int rStartingSecond;
int rStartingMillis;
String [] rEndingTime;
int rEndingHourOfDay;
int rEndingMinute;
int rEndingSecond;
int rEndingMillis;
rangeStartingTime = split (rangeStartingTimeString, colon);
if ((rangeStartingTime.length < 2) || (rangeStartingTime.length > 4))
{
throw new IllegalArgumentException ("Invalid time string '" + rangeStartingTimeString + "'");
}
rStartingHourOfDay = Integer.parseInt (rangeStartingTime[0]);
rStartingMinute = Integer.parseInt (rangeStartingTime[1]);
if (rangeStartingTime.length > 2)
{
rStartingSecond = Integer.parseInt (rangeStartingTime[2]); // depends on control dependency: [if], data = [none]
}
else
{
rStartingSecond = 0; // depends on control dependency: [if], data = [none]
}
if (rangeStartingTime.length == 4)
{
rStartingMillis = Integer.parseInt (rangeStartingTime[3]); // depends on control dependency: [if], data = [none]
}
else
{
rStartingMillis = 0; // depends on control dependency: [if], data = [none]
}
rEndingTime = split (rangeEndingTimeString, colon);
if ((rEndingTime.length < 2) || (rEndingTime.length > 4))
{
throw new IllegalArgumentException ("Invalid time string '" + rangeEndingTimeString + "'");
}
rEndingHourOfDay = Integer.parseInt (rEndingTime[0]);
rEndingMinute = Integer.parseInt (rEndingTime[1]);
if (rEndingTime.length > 2)
{
rEndingSecond = Integer.parseInt (rEndingTime[2]); // depends on control dependency: [if], data = [none]
}
else
{
rEndingSecond = 0; // depends on control dependency: [if], data = [none]
}
if (rEndingTime.length == 4)
{
rEndingMillis = Integer.parseInt (rEndingTime[3]); // depends on control dependency: [if], data = [none]
}
else
{
rEndingMillis = 0; // depends on control dependency: [if], data = [none]
}
setTimeRange (rStartingHourOfDay,
rStartingMinute,
rStartingSecond,
rStartingMillis,
rEndingHourOfDay,
rEndingMinute,
rEndingSecond,
rEndingMillis);
} } |
public class class_name {
protected List<AuthorizationValue> transform(List<AuthorizationValue> input) {
if (input == null) {
return null;
}
List<AuthorizationValue> output = new ArrayList<>();
for (AuthorizationValue value : input) {
AuthorizationValue v = new AuthorizationValue();
v.setKeyName(value.getKeyName());
v.setValue(value.getValue());
v.setType(value.getType());
output.add(v);
}
return output;
} } | public class class_name {
protected List<AuthorizationValue> transform(List<AuthorizationValue> input) {
if (input == null) {
return null; // depends on control dependency: [if], data = [none]
}
List<AuthorizationValue> output = new ArrayList<>();
for (AuthorizationValue value : input) {
AuthorizationValue v = new AuthorizationValue();
v.setKeyName(value.getKeyName()); // depends on control dependency: [for], data = [value]
v.setValue(value.getValue()); // depends on control dependency: [for], data = [value]
v.setType(value.getType()); // depends on control dependency: [for], data = [value]
output.add(v); // depends on control dependency: [for], data = [none]
}
return output;
} } |
public class class_name {
public short showMessageBox(XWindowPeer _xParentWindowPeer, String _sTitle, String _sMessage, String _aType, int _aButtons) {
short nResult = -1;
XComponent xComponent = null;
try {
Object oToolkit = m_xMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", m_xContext);
XMessageBoxFactory xMessageBoxFactory = (XMessageBoxFactory) UnoRuntime.queryInterface(XMessageBoxFactory.class, oToolkit);
// rectangle may be empty if position is in the center of the parent peer
Rectangle aRectangle = new Rectangle();
XMessageBox xMessageBox = xMessageBoxFactory.createMessageBox(_xParentWindowPeer, aRectangle, _aType, _aButtons, _sTitle, _sMessage);
xComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xMessageBox);
if (xMessageBox != null) {
nResult = xMessageBox.execute();
}
} catch (com.sun.star.uno.Exception ex) {
ex.printStackTrace(System.out);
} finally {
//make sure always to dispose the component and free the memory!
if (xComponent != null) {
xComponent.dispose();
}
}
return nResult;
} } | public class class_name {
public short showMessageBox(XWindowPeer _xParentWindowPeer, String _sTitle, String _sMessage, String _aType, int _aButtons) {
short nResult = -1;
XComponent xComponent = null;
try {
Object oToolkit = m_xMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", m_xContext);
XMessageBoxFactory xMessageBoxFactory = (XMessageBoxFactory) UnoRuntime.queryInterface(XMessageBoxFactory.class, oToolkit);
// rectangle may be empty if position is in the center of the parent peer
Rectangle aRectangle = new Rectangle();
XMessageBox xMessageBox = xMessageBoxFactory.createMessageBox(_xParentWindowPeer, aRectangle, _aType, _aButtons, _sTitle, _sMessage);
xComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xMessageBox); // depends on control dependency: [try], data = [none]
if (xMessageBox != null) {
nResult = xMessageBox.execute(); // depends on control dependency: [if], data = [none]
}
} catch (com.sun.star.uno.Exception ex) {
ex.printStackTrace(System.out);
} finally { // depends on control dependency: [catch], data = [none]
//make sure always to dispose the component and free the memory!
if (xComponent != null) {
xComponent.dispose(); // depends on control dependency: [if], data = [none]
}
}
return nResult;
} } |
public class class_name {
private static CouchbaseResponse handleSubdocumentMultiLookupResponseMessages(BinaryRequest request,
FullBinaryMemcacheResponse msg, ChannelHandlerContext ctx, ResponseStatus status) {
if (!(request instanceof BinarySubdocMultiLookupRequest))
return null;
BinarySubdocMultiLookupRequest subdocRequest = (BinarySubdocMultiLookupRequest) request;
short statusCode = msg.getStatus();
long cas = msg.getCAS();
String bucket = request.bucket();
ByteBuf body = msg.content();
List<MultiResult<Lookup>> responses;
if (status.isSuccess() || ResponseStatus.SUBDOC_MULTI_PATH_FAILURE.equals(status)) {
long bodyLength = body.readableBytes();
List<LookupCommand> commands = subdocRequest.commands();
responses = new ArrayList<MultiResult<Lookup>>(commands.size());
for (LookupCommand cmd : commands) {
if (msg.content().readableBytes() < 6) {
body.release();
throw new IllegalStateException("Expected " + commands.size() + " lookup responses, only got " +
responses.size() + ", total of " + bodyLength + " bytes");
}
short cmdStatus = body.readShort();
int valueLength = body.readInt();
ByteBuf value = ctx.alloc().buffer(valueLength, valueLength);
value.writeBytes(body, valueLength);
responses.add(MultiResult.create(cmdStatus, ResponseStatusConverter.fromBinary(cmdStatus),
cmd.path(), cmd.lookup(), value));
}
} else {
responses = Collections.emptyList();
}
body.release();
return new MultiLookupResponse(status, statusCode, bucket, responses, subdocRequest, cas);
} } | public class class_name {
private static CouchbaseResponse handleSubdocumentMultiLookupResponseMessages(BinaryRequest request,
FullBinaryMemcacheResponse msg, ChannelHandlerContext ctx, ResponseStatus status) {
if (!(request instanceof BinarySubdocMultiLookupRequest))
return null;
BinarySubdocMultiLookupRequest subdocRequest = (BinarySubdocMultiLookupRequest) request;
short statusCode = msg.getStatus();
long cas = msg.getCAS();
String bucket = request.bucket();
ByteBuf body = msg.content();
List<MultiResult<Lookup>> responses;
if (status.isSuccess() || ResponseStatus.SUBDOC_MULTI_PATH_FAILURE.equals(status)) {
long bodyLength = body.readableBytes();
List<LookupCommand> commands = subdocRequest.commands();
responses = new ArrayList<MultiResult<Lookup>>(commands.size()); // depends on control dependency: [if], data = [none]
for (LookupCommand cmd : commands) {
if (msg.content().readableBytes() < 6) {
body.release(); // depends on control dependency: [if], data = [none]
throw new IllegalStateException("Expected " + commands.size() + " lookup responses, only got " +
responses.size() + ", total of " + bodyLength + " bytes");
}
short cmdStatus = body.readShort();
int valueLength = body.readInt();
ByteBuf value = ctx.alloc().buffer(valueLength, valueLength);
value.writeBytes(body, valueLength); // depends on control dependency: [for], data = [none]
responses.add(MultiResult.create(cmdStatus, ResponseStatusConverter.fromBinary(cmdStatus),
cmd.path(), cmd.lookup(), value)); // depends on control dependency: [for], data = [cmd]
}
} else {
responses = Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
body.release();
return new MultiLookupResponse(status, statusCode, bucket, responses, subdocRequest, cas);
} } |
public class class_name {
public boolean decode_OpCompleteParm() throws ParserException {
boolean decoded = false;
if (chars[index] == 'v' && chars[index + 1] == 'i') {
// VoiceInterruptParm = ViParmToken EQUALS BOOLSTR;
index = index + 3;
boolean boolStrValue = decode_BOOLSTR();
BooleanValue boolValue = new BooleanValue(ParameterEnum.vi, boolStrValue);
value.put(ParameterEnum.vi, boolValue);
decoded = true;
} else if (chars[index] == 'i' && chars[index + 1] == 'k') {
// IntKeySeqParm = IkParmToken EQUALS CommandKeySequence;
index = index + 3;
String cmdKeySequence = "";
if ((chars[index] >= '0' && chars[index] <= '9') || chars[index] == '*' || chars[index] == '#') {
decoded = true;
cmdKeySequence = cmdKeySequence + chars[index];
index++;
for (int i = 1; i < 3 && (index < totalChars); i++) {
if ((chars[index] >= '0' && chars[index] <= '9') || chars[index] == '*' || chars[index] == '#') {
cmdKeySequence = cmdKeySequence + chars[index];
index++;
} else {
break;
}
}
StringValue s = new StringValue(ParameterEnum.ik, cmdKeySequence);
value.put(ParameterEnum.ik, s);
decoded = true;
} else {
throw new ParserException("Decoding of IntKeySeqParm failed");
}
} else if (chars[index] == 'n' && chars[index + 1] == 'a') {
// NumAttemptsParm = NaParmToken EQUALS NUMBER;
index = index + 3;
int number = decode_NUMBER();
NumberValue n = new NumberValue(ParameterEnum.na, number);
value.put(ParameterEnum.na, n);
decoded = true;
} else if (chars[index] == 'a' && chars[index + 1] == 'p') {
// AmtPlayedParm = ApParmToken EQUALS NUMBER;
index = index + 3;
int number = decode_NUMBER();
NumberValue n = new NumberValue(ParameterEnum.ap, number);
value.put(ParameterEnum.ap, n);
decoded = true;
} else if (chars[index] == 'd' && chars[index + 1] == 'c') {
// DigitsColParm = DcParmToken EQUALS KeySequence;
index = index + 3;
String keySequence = "";
if ((chars[index] >= '0' && chars[index] <= '9') || chars[index] == '*' || chars[index] == '#') {
decoded = true;
keySequence = keySequence + chars[index];
index++;
for (int i = 1; i < 64 && (index < totalChars); i++) {
if ((chars[index] >= '0' && chars[index] <= '9') || chars[index] == '*' || chars[index] == '#') {
keySequence = keySequence + chars[index];
index++;
} else {
break;
}
}
StringValue s = new StringValue(ParameterEnum.dc, keySequence);
value.put(ParameterEnum.dc, s);
decoded = true;
} else {
throw new ParserException("Decoding of DigitsColParm failed");
}
} else if (chars[index] == 'r' && chars[index + 1] == 'i') {
// RecordingIdParm = RiParmToken EQUALS NUMBER;
index = index + 3;
int number = decode_NUMBER();
NumberValue n = new NumberValue(ParameterEnum.ri, number);
value.put(ParameterEnum.ri, n);
decoded = true;
} else if (chars[index] == 'r' && chars[index + 1] == 'c') {
// ReturnCodeParm = RcParmToken EQUALS 3*3(DIGIT);
index = index + 3;
String rc = "";
if (chars[index] >= '0' && chars[index] <= '9') {
rc = rc + chars[index];
index++;
if (chars[index] >= '0' && chars[index] <= '9') {
rc = rc + chars[index];
index++;
if (chars[index] >= '0' && chars[index] <= '9') {
rc = rc + chars[index];
index++;
try {
int number = Integer.parseInt(rc);
NumberValue n = new NumberValue(ParameterEnum.rc, number);
value.put(ParameterEnum.rc, n);
decoded = true;
} catch (NumberFormatException e) {
throw new ParserException(
"Decoding of ReturnCodeParm failed. The Return code is not number");
}
} else {
throw new ParserException("Decoding of ReturnCodeParm failed");
}
} else {
throw new ParserException("Decoding of ReturnCodeParm failed");
}
} else {
throw new ParserException("Decoding of ReturnCodeParm failed");
}
} else {
throw new ParserException("Decoding of PlayRecParm failed");
}
return decoded;
} } | public class class_name {
public boolean decode_OpCompleteParm() throws ParserException {
boolean decoded = false;
if (chars[index] == 'v' && chars[index + 1] == 'i') {
// VoiceInterruptParm = ViParmToken EQUALS BOOLSTR;
index = index + 3;
boolean boolStrValue = decode_BOOLSTR();
BooleanValue boolValue = new BooleanValue(ParameterEnum.vi, boolStrValue);
value.put(ParameterEnum.vi, boolValue);
decoded = true;
} else if (chars[index] == 'i' && chars[index + 1] == 'k') {
// IntKeySeqParm = IkParmToken EQUALS CommandKeySequence;
index = index + 3;
String cmdKeySequence = "";
if ((chars[index] >= '0' && chars[index] <= '9') || chars[index] == '*' || chars[index] == '#') {
decoded = true;
cmdKeySequence = cmdKeySequence + chars[index];
index++;
for (int i = 1; i < 3 && (index < totalChars); i++) {
if ((chars[index] >= '0' && chars[index] <= '9') || chars[index] == '*' || chars[index] == '#') {
cmdKeySequence = cmdKeySequence + chars[index]; // depends on control dependency: [if], data = [none]
index++; // depends on control dependency: [if], data = [none]
} else {
break;
}
}
StringValue s = new StringValue(ParameterEnum.ik, cmdKeySequence);
value.put(ParameterEnum.ik, s);
decoded = true;
} else {
throw new ParserException("Decoding of IntKeySeqParm failed");
}
} else if (chars[index] == 'n' && chars[index + 1] == 'a') {
// NumAttemptsParm = NaParmToken EQUALS NUMBER;
index = index + 3;
int number = decode_NUMBER();
NumberValue n = new NumberValue(ParameterEnum.na, number);
value.put(ParameterEnum.na, n);
decoded = true;
} else if (chars[index] == 'a' && chars[index + 1] == 'p') {
// AmtPlayedParm = ApParmToken EQUALS NUMBER;
index = index + 3;
int number = decode_NUMBER();
NumberValue n = new NumberValue(ParameterEnum.ap, number);
value.put(ParameterEnum.ap, n);
decoded = true;
} else if (chars[index] == 'd' && chars[index + 1] == 'c') {
// DigitsColParm = DcParmToken EQUALS KeySequence;
index = index + 3;
String keySequence = "";
if ((chars[index] >= '0' && chars[index] <= '9') || chars[index] == '*' || chars[index] == '#') {
decoded = true;
keySequence = keySequence + chars[index];
index++;
for (int i = 1; i < 64 && (index < totalChars); i++) {
if ((chars[index] >= '0' && chars[index] <= '9') || chars[index] == '*' || chars[index] == '#') {
keySequence = keySequence + chars[index];
index++;
} else {
break;
}
}
StringValue s = new StringValue(ParameterEnum.dc, keySequence);
value.put(ParameterEnum.dc, s);
decoded = true;
} else {
throw new ParserException("Decoding of DigitsColParm failed");
}
} else if (chars[index] == 'r' && chars[index + 1] == 'i') {
// RecordingIdParm = RiParmToken EQUALS NUMBER;
index = index + 3;
int number = decode_NUMBER();
NumberValue n = new NumberValue(ParameterEnum.ri, number);
value.put(ParameterEnum.ri, n);
decoded = true;
} else if (chars[index] == 'r' && chars[index + 1] == 'c') {
// ReturnCodeParm = RcParmToken EQUALS 3*3(DIGIT);
index = index + 3;
String rc = "";
if (chars[index] >= '0' && chars[index] <= '9') {
rc = rc + chars[index];
index++;
if (chars[index] >= '0' && chars[index] <= '9') {
rc = rc + chars[index];
index++;
if (chars[index] >= '0' && chars[index] <= '9') {
rc = rc + chars[index];
index++;
try {
int number = Integer.parseInt(rc);
NumberValue n = new NumberValue(ParameterEnum.rc, number);
value.put(ParameterEnum.rc, n);
decoded = true;
} catch (NumberFormatException e) {
throw new ParserException(
"Decoding of ReturnCodeParm failed. The Return code is not number");
}
} else {
throw new ParserException("Decoding of ReturnCodeParm failed");
}
} else {
throw new ParserException("Decoding of ReturnCodeParm failed");
}
} else {
throw new ParserException("Decoding of ReturnCodeParm failed");
}
} else {
throw new ParserException("Decoding of PlayRecParm failed");
}
return decoded;
} } |
public class class_name {
protected SortedMap<String, String> getParametersToDisplay(List<ParameterSetOperation> params) {
// populate param map with sorted by key: key=index/name, value=first value
SortedMap<String, String> paramMap = new TreeMap<String, String>(new StringAsIntegerComparator());
for (ParameterSetOperation param : params) {
String key = getParameterKeyToDisplay(param);
String value = getParameterValueToDisplay(param);
paramMap.put(key, value);
}
return paramMap;
} } | public class class_name {
protected SortedMap<String, String> getParametersToDisplay(List<ParameterSetOperation> params) {
// populate param map with sorted by key: key=index/name, value=first value
SortedMap<String, String> paramMap = new TreeMap<String, String>(new StringAsIntegerComparator());
for (ParameterSetOperation param : params) {
String key = getParameterKeyToDisplay(param);
String value = getParameterValueToDisplay(param);
paramMap.put(key, value); // depends on control dependency: [for], data = [param]
}
return paramMap;
} } |
public class class_name {
public static String truncate(final String str, final int offset, final int maxWidth) {
if (offset < 0) {
throw new IllegalArgumentException("offset cannot be negative");
}
if (maxWidth < 0) {
throw new IllegalArgumentException("maxWith cannot be negative");
}
if (str == null) {
return null;
}
if (offset > str.length()) {
return EMPTY;
}
if (str.length() > maxWidth) {
final int ix = offset + maxWidth > str.length() ? str.length() : offset + maxWidth;
return str.substring(offset, ix);
}
return str.substring(offset);
} } | public class class_name {
public static String truncate(final String str, final int offset, final int maxWidth) {
if (offset < 0) {
throw new IllegalArgumentException("offset cannot be negative");
}
if (maxWidth < 0) {
throw new IllegalArgumentException("maxWith cannot be negative");
}
if (str == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (offset > str.length()) {
return EMPTY; // depends on control dependency: [if], data = [none]
}
if (str.length() > maxWidth) {
final int ix = offset + maxWidth > str.length() ? str.length() : offset + maxWidth;
return str.substring(offset, ix); // depends on control dependency: [if], data = [none]
}
return str.substring(offset);
} } |
public class class_name {
protected String buildSelectClause(final TableMetadata metadata, final Class<? extends Object> type,
final String sqlIdKeyName) {
final List<? extends TableMetadata.Column> columns = metadata.getColumns();
final StringBuilder sql = new StringBuilder("SELECT ").append("/* ").append(sqlIdKeyName).append(" */")
.append(System.lineSeparator());
boolean firstFlag = true;
for (final TableMetadata.Column col : columns) {
sql.append("\t");
if (firstFlag) {
sql.append(" ");
firstFlag = false;
} else {
sql.append(", ");
}
sql.append(col.getColumnIdentifier()).append("\tAS\t").append(col.getColumnIdentifier());
if (StringUtils.isNotEmpty(col.getRemarks())) {
sql.append("\t").append("-- ").append(col.getRemarks());
}
sql.append(System.lineSeparator());
}
sql.append("FROM ").append(metadata.getTableIdentifier()).append(System.lineSeparator());
return sql.toString();
} } | public class class_name {
protected String buildSelectClause(final TableMetadata metadata, final Class<? extends Object> type,
final String sqlIdKeyName) {
final List<? extends TableMetadata.Column> columns = metadata.getColumns();
final StringBuilder sql = new StringBuilder("SELECT ").append("/* ").append(sqlIdKeyName).append(" */")
.append(System.lineSeparator());
boolean firstFlag = true;
for (final TableMetadata.Column col : columns) {
sql.append("\t"); // depends on control dependency: [for], data = [none]
if (firstFlag) {
sql.append(" "); // depends on control dependency: [if], data = [none]
firstFlag = false; // depends on control dependency: [if], data = [none]
} else {
sql.append(", "); // depends on control dependency: [if], data = [none]
}
sql.append(col.getColumnIdentifier()).append("\tAS\t").append(col.getColumnIdentifier()); // depends on control dependency: [for], data = [col]
if (StringUtils.isNotEmpty(col.getRemarks())) {
sql.append("\t").append("-- ").append(col.getRemarks()); // depends on control dependency: [if], data = [none]
}
sql.append(System.lineSeparator()); // depends on control dependency: [for], data = [none]
}
sql.append("FROM ").append(metadata.getTableIdentifier()).append(System.lineSeparator());
return sql.toString();
} } |
public class class_name {
public void destroyAllSessions ()
{
// destroy all session scopes (use a copy, because we're invalidating
// the sessions internally!)
for (final ISessionScope aSessionScope : getAllSessionScopes ())
{
// Unfortunately we need a special handling here
if (aSessionScope.selfDestruct ().isContinue ())
{
// Remove from map
onScopeEnd (aSessionScope);
}
// Else the destruction was already started!
}
// Sanity check in case something went wrong
_checkIfAnySessionsExist ();
} } | public class class_name {
public void destroyAllSessions ()
{
// destroy all session scopes (use a copy, because we're invalidating
// the sessions internally!)
for (final ISessionScope aSessionScope : getAllSessionScopes ())
{
// Unfortunately we need a special handling here
if (aSessionScope.selfDestruct ().isContinue ())
{
// Remove from map
onScopeEnd (aSessionScope); // depends on control dependency: [if], data = [none]
}
// Else the destruction was already started!
}
// Sanity check in case something went wrong
_checkIfAnySessionsExist ();
} } |
public class class_name {
private void pushTag(String qName) {
final String currentTag = getCurrentTag();
if ("".equals(currentTag)) {
mTagStack.push(qName);
} else {
mTagStack.push(getCurrentTag() + "." + qName);
}
} } | public class class_name {
private void pushTag(String qName) {
final String currentTag = getCurrentTag();
if ("".equals(currentTag)) {
mTagStack.push(qName); // depends on control dependency: [if], data = [none]
} else {
mTagStack.push(getCurrentTag() + "." + qName); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static ApacheHttpClient newApacheHttpClient(HttpClientConfiguration configuration, EmbeddedServer<?> server) {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
if (!configuration.isFollowRedirect()) {
httpClientBuilder.disableRedirectHandling();
}
CloseableHttpClient client = httpClientBuilder.build();
return new ApacheHttpClient(configuration, server, client);
} } | public class class_name {
public static ApacheHttpClient newApacheHttpClient(HttpClientConfiguration configuration, EmbeddedServer<?> server) {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
if (!configuration.isFollowRedirect()) {
httpClientBuilder.disableRedirectHandling(); // depends on control dependency: [if], data = [none]
}
CloseableHttpClient client = httpClientBuilder.build();
return new ApacheHttpClient(configuration, server, client);
} } |
public class class_name {
private boolean drawBitmapAndCache(
int frameNumber,
@Nullable CloseableReference<Bitmap> bitmapReference,
Canvas canvas,
@FrameType int frameType) {
if (!CloseableReference.isValid(bitmapReference)) {
return false;
}
if (mBounds == null) {
canvas.drawBitmap(bitmapReference.get(), 0f, 0f, mPaint);
} else {
canvas.drawBitmap(bitmapReference.get(), null, mBounds, mPaint);
}
// Notify the cache that a frame has been rendered.
// We should not cache fallback frames since they do not represent the actual frame.
if (frameType != FRAME_TYPE_FALLBACK) {
mBitmapFrameCache.onFrameRendered(
frameNumber,
bitmapReference,
frameType);
}
if (mFrameListener != null) {
mFrameListener.onFrameDrawn(this, frameNumber, frameType);
}
return true;
} } | public class class_name {
private boolean drawBitmapAndCache(
int frameNumber,
@Nullable CloseableReference<Bitmap> bitmapReference,
Canvas canvas,
@FrameType int frameType) {
if (!CloseableReference.isValid(bitmapReference)) {
return false; // depends on control dependency: [if], data = [none]
}
if (mBounds == null) {
canvas.drawBitmap(bitmapReference.get(), 0f, 0f, mPaint); // depends on control dependency: [if], data = [none]
} else {
canvas.drawBitmap(bitmapReference.get(), null, mBounds, mPaint); // depends on control dependency: [if], data = [none]
}
// Notify the cache that a frame has been rendered.
// We should not cache fallback frames since they do not represent the actual frame.
if (frameType != FRAME_TYPE_FALLBACK) {
mBitmapFrameCache.onFrameRendered(
frameNumber,
bitmapReference,
frameType); // depends on control dependency: [if], data = [none]
}
if (mFrameListener != null) {
mFrameListener.onFrameDrawn(this, frameNumber, frameType); // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
private synchronized void parseTrustedPrivateHeaderOrigin(String[] trustedPrivateHeaderHosts, String[] trustedSensitiveHeaderHosts) {
// bump the updated count every time we call this.
updateCount.get().incrementAndGet();
// restore defaults
restrictPrivateHeaderOrigin = null;
restrictSensitiveHeaderOrigin = null;
usePrivateHeaders = true;
useSensitivePrivateHeaders = false;
// If trusted=false (non-default), don't allow private headers from any host, regardless of other settings
if (!wcTrusted) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "webcontainer trusted=false; private headers are not trusted from any host");
}
usePrivateHeaders = false;
return;
}
// Parse trustedHeaderOrigin. The default value is * (any host)
List<String> addrs = new ArrayList<String>();
if (trustedPrivateHeaderHosts != null && trustedPrivateHeaderHosts.length > 0) {
for (String ipaddr : trustedPrivateHeaderHosts) {
if ("none".equalsIgnoreCase(ipaddr)) {
// if "none" is listed, private headers are not trusted on any host.
// however any hosts listed in trustedSensitiveHeaderOrigin can still send private headers
usePrivateHeaders = false;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted private headers hosts: none");
}
break;
} else if ("*".equals(ipaddr)) {
// stop processing, empty the list, fall through to below.
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted private headers hosts: *");
}
addrs.clear();
break;
} else {
addrs.add(ipaddr);
}
}
} else {
// no trusted header hosts were defined, use defualt - "*"
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted private headers hosts: *");
}
}
if (usePrivateHeaders) {
// if IP addresses were listed, only trust private headers from those hosts
if (!addrs.isEmpty()) {
restrictPrivateHeaderOrigin = new HashSet<String>();
for (String s : addrs) {
if (s != null && !s.isEmpty()) {
restrictPrivateHeaderOrigin.add(s.toLowerCase());
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted private headers hosts: " + Arrays.toString(addrs.toArray()));
}
}
}
addrs.clear();
// Parse trustedSensiveHeaderOrigin. The default value is none (no hosts trusted)
if (trustedSensitiveHeaderHosts != null && trustedSensitiveHeaderHosts.length > 0) {
for (String ipaddr : trustedSensitiveHeaderHosts) {
if ("none".equalsIgnoreCase(ipaddr)) {
// don't trust sensitive private headers from any host
useSensitivePrivateHeaders = false;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted sensitive private headers hosts: none");
}
return;
} else if ("*".equals(ipaddr)) {
// sensitive private headers trusted from any host
addrs.clear();
useSensitivePrivateHeaders = true;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted sensitive private headers hosts: *");
}
break;
} else {
addrs.add(ipaddr);
useSensitivePrivateHeaders = true;
}
}
} else {
// no trusted sensitive header hosts were defined, use defualt - "none"
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted sensitive private headers hosts: none");
}
return;
}
// if IP addresses were listed, only trust sensitive private headers from those hosts
if (!addrs.isEmpty()) {
restrictSensitiveHeaderOrigin = new HashSet<String>();
for (String s : addrs) {
if (s != null && !s.isEmpty()) {
restrictSensitiveHeaderOrigin.add(s.toLowerCase());
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted sensitive private headers hosts: " + Arrays.toString(addrs.toArray()));
}
}
} } | public class class_name {
private synchronized void parseTrustedPrivateHeaderOrigin(String[] trustedPrivateHeaderHosts, String[] trustedSensitiveHeaderHosts) {
// bump the updated count every time we call this.
updateCount.get().incrementAndGet();
// restore defaults
restrictPrivateHeaderOrigin = null;
restrictSensitiveHeaderOrigin = null;
usePrivateHeaders = true;
useSensitivePrivateHeaders = false;
// If trusted=false (non-default), don't allow private headers from any host, regardless of other settings
if (!wcTrusted) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "webcontainer trusted=false; private headers are not trusted from any host"); // depends on control dependency: [if], data = [none]
}
usePrivateHeaders = false; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// Parse trustedHeaderOrigin. The default value is * (any host)
List<String> addrs = new ArrayList<String>();
if (trustedPrivateHeaderHosts != null && trustedPrivateHeaderHosts.length > 0) {
for (String ipaddr : trustedPrivateHeaderHosts) {
if ("none".equalsIgnoreCase(ipaddr)) {
// if "none" is listed, private headers are not trusted on any host.
// however any hosts listed in trustedSensitiveHeaderOrigin can still send private headers
usePrivateHeaders = false; // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted private headers hosts: none"); // depends on control dependency: [if], data = [none]
}
break;
} else if ("*".equals(ipaddr)) {
// stop processing, empty the list, fall through to below.
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted private headers hosts: *"); // depends on control dependency: [if], data = [none]
}
addrs.clear(); // depends on control dependency: [if], data = [none]
break;
} else {
addrs.add(ipaddr); // depends on control dependency: [if], data = [none]
}
}
} else {
// no trusted header hosts were defined, use defualt - "*"
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted private headers hosts: *"); // depends on control dependency: [if], data = [none]
}
}
if (usePrivateHeaders) {
// if IP addresses were listed, only trust private headers from those hosts
if (!addrs.isEmpty()) {
restrictPrivateHeaderOrigin = new HashSet<String>(); // depends on control dependency: [if], data = [none]
for (String s : addrs) {
if (s != null && !s.isEmpty()) {
restrictPrivateHeaderOrigin.add(s.toLowerCase()); // depends on control dependency: [if], data = [(s]
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted private headers hosts: " + Arrays.toString(addrs.toArray())); // depends on control dependency: [if], data = [none]
}
}
}
addrs.clear();
// Parse trustedSensiveHeaderOrigin. The default value is none (no hosts trusted)
if (trustedSensitiveHeaderHosts != null && trustedSensitiveHeaderHosts.length > 0) {
for (String ipaddr : trustedSensitiveHeaderHosts) {
if ("none".equalsIgnoreCase(ipaddr)) {
// don't trust sensitive private headers from any host
useSensitivePrivateHeaders = false; // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted sensitive private headers hosts: none"); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
} else if ("*".equals(ipaddr)) {
// sensitive private headers trusted from any host
addrs.clear(); // depends on control dependency: [if], data = [none]
useSensitivePrivateHeaders = true; // depends on control dependency: [if], data = [none]
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted sensitive private headers hosts: *"); // depends on control dependency: [if], data = [none]
}
break;
} else {
addrs.add(ipaddr); // depends on control dependency: [if], data = [none]
useSensitivePrivateHeaders = true; // depends on control dependency: [if], data = [none]
}
}
} else {
// no trusted sensitive header hosts were defined, use defualt - "none"
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted sensitive private headers hosts: none"); // depends on control dependency: [if], data = [none]
}
return; // depends on control dependency: [if], data = [none]
}
// if IP addresses were listed, only trust sensitive private headers from those hosts
if (!addrs.isEmpty()) {
restrictSensitiveHeaderOrigin = new HashSet<String>(); // depends on control dependency: [if], data = [none]
for (String s : addrs) {
if (s != null && !s.isEmpty()) {
restrictSensitiveHeaderOrigin.add(s.toLowerCase()); // depends on control dependency: [if], data = [(s]
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "trusted sensitive private headers hosts: " + Arrays.toString(addrs.toArray())); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private String isCheckSum ( final Coordinates c )
{
final String cext = c.getExtension ();
if ( cext == null )
{
return null;
}
for ( final String ext : this.options.getChecksumExtensions () )
{
if ( cext.endsWith ( "." + ext ) )
{
return ext;
}
}
return null;
} } | public class class_name {
private String isCheckSum ( final Coordinates c )
{
final String cext = c.getExtension ();
if ( cext == null )
{
return null; // depends on control dependency: [if], data = [none]
}
for ( final String ext : this.options.getChecksumExtensions () )
{
if ( cext.endsWith ( "." + ext ) )
{
return ext; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
private void executeSql(String databaseKey, String sqlScript, Map<String, String> replacers, boolean abortOnError) {
String filename = null;
try {
filename = m_basePath
+ CmsSetupBean.FOLDER_SETUP
+ "database"
+ File.separator
+ databaseKey
+ File.separator
+ sqlScript;
executeSql(new FileReader(filename), replacers, abortOnError);
} catch (FileNotFoundException e) {
if (m_errorLogging) {
m_errors.add("Database setup SQL script not found: " + filename);
m_errors.add(CmsException.getStackTraceAsString(e));
}
}
} } | public class class_name {
private void executeSql(String databaseKey, String sqlScript, Map<String, String> replacers, boolean abortOnError) {
String filename = null;
try {
filename = m_basePath
+ CmsSetupBean.FOLDER_SETUP
+ "database"
+ File.separator
+ databaseKey
+ File.separator
+ sqlScript; // depends on control dependency: [try], data = [none]
executeSql(new FileReader(filename), replacers, abortOnError); // depends on control dependency: [try], data = [none]
} catch (FileNotFoundException e) {
if (m_errorLogging) {
m_errors.add("Database setup SQL script not found: " + filename); // depends on control dependency: [if], data = [none]
m_errors.add(CmsException.getStackTraceAsString(e)); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <T> T[] toArray(final Object source, final Class<T> wrapperType) {
if (source != null) {
int length = Array.getLength(source);
T[] convertedArray = buildArray(wrapperType, length, null);
for (int i = 0; i < length; i++) {
@SuppressWarnings("unchecked")
T element = (T) Array.get(source, i);
convertedArray[i] = element;
}
return convertedArray;
} else {
return null;
}
} } | public class class_name {
public static <T> T[] toArray(final Object source, final Class<T> wrapperType) {
if (source != null) {
int length = Array.getLength(source);
T[] convertedArray = buildArray(wrapperType, length, null);
for (int i = 0; i < length; i++) {
@SuppressWarnings("unchecked")
T element = (T) Array.get(source, i);
convertedArray[i] = element; // depends on control dependency: [for], data = [i]
}
return convertedArray; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private String getResponseBody(HttpResponse postResponse) {
InputStream input = null;
try {
input = postResponse.getEntity().getContent();
Reader reader = new InputStreamReader(input,
MwsUtl.DEFAULT_ENCODING);
StringBuilder b = new StringBuilder();
char[] c = new char[1024];
int len;
while (0 < (len = reader.read(c))) {
b.append(c, 0, len);
}
return b.toString();
} catch (Exception e) {
throw MwsUtl.wrap(e);
} finally {
MwsUtl.close(input);
}
} } | public class class_name {
private String getResponseBody(HttpResponse postResponse) {
InputStream input = null;
try {
input = postResponse.getEntity().getContent(); // depends on control dependency: [try], data = [none]
Reader reader = new InputStreamReader(input,
MwsUtl.DEFAULT_ENCODING);
StringBuilder b = new StringBuilder();
char[] c = new char[1024];
int len;
while (0 < (len = reader.read(c))) {
b.append(c, 0, len); // depends on control dependency: [while], data = [none]
}
return b.toString(); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw MwsUtl.wrap(e);
} finally { // depends on control dependency: [catch], data = [none]
MwsUtl.close(input);
}
} } |
public class class_name {
public int run(String jobName, String[] args) {
int status = -1;
try {
Class<? extends SimpleJobTool> clazz = jobMap.get(jobName);
if (clazz == null) {
log.error("Tool " + jobName + " class not found.");
return status;
}
status = ToolRunner.run(clazz.newInstance(), args);
} catch (Exception e) {
e.printStackTrace();
log.error(e);
}
return status;
} } | public class class_name {
public int run(String jobName, String[] args) {
int status = -1;
try {
Class<? extends SimpleJobTool> clazz = jobMap.get(jobName);
if (clazz == null) {
log.error("Tool " + jobName + " class not found."); // depends on control dependency: [if], data = [none]
return status; // depends on control dependency: [if], data = [none]
}
status = ToolRunner.run(clazz.newInstance(), args); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
e.printStackTrace();
log.error(e);
} // depends on control dependency: [catch], data = [none]
return status;
} } |
public class class_name {
public static File mkParentDirs(File file) {
final File parentFile = file.getParentFile();
if (null != parentFile && false == parentFile.exists()) {
parentFile.mkdirs();
}
return parentFile;
} } | public class class_name {
public static File mkParentDirs(File file) {
final File parentFile = file.getParentFile();
if (null != parentFile && false == parentFile.exists()) {
parentFile.mkdirs();
// depends on control dependency: [if], data = [none]
}
return parentFile;
} } |
public class class_name {
public EClass getFGD() {
if (fgdEClass == null) {
fgdEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(321);
}
return fgdEClass;
} } | public class class_name {
public EClass getFGD() {
if (fgdEClass == null) {
fgdEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(321); // depends on control dependency: [if], data = [none]
}
return fgdEClass;
} } |
public class class_name {
public CmsUploadProgessInfo getInfo() {
if (m_finished) {
return new CmsUploadProgessInfo(
getItem(),
(int)getPercent(),
UPLOAD_STATE.finished,
getContentLength(),
getBytesRead());
}
return new CmsUploadProgessInfo(
getItem(),
(int)getPercent(),
UPLOAD_STATE.running,
getContentLength(),
getBytesRead());
} } | public class class_name {
public CmsUploadProgessInfo getInfo() {
if (m_finished) {
return new CmsUploadProgessInfo(
getItem(),
(int)getPercent(),
UPLOAD_STATE.finished,
getContentLength(),
getBytesRead()); // depends on control dependency: [if], data = [none]
}
return new CmsUploadProgessInfo(
getItem(),
(int)getPercent(),
UPLOAD_STATE.running,
getContentLength(),
getBytesRead());
} } |
public class class_name {
public static int matchingNibbleLength(byte[] a, byte[] b) {
int i = 0;
int length = a.length < b.length ? a.length : b.length;
while (i < length) {
if (a[i] != b[i])
return i;
i++;
}
return i;
} } | public class class_name {
public static int matchingNibbleLength(byte[] a, byte[] b) {
int i = 0;
int length = a.length < b.length ? a.length : b.length;
while (i < length) {
if (a[i] != b[i])
return i;
i++; // depends on control dependency: [while], data = [none]
}
return i;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.