code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public void marshall(CreateAccountRequest createAccountRequest, ProtocolMarshaller protocolMarshaller) {
if (createAccountRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createAccountRequest.getName(), NAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(CreateAccountRequest createAccountRequest, ProtocolMarshaller protocolMarshaller) {
if (createAccountRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createAccountRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static long computeMsgIdHelper(
ImmutableList<SoyMsgPart> msgParts,
boolean doUseBracedPhs,
@Nullable String meaning,
@Nullable String contentType) {
// Important: Do not change this algorithm. Doing so will break backwards compatibility.
String msgContentStrForMsgIdComputation =
buildMsgContentStrForMsgIdComputation(msgParts, doUseBracedPhs);
long fp = fingerprint(msgContentStrForMsgIdComputation);
// If there is a meaning, incorporate its fingerprint.
if (meaning != null) {
fp = (fp << 1) + (fp < 0 ? 1 : 0) + fingerprint(meaning);
}
// If there is a content type other than "text/html", incorporate its fingerprint.
if (contentType != null && !contentType.equals("text/html")) {
fp = (fp << 1) + (fp < 0 ? 1 : 0) + fingerprint(contentType);
}
// To avoid negative ids we strip the high-order bit.
return fp & 0x7fffffffffffffffL;
} } | public class class_name {
private static long computeMsgIdHelper(
ImmutableList<SoyMsgPart> msgParts,
boolean doUseBracedPhs,
@Nullable String meaning,
@Nullable String contentType) {
// Important: Do not change this algorithm. Doing so will break backwards compatibility.
String msgContentStrForMsgIdComputation =
buildMsgContentStrForMsgIdComputation(msgParts, doUseBracedPhs);
long fp = fingerprint(msgContentStrForMsgIdComputation);
// If there is a meaning, incorporate its fingerprint.
if (meaning != null) {
fp = (fp << 1) + (fp < 0 ? 1 : 0) + fingerprint(meaning); // depends on control dependency: [if], data = [(meaning]
}
// If there is a content type other than "text/html", incorporate its fingerprint.
if (contentType != null && !contentType.equals("text/html")) {
fp = (fp << 1) + (fp < 0 ? 1 : 0) + fingerprint(contentType); // depends on control dependency: [if], data = [(contentType]
}
// To avoid negative ids we strip the high-order bit.
return fp & 0x7fffffffffffffffL;
} } |
public class class_name {
public void addTranslation (String className, String streamedName)
{
if (_translations == null) {
_translations = Maps.newHashMap();
}
_translations.put(className, streamedName);
} } | public class class_name {
public void addTranslation (String className, String streamedName)
{
if (_translations == null) {
_translations = Maps.newHashMap(); // depends on control dependency: [if], data = [none]
}
_translations.put(className, streamedName);
} } |
public class class_name {
public static void goTo(ShanksSimulation simulation,
MobileShanksAgent agent, Location currentLocation,
Location targetLocation, double speed) {
if (currentLocation.is2DLocation() && targetLocation.is2DLocation()) {
ShanksAgentMovementCapability.goTo(simulation, agent,
currentLocation.getLocation2D(),
targetLocation.getLocation2D(), speed);
} else if (currentLocation.is3DLocation()
&& targetLocation.is3DLocation()) {
ShanksAgentMovementCapability.goTo(simulation, agent,
currentLocation.getLocation3D(),
targetLocation.getLocation3D(), speed);
}
} } | public class class_name {
public static void goTo(ShanksSimulation simulation,
MobileShanksAgent agent, Location currentLocation,
Location targetLocation, double speed) {
if (currentLocation.is2DLocation() && targetLocation.is2DLocation()) {
ShanksAgentMovementCapability.goTo(simulation, agent,
currentLocation.getLocation2D(),
targetLocation.getLocation2D(), speed);
// depends on control dependency: [if], data = [none]
} else if (currentLocation.is3DLocation()
&& targetLocation.is3DLocation()) {
ShanksAgentMovementCapability.goTo(simulation, agent,
currentLocation.getLocation3D(),
targetLocation.getLocation3D(), speed);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private final void startHeartbeat() {
if (timerTask == null || HsqlTimer.isCancelled(timerTask)) {
Runnable runner = new HeartbeatRunner();
timerTask = timer.schedulePeriodicallyAfter(0, HEARTBEAT_INTERVAL,
runner, true);
}
} } | public class class_name {
private final void startHeartbeat() {
if (timerTask == null || HsqlTimer.isCancelled(timerTask)) {
Runnable runner = new HeartbeatRunner();
timerTask = timer.schedulePeriodicallyAfter(0, HEARTBEAT_INTERVAL,
runner, true); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Option provision(final InputStream... streams) {
validateNotNull(streams, "streams");
final UrlProvisionOption[] options = new UrlProvisionOption[streams.length];
int i = 0;
for (InputStream stream : streams) {
options[i++] = streamBundle(stream);
}
return provision(options);
} } | public class class_name {
public static Option provision(final InputStream... streams) {
validateNotNull(streams, "streams");
final UrlProvisionOption[] options = new UrlProvisionOption[streams.length];
int i = 0;
for (InputStream stream : streams) {
options[i++] = streamBundle(stream); // depends on control dependency: [for], data = [stream]
}
return provision(options);
} } |
public class class_name {
private static String openTag(String tag, String clazz, String style, boolean contentIsHtml, String... content) {
StringBuilder result = new StringBuilder("<").append(tag);
if (clazz != null && !"".equals(clazz)) {
result.append(" ").append(Html.Attribute.CLASS).append("='").append(clazz).append("'");
}
if (style != null && !"".equals(style)) {
result.append(" ").append(Html.Attribute.STYLE).append("='").append(style).append("'");
}
result.append(">");
if (content != null && content.length > 0) {
for (String c : content) {
if (contentIsHtml) {
result.append(c);
} else {
result.append(htmlEncode(c));
}
}
}
return result.toString();
} } | public class class_name {
private static String openTag(String tag, String clazz, String style, boolean contentIsHtml, String... content) {
StringBuilder result = new StringBuilder("<").append(tag);
if (clazz != null && !"".equals(clazz)) {
result.append(" ").append(Html.Attribute.CLASS).append("='").append(clazz).append("'"); // depends on control dependency: [if], data = [(clazz]
}
if (style != null && !"".equals(style)) {
result.append(" ").append(Html.Attribute.STYLE).append("='").append(style).append("'"); // depends on control dependency: [if], data = [(style]
}
result.append(">");
if (content != null && content.length > 0) {
for (String c : content) {
if (contentIsHtml) {
result.append(c); // depends on control dependency: [if], data = [none]
} else {
result.append(htmlEncode(c)); // depends on control dependency: [if], data = [none]
}
}
}
return result.toString();
} } |
public class class_name {
private boolean addInactive(PeerAddress peerAddress) {
lock.lock();
try {
// Deduplicate
if (backoffMap.containsKey(peerAddress))
return false;
backoffMap.put(peerAddress, new ExponentialBackoff(peerBackoffParams));
inactives.offer(peerAddress);
return true;
} finally {
lock.unlock();
}
} } | public class class_name {
private boolean addInactive(PeerAddress peerAddress) {
lock.lock();
try {
// Deduplicate
if (backoffMap.containsKey(peerAddress))
return false;
backoffMap.put(peerAddress, new ExponentialBackoff(peerBackoffParams)); // depends on control dependency: [try], data = [none]
inactives.offer(peerAddress); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
} finally {
lock.unlock();
}
} } |
public class class_name {
@EachBean(ServiceHttpClientConfiguration.class)
@Requires(condition = ServiceHttpClientCondition.class)
DefaultHttpClient serviceHttpClient(
@Parameter ServiceHttpClientConfiguration configuration,
@Parameter StaticServiceInstanceList instanceList) {
List<URI> originalURLs = configuration.getUrls();
Collection<URI> loadBalancedURIs = instanceList.getLoadBalancedURIs();
boolean isHealthCheck = configuration.isHealthCheck();
LoadBalancer loadBalancer = loadBalancerFactory.create(instanceList);
Optional<String> path = configuration.getPath();
DefaultHttpClient httpClient;
if (path.isPresent()) {
httpClient = beanContext.createBean(DefaultHttpClient.class, loadBalancer, configuration, path.get());
} else {
httpClient = beanContext.createBean(DefaultHttpClient.class, loadBalancer, configuration);
}
httpClient.setClientIdentifiers(configuration.getServiceId());
if (isHealthCheck) {
taskScheduler.scheduleWithFixedDelay(configuration.getHealthCheckInterval(), configuration.getHealthCheckInterval(), () -> Flowable.fromIterable(originalURLs).flatMap(originalURI -> {
URI healthCheckURI = originalURI.resolve(configuration.getHealthCheckUri());
return httpClient.exchange(HttpRequest.GET(healthCheckURI)).onErrorResumeNext(throwable -> {
if (throwable instanceof HttpClientResponseException) {
HttpClientResponseException responseException = (HttpClientResponseException) throwable;
HttpResponse response = responseException.getResponse();
//noinspection unchecked
return Flowable.just(response);
}
return Flowable.just(HttpResponse.serverError());
}).map(response -> Collections.singletonMap(originalURI, response.getStatus()));
}).subscribe(uriToStatusMap -> {
Map.Entry<URI, HttpStatus> entry = uriToStatusMap.entrySet().iterator().next();
URI uri = entry.getKey();
HttpStatus status = entry.getValue();
if (status.getCode() >= 300) {
loadBalancedURIs.remove(uri);
} else if (!loadBalancedURIs.contains(uri)) {
loadBalancedURIs.add(uri);
}
}));
}
return httpClient;
} } | public class class_name {
@EachBean(ServiceHttpClientConfiguration.class)
@Requires(condition = ServiceHttpClientCondition.class)
DefaultHttpClient serviceHttpClient(
@Parameter ServiceHttpClientConfiguration configuration,
@Parameter StaticServiceInstanceList instanceList) {
List<URI> originalURLs = configuration.getUrls();
Collection<URI> loadBalancedURIs = instanceList.getLoadBalancedURIs();
boolean isHealthCheck = configuration.isHealthCheck();
LoadBalancer loadBalancer = loadBalancerFactory.create(instanceList);
Optional<String> path = configuration.getPath();
DefaultHttpClient httpClient;
if (path.isPresent()) {
httpClient = beanContext.createBean(DefaultHttpClient.class, loadBalancer, configuration, path.get()); // depends on control dependency: [if], data = [none]
} else {
httpClient = beanContext.createBean(DefaultHttpClient.class, loadBalancer, configuration); // depends on control dependency: [if], data = [none]
}
httpClient.setClientIdentifiers(configuration.getServiceId());
if (isHealthCheck) {
taskScheduler.scheduleWithFixedDelay(configuration.getHealthCheckInterval(), configuration.getHealthCheckInterval(), () -> Flowable.fromIterable(originalURLs).flatMap(originalURI -> {
URI healthCheckURI = originalURI.resolve(configuration.getHealthCheckUri());
return httpClient.exchange(HttpRequest.GET(healthCheckURI)).onErrorResumeNext(throwable -> {
if (throwable instanceof HttpClientResponseException) {
HttpClientResponseException responseException = (HttpClientResponseException) throwable;
HttpResponse response = responseException.getResponse();
//noinspection unchecked
return Flowable.just(response);
}
return Flowable.just(HttpResponse.serverError());
}).map(response -> Collections.singletonMap(originalURI, response.getStatus()));
}).subscribe(uriToStatusMap -> {
Map.Entry<URI, HttpStatus> entry = uriToStatusMap.entrySet().iterator().next();
URI uri = entry.getKey();
HttpStatus status = entry.getValue();
if (status.getCode() >= 300) {
loadBalancedURIs.remove(uri);
} else if (!loadBalancedURIs.contains(uri)) { // depends on control dependency: [if], data = [none]
loadBalancedURIs.add(uri);
}
}));
}
return httpClient;
} } |
public class class_name {
public String describeMismatch(final Request request) {
final Description desc = new StringDescription();
boolean first = true;
for (final Iterator<Matcher<? super Request>> it = this.predicates.iterator(); it.hasNext();) {
final Matcher<? super Request> m = it.next();
if (!m.matches(request)) {
if (!first) {
desc.appendText(" AND\n");
}
desc.appendText(" ");
m.describeMismatch(request, desc);
first = false;
}
}
return desc.toString();
} } | public class class_name {
public String describeMismatch(final Request request) {
final Description desc = new StringDescription();
boolean first = true;
for (final Iterator<Matcher<? super Request>> it = this.predicates.iterator(); it.hasNext();) {
final Matcher<? super Request> m = it.next();
if (!m.matches(request)) {
if (!first) {
desc.appendText(" AND\n"); // depends on control dependency: [if], data = [none]
}
desc.appendText(" "); // depends on control dependency: [if], data = [none]
m.describeMismatch(request, desc); // depends on control dependency: [if], data = [none]
first = false; // depends on control dependency: [if], data = [none]
}
}
return desc.toString();
} } |
public class class_name {
public ModelNode addOperationParameterDescription(final ResourceBundle bundle, final String prefix, final ModelNode operationDescription) {
final ModelNode param = getNoTextDescription(true);
param.get(ModelDescriptionConstants.DESCRIPTION).set(getAttributeTextDescription(bundle, prefix));
final ModelNode result = operationDescription.get(ModelDescriptionConstants.REQUEST_PROPERTIES, getName()).set(param);
ModelNode deprecated = addDeprecatedInfo(result);
if (deprecated != null) {
deprecated.get(ModelDescriptionConstants.REASON).set(getAttributeDeprecatedDescription(bundle, prefix));
}
return result;
} } | public class class_name {
public ModelNode addOperationParameterDescription(final ResourceBundle bundle, final String prefix, final ModelNode operationDescription) {
final ModelNode param = getNoTextDescription(true);
param.get(ModelDescriptionConstants.DESCRIPTION).set(getAttributeTextDescription(bundle, prefix));
final ModelNode result = operationDescription.get(ModelDescriptionConstants.REQUEST_PROPERTIES, getName()).set(param);
ModelNode deprecated = addDeprecatedInfo(result);
if (deprecated != null) {
deprecated.get(ModelDescriptionConstants.REASON).set(getAttributeDeprecatedDescription(bundle, prefix)); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
private void notifyStatus(SmsMessage message) {
URI callback = message.getStatusCallback();
if (callback != null) {
String method = message.getStatusCallbackMethod();
if (method != null && !method.isEmpty()) {
if (!org.apache.http.client.methods.HttpGet.METHOD_NAME.equalsIgnoreCase(method)
&& !org.apache.http.client.methods.HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
final Notification notification = notification(WARNING_NOTIFICATION, 14104, method
+ " is not a valid HTTP method for <Sms>");
storage.getNotificationsDao().addNotification(notification);
method = org.apache.http.client.methods.HttpPost.METHOD_NAME;
}
} else {
method = org.apache.http.client.methods.HttpPost.METHOD_NAME;
}
List<NameValuePair> parameters = populateReqParams(message);
HttpRequestDescriptor request = new HttpRequestDescriptor(callback, method, parameters);
downloader().tell(request, self());
}
} } | public class class_name {
private void notifyStatus(SmsMessage message) {
URI callback = message.getStatusCallback();
if (callback != null) {
String method = message.getStatusCallbackMethod();
if (method != null && !method.isEmpty()) {
if (!org.apache.http.client.methods.HttpGet.METHOD_NAME.equalsIgnoreCase(method)
&& !org.apache.http.client.methods.HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
final Notification notification = notification(WARNING_NOTIFICATION, 14104, method
+ " is not a valid HTTP method for <Sms>");
storage.getNotificationsDao().addNotification(notification); // depends on control dependency: [if], data = [none]
method = org.apache.http.client.methods.HttpPost.METHOD_NAME; // depends on control dependency: [if], data = [none]
}
} else {
method = org.apache.http.client.methods.HttpPost.METHOD_NAME; // depends on control dependency: [if], data = [none]
}
List<NameValuePair> parameters = populateReqParams(message);
HttpRequestDescriptor request = new HttpRequestDescriptor(callback, method, parameters);
downloader().tell(request, self()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static NodeExtension create(Node node, List<String> extensionPriorityList) {
try {
ClassLoader classLoader = node.getConfigClassLoader();
Class<NodeExtension> chosenExtension = null;
int chosenPriority = Integer.MAX_VALUE;
for (Iterator<Class<NodeExtension>> iter =
ServiceLoader.classIterator(NodeExtension.class, NODE_EXTENSION_FACTORY_ID, classLoader);
iter.hasNext();
) {
Class<NodeExtension> currExt = iter.next();
warnIfDuplicate(currExt);
int currPriority = extensionPriorityList.indexOf(currExt.getName());
if (currPriority == -1) {
continue;
}
if (currPriority < chosenPriority) {
chosenPriority = currPriority;
chosenExtension = currExt;
}
}
if (chosenExtension == null) {
throw new HazelcastException("ServiceLoader didn't find any services registered under "
+ NODE_EXTENSION_FACTORY_ID);
}
return chosenExtension.getConstructor(Node.class).newInstance(node);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
} } | public class class_name {
public static NodeExtension create(Node node, List<String> extensionPriorityList) {
try {
ClassLoader classLoader = node.getConfigClassLoader();
Class<NodeExtension> chosenExtension = null; // depends on control dependency: [try], data = [none]
int chosenPriority = Integer.MAX_VALUE;
for (Iterator<Class<NodeExtension>> iter =
ServiceLoader.classIterator(NodeExtension.class, NODE_EXTENSION_FACTORY_ID, classLoader);
iter.hasNext();
) {
Class<NodeExtension> currExt = iter.next();
warnIfDuplicate(currExt);
int currPriority = extensionPriorityList.indexOf(currExt.getName());
if (currPriority == -1) {
continue;
}
if (currPriority < chosenPriority) {
chosenPriority = currPriority; // depends on control dependency: [if], data = [none]
chosenExtension = currExt; // depends on control dependency: [if], data = [none]
}
}
if (chosenExtension == null) {
throw new HazelcastException("ServiceLoader didn't find any services registered under "
+ NODE_EXTENSION_FACTORY_ID);
}
return chosenExtension.getConstructor(Node.class).newInstance(node); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static List<Object> extract(Iterable<?> collection, Editor<Object> editor, boolean ignoreNull) {
final List<Object> fieldValueList = new ArrayList<>();
Object value;
for (Object bean : collection) {
value = editor.edit(bean);
if (null == value && ignoreNull) {
continue;
}
fieldValueList.add(value);
}
return fieldValueList;
} } | public class class_name {
public static List<Object> extract(Iterable<?> collection, Editor<Object> editor, boolean ignoreNull) {
final List<Object> fieldValueList = new ArrayList<>();
Object value;
for (Object bean : collection) {
value = editor.edit(bean);
// depends on control dependency: [for], data = [bean]
if (null == value && ignoreNull) {
continue;
}
fieldValueList.add(value);
// depends on control dependency: [for], data = [none]
}
return fieldValueList;
} } |
public class class_name {
public TypeMapping[] getPropertyTypes(InternalQName propName)
{
synchronized (typeMapping)
{
TypeMapping[] types = typeMapping.get(propName);
if (types != null)
{
return types;
}
else
{
return EMPTY;
}
}
} } | public class class_name {
public TypeMapping[] getPropertyTypes(InternalQName propName)
{
synchronized (typeMapping)
{
TypeMapping[] types = typeMapping.get(propName);
if (types != null)
{
return types; // depends on control dependency: [if], data = [none]
}
else
{
return EMPTY; // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private <T> CompletableFuture<T> executeOnTransientConnection(
Address address,
Function<ClientConnection, CompletableFuture<T>> callback,
Executor executor) {
CompletableFuture<T> future = new CompletableFuture<>();
if (address.equals(returnAddress)) {
callback.apply(localConnection).whenComplete((result, error) -> {
if (error == null) {
executor.execute(() -> future.complete(result));
} else {
executor.execute(() -> future.completeExceptionally(error));
}
});
return future;
}
openChannel(address).whenComplete((channel, channelError) -> {
if (channelError == null) {
callback.apply(getOrCreateClientConnection(channel)).whenComplete((result, sendError) -> {
if (sendError == null) {
executor.execute(() -> future.complete(result));
} else {
executor.execute(() -> future.completeExceptionally(sendError));
}
channel.close();
});
} else {
executor.execute(() -> future.completeExceptionally(channelError));
}
});
return future;
} } | public class class_name {
private <T> CompletableFuture<T> executeOnTransientConnection(
Address address,
Function<ClientConnection, CompletableFuture<T>> callback,
Executor executor) {
CompletableFuture<T> future = new CompletableFuture<>();
if (address.equals(returnAddress)) {
callback.apply(localConnection).whenComplete((result, error) -> {
if (error == null) {
executor.execute(() -> future.complete(result)); // depends on control dependency: [if], data = [none]
} else {
executor.execute(() -> future.completeExceptionally(error)); // depends on control dependency: [if], data = [(error]
}
});
return future; // depends on control dependency: [if], data = [none]
}
openChannel(address).whenComplete((channel, channelError) -> {
if (channelError == null) {
callback.apply(getOrCreateClientConnection(channel)).whenComplete((result, sendError) -> {
if (sendError == null) {
executor.execute(() -> future.complete(result)); // depends on control dependency: [if], data = [none]
} else {
executor.execute(() -> future.completeExceptionally(sendError)); // depends on control dependency: [if], data = [(sendError]
}
channel.close();
});
} else {
executor.execute(() -> future.completeExceptionally(channelError)); // depends on control dependency: [if], data = [(channelError]
}
});
return future;
} } |
public class class_name {
public void setTableIndex(TableIndex tableIndex) {
this.tableIndex = tableIndex;
if (tableIndex != null) {
tableName = tableIndex.getTableName();
} else {
tableName = null;
}
} } | public class class_name {
public void setTableIndex(TableIndex tableIndex) {
this.tableIndex = tableIndex;
if (tableIndex != null) {
tableName = tableIndex.getTableName(); // depends on control dependency: [if], data = [none]
} else {
tableName = null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static void columnOpTransform(Matrix M, int low, int high, int n, double q, double p, int shift)
{
double z;
for (int i = low; i <= high; i++)
{
z = M.get(i, n+shift);
M.set(i, n+shift, q * z + p * M.get(i, n));
M.set(i, n, q * M.get(i, n) - p * z);
}
} } | public class class_name {
private static void columnOpTransform(Matrix M, int low, int high, int n, double q, double p, int shift)
{
double z;
for (int i = low; i <= high; i++)
{
z = M.get(i, n+shift); // depends on control dependency: [for], data = [i]
M.set(i, n+shift, q * z + p * M.get(i, n)); // depends on control dependency: [for], data = [i]
M.set(i, n, q * M.get(i, n) - p * z); // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
private void initialize() {
if(this.initialized) {
return;
}
if (LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.INFO)) {
if (this.sessionStoreService==null) {
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.INFO, methodClassName, "initialize", "SessionMgrComponentImpl.noPersistence");
} else {
String modeName = "sessionPersistenceMode";
Object modeValue = this.mergedConfiguration.get(modeName);
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.INFO, methodClassName, "initialize", "SessionMgrComponentImpl.persistenceMode", new Object[] { modeValue });
}
}
SessionProperties.setPropertiesInSMC(this.serverLevelSessionManagerConfig, this.mergedConfiguration);
String cloneId = SessionManagerConfig.getCloneId();
if (cloneId == null) {
if (this.sessionStoreService==null && SessionManagerConfig.isTurnOffCloneId()) {
/*-
* In tWAS, WsSessionAffinityManager sets the CloneID to -1 when two conditions are both met:
* A) Running in a standalone server (com.ibm.ws.runtime.service.WLM#getMemberUID()==null)
* B) The HttpSessionCloneId custom property is not explicitly set
*
* In addition, tWAS will set the CloneID to "" (the empty String) if a third condition is also met:
* C) The NoAdditionalSessionInfo custom property is set to "true"
*
* In lWAS, there's no notion of a "standalone" server, because potentially any lWAS server
* could require a CloneID for session affinity. As a result, our logic for using an
* empty Clone ID on lWAS needs to be different than our logic on tWAS.
*
* Since most customers who specify a session store will be interested in session affinity,
* we'll assume that these customers are always interested in a non-empty Clone ID.
*
* We'll also assume that customers who do not specify a session store who also explicitly
* set the noAdditionalInfo property to "true" would prefer an empty Clone ID.
*
* All customers can always explicitly set the cloneId property to override these assumptions.
*/
cloneId = "";
} else {
String serverId = getServerId(); // never returns null
if (TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, "initialize", "serverId=" + serverId);
}
SessionManagerConfig.setServerId(serverId);
cloneId = EncodeCloneID.encodeString(serverId); // never returns null
}
SessionManagerConfig.setCloneId(cloneId);
}
this.initialized=true;
} } | public class class_name {
private void initialize() {
if(this.initialized) {
return; // depends on control dependency: [if], data = [none]
}
if (LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.INFO)) {
if (this.sessionStoreService==null) {
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.INFO, methodClassName, "initialize", "SessionMgrComponentImpl.noPersistence"); // depends on control dependency: [if], data = [none]
} else {
String modeName = "sessionPersistenceMode";
Object modeValue = this.mergedConfiguration.get(modeName);
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.INFO, methodClassName, "initialize", "SessionMgrComponentImpl.persistenceMode", new Object[] { modeValue }); // depends on control dependency: [if], data = [none]
}
}
SessionProperties.setPropertiesInSMC(this.serverLevelSessionManagerConfig, this.mergedConfiguration);
String cloneId = SessionManagerConfig.getCloneId();
if (cloneId == null) {
if (this.sessionStoreService==null && SessionManagerConfig.isTurnOffCloneId()) {
/*-
* In tWAS, WsSessionAffinityManager sets the CloneID to -1 when two conditions are both met:
* A) Running in a standalone server (com.ibm.ws.runtime.service.WLM#getMemberUID()==null)
* B) The HttpSessionCloneId custom property is not explicitly set
*
* In addition, tWAS will set the CloneID to "" (the empty String) if a third condition is also met:
* C) The NoAdditionalSessionInfo custom property is set to "true"
*
* In lWAS, there's no notion of a "standalone" server, because potentially any lWAS server
* could require a CloneID for session affinity. As a result, our logic for using an
* empty Clone ID on lWAS needs to be different than our logic on tWAS.
*
* Since most customers who specify a session store will be interested in session affinity,
* we'll assume that these customers are always interested in a non-empty Clone ID.
*
* We'll also assume that customers who do not specify a session store who also explicitly
* set the noAdditionalInfo property to "true" would prefer an empty Clone ID.
*
* All customers can always explicitly set the cloneId property to override these assumptions.
*/
cloneId = ""; // depends on control dependency: [if], data = [none]
} else {
String serverId = getServerId(); // never returns null
if (TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, "initialize", "serverId=" + serverId); // depends on control dependency: [if], data = [none]
}
SessionManagerConfig.setServerId(serverId); // depends on control dependency: [if], data = [none]
cloneId = EncodeCloneID.encodeString(serverId); // never returns null // depends on control dependency: [if], data = [none]
}
SessionManagerConfig.setCloneId(cloneId); // depends on control dependency: [if], data = [(cloneId]
}
this.initialized=true;
} } |
public class class_name {
@Override
public void installTheme(Theme theme) {
this.removeCssLinks();
if (this.currentTheme != null) {
for (CssLink link : this.currentTheme.getLinks()) {
link.getLink().removeFromParent();
}
}
this.currentTheme = theme;
this.resetTheme();
} } | public class class_name {
@Override
public void installTheme(Theme theme) {
this.removeCssLinks();
if (this.currentTheme != null) {
for (CssLink link : this.currentTheme.getLinks()) {
link.getLink().removeFromParent(); // depends on control dependency: [for], data = [link]
}
}
this.currentTheme = theme;
this.resetTheme();
} } |
public class class_name {
public final ProtoParser.enum_field_return enum_field(Proto proto, Message message, EnumGroup enumGroup) throws RecognitionException {
ProtoParser.enum_field_return retval = new ProtoParser.enum_field_return();
retval.start = input.LT(1);
Object root_0 = null;
Token ID127=null;
Token ASSIGN128=null;
Token NUMINT129=null;
Token SEMICOLON131=null;
ProtoParser.enum_options_return enum_options130 = null;
Object ID127_tree=null;
Object ASSIGN128_tree=null;
Object NUMINT129_tree=null;
Object SEMICOLON131_tree=null;
EnumGroup.Value v = null;
try {
// com/dyuproject/protostuff/parser/ProtoParser.g:547:5: ( ID ASSIGN NUMINT ( enum_options[proto, enumGroup, v] )? SEMICOLON )
// com/dyuproject/protostuff/parser/ProtoParser.g:547:9: ID ASSIGN NUMINT ( enum_options[proto, enumGroup, v] )? SEMICOLON
{
root_0 = (Object)adaptor.nil();
ID127=(Token)match(input,ID,FOLLOW_ID_in_enum_field2181); if (state.failed) return retval;
if ( state.backtracking==0 ) {
ID127_tree = (Object)adaptor.create(ID127);
adaptor.addChild(root_0, ID127_tree);
}
ASSIGN128=(Token)match(input,ASSIGN,FOLLOW_ASSIGN_in_enum_field2183); if (state.failed) return retval;
if ( state.backtracking==0 ) {
ASSIGN128_tree = (Object)adaptor.create(ASSIGN128);
adaptor.addChild(root_0, ASSIGN128_tree);
}
NUMINT129=(Token)match(input,NUMINT,FOLLOW_NUMINT_in_enum_field2185); if (state.failed) return retval;
if ( state.backtracking==0 ) {
NUMINT129_tree = (Object)adaptor.create(NUMINT129);
adaptor.addChild(root_0, NUMINT129_tree);
}
if ( state.backtracking==0 ) {
v = new EnumGroup.Value((ID127!=null?ID127.getText():null), Integer.parseInt((NUMINT129!=null?NUMINT129.getText():null)), enumGroup);
proto.addAnnotationsTo(v);
}
// com/dyuproject/protostuff/parser/ProtoParser.g:550:11: ( enum_options[proto, enumGroup, v] )?
int alt25=2;
switch ( input.LA(1) ) {
case LEFTSQUARE:
{
alt25=1;
}
break;
}
switch (alt25) {
case 1 :
// com/dyuproject/protostuff/parser/ProtoParser.g:550:12: enum_options[proto, enumGroup, v]
{
pushFollow(FOLLOW_enum_options_in_enum_field2190);
enum_options130=enum_options(proto, enumGroup, v);
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking==0 ) adaptor.addChild(root_0, enum_options130.getTree());
}
break;
}
SEMICOLON131=(Token)match(input,SEMICOLON,FOLLOW_SEMICOLON_in_enum_field2195); if (state.failed) return retval;
}
retval.stop = input.LT(-1);
if ( state.backtracking==0 ) {
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
}
return retval;
} } | public class class_name {
public final ProtoParser.enum_field_return enum_field(Proto proto, Message message, EnumGroup enumGroup) throws RecognitionException {
ProtoParser.enum_field_return retval = new ProtoParser.enum_field_return();
retval.start = input.LT(1);
Object root_0 = null;
Token ID127=null;
Token ASSIGN128=null;
Token NUMINT129=null;
Token SEMICOLON131=null;
ProtoParser.enum_options_return enum_options130 = null;
Object ID127_tree=null;
Object ASSIGN128_tree=null;
Object NUMINT129_tree=null;
Object SEMICOLON131_tree=null;
EnumGroup.Value v = null;
try {
// com/dyuproject/protostuff/parser/ProtoParser.g:547:5: ( ID ASSIGN NUMINT ( enum_options[proto, enumGroup, v] )? SEMICOLON )
// com/dyuproject/protostuff/parser/ProtoParser.g:547:9: ID ASSIGN NUMINT ( enum_options[proto, enumGroup, v] )? SEMICOLON
{
root_0 = (Object)adaptor.nil();
ID127=(Token)match(input,ID,FOLLOW_ID_in_enum_field2181); if (state.failed) return retval;
if ( state.backtracking==0 ) {
ID127_tree = (Object)adaptor.create(ID127); // depends on control dependency: [if], data = [none]
adaptor.addChild(root_0, ID127_tree); // depends on control dependency: [if], data = [none]
}
ASSIGN128=(Token)match(input,ASSIGN,FOLLOW_ASSIGN_in_enum_field2183); if (state.failed) return retval;
if ( state.backtracking==0 ) {
ASSIGN128_tree = (Object)adaptor.create(ASSIGN128); // depends on control dependency: [if], data = [none]
adaptor.addChild(root_0, ASSIGN128_tree); // depends on control dependency: [if], data = [none]
}
NUMINT129=(Token)match(input,NUMINT,FOLLOW_NUMINT_in_enum_field2185); if (state.failed) return retval;
if ( state.backtracking==0 ) {
NUMINT129_tree = (Object)adaptor.create(NUMINT129); // depends on control dependency: [if], data = [none]
adaptor.addChild(root_0, NUMINT129_tree); // depends on control dependency: [if], data = [none]
}
if ( state.backtracking==0 ) {
v = new EnumGroup.Value((ID127!=null?ID127.getText():null), Integer.parseInt((NUMINT129!=null?NUMINT129.getText():null)), enumGroup); // depends on control dependency: [if], data = [none]
proto.addAnnotationsTo(v); // depends on control dependency: [if], data = [none]
}
// com/dyuproject/protostuff/parser/ProtoParser.g:550:11: ( enum_options[proto, enumGroup, v] )?
int alt25=2;
switch ( input.LA(1) ) {
case LEFTSQUARE:
{
alt25=1;
}
break;
}
switch (alt25) {
case 1 :
// com/dyuproject/protostuff/parser/ProtoParser.g:550:12: enum_options[proto, enumGroup, v]
{
pushFollow(FOLLOW_enum_options_in_enum_field2190);
enum_options130=enum_options(proto, enumGroup, v);
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking==0 ) adaptor.addChild(root_0, enum_options130.getTree());
}
break;
}
SEMICOLON131=(Token)match(input,SEMICOLON,FOLLOW_SEMICOLON_in_enum_field2195); if (state.failed) return retval;
}
retval.stop = input.LT(-1);
if ( state.backtracking==0 ) {
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
}
return retval;
} } |
public class class_name {
protected String addExchangeToken(final String url, final OAuth2AccessToken accessToken) {
final FacebookProfileDefinition profileDefinition = (FacebookProfileDefinition) configuration.getProfileDefinition();
final FacebookConfiguration facebookConfiguration = (FacebookConfiguration) configuration;
String computedUrl = url;
if (facebookConfiguration.isUseAppsecretProof()) {
computedUrl = profileDefinition.computeAppSecretProof(computedUrl, accessToken, facebookConfiguration);
}
return CommonHelper.addParameter(computedUrl, EXCHANGE_TOKEN_PARAMETER, accessToken.getAccessToken());
} } | public class class_name {
protected String addExchangeToken(final String url, final OAuth2AccessToken accessToken) {
final FacebookProfileDefinition profileDefinition = (FacebookProfileDefinition) configuration.getProfileDefinition();
final FacebookConfiguration facebookConfiguration = (FacebookConfiguration) configuration;
String computedUrl = url;
if (facebookConfiguration.isUseAppsecretProof()) {
computedUrl = profileDefinition.computeAppSecretProof(computedUrl, accessToken, facebookConfiguration); // depends on control dependency: [if], data = [none]
}
return CommonHelper.addParameter(computedUrl, EXCHANGE_TOKEN_PARAMETER, accessToken.getAccessToken());
} } |
public class class_name {
private boolean hasScopeAnnotation(final Class<?> type, final boolean hkManaged) {
boolean found = false;
for (Annotation ann : type.getAnnotations()) {
final Class<? extends Annotation> annType = ann.annotationType();
if (annType.isAnnotationPresent(Scope.class)) {
found = true;
break;
}
// guice has special marker annotation
if (!hkManaged && annType.isAnnotationPresent(ScopeAnnotation.class)) {
found = true;
break;
}
}
return found;
} } | public class class_name {
private boolean hasScopeAnnotation(final Class<?> type, final boolean hkManaged) {
boolean found = false;
for (Annotation ann : type.getAnnotations()) {
final Class<? extends Annotation> annType = ann.annotationType();
if (annType.isAnnotationPresent(Scope.class)) {
found = true; // depends on control dependency: [if], data = [none]
break;
}
// guice has special marker annotation
if (!hkManaged && annType.isAnnotationPresent(ScopeAnnotation.class)) {
found = true; // depends on control dependency: [if], data = [none]
break;
}
}
return found;
} } |
public class class_name {
private void printImage(PrintStream out, ItemDocument itemDocument) {
String imageFile = null;
if (itemDocument != null) {
for (StatementGroup sg : itemDocument.getStatementGroups()) {
boolean isImage = "P18".equals(sg.getProperty().getId());
if (!isImage) {
continue;
}
for (Statement s : sg) {
if (s.getMainSnak() instanceof ValueSnak) {
Value value = s.getMainSnak().getValue();
if (value instanceof StringValue) {
imageFile = ((StringValue) value).getString();
break;
}
}
}
if (imageFile != null) {
break;
}
}
}
if (imageFile == null) {
out.print(",\"http://commons.wikimedia.org/w/thumb.php?f=MA_Route_blank.svg&w=50\"");
} else {
try {
String imageFileEncoded;
imageFileEncoded = URLEncoder.encode(
imageFile.replace(" ", "_"), "utf-8");
// Keep special title symbols unescaped:
imageFileEncoded = imageFileEncoded.replace("%3A", ":")
.replace("%2F", "/");
out.print(","
+ csvStringEscape("http://commons.wikimedia.org/w/thumb.php?f="
+ imageFileEncoded) + "&w=50");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(
"Your JRE does not support UTF-8 encoding. Srsly?!", e);
}
}
} } | public class class_name {
private void printImage(PrintStream out, ItemDocument itemDocument) {
String imageFile = null;
if (itemDocument != null) {
for (StatementGroup sg : itemDocument.getStatementGroups()) {
boolean isImage = "P18".equals(sg.getProperty().getId());
if (!isImage) {
continue;
}
for (Statement s : sg) {
if (s.getMainSnak() instanceof ValueSnak) {
Value value = s.getMainSnak().getValue();
if (value instanceof StringValue) {
imageFile = ((StringValue) value).getString(); // depends on control dependency: [if], data = [none]
break;
}
}
}
if (imageFile != null) {
break;
}
}
}
if (imageFile == null) {
out.print(",\"http://commons.wikimedia.org/w/thumb.php?f=MA_Route_blank.svg&w=50\"");
} else {
try {
String imageFileEncoded;
imageFileEncoded = URLEncoder.encode(
imageFile.replace(" ", "_"), "utf-8"); // depends on control dependency: [if], data = [none]
// Keep special title symbols unescaped:
imageFileEncoded = imageFileEncoded.replace("%3A", ":")
.replace("%2F", "/"); // depends on control dependency: [if], data = [none]
out.print(","
+ csvStringEscape("http://commons.wikimedia.org/w/thumb.php?f="
+ imageFileEncoded) + "&w=50"); // depends on control dependency: [if], data = [none]
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(
"Your JRE does not support UTF-8 encoding. Srsly?!", e);
}
}
} } |
public class class_name {
protected Map<String, String> initMapping() {
final Map<String, String> map = new TreeMap<>();
if (!this.converterReader.initializeConversions(map, this.context) && this.initializer != null) {
this.initializer.initializeConversions((simpleName, source, target) -> {
map.put(source, target);
});
}
return map;
} } | public class class_name {
protected Map<String, String> initMapping() {
final Map<String, String> map = new TreeMap<>();
if (!this.converterReader.initializeConversions(map, this.context) && this.initializer != null) {
this.initializer.initializeConversions((simpleName, source, target) -> {
map.put(source, target); // depends on control dependency: [if], data = [none]
});
}
return map;
} } |
public class class_name {
private void generateText(final INodeReadTrx paramRtx) {
try {
mContHandler.characters(paramRtx.getValueOfCurrentNode().toCharArray(), 0, paramRtx
.getValueOfCurrentNode().length());
} catch (final SAXException exc) {
exc.printStackTrace();
}
} } | public class class_name {
private void generateText(final INodeReadTrx paramRtx) {
try {
mContHandler.characters(paramRtx.getValueOfCurrentNode().toCharArray(), 0, paramRtx
.getValueOfCurrentNode().length()); // depends on control dependency: [try], data = [none]
} catch (final SAXException exc) {
exc.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void launchServer() {
try {
log.info("Configuring Android SDK");
if (config.getAndroidHome() != null) {
AndroidSdk.setAndroidHome(config.getAndroidHome());
}
if (config.getAndroidSdkVersion() != null) {
AndroidSdk.setAndroidSdkVersion(config.getAndroidSdkVersion());
}
if (config.getBuildToolsVersion() != null) {
AndroidSdk.setBuildToolsVersion(config.getBuildToolsVersion());
}
if (config.getAvdManager() !=null) {
AndroidSdk.setAvdManagerHome(config.getAvdManager());
}
if (config.getAdbHome() != null) {
AndroidSdk.setAdbHome(config.getAdbHome());
}
log.info("Using Android SDK installed in: " + AndroidSdk.androidHome());
log.info("Using Android SDK version: " + AndroidSdk.androidSdkFolder().getAbsolutePath());
log.info("Using build-tools in: " + AndroidSdk.buildToolsFolder().getAbsolutePath());
log.info("Using adb in: " + AndroidSdk.adb().getAbsolutePath());
log.info("Starting Selendroid standalone on port " + config.getPort());
server = new SelendroidStandaloneServer(config);
server.start();
} catch (AndroidSdkException e) {
log.severe("Selendroid standalone was not able to interact with the Android SDK: " + e.getMessage());
log.severe(
"Please make sure you have the latest version with the latest updates installed: ");
log.severe("http://developer.android.com/sdk/index.html");
throw Throwables.propagate(e);
} catch (Exception e) {
log.severe("Error building server: " + e.getMessage());
throw Throwables.propagate(e);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
log.info("Shutting down Selendroid standalone");
stopSelendroid();
}
});
} } | public class class_name {
private void launchServer() {
try {
log.info("Configuring Android SDK"); // depends on control dependency: [try], data = [none]
if (config.getAndroidHome() != null) {
AndroidSdk.setAndroidHome(config.getAndroidHome()); // depends on control dependency: [if], data = [(config.getAndroidHome()]
}
if (config.getAndroidSdkVersion() != null) {
AndroidSdk.setAndroidSdkVersion(config.getAndroidSdkVersion()); // depends on control dependency: [if], data = [(config.getAndroidSdkVersion()]
}
if (config.getBuildToolsVersion() != null) {
AndroidSdk.setBuildToolsVersion(config.getBuildToolsVersion()); // depends on control dependency: [if], data = [(config.getBuildToolsVersion()]
}
if (config.getAvdManager() !=null) {
AndroidSdk.setAvdManagerHome(config.getAvdManager()); // depends on control dependency: [if], data = [(config.getAvdManager()]
}
if (config.getAdbHome() != null) {
AndroidSdk.setAdbHome(config.getAdbHome()); // depends on control dependency: [if], data = [(config.getAdbHome()]
}
log.info("Using Android SDK installed in: " + AndroidSdk.androidHome()); // depends on control dependency: [try], data = [none]
log.info("Using Android SDK version: " + AndroidSdk.androidSdkFolder().getAbsolutePath()); // depends on control dependency: [try], data = [none]
log.info("Using build-tools in: " + AndroidSdk.buildToolsFolder().getAbsolutePath()); // depends on control dependency: [try], data = [none]
log.info("Using adb in: " + AndroidSdk.adb().getAbsolutePath()); // depends on control dependency: [try], data = [none]
log.info("Starting Selendroid standalone on port " + config.getPort()); // depends on control dependency: [try], data = [none]
server = new SelendroidStandaloneServer(config); // depends on control dependency: [try], data = [none]
server.start(); // depends on control dependency: [try], data = [none]
} catch (AndroidSdkException e) {
log.severe("Selendroid standalone was not able to interact with the Android SDK: " + e.getMessage());
log.severe(
"Please make sure you have the latest version with the latest updates installed: ");
log.severe("http://developer.android.com/sdk/index.html");
throw Throwables.propagate(e);
} catch (Exception e) { // depends on control dependency: [catch], data = [none]
log.severe("Error building server: " + e.getMessage());
throw Throwables.propagate(e);
} // depends on control dependency: [catch], data = [none]
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
log.info("Shutting down Selendroid standalone");
stopSelendroid();
}
});
} } |
public class class_name {
protected AuthenticationResult processExternalLogin(RequestContext requestContext, String externalId, List<String> emails, String firstName, String lastName) {
UserEmailDAO userEmailDAO = new UserEmailDAO();
UserIdentificationDAO userIdentificationDAO = new UserIdentificationDAO();
UserDAO userDAO = new UserDAO();
Locale locale = requestContext.getRequest().getLocale();
UserIdentification userIdentification = userIdentificationDAO.findByExternalId(externalId, authSource);
// Resolve to a common user account based on a variety of possible sources
User currentUser = RequestUtils.getUser(requestContext);
User emailUser = resolveUser(requestContext, emails);
User idUser = userIdentification == null ? null : userIdentification.getUser();
User resolvedUser = resolveUser(requestContext, new User[] {currentUser, emailUser, idUser});
if (resolvedUser == null) {
// Entirely new user account
Delfoi delfoi = RequestUtils.getDelfoi(requestContext);
DelfoiUserRole userRole = RequestUtils.getDefaults(requestContext).getDefaultDelfoiUserRole();
String email = emails.isEmpty() ? null : emails.get(0);
resolvedUser = registerExternalUser(firstName, lastName, email, delfoi, userRole, externalId, locale);
for (int i = 1; i < emails.size(); i++) {
userEmailDAO.create(resolvedUser, emails.get(i));
}
RequestUtils.loginUser(requestContext, resolvedUser, authSource.getId());
return AuthenticationResult.NEW_ACCOUNT;
} else {
if (idUser == null) {
// Existing user account but new external identification source
userIdentificationDAO.create(resolvedUser, externalId, authSource);
}
if (StringUtils.isBlank(resolvedUser.getFirstName()) && StringUtils.isNotBlank(firstName)) {
userDAO.updateFirstName(resolvedUser, firstName, resolvedUser);
}
if (StringUtils.isBlank(resolvedUser.getLastName()) && StringUtils.isNotBlank(lastName)) {
userDAO.updateLastName(resolvedUser, lastName, resolvedUser);
}
for (String email : emails) {
UserEmail userEmail = userEmailDAO.findByAddress(email);
if (userEmail == null) {
userEmailDAO.create(resolvedUser, email);
}
}
RequestUtils.loginUser(requestContext, resolvedUser, authSource.getId());
if (idUser == null) {
return AuthenticationResult.NEW_ACCOUNT;
}
return AuthenticationResult.LOGIN;
}
} } | public class class_name {
protected AuthenticationResult processExternalLogin(RequestContext requestContext, String externalId, List<String> emails, String firstName, String lastName) {
UserEmailDAO userEmailDAO = new UserEmailDAO();
UserIdentificationDAO userIdentificationDAO = new UserIdentificationDAO();
UserDAO userDAO = new UserDAO();
Locale locale = requestContext.getRequest().getLocale();
UserIdentification userIdentification = userIdentificationDAO.findByExternalId(externalId, authSource);
// Resolve to a common user account based on a variety of possible sources
User currentUser = RequestUtils.getUser(requestContext);
User emailUser = resolveUser(requestContext, emails);
User idUser = userIdentification == null ? null : userIdentification.getUser();
User resolvedUser = resolveUser(requestContext, new User[] {currentUser, emailUser, idUser});
if (resolvedUser == null) {
// Entirely new user account
Delfoi delfoi = RequestUtils.getDelfoi(requestContext);
DelfoiUserRole userRole = RequestUtils.getDefaults(requestContext).getDefaultDelfoiUserRole();
String email = emails.isEmpty() ? null : emails.get(0);
resolvedUser = registerExternalUser(firstName, lastName, email, delfoi, userRole, externalId, locale); // depends on control dependency: [if], data = [none]
for (int i = 1; i < emails.size(); i++) {
userEmailDAO.create(resolvedUser, emails.get(i)); // depends on control dependency: [for], data = [i]
}
RequestUtils.loginUser(requestContext, resolvedUser, authSource.getId()); // depends on control dependency: [if], data = [none]
return AuthenticationResult.NEW_ACCOUNT; // depends on control dependency: [if], data = [none]
} else {
if (idUser == null) {
// Existing user account but new external identification source
userIdentificationDAO.create(resolvedUser, externalId, authSource); // depends on control dependency: [if], data = [none]
}
if (StringUtils.isBlank(resolvedUser.getFirstName()) && StringUtils.isNotBlank(firstName)) {
userDAO.updateFirstName(resolvedUser, firstName, resolvedUser); // depends on control dependency: [if], data = [none]
}
if (StringUtils.isBlank(resolvedUser.getLastName()) && StringUtils.isNotBlank(lastName)) {
userDAO.updateLastName(resolvedUser, lastName, resolvedUser); // depends on control dependency: [if], data = [none]
}
for (String email : emails) {
UserEmail userEmail = userEmailDAO.findByAddress(email);
if (userEmail == null) {
userEmailDAO.create(resolvedUser, email); // depends on control dependency: [if], data = [none]
}
}
RequestUtils.loginUser(requestContext, resolvedUser, authSource.getId()); // depends on control dependency: [if], data = [none]
if (idUser == null) {
return AuthenticationResult.NEW_ACCOUNT; // depends on control dependency: [if], data = [none]
}
return AuthenticationResult.LOGIN; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Pair<Atom> getAxisEnds(Atom[] atoms) {
// Project each Atom onto the rotation axis to determine limits
double min, max;
min = max = Calc.scalarProduct(rotationAxis,atoms[0]);
for(int i=1;i<atoms.length;i++) {
double prod = Calc.scalarProduct(rotationAxis,atoms[i]);
if(prod<min) min = prod;
if(prod>max) max = prod;
}
double uLen = Calc.scalarProduct(rotationAxis,rotationAxis);// Should be 1, but double check
min/=uLen;
max/=uLen;
// Project the origin onto the axis. If the axis is undefined, use the center of mass
Atom axialPt;
if(rotationPos == null) {
Atom center = Calc.centerOfMass(atoms);
// Project center onto the axis
Atom centerOnAxis = Calc.scale(rotationAxis, Calc.scalarProduct(center, rotationAxis));
// Remainder is projection of origin onto axis
axialPt = Calc.subtract(center, centerOnAxis);
} else {
axialPt = rotationPos;
}
// Find end points of the rotation axis to display
Atom axisMin = (Atom) axialPt.clone();
Calc.scaleAdd(min, rotationAxis, axisMin);
Atom axisMax = (Atom) axialPt.clone();
Calc.scaleAdd(max, rotationAxis, axisMax);
return new Pair<>(axisMin, axisMax);
} } | public class class_name {
public Pair<Atom> getAxisEnds(Atom[] atoms) {
// Project each Atom onto the rotation axis to determine limits
double min, max;
min = max = Calc.scalarProduct(rotationAxis,atoms[0]);
for(int i=1;i<atoms.length;i++) {
double prod = Calc.scalarProduct(rotationAxis,atoms[i]);
if(prod<min) min = prod;
if(prod>max) max = prod;
}
double uLen = Calc.scalarProduct(rotationAxis,rotationAxis);// Should be 1, but double check
min/=uLen;
max/=uLen;
// Project the origin onto the axis. If the axis is undefined, use the center of mass
Atom axialPt;
if(rotationPos == null) {
Atom center = Calc.centerOfMass(atoms);
// Project center onto the axis
Atom centerOnAxis = Calc.scale(rotationAxis, Calc.scalarProduct(center, rotationAxis));
// Remainder is projection of origin onto axis
axialPt = Calc.subtract(center, centerOnAxis); // depends on control dependency: [if], data = [none]
} else {
axialPt = rotationPos; // depends on control dependency: [if], data = [none]
}
// Find end points of the rotation axis to display
Atom axisMin = (Atom) axialPt.clone();
Calc.scaleAdd(min, rotationAxis, axisMin);
Atom axisMax = (Atom) axialPt.clone();
Calc.scaleAdd(max, rotationAxis, axisMax);
return new Pair<>(axisMin, axisMax);
} } |
public class class_name {
boolean scanDire() {
String id = null;
StringBuilder para = null;
Token idToken = null;
Token paraToken = null;
while (true) {
switch (state) {
case 0:
if (peek() == '#') { // #
next();
skipBlanks();
state = 1;
continue ;
}
return fail();
case 1:
if (peek() == '(') { // # (
para = scanPara("");
idToken = new Token(Symbol.OUTPUT, beginRow);
paraToken = new ParaToken(para, beginRow);
return addOutputToken(idToken, paraToken);
}
if (CharTable.isLetter(peek())) { // # id
state = 10;
continue ;
}
if (peek() == '@') { // # @
next();
skipBlanks();
if (CharTable.isLetter(peek())) { // # @ id
state = 20;
continue ;
}
}
return fail();
// -----------------------------------------------------
case 10: // # id
id = scanId();
Symbol symbol = Symbol.getKeywordSym(id);
// 非关键字指令
if (symbol == null) {
state = 11;
continue ;
}
// define 指令
if (symbol == Symbol.DEFINE) {
state = 12;
continue ;
}
// 在支持 #seleif 的基础上,支持 #else if
if (symbol == Symbol.ELSE) {
if (foundFollowingIf()) {
id = "else if";
symbol = Symbol.ELSEIF;
}
}
// 无参关键字指令
if (symbol.noPara()) {
return addNoParaToken(new Token(symbol, id, beginRow));
}
// 有参关键字指令
skipBlanks();
if (peek() == '(') {
para = scanPara(id);
idToken = new Token(symbol, beginRow);
paraToken = new ParaToken(para, beginRow);
return addIdParaToken(idToken, paraToken);
}
throw new ParseException("#" + id + " directive requires parentheses \"()\"", new Location(fileName, beginRow));
case 11: // 用户自定义指令必须有参数
skipBlanks();
if (peek() == '(') {
para = scanPara(id);
idToken = new Token(Symbol.ID, id, beginRow);
paraToken = new ParaToken(para, beginRow);
return addIdParaToken(idToken, paraToken);
}
return fail(); // 用户自定义指令在没有左括号的情况下当作普通文本
case 12: // 处理 "# define id (para)" 指令
skipBlanks();
if (CharTable.isLetter(peek())) {
id = scanId(); // 模板函数名称
skipBlanks();
if (peek() == '(') {
para = scanPara("define " + id);
idToken = new Token(Symbol.DEFINE, id, beginRow);
paraToken = new ParaToken(para, beginRow);
return addIdParaToken(idToken, paraToken);
}
throw new ParseException("#define " + id + " : template function definition requires parentheses \"()\"", new Location(fileName, beginRow));
}
throw new ParseException("#define directive requires identifier as a function name", new Location(fileName, beginRow));
case 20: // # @ id
id = scanId();
skipBlanks();
boolean hasQuestionMark = peek() == '?';
if (hasQuestionMark) {
next();
skipBlanks();
}
if (peek() == '(') {
para = scanPara(hasQuestionMark ? "@" + id + "?" : "@" + id);
idToken = new Token(hasQuestionMark ? Symbol.CALL_IF_DEFINED : Symbol.CALL, id, beginRow);
paraToken = new ParaToken(para, beginRow);
return addIdParaToken(idToken, paraToken);
}
return fail();
default :
return fail();
}
}
} } | public class class_name {
boolean scanDire() {
String id = null;
StringBuilder para = null;
Token idToken = null;
Token paraToken = null;
while (true) {
switch (state) {
case 0:
if (peek() == '#') { // #
next();
// depends on control dependency: [if], data = [none]
skipBlanks();
// depends on control dependency: [if], data = [none]
state = 1;
// depends on control dependency: [if], data = [none]
continue ;
}
return fail();
case 1:
if (peek() == '(') { // # (
para = scanPara("");
// depends on control dependency: [if], data = [none]
idToken = new Token(Symbol.OUTPUT, beginRow);
// depends on control dependency: [if], data = [none]
paraToken = new ParaToken(para, beginRow);
// depends on control dependency: [if], data = [none]
return addOutputToken(idToken, paraToken);
// depends on control dependency: [if], data = [none]
}
if (CharTable.isLetter(peek())) { // # id
state = 10;
// depends on control dependency: [if], data = [none]
continue ;
}
if (peek() == '@') { // # @
next();
// depends on control dependency: [if], data = [none]
skipBlanks();
// depends on control dependency: [if], data = [none]
if (CharTable.isLetter(peek())) { // # @ id
state = 20;
// depends on control dependency: [if], data = [none]
continue ;
}
}
return fail();
// -----------------------------------------------------
case 10: // # id
id = scanId();
Symbol symbol = Symbol.getKeywordSym(id);
// 非关键字指令
if (symbol == null) {
state = 11;
// depends on control dependency: [if], data = [none]
continue ;
}
// define 指令
if (symbol == Symbol.DEFINE) {
state = 12;
// depends on control dependency: [if], data = [none]
continue ;
}
// 在支持 #seleif 的基础上,支持 #else if
if (symbol == Symbol.ELSE) {
if (foundFollowingIf()) {
id = "else if";
// depends on control dependency: [if], data = [none]
symbol = Symbol.ELSEIF;
// depends on control dependency: [if], data = [none]
}
}
// 无参关键字指令
if (symbol.noPara()) {
return addNoParaToken(new Token(symbol, id, beginRow));
// depends on control dependency: [if], data = [none]
}
// 有参关键字指令
skipBlanks();
if (peek() == '(') {
para = scanPara(id);
// depends on control dependency: [if], data = [none]
idToken = new Token(symbol, beginRow);
// depends on control dependency: [if], data = [none]
paraToken = new ParaToken(para, beginRow);
// depends on control dependency: [if], data = [none]
return addIdParaToken(idToken, paraToken);
// depends on control dependency: [if], data = [none]
}
throw new ParseException("#" + id + " directive requires parentheses \"()\"", new Location(fileName, beginRow));
case 11: // 用户自定义指令必须有参数
skipBlanks();
if (peek() == '(') {
para = scanPara(id);
// depends on control dependency: [if], data = [none]
idToken = new Token(Symbol.ID, id, beginRow);
// depends on control dependency: [if], data = [none]
paraToken = new ParaToken(para, beginRow);
// depends on control dependency: [if], data = [none]
return addIdParaToken(idToken, paraToken);
// depends on control dependency: [if], data = [none]
}
return fail(); // 用户自定义指令在没有左括号的情况下当作普通文本
case 12: // 处理 "# define id (para)" 指令
skipBlanks();
if (CharTable.isLetter(peek())) {
id = scanId(); // 模板函数名称
// depends on control dependency: [if], data = [none]
skipBlanks();
// depends on control dependency: [if], data = [none]
if (peek() == '(') {
para = scanPara("define " + id);
// depends on control dependency: [if], data = [none]
idToken = new Token(Symbol.DEFINE, id, beginRow);
// depends on control dependency: [if], data = [none]
paraToken = new ParaToken(para, beginRow);
// depends on control dependency: [if], data = [none]
return addIdParaToken(idToken, paraToken);
// depends on control dependency: [if], data = [none]
}
throw new ParseException("#define " + id + " : template function definition requires parentheses \"()\"", new Location(fileName, beginRow));
}
throw new ParseException("#define directive requires identifier as a function name", new Location(fileName, beginRow));
case 20: // # @ id
id = scanId();
skipBlanks();
boolean hasQuestionMark = peek() == '?';
if (hasQuestionMark) {
next();
// depends on control dependency: [if], data = [none]
skipBlanks();
// depends on control dependency: [if], data = [none]
}
if (peek() == '(') {
para = scanPara(hasQuestionMark ? "@" + id + "?" : "@" + id);
// depends on control dependency: [if], data = [none]
idToken = new Token(hasQuestionMark ? Symbol.CALL_IF_DEFINED : Symbol.CALL, id, beginRow);
// depends on control dependency: [if], data = [none]
paraToken = new ParaToken(para, beginRow);
// depends on control dependency: [if], data = [none]
return addIdParaToken(idToken, paraToken);
// depends on control dependency: [if], data = [none]
}
return fail();
default :
return fail();
}
}
} } |
public class class_name {
private void doGenerateBrownianMotion() {
if(brownianIncrements != null) {
return; // Nothing to do
}
// Create random number sequence generator
MersenneTwister mersenneTwister = new MersenneTwister(seed);
// Allocate memory
double[][][] brownianIncrementsArray = new double[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors][numberOfPaths];
// Pre-calculate square roots of deltaT
double[] sqrtOfTimeStep = new double[timeDiscretization.getNumberOfTimeSteps()];
for(int timeIndex=0; timeIndex<sqrtOfTimeStep.length; timeIndex++) {
sqrtOfTimeStep[timeIndex] = Math.sqrt(timeDiscretization.getTimeStep(timeIndex));
}
/*
* Generate normal distributed independent increments.
*
* The inner loop goes over time and factors.
* MersenneTwister is known to generate "independent" increments in 623 dimensions.
* Since we want to generate independent streams (paths), the loop over path is the outer loop.
*/
for(int path=0; path<numberOfPaths; path++) {
for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
double sqrtDeltaT = sqrtOfTimeStep[timeIndex];
// Generate uncorrelated Brownian increment
for(int factor=0; factor<numberOfFactors; factor++) {
double uniformIncrement = mersenneTwister.nextDouble();
brownianIncrementsArray[timeIndex][factor][path] = net.finmath.functions.NormalDistribution.inverseCumulativeDistribution(uniformIncrement) * sqrtDeltaT;
}
}
}
// Allocate memory for RandomVariable wrapper objects.
brownianIncrements = new RandomVariableInterface[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors];
// Wrap the values in RandomVariable objects
for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
double time = timeDiscretization.getTime(timeIndex+1);
for(int factor=0; factor<numberOfFactors; factor++) {
brownianIncrements[timeIndex][factor] =
randomVariableFactory.createRandomVariable(time, brownianIncrementsArray[timeIndex][factor]);
}
}
} } | public class class_name {
private void doGenerateBrownianMotion() {
if(brownianIncrements != null) {
return; // Nothing to do // depends on control dependency: [if], data = [none]
}
// Create random number sequence generator
MersenneTwister mersenneTwister = new MersenneTwister(seed);
// Allocate memory
double[][][] brownianIncrementsArray = new double[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors][numberOfPaths];
// Pre-calculate square roots of deltaT
double[] sqrtOfTimeStep = new double[timeDiscretization.getNumberOfTimeSteps()];
for(int timeIndex=0; timeIndex<sqrtOfTimeStep.length; timeIndex++) {
sqrtOfTimeStep[timeIndex] = Math.sqrt(timeDiscretization.getTimeStep(timeIndex)); // depends on control dependency: [for], data = [timeIndex]
}
/*
* Generate normal distributed independent increments.
*
* The inner loop goes over time and factors.
* MersenneTwister is known to generate "independent" increments in 623 dimensions.
* Since we want to generate independent streams (paths), the loop over path is the outer loop.
*/
for(int path=0; path<numberOfPaths; path++) {
for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
double sqrtDeltaT = sqrtOfTimeStep[timeIndex];
// Generate uncorrelated Brownian increment
for(int factor=0; factor<numberOfFactors; factor++) {
double uniformIncrement = mersenneTwister.nextDouble();
brownianIncrementsArray[timeIndex][factor][path] = net.finmath.functions.NormalDistribution.inverseCumulativeDistribution(uniformIncrement) * sqrtDeltaT; // depends on control dependency: [for], data = [factor]
}
}
}
// Allocate memory for RandomVariable wrapper objects.
brownianIncrements = new RandomVariableInterface[timeDiscretization.getNumberOfTimeSteps()][numberOfFactors];
// Wrap the values in RandomVariable objects
for(int timeIndex=0; timeIndex<timeDiscretization.getNumberOfTimeSteps(); timeIndex++) {
double time = timeDiscretization.getTime(timeIndex+1);
for(int factor=0; factor<numberOfFactors; factor++) {
brownianIncrements[timeIndex][factor] =
randomVariableFactory.createRandomVariable(time, brownianIncrementsArray[timeIndex][factor]); // depends on control dependency: [for], data = [factor]
}
}
} } |
public class class_name {
public boolean extend(SpatialComparable obj) {
final int dim = min.length;
assert (obj.getDimensionality() == dim);
boolean extended = false;
for(int i = 0; i < dim; i++) {
final double omin = obj.getMin(i);
final double omax = obj.getMax(i);
if(omin < min[i]) {
min[i] = omin;
extended = true;
}
if(omax > max[i]) {
max[i] = omax;
extended = true;
}
}
return extended;
} } | public class class_name {
public boolean extend(SpatialComparable obj) {
final int dim = min.length;
assert (obj.getDimensionality() == dim);
boolean extended = false;
for(int i = 0; i < dim; i++) {
final double omin = obj.getMin(i);
final double omax = obj.getMax(i);
if(omin < min[i]) {
min[i] = omin; // depends on control dependency: [if], data = [none]
extended = true; // depends on control dependency: [if], data = [none]
}
if(omax > max[i]) {
max[i] = omax; // depends on control dependency: [if], data = [none]
extended = true; // depends on control dependency: [if], data = [none]
}
}
return extended;
} } |
public class class_name {
private void safeCustomDelay(PollingStrategyContext pollingStrategyContext) {
try {
pollingStrategy.getDelayStrategy().delayBeforeNextRetry(pollingStrategyContext);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
} } | public class class_name {
private void safeCustomDelay(PollingStrategyContext pollingStrategyContext) {
try {
pollingStrategy.getDelayStrategy().delayBeforeNextRetry(pollingStrategyContext); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public Collection getReaders(Object obj)
{
Collection result = null;
try
{
Identity oid = new Identity(obj, getBroker());
byte selector = (byte) 'r';
byte[] requestBarr = buildRequestArray(oid, selector);
HttpURLConnection conn = getHttpUrlConnection();
//post request
BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(requestBarr,0,requestBarr.length);
out.flush();
// read result from
InputStream in = conn.getInputStream();
ObjectInputStream ois = new ObjectInputStream(in);
result = (Collection) ois.readObject();
// cleanup
ois.close();
out.close();
conn.disconnect();
}
catch (Throwable t)
{
throw new PersistenceBrokerException(t);
}
return result;
} } | public class class_name {
public Collection getReaders(Object obj)
{
Collection result = null;
try
{
Identity oid = new Identity(obj, getBroker());
byte selector = (byte) 'r';
byte[] requestBarr = buildRequestArray(oid, selector);
HttpURLConnection conn = getHttpUrlConnection();
//post request
BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(requestBarr,0,requestBarr.length);
// depends on control dependency: [try], data = [none]
out.flush();
// depends on control dependency: [try], data = [none]
// read result from
InputStream in = conn.getInputStream();
ObjectInputStream ois = new ObjectInputStream(in);
result = (Collection) ois.readObject();
// depends on control dependency: [try], data = [none]
// cleanup
ois.close();
// depends on control dependency: [try], data = [none]
out.close();
// depends on control dependency: [try], data = [none]
conn.disconnect();
// depends on control dependency: [try], data = [none]
}
catch (Throwable t)
{
throw new PersistenceBrokerException(t);
}
// depends on control dependency: [catch], data = [none]
return result;
} } |
public class class_name {
public java.util.List<String> getCcEmailAddresses() {
if (ccEmailAddresses == null) {
ccEmailAddresses = new com.amazonaws.internal.SdkInternalList<String>();
}
return ccEmailAddresses;
} } | public class class_name {
public java.util.List<String> getCcEmailAddresses() {
if (ccEmailAddresses == null) {
ccEmailAddresses = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return ccEmailAddresses;
} } |
public class class_name {
protected void setPost(JSONObject post) throws JSONException {
params_ = post;
if (getBranchRemoteAPIVersion() == BRANCH_API_VERSION.V2) {
try {
JSONObject userDataObj = new JSONObject();
params_.put(Defines.Jsonkey.UserData.getKey(), userDataObj);
DeviceInfo.getInstance().updateRequestWithV2Params(context_, prefHelper_, userDataObj);
} catch (JSONException ignore) {
}
} else {
DeviceInfo.getInstance().updateRequestWithV1Params(params_);
}
} } | public class class_name {
protected void setPost(JSONObject post) throws JSONException {
params_ = post;
if (getBranchRemoteAPIVersion() == BRANCH_API_VERSION.V2) {
try {
JSONObject userDataObj = new JSONObject();
params_.put(Defines.Jsonkey.UserData.getKey(), userDataObj); // depends on control dependency: [try], data = [none]
DeviceInfo.getInstance().updateRequestWithV2Params(context_, prefHelper_, userDataObj); // depends on control dependency: [try], data = [none]
} catch (JSONException ignore) {
} // depends on control dependency: [catch], data = [none]
} else {
DeviceInfo.getInstance().updateRequestWithV1Params(params_);
}
} } |
public class class_name {
protected void init(CollectorConfiguration config) {
for (String btxn : config.getTransactions().keySet()) {
TransactionConfig btc = config.getTransactions().get(btxn);
init(btxn, btc);
}
onlyNamedTransactions = new Boolean(config.getProperty(
"HAWKULAR_APM_COLLECTOR_ONLYNAMED", Boolean.FALSE.toString()));
} } | public class class_name {
protected void init(CollectorConfiguration config) {
for (String btxn : config.getTransactions().keySet()) {
TransactionConfig btc = config.getTransactions().get(btxn);
init(btxn, btc); // depends on control dependency: [for], data = [btxn]
}
onlyNamedTransactions = new Boolean(config.getProperty(
"HAWKULAR_APM_COLLECTOR_ONLYNAMED", Boolean.FALSE.toString()));
} } |
public class class_name {
static void register(String group, long durationMillis) {
for (ProfilingListener listener : LISTENERS) {
listener.register(group, durationMillis);
}
} } | public class class_name {
static void register(String group, long durationMillis) {
for (ProfilingListener listener : LISTENERS) {
listener.register(group, durationMillis); // depends on control dependency: [for], data = [listener]
}
} } |
public class class_name {
@Override
public EClass getPluginBundle() {
if (pluginBundleEClass == null) {
pluginBundleEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(106);
}
return pluginBundleEClass;
} } | public class class_name {
@Override
public EClass getPluginBundle() {
if (pluginBundleEClass == null) {
pluginBundleEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(106);
// depends on control dependency: [if], data = [none]
}
return pluginBundleEClass;
} } |
public class class_name {
public static List<Integer> getCandidates(INDArray x,List<RPTree> roots,String similarityFunction) {
Set<Integer> ret = new LinkedHashSet<>();
for(RPTree tree : roots) {
RPNode root = tree.getRoot();
RPNode query = query(root,tree.getRpHyperPlanes(),x,similarityFunction);
ret.addAll(query.getIndices());
}
return new ArrayList<>(ret);
} } | public class class_name {
public static List<Integer> getCandidates(INDArray x,List<RPTree> roots,String similarityFunction) {
Set<Integer> ret = new LinkedHashSet<>();
for(RPTree tree : roots) {
RPNode root = tree.getRoot();
RPNode query = query(root,tree.getRpHyperPlanes(),x,similarityFunction);
ret.addAll(query.getIndices()); // depends on control dependency: [for], data = [none]
}
return new ArrayList<>(ret);
} } |
public class class_name {
public static Feed buildFeed(FeedDesc feedDesc){
Feed feed = null;
NitFactory nitFactory = new NitFactory();
NitDesc nitDesc = nitDescFromDynamic(feedDesc);
nitDesc.setConstructorParameters(new Class [] { Map.class });
nitDesc.setConstructorArguments(new Object[] { feedDesc.getProperties() });
try {
feed = nitFactory.construct(nitDesc);
} catch (NitException e) {
throw new RuntimeException(e);
}
return feed;
} } | public class class_name {
public static Feed buildFeed(FeedDesc feedDesc){
Feed feed = null;
NitFactory nitFactory = new NitFactory();
NitDesc nitDesc = nitDescFromDynamic(feedDesc);
nitDesc.setConstructorParameters(new Class [] { Map.class });
nitDesc.setConstructorArguments(new Object[] { feedDesc.getProperties() });
try {
feed = nitFactory.construct(nitDesc); // depends on control dependency: [try], data = [none]
} catch (NitException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
return feed;
} } |
public class class_name {
private static boolean validateTermWithStartValue(BytesRef term,
ComponentTermVector termVector) {
if (termVector.startValue == null) {
return true;
} else if (termVector.subComponentFunction.sortType
.equals(CodecUtil.SORT_TERM)) {
if (term.length > termVector.startValue.length) {
byte[] zeroBytes = (new BytesRef("\u0000")).bytes;
int n = (int) (Math
.ceil(((double) (term.length - termVector.startValue.length))
/ zeroBytes.length));
byte[] newBytes = new byte[termVector.startValue.length
+ n * zeroBytes.length];
System.arraycopy(termVector.startValue.bytes, 0, newBytes, 0,
termVector.startValue.length);
for (int i = 0; i < n; i++) {
System.arraycopy(zeroBytes, 0, newBytes,
termVector.startValue.length + i * zeroBytes.length,
zeroBytes.length);
}
termVector.startValue = new BytesRef(newBytes);
}
if ((termVector.subComponentFunction.sortDirection.equals(
CodecUtil.SORT_ASC) && (termVector.startValue.compareTo(term) < 0))
|| (termVector.subComponentFunction.sortDirection
.equals(CodecUtil.SORT_DESC)
&& (termVector.startValue.compareTo(term) > 0))) {
return true;
}
}
return false;
} } | public class class_name {
private static boolean validateTermWithStartValue(BytesRef term,
ComponentTermVector termVector) {
if (termVector.startValue == null) {
return true; // depends on control dependency: [if], data = [none]
} else if (termVector.subComponentFunction.sortType
.equals(CodecUtil.SORT_TERM)) {
if (term.length > termVector.startValue.length) {
byte[] zeroBytes = (new BytesRef("\u0000")).bytes;
int n = (int) (Math
.ceil(((double) (term.length - termVector.startValue.length))
/ zeroBytes.length));
byte[] newBytes = new byte[termVector.startValue.length
+ n * zeroBytes.length];
System.arraycopy(termVector.startValue.bytes, 0, newBytes, 0,
termVector.startValue.length); // depends on control dependency: [if], data = [none]
for (int i = 0; i < n; i++) {
System.arraycopy(zeroBytes, 0, newBytes,
termVector.startValue.length + i * zeroBytes.length,
zeroBytes.length); // depends on control dependency: [for], data = [none]
}
termVector.startValue = new BytesRef(newBytes); // depends on control dependency: [if], data = [none]
}
if ((termVector.subComponentFunction.sortDirection.equals(
CodecUtil.SORT_ASC) && (termVector.startValue.compareTo(term) < 0))
|| (termVector.subComponentFunction.sortDirection
.equals(CodecUtil.SORT_DESC)
&& (termVector.startValue.compareTo(term) > 0))) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
@Deprecated
public void canUploadVersion(String name, long fileSize, String parentID) {
URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "OPTIONS");
JsonObject parent = new JsonObject();
parent.add("id", parentID);
JsonObject preflightInfo = new JsonObject();
preflightInfo.add("parent", parent);
if (name != null) {
preflightInfo.add("name", name);
}
preflightInfo.add("size", fileSize);
request.setBody(preflightInfo.toString());
BoxAPIResponse response = request.send();
response.disconnect();
} } | public class class_name {
@Deprecated
public void canUploadVersion(String name, long fileSize, String parentID) {
URL url = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "OPTIONS");
JsonObject parent = new JsonObject();
parent.add("id", parentID);
JsonObject preflightInfo = new JsonObject();
preflightInfo.add("parent", parent);
if (name != null) {
preflightInfo.add("name", name); // depends on control dependency: [if], data = [none]
}
preflightInfo.add("size", fileSize);
request.setBody(preflightInfo.toString());
BoxAPIResponse response = request.send();
response.disconnect();
} } |
public class class_name {
public List<CmsUUID> getRemoveIds() {
List<CmsUUID> toRemove = new ArrayList<CmsUUID>();
for (Map.Entry<CmsUUID, CmsPublishItemStatus> entry : m_status.entrySet()) {
CmsUUID key = entry.getKey();
CmsPublishItemStatus status = entry.getValue();
if (status.getState() == State.remove) {
toRemove.add(key);
}
}
return toRemove;
} } | public class class_name {
public List<CmsUUID> getRemoveIds() {
List<CmsUUID> toRemove = new ArrayList<CmsUUID>();
for (Map.Entry<CmsUUID, CmsPublishItemStatus> entry : m_status.entrySet()) {
CmsUUID key = entry.getKey();
CmsPublishItemStatus status = entry.getValue();
if (status.getState() == State.remove) {
toRemove.add(key); // depends on control dependency: [if], data = [none]
}
}
return toRemove;
} } |
public class class_name {
private void resetJcsegTaskConfig(JcsegTaskConfig config, JSONObject json)
{
if ( json.has("jcseg_maxlen") ) {
config.setMaxLength(json.getInt("jcseg_maxlen"));
}
if ( json.has("jcseg_icnname") ) {
config.setICnName(json.getBoolean("jcseg_icnname"));
}
if ( json.has("jcseg_pptmaxlen") ) {
config.setPPT_MAX_LENGTH(json.getInt("jcseg_pptmaxlen"));
}
if ( json.has("jcseg_cnmaxlnadron") ) {
config.setMaxCnLnadron(json.getInt("jcseg_cnmaxlnadron"));
}
if ( json.has("jcseg_clearstopword") ) {
config.setClearStopwords(json.getBoolean("jcseg_clearstopword"));
}
if ( json.has("jcseg_cnnumtoarabic") ) {
config.setCnNumToArabic(json.getBoolean("jcseg_cnnumtoarabic"));
}
if ( json.has("jcseg_cnfratoarabic") ) {
config.setCnFactionToArabic(json.getBoolean("jcseg_cnfratoarabic"));
}
if ( json.has("jcseg_keepunregword") ) {
config.setKeepUnregWords(json.getBoolean("jcseg_keepunregword"));
}
if ( json.has("jcseg_ensencondseg") ) {
config.setEnSecondSeg(json.getBoolean("jcseg_ensencondseg"));
}
if ( json.has("jcseg_stokenminlen") ) {
config.setSTokenMinLen(json.getInt("jcseg_stokenminlen"));
}
if ( json.has("jcseg_nsthreshold") ) {
config.setNameSingleThreshold(json.getInt("jcseg_nsthreshold"));
}
if ( json.has("jcseg_keeppunctuations") ) {
config.setKeepPunctuations(json.getString("jcseg_keeppunctuations"));
}
} } | public class class_name {
private void resetJcsegTaskConfig(JcsegTaskConfig config, JSONObject json)
{
if ( json.has("jcseg_maxlen") ) {
config.setMaxLength(json.getInt("jcseg_maxlen")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_icnname") ) {
config.setICnName(json.getBoolean("jcseg_icnname")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_pptmaxlen") ) {
config.setPPT_MAX_LENGTH(json.getInt("jcseg_pptmaxlen")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_cnmaxlnadron") ) {
config.setMaxCnLnadron(json.getInt("jcseg_cnmaxlnadron")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_clearstopword") ) {
config.setClearStopwords(json.getBoolean("jcseg_clearstopword")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_cnnumtoarabic") ) {
config.setCnNumToArabic(json.getBoolean("jcseg_cnnumtoarabic")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_cnfratoarabic") ) {
config.setCnFactionToArabic(json.getBoolean("jcseg_cnfratoarabic")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_keepunregword") ) {
config.setKeepUnregWords(json.getBoolean("jcseg_keepunregword")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_ensencondseg") ) {
config.setEnSecondSeg(json.getBoolean("jcseg_ensencondseg")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_stokenminlen") ) {
config.setSTokenMinLen(json.getInt("jcseg_stokenminlen")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_nsthreshold") ) {
config.setNameSingleThreshold(json.getInt("jcseg_nsthreshold")); // depends on control dependency: [if], data = [none]
}
if ( json.has("jcseg_keeppunctuations") ) {
config.setKeepPunctuations(json.getString("jcseg_keeppunctuations")); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void initDefaultLoginFilter(H http) {
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter != null && !isCustomLoginPage()) {
loginPageGeneratingFilter.setOpenIdEnabled(true);
loginPageGeneratingFilter.setOpenIDauthenticationUrl(getLoginProcessingUrl());
String loginPageUrl = loginPageGeneratingFilter.getLoginPageUrl();
if (loginPageUrl == null) {
loginPageGeneratingFilter.setLoginPageUrl(getLoginPage());
loginPageGeneratingFilter.setFailureUrl(getFailureUrl());
}
loginPageGeneratingFilter.setOpenIDusernameParameter(
OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD);
}
} } | public class class_name {
private void initDefaultLoginFilter(H http) {
DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
.getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter != null && !isCustomLoginPage()) {
loginPageGeneratingFilter.setOpenIdEnabled(true); // depends on control dependency: [if], data = [none]
loginPageGeneratingFilter.setOpenIDauthenticationUrl(getLoginProcessingUrl()); // depends on control dependency: [if], data = [none]
String loginPageUrl = loginPageGeneratingFilter.getLoginPageUrl();
if (loginPageUrl == null) {
loginPageGeneratingFilter.setLoginPageUrl(getLoginPage()); // depends on control dependency: [if], data = [none]
loginPageGeneratingFilter.setFailureUrl(getFailureUrl()); // depends on control dependency: [if], data = [none]
}
loginPageGeneratingFilter.setOpenIDusernameParameter(
OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected static void applyDefaults(final TableRequestOptions modifiedOptions) {
Utility.assertNotNull("modifiedOptions", modifiedOptions);
RequestOptions.applyBaseDefaultsInternal(modifiedOptions);
if (modifiedOptions.getTablePayloadFormat() == null) {
modifiedOptions.setTablePayloadFormat(TablePayloadFormat.Json);
}
if (modifiedOptions.getDateBackwardCompatibility() == null) {
modifiedOptions.setDateBackwardCompatibility(false);
}
} } | public class class_name {
protected static void applyDefaults(final TableRequestOptions modifiedOptions) {
Utility.assertNotNull("modifiedOptions", modifiedOptions);
RequestOptions.applyBaseDefaultsInternal(modifiedOptions);
if (modifiedOptions.getTablePayloadFormat() == null) {
modifiedOptions.setTablePayloadFormat(TablePayloadFormat.Json); // depends on control dependency: [if], data = [none]
}
if (modifiedOptions.getDateBackwardCompatibility() == null) {
modifiedOptions.setDateBackwardCompatibility(false); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static Stream<JarEntry> asStream( final JarInputStream pInputStream ) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
new Iterator<JarEntry>() {
JarEntry entry = null;
public boolean hasNext() {
try {
if (entry == null) {
entry = pInputStream.getNextJarEntry();
}
return entry != null;
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public JarEntry next() {
try {
JarEntry result = entry != null
? entry
: pInputStream.getNextJarEntry();
entry = null;
return result;
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}, Spliterator.IMMUTABLE), false);
} } | public class class_name {
public static Stream<JarEntry> asStream( final JarInputStream pInputStream ) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
new Iterator<JarEntry>() {
JarEntry entry = null;
public boolean hasNext() {
try {
if (entry == null) {
entry = pInputStream.getNextJarEntry(); // depends on control dependency: [if], data = [none]
}
return entry != null; // depends on control dependency: [try], data = [none]
} catch(IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
}
public JarEntry next() {
try {
JarEntry result = entry != null
? entry
: pInputStream.getNextJarEntry();
entry = null; // depends on control dependency: [try], data = [none]
return result; // depends on control dependency: [try], data = [none]
} catch(IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
}
}, Spliterator.IMMUTABLE), false);
} } |
public class class_name {
public Problem getProblem(final String letter) {
if (letter.isEmpty() || letter.length() > 1) {
return null;
}
final char identifier = letter.toUpperCase().charAt(0);
final int index = (int) identifier - (int) 'A';
final List<Problem> problems = info.getProblems();
if (index < 0 || index >= problems.size()) {
return null;
}
return problems.get(index);
} } | public class class_name {
public Problem getProblem(final String letter) {
if (letter.isEmpty() || letter.length() > 1) {
return null; // depends on control dependency: [if], data = [none]
}
final char identifier = letter.toUpperCase().charAt(0);
final int index = (int) identifier - (int) 'A';
final List<Problem> problems = info.getProblems();
if (index < 0 || index >= problems.size()) {
return null; // depends on control dependency: [if], data = [none]
}
return problems.get(index);
} } |
public class class_name {
public static boolean isMethodNode(ASTNode node, String methodNamePattern, Integer numArguments, Class returnType) {
if (!(node instanceof MethodNode)) {
return false;
}
if (!(((MethodNode) node).getName().matches(methodNamePattern))) {
return false;
}
if (numArguments != null && ((MethodNode)node).getParameters() != null && ((MethodNode)node).getParameters().length != numArguments) {
return false;
}
if (returnType != null && !AstUtil.classNodeImplementsType(((MethodNode) node).getReturnType(), returnType)) {
return false;
}
return true;
} } | public class class_name {
public static boolean isMethodNode(ASTNode node, String methodNamePattern, Integer numArguments, Class returnType) {
if (!(node instanceof MethodNode)) {
return false;
// depends on control dependency: [if], data = [none]
}
if (!(((MethodNode) node).getName().matches(methodNamePattern))) {
return false;
// depends on control dependency: [if], data = [none]
}
if (numArguments != null && ((MethodNode)node).getParameters() != null && ((MethodNode)node).getParameters().length != numArguments) {
return false;
// depends on control dependency: [if], data = [none]
}
if (returnType != null && !AstUtil.classNodeImplementsType(((MethodNode) node).getReturnType(), returnType)) {
return false;
// depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public static String readContentAsString(File file, String encoding) {
try {
return readContentAsString(new FileInputStream(file), encoding);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
} } | public class class_name {
public static String readContentAsString(File file, String encoding) {
try {
return readContentAsString(new FileInputStream(file), encoding); // depends on control dependency: [try], data = [none]
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void restore(BackupMetaData backup, File destinationFile) throws Exception
{
File tempFile = File.createTempFile("exhibitor-backup", ".tmp");
OutputStream out = new FileOutputStream(tempFile);
InputStream in = null;
try {
backupProvider.get().downloadBackup(exhibitor, backup, out, getBackupConfig());
CloseableUtils.closeQuietly(out);
out = null;
out = new FileOutputStream(destinationFile);
in = new GZIPInputStream(new FileInputStream(tempFile));
ByteStreams.copy(in, out);
}
finally {
CloseableUtils.closeQuietly(in);
CloseableUtils.closeQuietly(out);
if (!tempFile.delete()) {
exhibitor.getLog().add(ActivityLog.Type.ERROR, "Could not delete temp file (for restore): " + tempFile);
}
}
} } | public class class_name {
public void restore(BackupMetaData backup, File destinationFile) throws Exception
{
File tempFile = File.createTempFile("exhibitor-backup", ".tmp");
OutputStream out = new FileOutputStream(tempFile);
InputStream in = null;
try {
backupProvider.get().downloadBackup(exhibitor, backup, out, getBackupConfig());
CloseableUtils.closeQuietly(out);
out = null;
out = new FileOutputStream(destinationFile);
in = new GZIPInputStream(new FileInputStream(tempFile));
ByteStreams.copy(in, out);
}
finally {
CloseableUtils.closeQuietly(in);
CloseableUtils.closeQuietly(out);
if (!tempFile.delete()) {
exhibitor.getLog().add(ActivityLog.Type.ERROR, "Could not delete temp file (for restore): " + tempFile); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public Integer getAbsoluteSourcePort() {
if (this.getSourcePort() == null) {
return null;
}
if (this.fixedSourcePort) {
return this.sourcePort;
}
final int portOffset = this.socketBindingManager.getPortOffset();
return this.sourcePort + portOffset;
} } | public class class_name {
public Integer getAbsoluteSourcePort() {
if (this.getSourcePort() == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (this.fixedSourcePort) {
return this.sourcePort; // depends on control dependency: [if], data = [none]
}
final int portOffset = this.socketBindingManager.getPortOffset();
return this.sourcePort + portOffset;
} } |
public class class_name {
public void setContentView(View contentView, FrameLayout.LayoutParams params) {
if(params == null) {
params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
final int margin = getResources().getDimensionPixelSize(R.dimen.sub_action_button_content_margin);
params.setMargins(margin, margin, margin, margin);
}
contentView.setClickable(false);
this.addView(contentView, params);
} } | public class class_name {
public void setContentView(View contentView, FrameLayout.LayoutParams params) {
if(params == null) {
params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER); // depends on control dependency: [if], data = [none]
final int margin = getResources().getDimensionPixelSize(R.dimen.sub_action_button_content_margin);
params.setMargins(margin, margin, margin, margin); // depends on control dependency: [if], data = [none]
}
contentView.setClickable(false);
this.addView(contentView, params);
} } |
public class class_name {
public final EObject ruleParameter() throws RecognitionException {
EObject current = null;
Token lv_name_0_0=null;
enterRule();
try {
// InternalXtext.g:901:2: ( ( (lv_name_0_0= RULE_ID ) ) )
// InternalXtext.g:902:2: ( (lv_name_0_0= RULE_ID ) )
{
// InternalXtext.g:902:2: ( (lv_name_0_0= RULE_ID ) )
// InternalXtext.g:903:3: (lv_name_0_0= RULE_ID )
{
// InternalXtext.g:903:3: (lv_name_0_0= RULE_ID )
// InternalXtext.g:904:4: lv_name_0_0= RULE_ID
{
lv_name_0_0=(Token)match(input,RULE_ID,FollowSets000.FOLLOW_2);
newLeafNode(lv_name_0_0, grammarAccess.getParameterAccess().getNameIDTerminalRuleCall_0());
if (current==null) {
current = createModelElement(grammarAccess.getParameterRule());
}
setWithLastConsumed(
current,
"name",
lv_name_0_0,
"org.eclipse.xtext.common.Terminals.ID");
}
}
}
leaveRule();
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } | public class class_name {
public final EObject ruleParameter() throws RecognitionException {
EObject current = null;
Token lv_name_0_0=null;
enterRule();
try {
// InternalXtext.g:901:2: ( ( (lv_name_0_0= RULE_ID ) ) )
// InternalXtext.g:902:2: ( (lv_name_0_0= RULE_ID ) )
{
// InternalXtext.g:902:2: ( (lv_name_0_0= RULE_ID ) )
// InternalXtext.g:903:3: (lv_name_0_0= RULE_ID )
{
// InternalXtext.g:903:3: (lv_name_0_0= RULE_ID )
// InternalXtext.g:904:4: lv_name_0_0= RULE_ID
{
lv_name_0_0=(Token)match(input,RULE_ID,FollowSets000.FOLLOW_2);
newLeafNode(lv_name_0_0, grammarAccess.getParameterAccess().getNameIDTerminalRuleCall_0());
if (current==null) {
current = createModelElement(grammarAccess.getParameterRule()); // depends on control dependency: [if], data = [none]
}
setWithLastConsumed(
current,
"name",
lv_name_0_0,
"org.eclipse.xtext.common.Terminals.ID");
}
}
}
leaveRule();
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } |
public class class_name {
public static ZMatrixRMaj[] columnsToVector(ZMatrixRMaj A, ZMatrixRMaj[] v)
{
ZMatrixRMaj[]ret;
if( v == null || v.length < A.numCols ) {
ret = new ZMatrixRMaj[ A.numCols ];
} else {
ret = v;
}
for( int i = 0; i < ret.length; i++ ) {
if( ret[i] == null ) {
ret[i] = new ZMatrixRMaj(A.numRows,1);
} else {
ret[i].reshape(A.numRows,1);
}
ZMatrixRMaj u = ret[i];
int indexU = 0;
for( int j = 0; j < A.numRows; j++ ) {
int indexA = A.getIndex(j,i);
u.data[indexU++] = A.data[indexA++];
u.data[indexU++] = A.data[indexA];
}
}
return ret;
} } | public class class_name {
public static ZMatrixRMaj[] columnsToVector(ZMatrixRMaj A, ZMatrixRMaj[] v)
{
ZMatrixRMaj[]ret;
if( v == null || v.length < A.numCols ) {
ret = new ZMatrixRMaj[ A.numCols ]; // depends on control dependency: [if], data = [none]
} else {
ret = v; // depends on control dependency: [if], data = [none]
}
for( int i = 0; i < ret.length; i++ ) {
if( ret[i] == null ) {
ret[i] = new ZMatrixRMaj(A.numRows,1); // depends on control dependency: [if], data = [none]
} else {
ret[i].reshape(A.numRows,1); // depends on control dependency: [if], data = [none]
}
ZMatrixRMaj u = ret[i];
int indexU = 0;
for( int j = 0; j < A.numRows; j++ ) {
int indexA = A.getIndex(j,i);
u.data[indexU++] = A.data[indexA++]; // depends on control dependency: [for], data = [none]
u.data[indexU++] = A.data[indexA]; // depends on control dependency: [for], data = [none]
}
}
return ret;
} } |
public class class_name {
static Visibility getEffectiveVisibilityForOverriddenProperty(
Visibility visibility,
@Nullable Visibility fileOverviewVisibility,
String propertyName,
@Nullable CodingConvention codingConvention) {
if (codingConvention != null && codingConvention.isPrivate(propertyName)) {
return Visibility.PRIVATE;
}
return (fileOverviewVisibility != null
&& visibility == Visibility.INHERITED)
? fileOverviewVisibility
: visibility;
} } | public class class_name {
static Visibility getEffectiveVisibilityForOverriddenProperty(
Visibility visibility,
@Nullable Visibility fileOverviewVisibility,
String propertyName,
@Nullable CodingConvention codingConvention) {
if (codingConvention != null && codingConvention.isPrivate(propertyName)) {
return Visibility.PRIVATE; // depends on control dependency: [if], data = [none]
}
return (fileOverviewVisibility != null
&& visibility == Visibility.INHERITED)
? fileOverviewVisibility
: visibility;
} } |
public class class_name {
public void awaitTermination(boolean waitQuietPeriod) {
LOG.info("{}: Journal checkpointer shutdown has been initiated.", mMaster.getName());
mWaitQuietPeriod = waitQuietPeriod;
mShutdownInitiated = true;
// Actively interrupt to cancel slow checkpoints.
synchronized (mCheckpointingLock) {
if (mCheckpointing) {
interrupt();
}
}
try {
// Wait for the thread to finish.
join();
LOG.info("{}: Journal shutdown complete", mMaster.getName());
} catch (InterruptedException e) {
LOG.error("{}: journal checkpointer shutdown is interrupted.", mMaster.getName(), e);
// Kills the master. This can happen in the following two scenarios:
// 1. The user Ctrl-C the server.
// 2. Zookeeper selects this master as standby before the master finishes the previous
// standby->leader transition. It is safer to crash the server because the behavior is
// undefined to have two journal checkpointer running concurrently.
throw new RuntimeException(e);
}
mStopped = true;
} } | public class class_name {
public void awaitTermination(boolean waitQuietPeriod) {
LOG.info("{}: Journal checkpointer shutdown has been initiated.", mMaster.getName());
mWaitQuietPeriod = waitQuietPeriod;
mShutdownInitiated = true;
// Actively interrupt to cancel slow checkpoints.
synchronized (mCheckpointingLock) {
if (mCheckpointing) {
interrupt(); // depends on control dependency: [if], data = [none]
}
}
try {
// Wait for the thread to finish.
join(); // depends on control dependency: [try], data = [none]
LOG.info("{}: Journal shutdown complete", mMaster.getName()); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
LOG.error("{}: journal checkpointer shutdown is interrupted.", mMaster.getName(), e);
// Kills the master. This can happen in the following two scenarios:
// 1. The user Ctrl-C the server.
// 2. Zookeeper selects this master as standby before the master finishes the previous
// standby->leader transition. It is safer to crash the server because the behavior is
// undefined to have two journal checkpointer running concurrently.
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
mStopped = true;
} } |
public class class_name {
protected void release() {
if (!releaseNeeded.get()) {
return; // there is no point in releasing if we do not wait. Avoid excessive releasing.
}
releaseNeeded.set(false);// release is under way
backgroundExecutor.execute(new Runnable() {
@Override
public void run() {
try {
List<Command> releaseCommandList = new ArrayList<Command>(Collections.singletonList(releaseCommand));
transmit(releaseCommandList);
} catch (DolphinRemotingException e) {
handleError(e);
}
}
});
} } | public class class_name {
protected void release() {
if (!releaseNeeded.get()) {
return; // there is no point in releasing if we do not wait. Avoid excessive releasing. // depends on control dependency: [if], data = [none]
}
releaseNeeded.set(false);// release is under way
backgroundExecutor.execute(new Runnable() {
@Override
public void run() {
try {
List<Command> releaseCommandList = new ArrayList<Command>(Collections.singletonList(releaseCommand));
transmit(releaseCommandList); // depends on control dependency: [try], data = [none]
} catch (DolphinRemotingException e) {
handleError(e);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public void writeTag(int tagClass, boolean primitive, int tag) throws AsnException {
if (tag < 0)
throw new AsnException("Tag must not be negative");
if (tag <= 30) {
int toEncode = (tagClass & 0x03) << 6;
toEncode |= (primitive ? 0 : 1) << 5;
toEncode |= tag & 0x1F;
this.write(toEncode);
} else {
int toEncode = (tagClass & 0x03) << 6;
toEncode |= (primitive ? 0 : 1) << 5;
toEncode |= 0x1F;
this.write(toEncode);
int byteArr = 8;
byte[] buf = new byte[byteArr];
int pos = byteArr;
while (true) {
int dd;
if (tag <= 0x7F) {
dd = tag;
if (pos != byteArr)
dd = dd | 0x80;
buf[--pos] = (byte) dd;
break;
} else {
dd = (tag & 0x7F);
tag >>= 7;
if (pos != byteArr)
dd = dd | 0x80;
buf[--pos] = (byte) dd;
}
}
this.write(buf, pos, byteArr - pos);
}
} } | public class class_name {
public void writeTag(int tagClass, boolean primitive, int tag) throws AsnException {
if (tag < 0)
throw new AsnException("Tag must not be negative");
if (tag <= 30) {
int toEncode = (tagClass & 0x03) << 6;
toEncode |= (primitive ? 0 : 1) << 5;
toEncode |= tag & 0x1F;
this.write(toEncode);
} else {
int toEncode = (tagClass & 0x03) << 6;
toEncode |= (primitive ? 0 : 1) << 5;
toEncode |= 0x1F;
this.write(toEncode);
int byteArr = 8;
byte[] buf = new byte[byteArr];
int pos = byteArr;
while (true) {
int dd;
if (tag <= 0x7F) {
dd = tag;
// depends on control dependency: [if], data = [none]
if (pos != byteArr)
dd = dd | 0x80;
buf[--pos] = (byte) dd;
// depends on control dependency: [if], data = [none]
break;
} else {
dd = (tag & 0x7F);
// depends on control dependency: [if], data = [(tag]
tag >>= 7;
// depends on control dependency: [if], data = [none]
if (pos != byteArr)
dd = dd | 0x80;
buf[--pos] = (byte) dd;
// depends on control dependency: [if], data = [none]
}
}
this.write(buf, pos, byteArr - pos);
}
} } |
public class class_name {
public static String getJsonString(Object object) {
ObjectMapper objectMapper = new ObjectMapper();
String json = null;
try {
json = objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
} } | public class class_name {
public static String getJsonString(Object object) {
ObjectMapper objectMapper = new ObjectMapper();
String json = null;
try {
json = objectMapper.writeValueAsString(object); // depends on control dependency: [try], data = [none]
} catch (JsonProcessingException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
return json;
} } |
public class class_name {
public static String relativizeLink(final String baseDirUri, final String link) {
// taken from org.apache.maven.doxia.site.decoration.inheritance.DecorationModelInheritanceAssembler
if (link == null || baseDirUri == null) {
return link;
}
// this shouldn't be necessary, just to swallow malformed hrefs
try {
final URIPathDescriptor path = new URIPathDescriptor(baseDirUri, link);
return path.relativizeLink().toString();
}
catch (IllegalArgumentException e) {
return link;
}
} } | public class class_name {
public static String relativizeLink(final String baseDirUri, final String link) {
// taken from org.apache.maven.doxia.site.decoration.inheritance.DecorationModelInheritanceAssembler
if (link == null || baseDirUri == null) {
return link; // depends on control dependency: [if], data = [none]
}
// this shouldn't be necessary, just to swallow malformed hrefs
try {
final URIPathDescriptor path = new URIPathDescriptor(baseDirUri, link);
return path.relativizeLink().toString(); // depends on control dependency: [try], data = [none]
}
catch (IllegalArgumentException e) {
return link;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static byte[] encodeLength(int length, int offset) {
if (length < SIZE_THRESHOLD) {
byte firstByte = (byte) (length + offset);
return new byte[] { firstByte };
} else if (length < MAX_ITEM_LENGTH) {
byte[] binaryLength;
if (length > 0xFF)
binaryLength = intToBytesNoLeadZeroes(length);
else
binaryLength = new byte[] { (byte) length };
byte firstByte = (byte) (binaryLength.length + offset + SIZE_THRESHOLD - 1);
return concatenate(new byte[] { firstByte }, binaryLength);
} else {
throw new RuntimeException("Input too long");
}
} } | public class class_name {
public static byte[] encodeLength(int length, int offset) {
if (length < SIZE_THRESHOLD) {
byte firstByte = (byte) (length + offset);
return new byte[] { firstByte }; // depends on control dependency: [if], data = [none]
} else if (length < MAX_ITEM_LENGTH) {
byte[] binaryLength;
if (length > 0xFF)
binaryLength = intToBytesNoLeadZeroes(length);
else
binaryLength = new byte[] { (byte) length };
byte firstByte = (byte) (binaryLength.length + offset + SIZE_THRESHOLD - 1);
return concatenate(new byte[] { firstByte }, binaryLength); // depends on control dependency: [if], data = [none]
} else {
throw new RuntimeException("Input too long");
}
} } |
public class class_name {
private static ConsistencyLevel downgrade(
ConsistencyLevel current, int acknowledgements, DriverException original) {
if (acknowledgements >= 3) {
return DefaultConsistencyLevel.THREE;
}
if (acknowledgements == 2) {
return DefaultConsistencyLevel.TWO;
}
if (acknowledgements == 1) {
return DefaultConsistencyLevel.ONE;
}
// Edge case: EACH_QUORUM does not report a global number of alive replicas
// so even if we get 0 alive replicas, there might be
// a node up in some other datacenter, so retry at ONE.
if (current == DefaultConsistencyLevel.EACH_QUORUM) {
return DefaultConsistencyLevel.ONE;
}
throw original;
} } | public class class_name {
private static ConsistencyLevel downgrade(
ConsistencyLevel current, int acknowledgements, DriverException original) {
if (acknowledgements >= 3) {
return DefaultConsistencyLevel.THREE; // depends on control dependency: [if], data = [none]
}
if (acknowledgements == 2) {
return DefaultConsistencyLevel.TWO; // depends on control dependency: [if], data = [none]
}
if (acknowledgements == 1) {
return DefaultConsistencyLevel.ONE; // depends on control dependency: [if], data = [none]
}
// Edge case: EACH_QUORUM does not report a global number of alive replicas
// so even if we get 0 alive replicas, there might be
// a node up in some other datacenter, so retry at ONE.
if (current == DefaultConsistencyLevel.EACH_QUORUM) {
return DefaultConsistencyLevel.ONE; // depends on control dependency: [if], data = [none]
}
throw original;
} } |
public class class_name {
public void doFormat(double number, StringBuilder toInsertInto, int pos, int recursionCount) {
// first, insert the rule's rule text into toInsertInto at the
// specified position, then insert the results of the substitutions
// into the right places in toInsertInto
// [again, we have two copies of this routine that do the same thing
// so that we don't sacrifice precision in a long by casting it
// to a double]
int pluralRuleStart = ruleText.length();
int lengthOffset = 0;
if (rulePatternFormat == null) {
toInsertInto.insert(pos, ruleText);
}
else {
pluralRuleStart = ruleText.indexOf("$(");
int pluralRuleEnd = ruleText.indexOf(")$", pluralRuleStart);
int initialLength = toInsertInto.length();
if (pluralRuleEnd < ruleText.length() - 1) {
toInsertInto.insert(pos, ruleText.substring(pluralRuleEnd + 2));
}
double pluralVal = number;
if (0 <= pluralVal && pluralVal < 1) {
// We're in a fractional rule, and we have to match the NumeratorSubstitution behavior.
// 2.3 can become 0.2999999999999998 for the fraction due to rounding errors.
pluralVal = Math.round(pluralVal * power(radix, exponent));
}
else {
pluralVal = pluralVal / power(radix, exponent);
}
toInsertInto.insert(pos, rulePatternFormat.format((long)(pluralVal)));
if (pluralRuleStart > 0) {
toInsertInto.insert(pos, ruleText.substring(0, pluralRuleStart));
}
lengthOffset = ruleText.length() - (toInsertInto.length() - initialLength);
}
if (sub2 != null) {
sub2.doSubstitution(number, toInsertInto, pos - (sub2.getPos() > pluralRuleStart ? lengthOffset : 0), recursionCount);
}
if (sub1 != null) {
sub1.doSubstitution(number, toInsertInto, pos - (sub1.getPos() > pluralRuleStart ? lengthOffset : 0), recursionCount);
}
} } | public class class_name {
public void doFormat(double number, StringBuilder toInsertInto, int pos, int recursionCount) {
// first, insert the rule's rule text into toInsertInto at the
// specified position, then insert the results of the substitutions
// into the right places in toInsertInto
// [again, we have two copies of this routine that do the same thing
// so that we don't sacrifice precision in a long by casting it
// to a double]
int pluralRuleStart = ruleText.length();
int lengthOffset = 0;
if (rulePatternFormat == null) {
toInsertInto.insert(pos, ruleText); // depends on control dependency: [if], data = [none]
}
else {
pluralRuleStart = ruleText.indexOf("$(");
int pluralRuleEnd = ruleText.indexOf(")$", pluralRuleStart); // depends on control dependency: [if], data = [none]
int initialLength = toInsertInto.length();
if (pluralRuleEnd < ruleText.length() - 1) {
toInsertInto.insert(pos, ruleText.substring(pluralRuleEnd + 2)); // depends on control dependency: [if], data = [(pluralRuleEnd]
}
double pluralVal = number;
if (0 <= pluralVal && pluralVal < 1) {
// We're in a fractional rule, and we have to match the NumeratorSubstitution behavior.
// 2.3 can become 0.2999999999999998 for the fraction due to rounding errors.
pluralVal = Math.round(pluralVal * power(radix, exponent)); // depends on control dependency: [if], data = [none]
}
else {
pluralVal = pluralVal / power(radix, exponent); // depends on control dependency: [if], data = [none]
}
toInsertInto.insert(pos, rulePatternFormat.format((long)(pluralVal))); // depends on control dependency: [if], data = [none]
if (pluralRuleStart > 0) {
toInsertInto.insert(pos, ruleText.substring(0, pluralRuleStart)); // depends on control dependency: [if], data = [none]
}
lengthOffset = ruleText.length() - (toInsertInto.length() - initialLength); // depends on control dependency: [if], data = [none]
}
if (sub2 != null) {
sub2.doSubstitution(number, toInsertInto, pos - (sub2.getPos() > pluralRuleStart ? lengthOffset : 0), recursionCount); // depends on control dependency: [if], data = [(sub2]
}
if (sub1 != null) {
sub1.doSubstitution(number, toInsertInto, pos - (sub1.getPos() > pluralRuleStart ? lengthOffset : 0), recursionCount); // depends on control dependency: [if], data = [(sub1]
}
} } |
public class class_name {
public static BigDecimal mantissa(BigDecimal value) {
int exponent = exponent(value);
if (exponent == 0) {
return value;
}
return value.movePointLeft(exponent);
} } | public class class_name {
public static BigDecimal mantissa(BigDecimal value) {
int exponent = exponent(value);
if (exponent == 0) {
return value; // depends on control dependency: [if], data = [none]
}
return value.movePointLeft(exponent);
} } |
public class class_name {
public static void decodeTo(InputStream in, MultiMap<String> map, Charset charset, int maxLength, int maxKeys)
throws IOException {
//no charset present, use the configured default
if (charset == null)
charset = ENCODING;
if (StandardCharsets.UTF_8.equals(charset)) {
decodeUtf8To(in, map, maxLength, maxKeys);
return;
}
if (StandardCharsets.ISO_8859_1.equals(charset)) {
decode88591To(in, map, maxLength, maxKeys);
return;
}
if (StandardCharsets.UTF_16.equals(charset)) // Should be all 2 byte encodings
{
decodeUtf16To(in, map, maxLength, maxKeys);
return;
}
synchronized (map) {
String key = null;
String value = null;
int c;
int totalLength = 0;
try (ByteArrayOutputStream2 output = new ByteArrayOutputStream2();) {
int size = 0;
while ((c = in.read()) > 0) {
switch ((char) c) {
case '&':
size = output.size();
value = size == 0 ? "" : output.toString(charset);
output.setCount(0);
if (key != null) {
map.add(key, value);
} else if (value != null && value.length() > 0) {
map.add(value, "");
}
key = null;
value = null;
if (maxKeys > 0 && map.size() > maxKeys)
throw new IllegalStateException(String.format("Form with too many keys [%d > %d]", map.size(), maxKeys));
break;
case '=':
if (key != null) {
output.write(c);
break;
}
size = output.size();
key = size == 0 ? "" : output.toString(charset);
output.setCount(0);
break;
case '+':
output.write(' ');
break;
case '%':
int code0 = in.read();
int code1 = in.read();
output.write(decodeHexChar(code0, code1));
break;
default:
output.write(c);
break;
}
totalLength++;
if (maxLength >= 0 && totalLength > maxLength)
throw new IllegalStateException("Form is too large");
}
size = output.size();
if (key != null) {
value = size == 0 ? "" : output.toString(charset);
output.setCount(0);
map.add(key, value);
} else if (size > 0)
map.add(output.toString(charset), "");
}
}
} } | public class class_name {
public static void decodeTo(InputStream in, MultiMap<String> map, Charset charset, int maxLength, int maxKeys)
throws IOException {
//no charset present, use the configured default
if (charset == null)
charset = ENCODING;
if (StandardCharsets.UTF_8.equals(charset)) {
decodeUtf8To(in, map, maxLength, maxKeys);
return;
}
if (StandardCharsets.ISO_8859_1.equals(charset)) {
decode88591To(in, map, maxLength, maxKeys);
return;
}
if (StandardCharsets.UTF_16.equals(charset)) // Should be all 2 byte encodings
{
decodeUtf16To(in, map, maxLength, maxKeys);
return;
}
synchronized (map) {
String key = null;
String value = null;
int c;
int totalLength = 0;
try (ByteArrayOutputStream2 output = new ByteArrayOutputStream2();) {
int size = 0;
while ((c = in.read()) > 0) {
switch ((char) c) { // depends on control dependency: [while], data = [none]
case '&':
size = output.size();
value = size == 0 ? "" : output.toString(charset);
output.setCount(0);
if (key != null) {
map.add(key, value); // depends on control dependency: [if], data = [(key]
} else if (value != null && value.length() > 0) {
map.add(value, ""); // depends on control dependency: [if], data = [(value]
}
key = null;
value = null;
if (maxKeys > 0 && map.size() > maxKeys)
throw new IllegalStateException(String.format("Form with too many keys [%d > %d]", map.size(), maxKeys));
break;
case '=':
if (key != null) {
output.write(c); // depends on control dependency: [if], data = [none]
break;
}
size = output.size();
key = size == 0 ? "" : output.toString(charset);
output.setCount(0);
break;
case '+':
output.write(' ');
break;
case '%':
int code0 = in.read();
int code1 = in.read();
output.write(decodeHexChar(code0, code1));
break;
default:
output.write(c);
break;
}
totalLength++; // depends on control dependency: [while], data = [none]
if (maxLength >= 0 && totalLength > maxLength)
throw new IllegalStateException("Form is too large");
}
size = output.size();
if (key != null) {
value = size == 0 ? "" : output.toString(charset); // depends on control dependency: [if], data = [none]
output.setCount(0); // depends on control dependency: [if], data = [none]
map.add(key, value); // depends on control dependency: [if], data = [(key]
} else if (size > 0)
map.add(output.toString(charset), "");
}
}
} } |
public class class_name {
public static File createTempFile(final String prefix, final String suffix, final File tempDir) throws IOException {
int exceptionsCount = ZERO;
while (true) {
try {
return File.createTempFile(prefix, suffix, tempDir).getCanonicalFile();
} catch (IOException ioex) { // fixes java.io.WinNTFileSystem.createFileExclusively access denied
if (++exceptionsCount >= 50) {
throw ioex;
}
}
}
} } | public class class_name {
public static File createTempFile(final String prefix, final String suffix, final File tempDir) throws IOException {
int exceptionsCount = ZERO;
while (true) {
try {
return File.createTempFile(prefix, suffix, tempDir).getCanonicalFile(); // depends on control dependency: [try], data = [none]
} catch (IOException ioex) { // fixes java.io.WinNTFileSystem.createFileExclusively access denied
if (++exceptionsCount >= 50) {
throw ioex;
}
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
protected void handleNonListenerError(String msg, Exception error) {
if(logger != null) {
logger.error(msg, error);
}
else {
Log.e("Socialize", msg, error);
}
} } | public class class_name {
protected void handleNonListenerError(String msg, Exception error) {
if(logger != null) {
logger.error(msg, error); // depends on control dependency: [if], data = [none]
}
else {
Log.e("Socialize", msg, error); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public String getFileType() {
if (fileTypeOrName != null && fileTypeOrName.contains(".")) {
return FileUtils.getExtension(fileTypeOrName);
} else {
return fileTypeOrName;
}
} } | public class class_name {
public String getFileType() {
if (fileTypeOrName != null && fileTypeOrName.contains(".")) {
return FileUtils.getExtension(fileTypeOrName); // depends on control dependency: [if], data = [(fileTypeOrName]
} else {
return fileTypeOrName; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Deprecated
public static Locale getLocale() {
Locale locale = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null && facesContext.getViewRoot() != null) {
locale = facesContext.getViewRoot().getLocale();
if (locale == null) {
locale = Locale.getDefault();
}
}
else {
locale = Locale.getDefault();
}
return locale;
} } | public class class_name {
@Deprecated
public static Locale getLocale() {
Locale locale = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null && facesContext.getViewRoot() != null) {
locale = facesContext.getViewRoot().getLocale(); // depends on control dependency: [if], data = [none]
if (locale == null) {
locale = Locale.getDefault(); // depends on control dependency: [if], data = [none]
}
}
else {
locale = Locale.getDefault(); // depends on control dependency: [if], data = [none]
}
return locale;
} } |
public class class_name {
@Override
public boolean clientSelectOneByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
for (ISelectOneByExamplePluginHook plugin : this.getPlugins(ISelectOneByExamplePluginHook.class)) {
if (!plugin.clientSelectOneByExampleWithBLOBsMethodGenerated(method, interfaze, introspectedTable)) {
return false;
}
}
return true;
} } | public class class_name {
@Override
public boolean clientSelectOneByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
for (ISelectOneByExamplePluginHook plugin : this.getPlugins(ISelectOneByExamplePluginHook.class)) {
if (!plugin.clientSelectOneByExampleWithBLOBsMethodGenerated(method, interfaze, introspectedTable)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
@SuppressWarnings ("unchecked")
public ABTreeMap<K,V> updated (K key, V value) {
final UpdateResult result = _updated (key, value);
if (result.optRight == null) {
return result.left;
}
// This is the only place where the tree depth can grow.
// The 'minimum number of children' constraint does not apply to root nodes.
return new IndexNode (spec, new Object[] {result.separator}, new ABTreeMap[] {result.left, result.optRight});
} } | public class class_name {
@SuppressWarnings ("unchecked")
public ABTreeMap<K,V> updated (K key, V value) {
final UpdateResult result = _updated (key, value);
if (result.optRight == null) {
return result.left; // depends on control dependency: [if], data = [none]
}
// This is the only place where the tree depth can grow.
// The 'minimum number of children' constraint does not apply to root nodes.
return new IndexNode (spec, new Object[] {result.separator}, new ABTreeMap[] {result.left, result.optRight});
} } |
public class class_name {
private void addPostParams(final Request request) {
if (language != null) {
request.addPostParam("Language", language);
}
if (value != null) {
request.addPostParam("Value", value);
}
if (synonymOf != null) {
request.addPostParam("SynonymOf", synonymOf.toString());
}
} } | public class class_name {
private void addPostParams(final Request request) {
if (language != null) {
request.addPostParam("Language", language); // depends on control dependency: [if], data = [none]
}
if (value != null) {
request.addPostParam("Value", value); // depends on control dependency: [if], data = [none]
}
if (synonymOf != null) {
request.addPostParam("SynonymOf", synonymOf.toString()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public <T extends AbstractJaxb> void saveToStringWriter(T tag,
StringWriter writer) {
// add one white space into script tag
// having empty content.
for (Script script : tag.getDescendants(Script.class)) {
if (script.getContent() == null || script.getContent().length() < 1) {
script.setContent(" ");
}
}
// add one white space into iframe tag having empty content.
for (Iframe iframe : tag.getDescendants(Iframe.class)) {
if (iframe.getContent() == null || iframe.getContent().size() < 1) {
iframe.getContent().add(" ");
}
}
// add one line break into textarea tag
// having empty content.
for (Textarea textarea : tag.getDescendants(Textarea.class)) {
if (textarea.getContent() == null || textarea.getContent().length() < 1) {
textarea.setContent(System.getProperty("line.separator"));
}
}
tag.removeEmptyCssClass();
StringWriter tmpWriter = new StringWriter();
Marshaller m;
try {
m = jaxbContext.createMarshaller();
m.setProperty(Marshaller.JAXB_ENCODING, Charset.defaultCharset()
.name());
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
m.setProperty(Marshaller.JAXB_FRAGMENT, true);
XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance()
.createXMLEventWriter(tmpWriter);
m.marshal(tag, new TagCustomizeWriter(xmlEventWriter));
} catch (JAXBException e) {
log.warn("marshal failed.", e);
} catch (XMLStreamException e) {
log.warn("XMLStreamException happend. while saveToWriter().", e);
} catch (FactoryConfigurationError e) {
log.warn(
"FactoryConfigurationError happend. while saveToWriter().",
e);
}
// transform xhtml strings
String xmlStr;
if (tag.getClass().getSimpleName().toLowerCase().equals("html")) {
xmlStr = tmpWriter.toString().trim();
} else {
xmlStr = tmpWriter.toString().trim()
.replaceFirst("xmlns=\"[^\"]+\"", "");
}
Reader xml = new StringReader(xmlStr);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = transFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
"yes");
transformer.transform(new StreamSource(xml), new StreamResult(
writer));
} catch (TransformerConfigurationException e) {
log.warn(
"TransformerConfigurationException happend. while saveToWriter().",
e);
} catch (TransformerException e) {
log.warn("TransformerException happend. while saveToWriter().", e);
}
} } | public class class_name {
public <T extends AbstractJaxb> void saveToStringWriter(T tag,
StringWriter writer) {
// add one white space into script tag
// having empty content.
for (Script script : tag.getDescendants(Script.class)) {
if (script.getContent() == null || script.getContent().length() < 1) {
script.setContent(" "); // depends on control dependency: [if], data = [none]
}
}
// add one white space into iframe tag having empty content.
for (Iframe iframe : tag.getDescendants(Iframe.class)) {
if (iframe.getContent() == null || iframe.getContent().size() < 1) {
iframe.getContent().add(" "); // depends on control dependency: [if], data = [none]
}
}
// add one line break into textarea tag
// having empty content.
for (Textarea textarea : tag.getDescendants(Textarea.class)) {
if (textarea.getContent() == null || textarea.getContent().length() < 1) {
textarea.setContent(System.getProperty("line.separator"));
}
}
tag.removeEmptyCssClass();
StringWriter tmpWriter = new StringWriter();
Marshaller m;
try {
m = jaxbContext.createMarshaller(); // depends on control dependency: [try], data = [none]
m.setProperty(Marshaller.JAXB_ENCODING, Charset.defaultCharset()
.name()); // depends on control dependency: [try], data = [none]
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false); // depends on control dependency: [try], data = [none]
m.setProperty(Marshaller.JAXB_FRAGMENT, true); // depends on control dependency: [try], data = [none]
XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance()
.createXMLEventWriter(tmpWriter);
m.marshal(tag, new TagCustomizeWriter(xmlEventWriter)); // depends on control dependency: [try], data = [none]
} catch (JAXBException e) {
log.warn("marshal failed.", e);
} catch (XMLStreamException e) { // depends on control dependency: [catch], data = [none]
log.warn("XMLStreamException happend. while saveToWriter().", e);
} catch (FactoryConfigurationError e) { // depends on control dependency: [catch], data = [none]
log.warn(
"FactoryConfigurationError happend. while saveToWriter().",
e);
} // depends on control dependency: [catch], data = [none]
// transform xhtml strings
String xmlStr;
if (tag.getClass().getSimpleName().toLowerCase().equals("html")) {
xmlStr = tmpWriter.toString().trim(); // depends on control dependency: [if], data = [none]
} else {
xmlStr = tmpWriter.toString().trim()
.replaceFirst("xmlns=\"[^\"]+\"", ""); // depends on control dependency: [if], data = [none]
}
Reader xml = new StringReader(xmlStr);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = transFactory.newTransformer(); // depends on control dependency: [try], data = [none]
transformer.setOutputProperty(OutputKeys.INDENT, "no"); // depends on control dependency: [try], data = [none]
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
"yes"); // depends on control dependency: [try], data = [none]
transformer.transform(new StreamSource(xml), new StreamResult(
writer)); // depends on control dependency: [try], data = [none]
} catch (TransformerConfigurationException e) {
log.warn(
"TransformerConfigurationException happend. while saveToWriter().",
e);
} catch (TransformerException e) { // depends on control dependency: [catch], data = [none]
log.warn("TransformerException happend. while saveToWriter().", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private double distance(Instance inst1, double[] inst2){
double distance = 0.0;
for (int i = 0; i < numDims; i++) {
double d = inst1.value(i) - inst2[i];
distance += d * d;
}
return Math.sqrt(distance);
} } | public class class_name {
private double distance(Instance inst1, double[] inst2){
double distance = 0.0;
for (int i = 0; i < numDims; i++) {
double d = inst1.value(i) - inst2[i];
distance += d * d; // depends on control dependency: [for], data = [none]
}
return Math.sqrt(distance);
} } |
public class class_name {
public void setDefault(Currency currency) {
if (currencyList.containsKey(currency.getName())) {
Common.getInstance().getStorageHandler().getStorageEngine().setDefaultCurrency(currency);
defaultCurrency = currency;
currency.setDefault(true);
for (Map.Entry<String, Currency> currencyEntry : currencyList.entrySet()) {
if (!currencyEntry.getValue().equals(currency)) {
currency.setDefault(false);
}
}
}
} } | public class class_name {
public void setDefault(Currency currency) {
if (currencyList.containsKey(currency.getName())) {
Common.getInstance().getStorageHandler().getStorageEngine().setDefaultCurrency(currency); // depends on control dependency: [if], data = [none]
defaultCurrency = currency; // depends on control dependency: [if], data = [none]
currency.setDefault(true); // depends on control dependency: [if], data = [none]
for (Map.Entry<String, Currency> currencyEntry : currencyList.entrySet()) {
if (!currencyEntry.getValue().equals(currency)) {
currency.setDefault(false); // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
public FacesConfigReferencedBeanType<WebFacesConfigDescriptor> getOrCreateReferencedBean()
{
List<Node> nodeList = model.get("referenced-bean");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigReferencedBeanTypeImpl<WebFacesConfigDescriptor>(this, "referenced-bean", model, nodeList.get(0));
}
return createReferencedBean();
} } | public class class_name {
public FacesConfigReferencedBeanType<WebFacesConfigDescriptor> getOrCreateReferencedBean()
{
List<Node> nodeList = model.get("referenced-bean");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigReferencedBeanTypeImpl<WebFacesConfigDescriptor>(this, "referenced-bean", model, nodeList.get(0)); // depends on control dependency: [if], data = [none]
}
return createReferencedBean();
} } |
public class class_name {
private static List<Field> findFields() {
List<Field> result = new ArrayList<Field>();
for (Field f : LoadStatistics.class.getFields()) {
if (Modifier.isPublic(f.getModifiers()) && MultiStageTimeSeries.class.isAssignableFrom(f.getType())
&& f.getAnnotation(Deprecated.class) == null) {
result.add(f);
}
}
return result;
} } | public class class_name {
private static List<Field> findFields() {
List<Field> result = new ArrayList<Field>();
for (Field f : LoadStatistics.class.getFields()) {
if (Modifier.isPublic(f.getModifiers()) && MultiStageTimeSeries.class.isAssignableFrom(f.getType())
&& f.getAnnotation(Deprecated.class) == null) {
result.add(f); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
void onCompletion(Collection<ApplicationDependency> dependencies) {
if (!dependencies.isEmpty()) {
for (ApplicationDependency dependency : dependencies) {
dependency.onCompletion(this);
}
}
} } | public class class_name {
void onCompletion(Collection<ApplicationDependency> dependencies) {
if (!dependencies.isEmpty()) {
for (ApplicationDependency dependency : dependencies) {
dependency.onCompletion(this); // depends on control dependency: [for], data = [dependency]
}
}
} } |
public class class_name {
public Object getValueAt(int iRowIndex, int iColumnIndex)
{
int iEditMode = Constants.EDIT_NONE;
try {
if (iRowIndex >= 0)
{
FieldList fieldList = this.makeRowCurrent(iRowIndex, false);
if (fieldList != null)
iEditMode = fieldList.getEditMode();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return this.getColumnValue(iColumnIndex, iEditMode);
} } | public class class_name {
public Object getValueAt(int iRowIndex, int iColumnIndex)
{
int iEditMode = Constants.EDIT_NONE;
try {
if (iRowIndex >= 0)
{
FieldList fieldList = this.makeRowCurrent(iRowIndex, false);
if (fieldList != null)
iEditMode = fieldList.getEditMode();
}
} catch (Exception ex) {
ex.printStackTrace();
} // depends on control dependency: [catch], data = [none]
return this.getColumnValue(iColumnIndex, iEditMode);
} } |
public class class_name {
private ExtractionInfo extractSingleLineBlock() {
// Get the current starting point.
stream.update();
int lineno = stream.getLineno();
int charno = stream.getCharno() + 1;
String line = getRemainingJSDocLine().trim();
// Record the textual description.
if (line.length() > 0) {
jsdocBuilder.markText(line, lineno, charno, lineno,
charno + line.length());
}
return new ExtractionInfo(line, next());
} } | public class class_name {
private ExtractionInfo extractSingleLineBlock() {
// Get the current starting point.
stream.update();
int lineno = stream.getLineno();
int charno = stream.getCharno() + 1;
String line = getRemainingJSDocLine().trim();
// Record the textual description.
if (line.length() > 0) {
jsdocBuilder.markText(line, lineno, charno, lineno,
charno + line.length()); // depends on control dependency: [if], data = [none]
}
return new ExtractionInfo(line, next());
} } |
public class class_name {
public String
computefqn()
{
List<DapNode> path = getPath(); // excludes root/wrt
StringBuilder fqn = new StringBuilder();
DapNode parent = path.get(0);
for(int i = 1; i < path.size(); i++) { // start at 1 to skip root
DapNode current = path.get(i);
// Depending on what parent is, use different delimiters
switch (parent.getSort()) {
case DATASET:
case GROUP:
case ENUMERATION:
fqn.append('/');
fqn.append(Escape.backslashEscape(current.getShortName(),"/."));
break;
// These use '.'
case STRUCTURE:
case SEQUENCE:
case ENUMCONST:
case VARIABLE:
fqn.append('.');
fqn.append(current.getEscapedShortName());
break;
default: // Others should never happen
throw new IllegalArgumentException("Illegal FQN parent");
}
parent = current;
}
return fqn.toString();
} } | public class class_name {
public String
computefqn()
{
List<DapNode> path = getPath(); // excludes root/wrt
StringBuilder fqn = new StringBuilder();
DapNode parent = path.get(0);
for(int i = 1; i < path.size(); i++) { // start at 1 to skip root
DapNode current = path.get(i);
// Depending on what parent is, use different delimiters
switch (parent.getSort()) {
case DATASET:
case GROUP:
case ENUMERATION:
fqn.append('/');
fqn.append(Escape.backslashEscape(current.getShortName(),"/.")); // depends on control dependency: [for], data = [none]
break;
// These use '.'
case STRUCTURE:
case SEQUENCE:
case ENUMCONST:
case VARIABLE:
fqn.append('.');
fqn.append(current.getEscapedShortName()); // depends on control dependency: [for], data = [none]
break;
default: // Others should never happen
throw new IllegalArgumentException("Illegal FQN parent");
}
parent = current;
}
return fqn.toString();
} } |
public class class_name {
@Override
public int executeBatch()
{
if (batchSize > 0)
{
boolean nodeAutoIndexingEnabled = indexer.isNodeAutoIndexingEnabled(factory.getConnection());
boolean relationshipAutoIndexingEnabled = indexer
.isRelationshipAutoIndexingEnabled(factory.getConnection());
BatchInserter inserter = getBatchInserter();
BatchInserterIndexProvider indexProvider = new LuceneBatchInserterIndexProvider(inserter);
if (inserter == null)
{
log.error("Unable to create instance of BatchInserter. Opertion will fail");
throw new PersistenceException("Unable to create instance of BatchInserter. Opertion will fail");
}
if (resource != null && resource.isActive())
{
log.error("Batch Insertion MUST not be executed in a transaction");
throw new PersistenceException("Batch Insertion MUST not be executed in a transaction");
}
Map<Object, Long> pkToNodeIdMap = new HashMap<Object, Long>();
for (com.impetus.kundera.graph.Node graphNode : nodes)
{
if (graphNode.isDirty())
{
graphNode.handlePreEvent();
// Delete can not be executed in batch, deleting normally
if (graphNode.isInState(RemovedState.class))
{
delete(graphNode.getData(), graphNode.getEntityId());
}
else if (graphNode.isUpdate())
{
// Neo4J allows only batch insertion, follow usual path
// for normal updates
persist(graphNode);
}
else
{
// Insert node
Object entity = graphNode.getData();
EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
Object pk = PropertyAccessorHelper.getId(entity, m);
Map<String, Object> nodeProperties = mapper.createNodeProperties(entity, m);
long nodeId = inserter.createNode(nodeProperties);
pkToNodeIdMap.put(pk, nodeId);
// Index Node
indexer.indexNodeUsingBatchIndexer(indexProvider, m, nodeId, nodeProperties,
nodeAutoIndexingEnabled);
// Insert relationships for this particular node
if (!getRelationHolders(graphNode).isEmpty())
{
for (RelationHolder rh : getRelationHolders(graphNode))
{
// Search Node (to be connected to ) in Neo4J
// graph
EntityMetadata targetNodeMetadata = KunderaMetadataManager.getEntityMetadata(
kunderaMetadata, rh.getRelationValue().getClass());
Object targetNodeKey = PropertyAccessorHelper.getId(rh.getRelationValue(),
targetNodeMetadata);
Long targetNodeId = pkToNodeIdMap.get(targetNodeKey);
if (targetNodeId != null)
{
/**
* Join this node (source node) to target
* node via relationship
*/
// Relationship Type
DynamicRelationshipType relType = DynamicRelationshipType.withName(rh
.getRelationName());
// Relationship Properties
Map<String, Object> relationshipProperties = null;
Object relationshipObj = rh.getRelationVia();
if (relationshipObj != null)
{
EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(
kunderaMetadata, relationshipObj.getClass());
relationshipProperties = mapper.createRelationshipProperties(m,
targetNodeMetadata, relationshipObj);
// Finally insert relationship
long relationshipId = inserter.createRelationship(nodeId, targetNodeId,
relType, relationshipProperties);
// Index this relationship
indexer.indexRelationshipUsingBatchIndexer(indexProvider, relationMetadata,
relationshipId, relationshipProperties, relationshipAutoIndexingEnabled);
}
}
}
}
}
graphNode.handlePostEvent();
}
}
// Shutdown Batch inserter
indexProvider.shutdown();
inserter.shutdown();
// Restore Graph Database service
factory.setConnection((GraphDatabaseService) factory.createPoolOrConnection());
return pkToNodeIdMap.size();
}
else
{
return 0;
}
} } | public class class_name {
@Override
public int executeBatch()
{
if (batchSize > 0)
{
boolean nodeAutoIndexingEnabled = indexer.isNodeAutoIndexingEnabled(factory.getConnection());
boolean relationshipAutoIndexingEnabled = indexer
.isRelationshipAutoIndexingEnabled(factory.getConnection());
BatchInserter inserter = getBatchInserter();
BatchInserterIndexProvider indexProvider = new LuceneBatchInserterIndexProvider(inserter);
if (inserter == null)
{
log.error("Unable to create instance of BatchInserter. Opertion will fail"); // depends on control dependency: [if], data = [none]
throw new PersistenceException("Unable to create instance of BatchInserter. Opertion will fail");
}
if (resource != null && resource.isActive())
{
log.error("Batch Insertion MUST not be executed in a transaction"); // depends on control dependency: [if], data = [none]
throw new PersistenceException("Batch Insertion MUST not be executed in a transaction");
}
Map<Object, Long> pkToNodeIdMap = new HashMap<Object, Long>();
for (com.impetus.kundera.graph.Node graphNode : nodes)
{
if (graphNode.isDirty())
{
graphNode.handlePreEvent(); // depends on control dependency: [if], data = [none]
// Delete can not be executed in batch, deleting normally
if (graphNode.isInState(RemovedState.class))
{
delete(graphNode.getData(), graphNode.getEntityId()); // depends on control dependency: [if], data = [none]
}
else if (graphNode.isUpdate())
{
// Neo4J allows only batch insertion, follow usual path
// for normal updates
persist(graphNode); // depends on control dependency: [if], data = [none]
}
else
{
// Insert node
Object entity = graphNode.getData();
EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
Object pk = PropertyAccessorHelper.getId(entity, m);
Map<String, Object> nodeProperties = mapper.createNodeProperties(entity, m);
long nodeId = inserter.createNode(nodeProperties);
pkToNodeIdMap.put(pk, nodeId); // depends on control dependency: [if], data = [none]
// Index Node
indexer.indexNodeUsingBatchIndexer(indexProvider, m, nodeId, nodeProperties,
nodeAutoIndexingEnabled); // depends on control dependency: [if], data = [none]
// Insert relationships for this particular node
if (!getRelationHolders(graphNode).isEmpty())
{
for (RelationHolder rh : getRelationHolders(graphNode))
{
// Search Node (to be connected to ) in Neo4J
// graph
EntityMetadata targetNodeMetadata = KunderaMetadataManager.getEntityMetadata(
kunderaMetadata, rh.getRelationValue().getClass());
Object targetNodeKey = PropertyAccessorHelper.getId(rh.getRelationValue(),
targetNodeMetadata);
Long targetNodeId = pkToNodeIdMap.get(targetNodeKey);
if (targetNodeId != null)
{
/**
* Join this node (source node) to target
* node via relationship
*/
// Relationship Type
DynamicRelationshipType relType = DynamicRelationshipType.withName(rh
.getRelationName());
// Relationship Properties
Map<String, Object> relationshipProperties = null;
Object relationshipObj = rh.getRelationVia();
if (relationshipObj != null)
{
EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(
kunderaMetadata, relationshipObj.getClass());
relationshipProperties = mapper.createRelationshipProperties(m,
targetNodeMetadata, relationshipObj); // depends on control dependency: [if], data = [none]
// Finally insert relationship
long relationshipId = inserter.createRelationship(nodeId, targetNodeId,
relType, relationshipProperties);
// Index this relationship
indexer.indexRelationshipUsingBatchIndexer(indexProvider, relationMetadata,
relationshipId, relationshipProperties, relationshipAutoIndexingEnabled); // depends on control dependency: [if], data = [none]
}
}
}
}
}
graphNode.handlePostEvent(); // depends on control dependency: [if], data = [none]
}
}
// Shutdown Batch inserter
indexProvider.shutdown(); // depends on control dependency: [if], data = [none]
inserter.shutdown(); // depends on control dependency: [if], data = [none]
// Restore Graph Database service
factory.setConnection((GraphDatabaseService) factory.createPoolOrConnection()); // depends on control dependency: [if], data = [none]
return pkToNodeIdMap.size(); // depends on control dependency: [if], data = [none]
}
else
{
return 0; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public EClass getIfcRelationship() {
if (ifcRelationshipEClass == null) {
ifcRelationshipEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(486);
}
return ifcRelationshipEClass;
} } | public class class_name {
public EClass getIfcRelationship() {
if (ifcRelationshipEClass == null) {
ifcRelationshipEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(486);
// depends on control dependency: [if], data = [none]
}
return ifcRelationshipEClass;
} } |
public class class_name {
public static String trimWhitespace(final String str) {
if (!StringUtils.hasLength(str)) {
return str;
}
int beginIndex = 0;
int endIndex = str.length() - 1;
while (beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex))) {
beginIndex++;
}
while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) {
endIndex--;
}
return str.substring(beginIndex, endIndex + 1);
} } | public class class_name {
public static String trimWhitespace(final String str) {
if (!StringUtils.hasLength(str)) {
return str; // depends on control dependency: [if], data = [none]
}
int beginIndex = 0;
int endIndex = str.length() - 1;
while (beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex))) {
beginIndex++; // depends on control dependency: [while], data = [none]
}
while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) {
endIndex--; // depends on control dependency: [while], data = [none]
}
return str.substring(beginIndex, endIndex + 1);
} } |
public class class_name {
public static base_responses delete(nitro_service client, String ipfrom[]) throws Exception {
base_responses result = null;
if (ipfrom != null && ipfrom.length > 0) {
location deleteresources[] = new location[ipfrom.length];
for (int i=0;i<ipfrom.length;i++){
deleteresources[i] = new location();
deleteresources[i].ipfrom = ipfrom[i];
}
result = delete_bulk_request(client, deleteresources);
}
return result;
} } | public class class_name {
public static base_responses delete(nitro_service client, String ipfrom[]) throws Exception {
base_responses result = null;
if (ipfrom != null && ipfrom.length > 0) {
location deleteresources[] = new location[ipfrom.length];
for (int i=0;i<ipfrom.length;i++){
deleteresources[i] = new location(); // depends on control dependency: [for], data = [i]
deleteresources[i].ipfrom = ipfrom[i]; // depends on control dependency: [for], data = [i]
}
result = delete_bulk_request(client, deleteresources);
}
return result;
} } |
public class class_name {
private void verifyIfBundleIsModified(JoinableResourceBundleImpl bundle, List<String> mappings,
PropertiesConfigHelper props) {
// Retrieves current available variant
Map<String, VariantSet> variants = new TreeMap<>();
for (String mapping : mappings) {
variants = VariantUtils.concatVariants(variants, generatorRegistry.getAvailableVariants(mapping));
}
// Checks if the current variant are the same as the stored one
if (!variants.equals(bundle.getVariants())) {
bundle.setVariants(variants);
bundle.setDirty(true);
} else {
String bundleName = bundle.getName();
List<String> fileMappings = props.getCustomBundlePropertyAsList(bundleName,
PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_FILEPATH_MAPPINGS);
if (fileMappings != null) {
List<FilePathMapping> bundleFileMappings = bundle.getFilePathMappings();
if (bundleFileMappings.size() != fileMappings.size()) {
bundle.setDirty(true);
} else {
Set<FilePathMapping> storedFilePathMapping = new HashSet<>();
for (String filePathWithTimeStamp : fileMappings) {
String[] tmp = filePathWithTimeStamp.split(LAST_MODIFIED_SEPARATOR);
String filePath = tmp[0];
long storedLastModified = Long.parseLong(tmp[1]);
storedFilePathMapping.add(new FilePathMapping(bundle, filePath, storedLastModified));
}
Set<FilePathMapping> bundleFilePathMappingSet = new HashSet<>(bundleFileMappings);
if (!bundleFilePathMappingSet.equals(storedFilePathMapping)) {
bundle.setDirty(true);
}
}
}
// Checks if the linked resource has been modified
fileMappings = props.getCustomBundlePropertyAsList(bundleName,
PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_LINKED_FILEPATH_MAPPINGS);
for (String filePathWithTimeStamp : fileMappings) {
int idx = filePathWithTimeStamp.lastIndexOf(LAST_MODIFIED_SEPARATOR);
if (idx != -1) {
String filePath = filePathWithTimeStamp.substring(0, idx);
long storedLastModified = Long.parseLong(filePathWithTimeStamp.substring(idx + 1));
long currentLastModified = rsReaderHandler.getLastModified(filePath);
FilePathMapping fPathMapping = new FilePathMapping(bundle, filePath, currentLastModified);
bundle.getLinkedFilePathMappings().add(fPathMapping);
if (storedLastModified != currentLastModified) {
bundle.setDirty(true);
}
}
}
}
} } | public class class_name {
private void verifyIfBundleIsModified(JoinableResourceBundleImpl bundle, List<String> mappings,
PropertiesConfigHelper props) {
// Retrieves current available variant
Map<String, VariantSet> variants = new TreeMap<>();
for (String mapping : mappings) {
variants = VariantUtils.concatVariants(variants, generatorRegistry.getAvailableVariants(mapping)); // depends on control dependency: [for], data = [mapping]
}
// Checks if the current variant are the same as the stored one
if (!variants.equals(bundle.getVariants())) {
bundle.setVariants(variants); // depends on control dependency: [if], data = [none]
bundle.setDirty(true); // depends on control dependency: [if], data = [none]
} else {
String bundleName = bundle.getName();
List<String> fileMappings = props.getCustomBundlePropertyAsList(bundleName,
PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_FILEPATH_MAPPINGS);
if (fileMappings != null) {
List<FilePathMapping> bundleFileMappings = bundle.getFilePathMappings();
if (bundleFileMappings.size() != fileMappings.size()) {
bundle.setDirty(true); // depends on control dependency: [if], data = [none]
} else {
Set<FilePathMapping> storedFilePathMapping = new HashSet<>();
for (String filePathWithTimeStamp : fileMappings) {
String[] tmp = filePathWithTimeStamp.split(LAST_MODIFIED_SEPARATOR);
String filePath = tmp[0];
long storedLastModified = Long.parseLong(tmp[1]);
storedFilePathMapping.add(new FilePathMapping(bundle, filePath, storedLastModified)); // depends on control dependency: [for], data = [none]
}
Set<FilePathMapping> bundleFilePathMappingSet = new HashSet<>(bundleFileMappings);
if (!bundleFilePathMappingSet.equals(storedFilePathMapping)) {
bundle.setDirty(true); // depends on control dependency: [if], data = [none]
}
}
}
// Checks if the linked resource has been modified
fileMappings = props.getCustomBundlePropertyAsList(bundleName,
PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_LINKED_FILEPATH_MAPPINGS); // depends on control dependency: [if], data = [none]
for (String filePathWithTimeStamp : fileMappings) {
int idx = filePathWithTimeStamp.lastIndexOf(LAST_MODIFIED_SEPARATOR);
if (idx != -1) {
String filePath = filePathWithTimeStamp.substring(0, idx);
long storedLastModified = Long.parseLong(filePathWithTimeStamp.substring(idx + 1));
long currentLastModified = rsReaderHandler.getLastModified(filePath);
FilePathMapping fPathMapping = new FilePathMapping(bundle, filePath, currentLastModified);
bundle.getLinkedFilePathMappings().add(fPathMapping); // depends on control dependency: [if], data = [none]
if (storedLastModified != currentLastModified) {
bundle.setDirty(true); // depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
private Rectangle2D getBounds(ServletRequest pReq, BufferedImage pImage,
double pAng) {
// Get dimensions of original image
int width = pImage.getWidth(); // loads the image
int height = pImage.getHeight();
// Test if we want to crop image (default)
// if true
// - find the largest bounding box INSIDE the rotated image,
// that matches the original proportions (nearest 90deg)
// (scale up to fit dimensions?)
// else
// - find the smallest bounding box OUTSIDE the rotated image.
// - that matches the original proportions (nearest 90deg) ?
// (scale down to fit dimensions?)
AffineTransform at =
AffineTransform.getRotateInstance(pAng, width / 2.0, height / 2.0);
Rectangle2D orig = new Rectangle(width, height);
Shape rotated = at.createTransformedShape(orig);
if (ServletUtil.getBooleanParameter(pReq, PARAM_CROP, false)) {
// TODO: Inside box
return rotated.getBounds2D();
}
else {
return rotated.getBounds2D();
}
} } | public class class_name {
private Rectangle2D getBounds(ServletRequest pReq, BufferedImage pImage,
double pAng) {
// Get dimensions of original image
int width = pImage.getWidth(); // loads the image
int height = pImage.getHeight();
// Test if we want to crop image (default)
// if true
// - find the largest bounding box INSIDE the rotated image,
// that matches the original proportions (nearest 90deg)
// (scale up to fit dimensions?)
// else
// - find the smallest bounding box OUTSIDE the rotated image.
// - that matches the original proportions (nearest 90deg) ?
// (scale down to fit dimensions?)
AffineTransform at =
AffineTransform.getRotateInstance(pAng, width / 2.0, height / 2.0);
Rectangle2D orig = new Rectangle(width, height);
Shape rotated = at.createTransformedShape(orig);
if (ServletUtil.getBooleanParameter(pReq, PARAM_CROP, false)) {
// TODO: Inside box
return rotated.getBounds2D();
// depends on control dependency: [if], data = [none]
}
else {
return rotated.getBounds2D();
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void undo() {
if (hasUndo()) {
ChangeType type = m_current.getType();
String entityId = m_current.getEntityId();
String attributeName = m_current.getAttributeName();
int valueIndex = m_current.getValueIndex();
m_redo.push(m_current);
m_current = m_undo.pop();
changeEntityContentValues(m_current.getEntityData(), entityId, attributeName, valueIndex, type);
fireStateChange();
}
} } | public class class_name {
public void undo() {
if (hasUndo()) {
ChangeType type = m_current.getType();
String entityId = m_current.getEntityId();
String attributeName = m_current.getAttributeName();
int valueIndex = m_current.getValueIndex();
m_redo.push(m_current); // depends on control dependency: [if], data = [none]
m_current = m_undo.pop(); // depends on control dependency: [if], data = [none]
changeEntityContentValues(m_current.getEntityData(), entityId, attributeName, valueIndex, type); // depends on control dependency: [if], data = [none]
fireStateChange(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void setMonth(int month) {
calendar.set(Calendar.MONTH, month);
int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
int adjustedDay = day;
if (day > maxDays) {
adjustedDay = maxDays;
setDay(adjustedDay);
}
drawDays();
} } | public class class_name {
public void setMonth(int month) {
calendar.set(Calendar.MONTH, month);
int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
int adjustedDay = day;
if (day > maxDays) {
adjustedDay = maxDays; // depends on control dependency: [if], data = [none]
setDay(adjustedDay); // depends on control dependency: [if], data = [none]
}
drawDays();
} } |
public class class_name {
public CreateIndexRequest withOrderedIndexedAttributeList(AttributeKey... orderedIndexedAttributeList) {
if (this.orderedIndexedAttributeList == null) {
setOrderedIndexedAttributeList(new java.util.ArrayList<AttributeKey>(orderedIndexedAttributeList.length));
}
for (AttributeKey ele : orderedIndexedAttributeList) {
this.orderedIndexedAttributeList.add(ele);
}
return this;
} } | public class class_name {
public CreateIndexRequest withOrderedIndexedAttributeList(AttributeKey... orderedIndexedAttributeList) {
if (this.orderedIndexedAttributeList == null) {
setOrderedIndexedAttributeList(new java.util.ArrayList<AttributeKey>(orderedIndexedAttributeList.length)); // depends on control dependency: [if], data = [none]
}
for (AttributeKey ele : orderedIndexedAttributeList) {
this.orderedIndexedAttributeList.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public static void main(String[] args) {
try {
Stemming.useStemmer(new PTStemmer(), args);
}
catch (Exception e) {
e.printStackTrace();
}
} } | public class class_name {
public static void main(String[] args) {
try {
Stemming.useStemmer(new PTStemmer(), args); // depends on control dependency: [try], data = [none]
}
catch (Exception e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private double calculateC(ExampleSet data) //throws Exception
{
String svmCost = parameter.getProperty("svm-cost");
if (svmCost != null)
return Integer.parseInt(svmCost);
logger.info("calculate default SVM cost parameter C");
//double c = 1;
double avr = 0;
// the example set is normalized
// all vectors have the same norm
for (int i=0;i<data.size();i++)
{
Vector v = (Vector) data.x(i);
double norm = v.norm();
//logger.info(i + ", norm = " + norm);
//if (norm > c)
// c = norm;
avr += norm;
} // end for i
return 1/Math.pow(avr / data.size(), 2);
} } | public class class_name {
private double calculateC(ExampleSet data) //throws Exception
{
String svmCost = parameter.getProperty("svm-cost");
if (svmCost != null)
return Integer.parseInt(svmCost);
logger.info("calculate default SVM cost parameter C");
//double c = 1;
double avr = 0;
// the example set is normalized
// all vectors have the same norm
for (int i=0;i<data.size();i++)
{
Vector v = (Vector) data.x(i);
double norm = v.norm();
//logger.info(i + ", norm = " + norm);
//if (norm > c)
// c = norm;
avr += norm; // depends on control dependency: [for], data = [none]
} // end for i
return 1/Math.pow(avr / data.size(), 2);
} } |
public class class_name {
@Override
public JsonArray deepCopy() {
if (!elements.isEmpty()) {
JsonArray result = new JsonArray(elements.size());
for (JsonElement element : elements) {
result.add(element.deepCopy());
}
return result;
}
return new JsonArray();
} } | public class class_name {
@Override
public JsonArray deepCopy() {
if (!elements.isEmpty()) {
JsonArray result = new JsonArray(elements.size());
for (JsonElement element : elements) {
result.add(element.deepCopy()); // depends on control dependency: [for], data = [element]
}
return result; // depends on control dependency: [if], data = [none]
}
return new JsonArray();
} } |
public class class_name {
public void setSqlRunConfigurations(java.util.Collection<SqlRunConfiguration> sqlRunConfigurations) {
if (sqlRunConfigurations == null) {
this.sqlRunConfigurations = null;
return;
}
this.sqlRunConfigurations = new java.util.ArrayList<SqlRunConfiguration>(sqlRunConfigurations);
} } | public class class_name {
public void setSqlRunConfigurations(java.util.Collection<SqlRunConfiguration> sqlRunConfigurations) {
if (sqlRunConfigurations == null) {
this.sqlRunConfigurations = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.sqlRunConfigurations = new java.util.ArrayList<SqlRunConfiguration>(sqlRunConfigurations);
} } |
public class class_name {
public static boolean validateSign(Map<String,String> map,String sign_type,String key){
if(map.get("sign") == null){
return false;
}
return map.get("sign").equals(generateSign(map,sign_type,key));
} } | public class class_name {
public static boolean validateSign(Map<String,String> map,String sign_type,String key){
if(map.get("sign") == null){
return false;
// depends on control dependency: [if], data = [none]
}
return map.get("sign").equals(generateSign(map,sign_type,key));
} } |
public class class_name {
public static SparseTensor vector(int dimensionNumber, int dimensionSize, double[] values) {
long[] keyNums = new long[dimensionSize];
double[] outcomeValues = new double[dimensionSize];
int numEntries = 0;
for (int i = 0; i < dimensionSize; i++) {
if (values[i] != 0.0) {
keyNums[numEntries] = i;
outcomeValues[numEntries] = values[i];
numEntries++;
}
}
return resizeIntoTable(new int[] { dimensionNumber }, new int[] { dimensionSize },
keyNums, outcomeValues, numEntries);
} } | public class class_name {
public static SparseTensor vector(int dimensionNumber, int dimensionSize, double[] values) {
long[] keyNums = new long[dimensionSize];
double[] outcomeValues = new double[dimensionSize];
int numEntries = 0;
for (int i = 0; i < dimensionSize; i++) {
if (values[i] != 0.0) {
keyNums[numEntries] = i; // depends on control dependency: [if], data = [none]
outcomeValues[numEntries] = values[i]; // depends on control dependency: [if], data = [none]
numEntries++; // depends on control dependency: [if], data = [none]
}
}
return resizeIntoTable(new int[] { dimensionNumber }, new int[] { dimensionSize },
keyNums, outcomeValues, numEntries);
} } |
public class class_name {
public synchronized EvaluatorContext getContext(final String contextId) {
for (final EvaluatorContext context : this.contextStack) {
if (context.getId().equals(contextId)) {
return context;
}
}
throw new RuntimeException("Unknown evaluator context " + contextId);
} } | public class class_name {
public synchronized EvaluatorContext getContext(final String contextId) {
for (final EvaluatorContext context : this.contextStack) {
if (context.getId().equals(contextId)) {
return context; // depends on control dependency: [if], data = [none]
}
}
throw new RuntimeException("Unknown evaluator context " + contextId);
} } |
public class class_name {
public Map<String, String> getSkeletons(Map<String, String> result) {
if (result == null) {
result = new LinkedHashMap<String, String>();
}
for (DateTimeMatcher item : skeleton2pattern.keySet()) {
PatternWithSkeletonFlag patternWithSkelFlag = skeleton2pattern.get(item);
String pattern = patternWithSkelFlag.pattern;
if (CANONICAL_SET.contains(pattern)) {
continue;
}
result.put(item.toString(), pattern);
}
return result;
} } | public class class_name {
public Map<String, String> getSkeletons(Map<String, String> result) {
if (result == null) {
result = new LinkedHashMap<String, String>(); // depends on control dependency: [if], data = [none]
}
for (DateTimeMatcher item : skeleton2pattern.keySet()) {
PatternWithSkeletonFlag patternWithSkelFlag = skeleton2pattern.get(item);
String pattern = patternWithSkelFlag.pattern;
if (CANONICAL_SET.contains(pattern)) {
continue;
}
result.put(item.toString(), pattern); // depends on control dependency: [for], data = [item]
}
return result;
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.