code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
|---|---|
public class class_name {
public Object getService(TargetMetaDef targetMetaDef) {
Debug.logVerbose("[JdonFramework] --> enter getService from dynamicProxy", module);
Object dynamicProxy = _proxyCache.get(targetMetaDef);
if (dynamicProxy == null) {
dynamicProxy = getServiceFromProxy(targetMetaDef);
_proxyCache.put(targetMetaDef, dynamicProxy);
}
return dynamicProxy;
} }
|
public class class_name {
public Object getService(TargetMetaDef targetMetaDef) {
Debug.logVerbose("[JdonFramework] --> enter getService from dynamicProxy", module);
Object dynamicProxy = _proxyCache.get(targetMetaDef);
if (dynamicProxy == null) {
dynamicProxy = getServiceFromProxy(targetMetaDef);
// depends on control dependency: [if], data = [none]
_proxyCache.put(targetMetaDef, dynamicProxy);
// depends on control dependency: [if], data = [none]
}
return dynamicProxy;
} }
|
public class class_name {
public byte[] encrypt(byte[] message, byte[] aad, byte[] iv) throws GeneralSecurityException {
Cipher cipher = getCipher(true);
if(iv == null && generateIV && ivLength > 0) {
iv = generateIV();
}
if(iv != null) {
cipher.init(Cipher.ENCRYPT_MODE, getKey(), getAlgorithmParameterSpec(iv));
} else {
cipher.init(Cipher.ENCRYPT_MODE, getKey());
iv = cipher.getIV();
}
ivThreadLocal.set(iv);
if(aad != null) {
cipher.updateAAD(aad);
}
byte[] encrypted;
if(prependIV && iv != null) {
int outputSize = cipher.getOutputSize(message.length);
encrypted = new byte[iv.length + outputSize];
System.arraycopy(iv, 0, encrypted, 0, iv.length);
try {
int nBytes = cipher.doFinal(message, 0, message.length, encrypted, iv.length);
if(nBytes < outputSize) {
int excessBytes = outputSize - nBytes;
byte[] resized = new byte[encrypted.length - excessBytes];
System.arraycopy(encrypted, 0, resized, 0, resized.length);
encrypted = resized;
}
} catch (ShortBufferException e) {
throw new RuntimeException(e);
}
} else {
encrypted = cipher.doFinal(message);
}
return encrypted;
} }
|
public class class_name {
public byte[] encrypt(byte[] message, byte[] aad, byte[] iv) throws GeneralSecurityException {
Cipher cipher = getCipher(true);
if(iv == null && generateIV && ivLength > 0) {
iv = generateIV();
}
if(iv != null) {
cipher.init(Cipher.ENCRYPT_MODE, getKey(), getAlgorithmParameterSpec(iv));
} else {
cipher.init(Cipher.ENCRYPT_MODE, getKey());
iv = cipher.getIV();
}
ivThreadLocal.set(iv);
if(aad != null) {
cipher.updateAAD(aad);
}
byte[] encrypted;
if(prependIV && iv != null) {
int outputSize = cipher.getOutputSize(message.length);
encrypted = new byte[iv.length + outputSize];
System.arraycopy(iv, 0, encrypted, 0, iv.length);
try {
int nBytes = cipher.doFinal(message, 0, message.length, encrypted, iv.length);
if(nBytes < outputSize) {
int excessBytes = outputSize - nBytes;
byte[] resized = new byte[encrypted.length - excessBytes];
System.arraycopy(encrypted, 0, resized, 0, resized.length); // depends on control dependency: [if], data = [none]
encrypted = resized; // depends on control dependency: [if], data = [none]
}
} catch (ShortBufferException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} else {
encrypted = cipher.doFinal(message);
}
return encrypted;
} }
|
public class class_name {
public List<ServiceRefType<MessageDrivenBeanType<T>>> getAllServiceRef()
{
List<ServiceRefType<MessageDrivenBeanType<T>>> list = new ArrayList<ServiceRefType<MessageDrivenBeanType<T>>>();
List<Node> nodeList = childNode.get("service-ref");
for(Node node: nodeList)
{
ServiceRefType<MessageDrivenBeanType<T>> type = new ServiceRefTypeImpl<MessageDrivenBeanType<T>>(this, "service-ref", childNode, node);
list.add(type);
}
return list;
} }
|
public class class_name {
public List<ServiceRefType<MessageDrivenBeanType<T>>> getAllServiceRef()
{
List<ServiceRefType<MessageDrivenBeanType<T>>> list = new ArrayList<ServiceRefType<MessageDrivenBeanType<T>>>();
List<Node> nodeList = childNode.get("service-ref");
for(Node node: nodeList)
{
ServiceRefType<MessageDrivenBeanType<T>> type = new ServiceRefTypeImpl<MessageDrivenBeanType<T>>(this, "service-ref", childNode, node);
list.add(type); // depends on control dependency: [for], data = [none]
}
return list;
} }
|
public class class_name {
public void getAll(BoundingBox bounds, Handler<GpsTrackpoint> handler, int page)
{
if(page < 0)
throw new IllegalArgumentException("Page number must be greater than or equal to 0");
String query = "trackpoints?bbox="+bounds.getAsLeftBottomRightTopString() + "&page=" + page;
try
{
osm.makeRequest(query, new GpxTrackParser(handler));
}
catch(OsmBadUserInputException e)
{
/* we can be more specific here because we checked the validity of all the other
parameters already */
throw new OsmQueryTooBigException(e);
}
} }
|
public class class_name {
public void getAll(BoundingBox bounds, Handler<GpsTrackpoint> handler, int page)
{
if(page < 0)
throw new IllegalArgumentException("Page number must be greater than or equal to 0");
String query = "trackpoints?bbox="+bounds.getAsLeftBottomRightTopString() + "&page=" + page;
try
{
osm.makeRequest(query, new GpxTrackParser(handler));
// depends on control dependency: [try], data = [none]
}
catch(OsmBadUserInputException e)
{
/* we can be more specific here because we checked the validity of all the other
parameters already */
throw new OsmQueryTooBigException(e);
}
// depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private AuthConfig getAuthConfigFromEC2InstanceRole() throws IOException {
log.debug("No user and password set for ECR, checking EC2 instance role");
try (CloseableHttpClient client = HttpClients.custom().useSystemProperties().build()) {
// we can set very low timeouts because the request returns almost instantly on
// an EC2 instance
// on a non-EC2 instance we can fail early
RequestConfig conf = RequestConfig.custom().setConnectionRequestTimeout(1000).setConnectTimeout(1000)
.setSocketTimeout(1000).build();
// get instance role - if available
HttpGet request = new HttpGet("http://169.254.169.254/latest/meta-data/iam/security-credentials");
request.setConfig(conf);
String instanceRole;
try (CloseableHttpResponse response = client.execute(request)) {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// no instance role found
log.debug("No instance role found, return code was %d", response.getStatusLine().getStatusCode());
return null;
}
// read instance role
try (InputStream is = response.getEntity().getContent()) {
instanceRole = IOUtils.toString(is, StandardCharsets.UTF_8);
}
}
log.debug("Found instance role %s, getting temporary security credentials", instanceRole);
// get temporary credentials
request = new HttpGet("http://169.254.169.254/latest/meta-data/iam/security-credentials/"
+ UrlEscapers.urlPathSegmentEscaper().escape(instanceRole));
request.setConfig(conf);
try (CloseableHttpResponse response = client.execute(request)) {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
log.debug("No security credential found, return code was %d",
response.getStatusLine().getStatusCode());
// no instance role found
return null;
}
// read instance role
try (Reader r = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)) {
JsonObject securityCredentials = new Gson().fromJson(r, JsonObject.class);
String user = securityCredentials.getAsJsonPrimitive("AccessKeyId").getAsString();
String password = securityCredentials.getAsJsonPrimitive("SecretAccessKey").getAsString();
String token = securityCredentials.getAsJsonPrimitive("Token").getAsString();
log.debug("Received temporary access key %s...", user.substring(0, 8));
return new AuthConfig(user, password, "none", token);
}
}
}
} }
|
public class class_name {
private AuthConfig getAuthConfigFromEC2InstanceRole() throws IOException {
log.debug("No user and password set for ECR, checking EC2 instance role");
try (CloseableHttpClient client = HttpClients.custom().useSystemProperties().build()) {
// we can set very low timeouts because the request returns almost instantly on
// an EC2 instance
// on a non-EC2 instance we can fail early
RequestConfig conf = RequestConfig.custom().setConnectionRequestTimeout(1000).setConnectTimeout(1000)
.setSocketTimeout(1000).build();
// get instance role - if available
HttpGet request = new HttpGet("http://169.254.169.254/latest/meta-data/iam/security-credentials");
request.setConfig(conf);
String instanceRole;
try (CloseableHttpResponse response = client.execute(request)) {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// no instance role found
log.debug("No instance role found, return code was %d", response.getStatusLine().getStatusCode()); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
// read instance role
try (InputStream is = response.getEntity().getContent()) {
instanceRole = IOUtils.toString(is, StandardCharsets.UTF_8);
}
}
log.debug("Found instance role %s, getting temporary security credentials", instanceRole);
// get temporary credentials
request = new HttpGet("http://169.254.169.254/latest/meta-data/iam/security-credentials/"
+ UrlEscapers.urlPathSegmentEscaper().escape(instanceRole));
request.setConfig(conf);
try (CloseableHttpResponse response = client.execute(request)) {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
log.debug("No security credential found, return code was %d",
response.getStatusLine().getStatusCode());
// no instance role found
return null;
}
// read instance role
try (Reader r = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)) {
JsonObject securityCredentials = new Gson().fromJson(r, JsonObject.class);
String user = securityCredentials.getAsJsonPrimitive("AccessKeyId").getAsString();
String password = securityCredentials.getAsJsonPrimitive("SecretAccessKey").getAsString();
String token = securityCredentials.getAsJsonPrimitive("Token").getAsString();
log.debug("Received temporary access key %s...", user.substring(0, 8));
return new AuthConfig(user, password, "none", token);
}
}
}
} }
|
public class class_name {
public static lbmonitor_binding[] get(nitro_service service, String monitorname[]) throws Exception{
if (monitorname !=null && monitorname.length>0) {
lbmonitor_binding response[] = new lbmonitor_binding[monitorname.length];
lbmonitor_binding obj[] = new lbmonitor_binding[monitorname.length];
for (int i=0;i<monitorname.length;i++) {
obj[i] = new lbmonitor_binding();
obj[i].set_monitorname(monitorname[i]);
response[i] = (lbmonitor_binding) obj[i].get_resource(service);
}
return response;
}
return null;
} }
|
public class class_name {
public static lbmonitor_binding[] get(nitro_service service, String monitorname[]) throws Exception{
if (monitorname !=null && monitorname.length>0) {
lbmonitor_binding response[] = new lbmonitor_binding[monitorname.length];
lbmonitor_binding obj[] = new lbmonitor_binding[monitorname.length];
for (int i=0;i<monitorname.length;i++) {
obj[i] = new lbmonitor_binding(); // depends on control dependency: [for], data = [i]
obj[i].set_monitorname(monitorname[i]); // depends on control dependency: [for], data = [i]
response[i] = (lbmonitor_binding) obj[i].get_resource(service); // depends on control dependency: [for], data = [i]
}
return response;
}
return null;
} }
|
public class class_name {
@Override
public void execute(FunctionContext<Object> functionContext)
{
ResultSender<Object> sender = functionContext.getResultSender();
Cache cache = CacheFactory.getAnyInstance();
Logger logWriter = LogManager.getLogger(getClass());
try
{
//export data
String[] args = (String[])functionContext.getArguments();
if(args == null || args.length != 2 )
throw new FunctionException("Required array args: [region,extension]");
String extensionArg = args[0];
if(extensionArg == null || extensionArg.length() == 0)
{
throw new IllegalArgumentException("File extension required");
}
ExportFileType extension = ExportFileType.valueOf(extensionArg);
String regionName = args[1]; //TODO: accept multiple regions
Region<Object,Object> region = cache.getRegion(regionName);
if(region == null)
{
sender.lastResult(null);
return;
}
//TODO: get file from functions
File file = new File(new StringBuilder(directoryPath).append("/").append(regionName)
.append(".").append(extensionArg).toString());
//get server name
String serverName = cache.getDistributedSystem().getDistributedMember().getName();
switch(extension)
{
case gfd:
new GfdExportFunction().exportRegion(region);
break;
default:
throw new IllegalArgumentException("Unsupported extension file type:"+extension);
}
Serializable content = readContent(file,extension,logWriter);
Serializable[] arrayResults = {serverName,content,file.getAbsolutePath()};
sender.lastResult(arrayResults);
}
catch (Exception e)
{
String stackTrace = Debugger.stackTrace(e);
logWriter.error(stackTrace);
throw new FunctionException(stackTrace);
}
} }
|
public class class_name {
@Override
public void execute(FunctionContext<Object> functionContext)
{
ResultSender<Object> sender = functionContext.getResultSender();
Cache cache = CacheFactory.getAnyInstance();
Logger logWriter = LogManager.getLogger(getClass());
try
{
//export data
String[] args = (String[])functionContext.getArguments();
if(args == null || args.length != 2 )
throw new FunctionException("Required array args: [region,extension]");
String extensionArg = args[0];
if(extensionArg == null || extensionArg.length() == 0)
{
throw new IllegalArgumentException("File extension required");
}
ExportFileType extension = ExportFileType.valueOf(extensionArg);
String regionName = args[1]; //TODO: accept multiple regions
Region<Object,Object> region = cache.getRegion(regionName);
if(region == null)
{
sender.lastResult(null);
// depends on control dependency: [if], data = [null)]
return;
// depends on control dependency: [if], data = [none]
}
//TODO: get file from functions
File file = new File(new StringBuilder(directoryPath).append("/").append(regionName)
.append(".").append(extensionArg).toString());
//get server name
String serverName = cache.getDistributedSystem().getDistributedMember().getName();
switch(extension)
{
case gfd:
new GfdExportFunction().exportRegion(region);
break;
default:
throw new IllegalArgumentException("Unsupported extension file type:"+extension);
}
Serializable content = readContent(file,extension,logWriter);
Serializable[] arrayResults = {serverName,content,file.getAbsolutePath()};
sender.lastResult(arrayResults);
// depends on control dependency: [try], data = [none]
}
catch (Exception e)
{
String stackTrace = Debugger.stackTrace(e);
logWriter.error(stackTrace);
throw new FunctionException(stackTrace);
}
// depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
protected <T> void createObserversProducersDisposers(AbstractClassBean<T> bean) {
if (bean instanceof ManagedBean<?> || bean instanceof SessionBean<?>) {
// disposal methods have to go first as we want them to be ready for resolution when initializing producer method/fields
createDisposalMethods(bean, bean.getEnhancedAnnotated());
createProducerMethods(bean, bean.getEnhancedAnnotated());
createProducerFields(bean, bean.getEnhancedAnnotated());
if (manager.isBeanEnabled(bean)) {
createObserverMethods(bean, bean.getEnhancedAnnotated());
}
}
} }
|
public class class_name {
protected <T> void createObserversProducersDisposers(AbstractClassBean<T> bean) {
if (bean instanceof ManagedBean<?> || bean instanceof SessionBean<?>) {
// disposal methods have to go first as we want them to be ready for resolution when initializing producer method/fields
createDisposalMethods(bean, bean.getEnhancedAnnotated()); // depends on control dependency: [if], data = [none]
createProducerMethods(bean, bean.getEnhancedAnnotated()); // depends on control dependency: [if], data = [none]
createProducerFields(bean, bean.getEnhancedAnnotated()); // depends on control dependency: [if], data = [none]
if (manager.isBeanEnabled(bean)) {
createObserverMethods(bean, bean.getEnhancedAnnotated()); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
@Override
public String getFormattedMessage() {
String result = localizedMessage==null ? rawMessage : localizedMessage;
if (parameters != null) {
try {
return MessageFormat.format(result, parameters);
} catch (IllegalArgumentException iae) {
// In case of problem with positional parameters fall through and
// return unformatted string.
}
}
return result;
} }
|
public class class_name {
@Override
public String getFormattedMessage() {
String result = localizedMessage==null ? rawMessage : localizedMessage;
if (parameters != null) {
try {
return MessageFormat.format(result, parameters); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException iae) {
// In case of problem with positional parameters fall through and
// return unformatted string.
} // depends on control dependency: [catch], data = [none]
}
return result;
} }
|
public class class_name {
public int indexOf( Widget w )
{
for( int i = 0; i < size; ++i )
{
if( array[i] == w )
{
return i;
}
}
return -1;
} }
|
public class class_name {
public int indexOf( Widget w )
{
for( int i = 0; i < size; ++i )
{
if( array[i] == w )
{
return i; // depends on control dependency: [if], data = [none]
}
}
return -1;
} }
|
public class class_name {
private UserRegistry determineActiveUserRegistry(boolean exceptionOnError) throws RegistryException {
synchronized (userRegistrySync) {
UserRegistry ur = userRegistry.get();
if (ur == null) {
if (isConfigured()) {
ur = getUserRegistryFromConfiguration();
} else {
ur = autoDetectUserRegistry(exceptionOnError);
}
// remember the user registry to use
userRegistry.set(ur);
}
return ur;
}
} }
|
public class class_name {
private UserRegistry determineActiveUserRegistry(boolean exceptionOnError) throws RegistryException {
synchronized (userRegistrySync) {
UserRegistry ur = userRegistry.get();
if (ur == null) {
if (isConfigured()) {
ur = getUserRegistryFromConfiguration(); // depends on control dependency: [if], data = [none]
} else {
ur = autoDetectUserRegistry(exceptionOnError); // depends on control dependency: [if], data = [none]
}
// remember the user registry to use
userRegistry.set(ur); // depends on control dependency: [if], data = [(ur]
}
return ur;
}
} }
|
public class class_name {
@Override
public DescriptorValue calculate(IAtomContainer atomContainer) {
int n = 0; // count all heavy atom - heavy atom bonds
for (IBond bond : atomContainer.bonds()) {
if (bond.getBegin().getAtomicNumber() != 1 && bond.getEnd().getAtomicNumber() != 1) {
n++;
}
}
double vadjMa = 0;
if (n > 0) {
vadjMa += (Math.log(n) / Math.log(2)) + 1;
}
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new DoubleResult(vadjMa),
getDescriptorNames());
} }
|
public class class_name {
@Override
public DescriptorValue calculate(IAtomContainer atomContainer) {
int n = 0; // count all heavy atom - heavy atom bonds
for (IBond bond : atomContainer.bonds()) {
if (bond.getBegin().getAtomicNumber() != 1 && bond.getEnd().getAtomicNumber() != 1) {
n++; // depends on control dependency: [if], data = [none]
}
}
double vadjMa = 0;
if (n > 0) {
vadjMa += (Math.log(n) / Math.log(2)) + 1; // depends on control dependency: [if], data = [(n]
}
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new DoubleResult(vadjMa),
getDescriptorNames());
} }
|
public class class_name {
private String getStringInternal(final String key, final String defaultValue) {
synchronized (this.confData) {
if (!this.confData.containsKey(key)) {
return defaultValue;
}
return this.confData.get(key);
}
} }
|
public class class_name {
private String getStringInternal(final String key, final String defaultValue) {
synchronized (this.confData) {
if (!this.confData.containsKey(key)) {
return defaultValue; // depends on control dependency: [if], data = [none]
}
return this.confData.get(key);
}
} }
|
public class class_name {
@Override
public void mustReplace(final int slotNo, final int value) {
final int idx = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo);
if (idx >= 0) {
auxIntArr[idx] = HllUtil.pair(slotNo, value); //replace
return;
}
final String pairStr = HllUtil.pairString(HllUtil.pair(slotNo, value));
throw new SketchesStateException("Pair not found: " + pairStr);
} }
|
public class class_name {
@Override
public void mustReplace(final int slotNo, final int value) {
final int idx = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo);
if (idx >= 0) {
auxIntArr[idx] = HllUtil.pair(slotNo, value); //replace // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
final String pairStr = HllUtil.pairString(HllUtil.pair(slotNo, value));
throw new SketchesStateException("Pair not found: " + pairStr);
} }
|
public class class_name {
@Override
public Future<RawGcsCreationToken> continueObjectCreationAsync(final RawGcsCreationToken token,
final ByteBuffer chunk, long timeoutMillis) {
try {
ensureInitialized();
} catch (IOException e) {
throw new RuntimeException(e);
}
final Environment environment = ApiProxy.getCurrentEnvironment();
return writePool.schedule(new Callable<RawGcsCreationToken>() {
@Override
public RawGcsCreationToken call() throws Exception {
ApiProxy.setEnvironmentForCurrentThread(environment);
return append(token, chunk);
}
}, 50, TimeUnit.MILLISECONDS);
} }
|
public class class_name {
@Override
public Future<RawGcsCreationToken> continueObjectCreationAsync(final RawGcsCreationToken token,
final ByteBuffer chunk, long timeoutMillis) {
try {
ensureInitialized(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
final Environment environment = ApiProxy.getCurrentEnvironment();
return writePool.schedule(new Callable<RawGcsCreationToken>() {
@Override
public RawGcsCreationToken call() throws Exception {
ApiProxy.setEnvironmentForCurrentThread(environment);
return append(token, chunk);
}
}, 50, TimeUnit.MILLISECONDS);
} }
|
public class class_name {
Location append(String relativeURI) {
relativeURI = encodeIllegalCharacters(relativeURI);
if (uri.toString().endsWith("/") && relativeURI.startsWith("/")) {
relativeURI = relativeURI.substring(1);
}
if (!uri.toString().endsWith("/") && !relativeURI.startsWith("/")) {
relativeURI = "/" + relativeURI;
}
return Location.of(URI.create(uri + relativeURI));
} }
|
public class class_name {
Location append(String relativeURI) {
relativeURI = encodeIllegalCharacters(relativeURI);
if (uri.toString().endsWith("/") && relativeURI.startsWith("/")) {
relativeURI = relativeURI.substring(1); // depends on control dependency: [if], data = [none]
}
if (!uri.toString().endsWith("/") && !relativeURI.startsWith("/")) {
relativeURI = "/" + relativeURI; // depends on control dependency: [if], data = [none]
}
return Location.of(URI.create(uri + relativeURI));
} }
|
public class class_name {
public Object evaluate(Reader in, String fileName) throws CompilationFailedException {
Script script = null;
try {
script = parse(in, fileName);
return script.run();
} finally {
if (script != null) {
InvokerHelper.removeClass(script.getClass());
}
}
} }
|
public class class_name {
public Object evaluate(Reader in, String fileName) throws CompilationFailedException {
Script script = null;
try {
script = parse(in, fileName);
return script.run();
} finally {
if (script != null) {
InvokerHelper.removeClass(script.getClass()); // depends on control dependency: [if], data = [(script]
}
}
} }
|
public class class_name {
protected boolean addItem(final Suggestion suggestion) {
SelectionEvent.fire(MaterialAutoComplete.this, suggestion);
if (getLimit() > 0) {
if (suggestionMap.size() >= getLimit()) {
return false;
}
}
if (suggestionMap.containsKey(suggestion)) {
return false;
}
final ListItem displayItem = new ListItem();
displayItem.setStyleName(AddinsCssName.MULTIVALUESUGGESTBOX_TOKEN);
if (getType() == AutocompleteType.TEXT) {
suggestionMap.clear();
itemBox.setText(suggestion.getReplacementString());
} else {
final MaterialChip chip = chipProvider.getChip(suggestion);
if (chip == null) {
return false;
}
registerHandler(chip.addClickHandler(event -> {
if (chipProvider.isChipSelectable(suggestion)) {
if (itemsHighlighted.contains(displayItem)) {
chip.removeStyleName(selectedChipStyle);
itemsHighlighted.remove(displayItem);
} else {
chip.addStyleName(selectedChipStyle);
itemsHighlighted.add(displayItem);
}
}
}));
if (chip.getIcon() != null) {
registerHandler(chip.getIcon().addClickHandler(event -> {
if (chipProvider.isChipRemovable(suggestion)) {
suggestionMap.remove(suggestion);
list.remove(displayItem);
itemsHighlighted.remove(displayItem);
ValueChangeEvent.fire(MaterialAutoComplete.this, getValue());
suggestBox.showSuggestionList();
}
}));
}
suggestionMap.put(suggestion, chip);
displayItem.add(chip);
list.insert(displayItem, list.getWidgetCount() - 1);
}
return true;
} }
|
public class class_name {
protected boolean addItem(final Suggestion suggestion) {
SelectionEvent.fire(MaterialAutoComplete.this, suggestion);
if (getLimit() > 0) {
if (suggestionMap.size() >= getLimit()) {
return false; // depends on control dependency: [if], data = [none]
}
}
if (suggestionMap.containsKey(suggestion)) {
return false; // depends on control dependency: [if], data = [none]
}
final ListItem displayItem = new ListItem();
displayItem.setStyleName(AddinsCssName.MULTIVALUESUGGESTBOX_TOKEN);
if (getType() == AutocompleteType.TEXT) {
suggestionMap.clear(); // depends on control dependency: [if], data = [none]
itemBox.setText(suggestion.getReplacementString()); // depends on control dependency: [if], data = [none]
} else {
final MaterialChip chip = chipProvider.getChip(suggestion);
if (chip == null) {
return false; // depends on control dependency: [if], data = [none]
}
registerHandler(chip.addClickHandler(event -> {
if (chipProvider.isChipSelectable(suggestion)) {
if (itemsHighlighted.contains(displayItem)) {
chip.removeStyleName(selectedChipStyle);
itemsHighlighted.remove(displayItem);
} else {
chip.addStyleName(selectedChipStyle);
itemsHighlighted.add(displayItem);
}
}
})); // depends on control dependency: [if], data = [none]
if (chip.getIcon() != null) {
registerHandler(chip.getIcon().addClickHandler(event -> {
if (chipProvider.isChipRemovable(suggestion)) {
suggestionMap.remove(suggestion);
list.remove(displayItem);
itemsHighlighted.remove(displayItem);
ValueChangeEvent.fire(MaterialAutoComplete.this, getValue());
suggestBox.showSuggestionList();
}
})); // depends on control dependency: [if], data = [none]
}
suggestionMap.put(suggestion, chip); // depends on control dependency: [if], data = [none]
displayItem.add(chip); // depends on control dependency: [if], data = [none]
list.insert(displayItem, list.getWidgetCount() - 1); // depends on control dependency: [if], data = [none]
}
return true;
} }
|
public class class_name {
public static void safeClose(@Nullable Closeable closeable) {
if (closeable == null) return;
try {
closeable.close();
} catch (IOException ignored) {
// We made out best effort to release this resource. Nothing more we can do.
}
} }
|
public class class_name {
public static void safeClose(@Nullable Closeable closeable) {
if (closeable == null) return;
try {
closeable.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ignored) {
// We made out best effort to release this resource. Nothing more we can do.
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private GeoResult<?> buildGeoResult(final ArangoCursor<?> cursor) {
GeoResult<?> geoResult = null;
while (cursor.hasNext() && geoResult == null) {
final Object object = cursor.next();
if (!(object instanceof VPackSlice)) {
continue;
}
final VPackSlice slice = (VPackSlice) object;
final VPackSlice distSlice = slice.get("_distance");
final Double distanceInMeters = distSlice.isDouble() ? distSlice.getAsDouble() : null;
if (distanceInMeters == null) {
continue;
}
final Object entity = operations.getConverter().read(domainClass, slice);
final Distance distance = new Distance(distanceInMeters / 1000, Metrics.KILOMETERS);
geoResult = new GeoResult<>(entity, distance);
}
return geoResult;
} }
|
public class class_name {
private GeoResult<?> buildGeoResult(final ArangoCursor<?> cursor) {
GeoResult<?> geoResult = null;
while (cursor.hasNext() && geoResult == null) {
final Object object = cursor.next();
if (!(object instanceof VPackSlice)) {
continue;
}
final VPackSlice slice = (VPackSlice) object;
final VPackSlice distSlice = slice.get("_distance");
final Double distanceInMeters = distSlice.isDouble() ? distSlice.getAsDouble() : null;
if (distanceInMeters == null) {
continue;
}
final Object entity = operations.getConverter().read(domainClass, slice);
final Distance distance = new Distance(distanceInMeters / 1000, Metrics.KILOMETERS);
geoResult = new GeoResult<>(entity, distance); // depends on control dependency: [while], data = [none]
}
return geoResult;
} }
|
public class class_name {
public void start(URL deployableUnitURL, String deployableUnitName) throws DeploymentException {
synchronized (this) {
if (!shutdown) {
sleeSubDeployer.start(deployableUnitURL, deployableUnitName);
}
else {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Ignoring deploy invoked from external deployer, SLEE in shutdown");
}
}
} }
|
public class class_name {
public void start(URL deployableUnitURL, String deployableUnitName) throws DeploymentException {
synchronized (this) {
if (!shutdown) {
sleeSubDeployer.start(deployableUnitURL, deployableUnitName); // depends on control dependency: [if], data = [none]
}
else {
if (LOGGER.isDebugEnabled())
LOGGER.debug("Ignoring deploy invoked from external deployer, SLEE in shutdown");
}
}
} }
|
public class class_name {
public String splitSpecialStateSwitch(String specialStateTransition){
Matcher transformedSpecialStateMatcher =
TRANSORMED_SPECIAL_STATE_TRANSITION_METHOD.matcher(specialStateTransition);
if( !transformedSpecialStateMatcher.find() ){
return specialStateTransition;
}
String specialStateSwitch = transformedSpecialStateMatcher.group(3);
Matcher transformedCaseMatcher = TRANSFORMED_CASE_PATTERN.matcher(specialStateSwitch);
StringBuffer switchReplacementBuffer = new StringBuffer();
StringBuffer extractedMethods = new StringBuffer();
List<String> extractedCasesList = new ArrayList<String>();
switchReplacementBuffer.append("$2\n");
boolean methodExtracted = false;
boolean isFirst = true;
String from = "0";
String to = "0";
//Process individual case statements
while(transformedCaseMatcher.find()){
if(isFirst){
isFirst = false;
from = transformedCaseMatcher.group(2);
}
to = transformedCaseMatcher.group(2);
extractedCasesList.add(transformedCaseMatcher.group());
//If the list of not processed extracted cases exceeds the maximal allowed number
//generate individual method for those cases
if (extractedCasesList.size() >= casesPerSpecialStateSwitch ){
generateExtractedSwitch(extractedCasesList, from, to, extractedMethods, switchReplacementBuffer);
extractedCasesList.clear();
isFirst = true;
methodExtracted = true;
}
}
//If no method was extracted return the input unchanged
//or process rest of cases by generating method for them
if(!methodExtracted){
return specialStateTransition;
}else if(!extractedCasesList.isEmpty() && methodExtracted){
generateExtractedSwitch(extractedCasesList, from, to, extractedMethods, switchReplacementBuffer);
}
switchReplacementBuffer.append("$5");
StringBuffer result = new StringBuffer();
transformedSpecialStateMatcher.appendReplacement( result, switchReplacementBuffer.toString());
result.append(extractedMethods);
transformedSpecialStateMatcher.appendTail(result);
return result.toString();
} }
|
public class class_name {
public String splitSpecialStateSwitch(String specialStateTransition){
Matcher transformedSpecialStateMatcher =
TRANSORMED_SPECIAL_STATE_TRANSITION_METHOD.matcher(specialStateTransition);
if( !transformedSpecialStateMatcher.find() ){
return specialStateTransition; // depends on control dependency: [if], data = [none]
}
String specialStateSwitch = transformedSpecialStateMatcher.group(3);
Matcher transformedCaseMatcher = TRANSFORMED_CASE_PATTERN.matcher(specialStateSwitch);
StringBuffer switchReplacementBuffer = new StringBuffer();
StringBuffer extractedMethods = new StringBuffer();
List<String> extractedCasesList = new ArrayList<String>();
switchReplacementBuffer.append("$2\n");
boolean methodExtracted = false;
boolean isFirst = true;
String from = "0";
String to = "0";
//Process individual case statements
while(transformedCaseMatcher.find()){
if(isFirst){
isFirst = false; // depends on control dependency: [if], data = [none]
from = transformedCaseMatcher.group(2); // depends on control dependency: [if], data = [none]
}
to = transformedCaseMatcher.group(2); // depends on control dependency: [while], data = [none]
extractedCasesList.add(transformedCaseMatcher.group()); // depends on control dependency: [while], data = [none]
//If the list of not processed extracted cases exceeds the maximal allowed number
//generate individual method for those cases
if (extractedCasesList.size() >= casesPerSpecialStateSwitch ){
generateExtractedSwitch(extractedCasesList, from, to, extractedMethods, switchReplacementBuffer); // depends on control dependency: [if], data = [none]
extractedCasesList.clear(); // depends on control dependency: [if], data = [none]
isFirst = true; // depends on control dependency: [if], data = [none]
methodExtracted = true; // depends on control dependency: [if], data = [none]
}
}
//If no method was extracted return the input unchanged
//or process rest of cases by generating method for them
if(!methodExtracted){
return specialStateTransition; // depends on control dependency: [if], data = [none]
}else if(!extractedCasesList.isEmpty() && methodExtracted){
generateExtractedSwitch(extractedCasesList, from, to, extractedMethods, switchReplacementBuffer); // depends on control dependency: [if], data = [none]
}
switchReplacementBuffer.append("$5");
StringBuffer result = new StringBuffer();
transformedSpecialStateMatcher.appendReplacement( result, switchReplacementBuffer.toString());
result.append(extractedMethods);
transformedSpecialStateMatcher.appendTail(result);
return result.toString();
} }
|
public class class_name {
public static <T> boolean containsAll(T[] array, T[] check) {
for (T checkItem : check) {
if (!contains(array, checkItem)) {
return false;
}
}
return true;
} }
|
public class class_name {
public static <T> boolean containsAll(T[] array, T[] check) {
for (T checkItem : check) {
if (!contains(array, checkItem)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} }
|
public class class_name {
private ImmutableTerm getNestedConcat(String str) {
List<ImmutableTerm> terms;
terms = addToTermsList(str);
if (terms.size() == 1) {
return terms.get(0);
}
ImmutableFunctionalTerm f = termFactory.getImmutableFunctionalTerm(ExpressionOperation.CONCAT, terms.get(0), terms.get(1));
for (int j = 2; j < terms.size(); j++) {
f = termFactory.getImmutableFunctionalTerm(ExpressionOperation.CONCAT, f, terms.get(j));
}
return f;
} }
|
public class class_name {
private ImmutableTerm getNestedConcat(String str) {
List<ImmutableTerm> terms;
terms = addToTermsList(str);
if (terms.size() == 1) {
return terms.get(0); // depends on control dependency: [if], data = [none]
}
ImmutableFunctionalTerm f = termFactory.getImmutableFunctionalTerm(ExpressionOperation.CONCAT, terms.get(0), terms.get(1));
for (int j = 2; j < terms.size(); j++) {
f = termFactory.getImmutableFunctionalTerm(ExpressionOperation.CONCAT, f, terms.get(j)); // depends on control dependency: [for], data = [j]
}
return f;
} }
|
public class class_name {
public boolean hasAnyScopeMatching(String... scopesRegex) {
boolean result = OAuth2ExpressionUtils.hasAnyScopeMatching(authentication, scopesRegex);
if (!result) {
missingScopes.addAll(Arrays.asList(scopesRegex));
}
return result;
} }
|
public class class_name {
public boolean hasAnyScopeMatching(String... scopesRegex) {
boolean result = OAuth2ExpressionUtils.hasAnyScopeMatching(authentication, scopesRegex);
if (!result) {
missingScopes.addAll(Arrays.asList(scopesRegex)); // depends on control dependency: [if], data = [none]
}
return result;
} }
|
public class class_name {
private boolean isTokenInSentence(AnalyzedTokenReadings testToken, AnalyzedTokenReadings[] tokens, int notCheck) {
if (testToken == null || tokens == null) {
return false;
}
List<AnalyzedToken> readings = testToken.getReadings();
List<String> lemmas = new ArrayList<>();
for (AnalyzedToken reading : readings) {
if (reading.getLemma() != null) {
lemmas.add(reading.getLemma());
}
}
for (int i = 0; i < tokens.length; i++) {
if (i != notCheck && isTokenToCheck(tokens[i])) {
if ((!lemmas.isEmpty() && tokens[i].hasAnyLemma(lemmas.toArray(new String[0])))
|| isPartOfWord(testToken.getToken(), tokens[i].getToken())) {
if (notCheck >= 0) {
if (notCheck == i - 2) {
return !isTokenPair(tokens, i, true);
} else if (notCheck == i + 2) {
return !isTokenPair(tokens, i, false);
} else if ((notCheck == i + 1 || notCheck == i - 1)
&& testToken.getToken().equals(tokens[i].getToken())) {
return false;
}
}
return true;
}
}
}
return false;
} }
|
public class class_name {
private boolean isTokenInSentence(AnalyzedTokenReadings testToken, AnalyzedTokenReadings[] tokens, int notCheck) {
if (testToken == null || tokens == null) {
return false; // depends on control dependency: [if], data = [none]
}
List<AnalyzedToken> readings = testToken.getReadings();
List<String> lemmas = new ArrayList<>();
for (AnalyzedToken reading : readings) {
if (reading.getLemma() != null) {
lemmas.add(reading.getLemma()); // depends on control dependency: [if], data = [(reading.getLemma()]
}
}
for (int i = 0; i < tokens.length; i++) {
if (i != notCheck && isTokenToCheck(tokens[i])) {
if ((!lemmas.isEmpty() && tokens[i].hasAnyLemma(lemmas.toArray(new String[0])))
|| isPartOfWord(testToken.getToken(), tokens[i].getToken())) {
if (notCheck >= 0) {
if (notCheck == i - 2) {
return !isTokenPair(tokens, i, true); // depends on control dependency: [if], data = [none]
} else if (notCheck == i + 2) {
return !isTokenPair(tokens, i, false); // depends on control dependency: [if], data = [none]
} else if ((notCheck == i + 1 || notCheck == i - 1)
&& testToken.getToken().equals(tokens[i].getToken())) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true; // depends on control dependency: [if], data = [none]
}
}
}
return false;
} }
|
public class class_name {
public static TimeZone parseBackendTimeZone(String timeZone) {
if (timeZone.startsWith("GMT")) {
TimeZone tz = GMT_ZONES.get(timeZone);
if (tz != null) {
return tz;
}
}
return TimeZone.getTimeZone(timeZone);
} }
|
public class class_name {
public static TimeZone parseBackendTimeZone(String timeZone) {
if (timeZone.startsWith("GMT")) {
TimeZone tz = GMT_ZONES.get(timeZone);
if (tz != null) {
return tz; // depends on control dependency: [if], data = [none]
}
}
return TimeZone.getTimeZone(timeZone);
} }
|
public class class_name {
public float[][] latLonToProj(float[][] from, float[][] to, int latIndex,
int lonIndex) {
int cnt = from[0].length;
float[] fromLatA = from[latIndex];
float[] fromLonA = from[lonIndex];
float[] resultXA = to[INDEX_X];
float[] resultYA = to[INDEX_Y];
double toX, toY;
for (int i = 0; i < cnt; i++) {
double fromLat = fromLatA[i];
double fromLon = fromLonA[i];
fromLat = Math.toRadians(fromLat);
double lonDiff = Math.toRadians(LatLonPointImpl.lonNormal(fromLon
- lon0Degrees));
double cosc = sinLat0 * Math.sin(fromLat)
+ cosLat0 * Math.cos(fromLat) * Math.cos(lonDiff);
double ksp = (P - 1.0) / (P - cosc);
if (cosc < 1.0 / P) {
toX = Double.POSITIVE_INFINITY;
toY = Double.POSITIVE_INFINITY;
} else {
toX = false_east
+ R * ksp * Math.cos(fromLat) * Math.sin(lonDiff);
toY = false_north
+ R * ksp
* (cosLat0 * Math.sin(fromLat)
- sinLat0 * Math.cos(fromLat) * Math.cos(lonDiff));
}
resultXA[i] = (float) toX;
resultYA[i] = (float) toY;
}
return to;
} }
|
public class class_name {
public float[][] latLonToProj(float[][] from, float[][] to, int latIndex,
int lonIndex) {
int cnt = from[0].length;
float[] fromLatA = from[latIndex];
float[] fromLonA = from[lonIndex];
float[] resultXA = to[INDEX_X];
float[] resultYA = to[INDEX_Y];
double toX, toY;
for (int i = 0; i < cnt; i++) {
double fromLat = fromLatA[i];
double fromLon = fromLonA[i];
fromLat = Math.toRadians(fromLat);
// depends on control dependency: [for], data = [none]
double lonDiff = Math.toRadians(LatLonPointImpl.lonNormal(fromLon
- lon0Degrees));
double cosc = sinLat0 * Math.sin(fromLat)
+ cosLat0 * Math.cos(fromLat) * Math.cos(lonDiff);
double ksp = (P - 1.0) / (P - cosc);
if (cosc < 1.0 / P) {
toX = Double.POSITIVE_INFINITY;
// depends on control dependency: [if], data = [none]
toY = Double.POSITIVE_INFINITY;
// depends on control dependency: [if], data = [none]
} else {
toX = false_east
+ R * ksp * Math.cos(fromLat) * Math.sin(lonDiff);
// depends on control dependency: [if], data = [none]
toY = false_north
+ R * ksp
* (cosLat0 * Math.sin(fromLat)
- sinLat0 * Math.cos(fromLat) * Math.cos(lonDiff));
// depends on control dependency: [if], data = [none]
}
resultXA[i] = (float) toX;
// depends on control dependency: [for], data = [i]
resultYA[i] = (float) toY;
// depends on control dependency: [for], data = [i]
}
return to;
} }
|
public class class_name {
private static boolean isEditableTemplate(@NotNull Template template) {
Resource resource = template.adaptTo(Resource.class);
if (resource != null) {
return resource.getChild(NN_EDITABLE_TEMPLATE_INITIAL) != null
&& resource.getChild(NN_EDITABLE_TEMPLATE_STRUCTURE) != null
&& resource.getChild(NN_EDITABLE_TEMPLATE_POLICIES) != null;
}
return false;
} }
|
public class class_name {
private static boolean isEditableTemplate(@NotNull Template template) {
Resource resource = template.adaptTo(Resource.class);
if (resource != null) {
return resource.getChild(NN_EDITABLE_TEMPLATE_INITIAL) != null
&& resource.getChild(NN_EDITABLE_TEMPLATE_STRUCTURE) != null
&& resource.getChild(NN_EDITABLE_TEMPLATE_POLICIES) != null; // depends on control dependency: [if], data = [none]
}
return false;
} }
|
public class class_name {
public static String genSequence6Tags(String[] wordArray){
StringBuilder sb = new StringBuilder();
for(int i=0; i<wordArray.length; i++) {
String word = wordArray[i];
String tag = null;
int len = word.length();
switch(len){
case 1:
tag = "S";break;
case 2:
tag = "BE";break;
case 3:
tag = "B2E";break;
case 4:
tag = "B23E";break;
default :
tag = "B23";
int rest = len-4;
while(rest-->0){
tag+="M";
}
tag+="E";
}
assert tag.length() ==len;
for(int j=0; j<word.length(); j++) {
char c = word.charAt(j);
sb.append(c);
sb.append('\t');
sb.append(tag.charAt(j));
sb.append('\n');
}
}
sb.append('\n');
return sb.toString();
} }
|
public class class_name {
public static String genSequence6Tags(String[] wordArray){
StringBuilder sb = new StringBuilder();
for(int i=0; i<wordArray.length; i++) {
String word = wordArray[i];
String tag = null;
int len = word.length();
switch(len){
case 1:
tag = "S";break;
case 2:
tag = "BE";break;
case 3:
tag = "B2E";break;
case 4:
tag = "B23E";break;
default :
tag = "B23";
int rest = len-4;
while(rest-->0){
tag+="M";
// depends on control dependency: [while], data = [none]
}
tag+="E";
}
assert tag.length() ==len;
for(int j=0; j<word.length(); j++) {
char c = word.charAt(j);
sb.append(c);
// depends on control dependency: [for], data = [none]
sb.append('\t');
// depends on control dependency: [for], data = [none]
sb.append(tag.charAt(j));
// depends on control dependency: [for], data = [j]
sb.append('\n');
// depends on control dependency: [for], data = [none]
}
}
sb.append('\n');
return sb.toString();
} }
|
public class class_name {
private void obtainDialogHeaderIcon(@NonNull final TypedArray typedArray) {
int resourceId =
typedArray.getResourceId(R.styleable.DialogPreference_dialogHeaderIcon, -1);
if (resourceId != -1) {
setDialogHeaderIcon(resourceId);
}
} }
|
public class class_name {
private void obtainDialogHeaderIcon(@NonNull final TypedArray typedArray) {
int resourceId =
typedArray.getResourceId(R.styleable.DialogPreference_dialogHeaderIcon, -1);
if (resourceId != -1) {
setDialogHeaderIcon(resourceId); // depends on control dependency: [if], data = [(resourceId]
}
} }
|
public class class_name {
private static boolean checkPixel(MapTile map, ImageBuffer tileRef, int progressTileX, int progressTileY)
{
final int x = progressTileX * map.getTileWidth();
final int y = progressTileY * map.getTileHeight();
final int pixel = tileRef.getRgb(x, y);
// Skip blank tile of image map
if (TilesExtractor.IGNORED_COLOR_VALUE != pixel)
{
// Search if tile is on sheet and get it
final Tile tile = searchForTile(map, tileRef, progressTileX, progressTileY);
if (tile == null)
{
return false;
}
map.setTile(tile);
}
return true;
} }
|
public class class_name {
private static boolean checkPixel(MapTile map, ImageBuffer tileRef, int progressTileX, int progressTileY)
{
final int x = progressTileX * map.getTileWidth();
final int y = progressTileY * map.getTileHeight();
final int pixel = tileRef.getRgb(x, y);
// Skip blank tile of image map
if (TilesExtractor.IGNORED_COLOR_VALUE != pixel)
{
// Search if tile is on sheet and get it
final Tile tile = searchForTile(map, tileRef, progressTileX, progressTileY);
if (tile == null)
{
return false; // depends on control dependency: [if], data = [none]
}
map.setTile(tile); // depends on control dependency: [if], data = [none]
}
return true;
} }
|
public class class_name {
public Location withJdbc(CodeGenNodeArg... jdbc) {
if (this.jdbc == null) {
setJdbc(new java.util.ArrayList<CodeGenNodeArg>(jdbc.length));
}
for (CodeGenNodeArg ele : jdbc) {
this.jdbc.add(ele);
}
return this;
} }
|
public class class_name {
public Location withJdbc(CodeGenNodeArg... jdbc) {
if (this.jdbc == null) {
setJdbc(new java.util.ArrayList<CodeGenNodeArg>(jdbc.length)); // depends on control dependency: [if], data = [none]
}
for (CodeGenNodeArg ele : jdbc) {
this.jdbc.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} }
|
public class class_name {
public String asTagsString()
{
TreeMap<Tag, Value> orderedAttributes = new TreeMap<Tag, Value>(attributes);
StringBuilder result = new StringBuilder();
for (Iterator<Tag> tags = orderedAttributes.keySet().iterator(); tags.hasNext(); )
{
Tag tag = tags.next();
result.append(tag.tag);
if (tags.hasNext()) result.append(",");
}
return result.toString();
} }
|
public class class_name {
public String asTagsString()
{
TreeMap<Tag, Value> orderedAttributes = new TreeMap<Tag, Value>(attributes);
StringBuilder result = new StringBuilder();
for (Iterator<Tag> tags = orderedAttributes.keySet().iterator(); tags.hasNext(); )
{
Tag tag = tags.next();
result.append(tag.tag); // depends on control dependency: [for], data = [none]
if (tags.hasNext()) result.append(",");
}
return result.toString();
} }
|
public class class_name {
public void setTraversalAfter(AccessibilityNodeInfo info) {
if (this.traversalAfter != null) {
this.traversalAfter.recycle();
}
this.traversalAfter = obtain(info);
} }
|
public class class_name {
public void setTraversalAfter(AccessibilityNodeInfo info) {
if (this.traversalAfter != null) {
this.traversalAfter.recycle(); // depends on control dependency: [if], data = [none]
}
this.traversalAfter = obtain(info);
} }
|
public class class_name {
public static String encodeXmlAttribute(String str) {
if (str == null) return null;
int len = str.length();
if (len == 0) return str;
StringBuffer encoded = new StringBuffer();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c == '<') encoded.append("<");
else if (c == '\"') encoded.append(""");
else if (c == '>') encoded.append(">");
else if (c == '\'') encoded.append("'");
else if (c == '&') encoded.append("&");
else encoded.append(c);
}
return encoded.toString();
} }
|
public class class_name {
public static String encodeXmlAttribute(String str) {
if (str == null) return null;
int len = str.length();
if (len == 0) return str;
StringBuffer encoded = new StringBuffer();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c == '<') encoded.append("<");
else if (c == '\"') encoded.append("""); // depends on control dependency: [for], data = [none] // depends on control dependency: [for], data = [none]
else if (c == '>') encoded.append(">"); // depends on control dependency: [for], data = [none] // depends on control dependency: [for], data = [none]
else if (c == '\'') encoded.append("'"); // depends on control dependency: [for], data = [none] // depends on control dependency: [for], data = [none]
else if (c == '&') encoded.append("&"); // depends on control dependency: [for], data = [none] // depends on control dependency: [for], data = [none]
else encoded.append(c); // depends on control dependency: [for], data = [none]
}
return encoded.toString();
} }
|
public class class_name {
public void addOrMergeMention(Mention mention)
{
if (!mention.getSentence().equals(this))
throw new IllegalArgumentException();
List<Mention> overlapping = new ArrayList<Mention>();
for (Mention mention2 : mentions)
{
if (mention.overlaps(mention2) && mention.getType().equals(mention2.getType()))
overlapping.add(mention2);
}
if (overlapping.size() == 0)
{
mentions.add(mention);
}
else
{
for (Mention mention2 : overlapping)
{
mentions.remove(mention2);
mentions.add(new Mention(this, mention.getType(), Math.min(mention.getStart(), mention2.getStart()), Math.max(mention.getEnd(),
mention2.getEnd())));
}
}
} }
|
public class class_name {
public void addOrMergeMention(Mention mention)
{
if (!mention.getSentence().equals(this))
throw new IllegalArgumentException();
List<Mention> overlapping = new ArrayList<Mention>();
for (Mention mention2 : mentions)
{
if (mention.overlaps(mention2) && mention.getType().equals(mention2.getType()))
overlapping.add(mention2);
}
if (overlapping.size() == 0)
{
mentions.add(mention);
// depends on control dependency: [if], data = [none]
}
else
{
for (Mention mention2 : overlapping)
{
mentions.remove(mention2);
// depends on control dependency: [for], data = [mention2]
mentions.add(new Mention(this, mention.getType(), Math.min(mention.getStart(), mention2.getStart()), Math.max(mention.getEnd(),
mention2.getEnd())));
// depends on control dependency: [for], data = [mention2]
}
}
} }
|
public class class_name {
private Direction getScrollDirection(int offset) {
if (m_scrollElement == null) {
Element body = RootPanel.getBodyElement();
int windowHeight = Window.getClientHeight();
int bodyHeight = body.getClientHeight();
if (windowHeight < bodyHeight) {
if (((windowHeight - m_clientY) < offset) && (Window.getScrollTop() < (bodyHeight - windowHeight))) {
return Direction.down;
}
if ((m_clientY < offset) && (Window.getScrollTop() > 0)) {
return Direction.up;
}
}
int windowWidth = Window.getClientWidth();
int bodyWidth = body.getClientWidth();
if (windowWidth < bodyWidth) {
if (((windowWidth - m_clientX) < offset) && (Window.getScrollLeft() < (bodyWidth - windowWidth))) {
return Direction.right;
}
if ((m_clientX < offset) && (Window.getScrollLeft() > 0)) {
return Direction.left;
}
}
return null;
} else {
int outerHeight = m_scrollElement.getClientHeight();
int innerHeight = m_scrollElement.getScrollHeight();
if (outerHeight < innerHeight) {
if ((((outerHeight + m_scrollElement.getAbsoluteTop()) - m_clientY) < offset)
&& (m_scrollElement.getScrollTop() < (innerHeight - outerHeight))) {
return Direction.down;
}
if (((m_clientY - m_scrollElement.getAbsoluteTop()) < offset) && (m_scrollElement.getScrollTop() > 0)) {
return Direction.up;
}
}
int outerWidth = m_scrollElement.getClientWidth();
int innerWidth = m_scrollElement.getScrollWidth();
if (outerWidth < innerWidth) {
if ((((outerWidth + m_scrollElement.getAbsoluteLeft()) - m_clientX) < offset)
&& (m_scrollElement.getScrollLeft() < (innerWidth - outerWidth))) {
return Direction.right;
}
if (((m_clientX - m_scrollElement.getAbsoluteLeft()) < offset)
&& (m_scrollElement.getScrollLeft() > 0)) {
return Direction.left;
}
}
return null;
}
} }
|
public class class_name {
private Direction getScrollDirection(int offset) {
if (m_scrollElement == null) {
Element body = RootPanel.getBodyElement();
int windowHeight = Window.getClientHeight();
int bodyHeight = body.getClientHeight();
if (windowHeight < bodyHeight) {
if (((windowHeight - m_clientY) < offset) && (Window.getScrollTop() < (bodyHeight - windowHeight))) {
return Direction.down; // depends on control dependency: [if], data = [none]
}
if ((m_clientY < offset) && (Window.getScrollTop() > 0)) {
return Direction.up; // depends on control dependency: [if], data = [none]
}
}
int windowWidth = Window.getClientWidth();
int bodyWidth = body.getClientWidth();
if (windowWidth < bodyWidth) {
if (((windowWidth - m_clientX) < offset) && (Window.getScrollLeft() < (bodyWidth - windowWidth))) {
return Direction.right; // depends on control dependency: [if], data = [none]
}
if ((m_clientX < offset) && (Window.getScrollLeft() > 0)) {
return Direction.left; // depends on control dependency: [if], data = [none]
}
}
return null; // depends on control dependency: [if], data = [none]
} else {
int outerHeight = m_scrollElement.getClientHeight();
int innerHeight = m_scrollElement.getScrollHeight();
if (outerHeight < innerHeight) {
if ((((outerHeight + m_scrollElement.getAbsoluteTop()) - m_clientY) < offset)
&& (m_scrollElement.getScrollTop() < (innerHeight - outerHeight))) {
return Direction.down; // depends on control dependency: [if], data = [none]
}
if (((m_clientY - m_scrollElement.getAbsoluteTop()) < offset) && (m_scrollElement.getScrollTop() > 0)) {
return Direction.up; // depends on control dependency: [if], data = [none]
}
}
int outerWidth = m_scrollElement.getClientWidth();
int innerWidth = m_scrollElement.getScrollWidth();
if (outerWidth < innerWidth) {
if ((((outerWidth + m_scrollElement.getAbsoluteLeft()) - m_clientX) < offset)
&& (m_scrollElement.getScrollLeft() < (innerWidth - outerWidth))) {
return Direction.right; // depends on control dependency: [if], data = [none]
}
if (((m_clientX - m_scrollElement.getAbsoluteLeft()) < offset)
&& (m_scrollElement.getScrollLeft() > 0)) {
return Direction.left; // depends on control dependency: [if], data = [none]
}
}
return null; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void matchList(String elementName, Vector values, int oper)
{
// Delete the old search criteria
criteria = new Criteria();
if (oper != NOT_IN)
{
for (int i = 0; i < values.size(); i++)
{
Criteria tempCrit = new Criteria();
tempCrit.addEqualTo(elementName, values.elementAt(i));
criteria.addOrCriteria(tempCrit);
}
}
else
{
for (int i = 0; i < values.size(); i++)
{
criteria.addNotEqualTo(elementName, values.elementAt(i));
}
}
} }
|
public class class_name {
public void matchList(String elementName, Vector values, int oper)
{
// Delete the old search criteria
criteria = new Criteria();
if (oper != NOT_IN)
{
for (int i = 0; i < values.size(); i++)
{
Criteria tempCrit = new Criteria();
tempCrit.addEqualTo(elementName, values.elementAt(i));
// depends on control dependency: [for], data = [i]
criteria.addOrCriteria(tempCrit);
// depends on control dependency: [for], data = [none]
}
}
else
{
for (int i = 0; i < values.size(); i++)
{
criteria.addNotEqualTo(elementName, values.elementAt(i));
// depends on control dependency: [for], data = [i]
}
}
} }
|
public class class_name {
public FileGetFromComputeNodeOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null;
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate);
}
return this;
} }
|
public class class_name {
public FileGetFromComputeNodeOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null; // depends on control dependency: [if], data = [none]
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate); // depends on control dependency: [if], data = [(ocpDate]
}
return this;
} }
|
public class class_name {
public static final Box getBox(CSSBoxView v)
{
try
{
AttributeSet attr = v.getAttributes();
return (Box) attr.getAttribute(Constants.ATTRIBUTE_BOX_REFERENCE);
} catch (Exception e)
{
throw new IllegalStateException(e);
}
} }
|
public class class_name {
public static final Box getBox(CSSBoxView v)
{
try
{
AttributeSet attr = v.getAttributes();
return (Box) attr.getAttribute(Constants.ATTRIBUTE_BOX_REFERENCE); // depends on control dependency: [try], data = [none]
} catch (Exception e)
{
throw new IllegalStateException(e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private void executeBehaviorMethodsInParalellWithSynchroAtTheEnd(Collection<Runnable> behaviorsMethodsToExecute)
throws InterruptedException, ExecutionException {
final CountDownLatch doneSignal = new CountDownLatch(behaviorsMethodsToExecute.size());
final OutputParameter<Throwable> runException = new OutputParameter<>();
for (final Runnable runnable : behaviorsMethodsToExecute) {
this.executor.execute(new JanusRunnable() {
@Override
public void run() {
try {
runnable.run();
} catch (EarlyExitException e) {
// Ignore this exception
} catch (RuntimeException e) {
// Catch exception for notifying the caller
runException.set(e);
// Do the standard behavior too -> logging
throw e;
} catch (Exception e) {
// Catch exception for notifying the caller
runException.set(e);
// Do the standard behavior too -> logging
throw new RuntimeException(e);
} finally {
doneSignal.countDown();
}
}
});
}
// Wait for all Behaviors runnable to complete before continuing
try {
doneSignal.await();
} catch (InterruptedException ex) {
// This exception occurs when one of the launched task kills the agent before all the
// submitted tasks are finished. Keep in mind that killing an agent should kill the
// launched tasks.
// Example of code that is generating this issue:
//
// on Initialize {
// in (100) [
// killMe
// ]
// }
//
// In this example, the killMe is launched before the Initialize code is finished;
// and because the Initialize event is fired through the current function, it
// causes the InterruptedException.
}
// Re-throw the run-time exception
if (runException.get() != null) {
throw new ExecutionException(runException.get());
}
} }
|
public class class_name {
private void executeBehaviorMethodsInParalellWithSynchroAtTheEnd(Collection<Runnable> behaviorsMethodsToExecute)
throws InterruptedException, ExecutionException {
final CountDownLatch doneSignal = new CountDownLatch(behaviorsMethodsToExecute.size());
final OutputParameter<Throwable> runException = new OutputParameter<>();
for (final Runnable runnable : behaviorsMethodsToExecute) {
this.executor.execute(new JanusRunnable() {
@Override
public void run() {
try {
runnable.run(); // depends on control dependency: [try], data = [none]
} catch (EarlyExitException e) {
// Ignore this exception
} catch (RuntimeException e) { // depends on control dependency: [catch], data = [none]
// Catch exception for notifying the caller
runException.set(e);
// Do the standard behavior too -> logging
throw e;
} catch (Exception e) { // depends on control dependency: [catch], data = [none]
// Catch exception for notifying the caller
runException.set(e);
// Do the standard behavior too -> logging
throw new RuntimeException(e);
} finally { // depends on control dependency: [catch], data = [none]
doneSignal.countDown();
}
}
});
}
// Wait for all Behaviors runnable to complete before continuing
try {
doneSignal.await();
} catch (InterruptedException ex) {
// This exception occurs when one of the launched task kills the agent before all the
// submitted tasks are finished. Keep in mind that killing an agent should kill the
// launched tasks.
// Example of code that is generating this issue:
//
// on Initialize {
// in (100) [
// killMe
// ]
// }
//
// In this example, the killMe is launched before the Initialize code is finished;
// and because the Initialize event is fired through the current function, it
// causes the InterruptedException.
}
// Re-throw the run-time exception
if (runException.get() != null) {
throw new ExecutionException(runException.get());
}
} }
|
public class class_name {
public static void compact(Set<String> source, Adder adder, boolean shorterPairs, boolean moreCompact) {
if (!moreCompact) {
String start = null;
String end = null;
int lastCp = 0;
int prefixLen = 0;
for (String s : source) {
if (start != null) { // We have something queued up
if (s.regionMatches(0, start, 0, prefixLen)) {
int currentCp = s.codePointAt(prefixLen);
if (currentCp == 1+lastCp && s.length() == prefixLen + Character.charCount(currentCp)) {
end = s;
lastCp = currentCp;
continue;
}
}
// We failed to find continuation. Add what we have and restart
adder.add(start, end == null ? null
: !shorterPairs ? end
: end.substring(prefixLen, end.length()));
}
// new possible range
start = s;
end = null;
lastCp = s.codePointBefore(s.length());
prefixLen = s.length() - Character.charCount(lastCp);
}
adder.add(start, end == null ? null
: !shorterPairs ? end
: end.substring(prefixLen, end.length()));
} else {
// not a fast algorithm, but ok for now
// TODO rewire to use the first (slower) algorithm to generate the ranges, then compact them from there.
// first sort by lengths
Relation<Integer,Ranges> lengthToArrays = Relation.of(new TreeMap<Integer,Set<Ranges>>(), TreeSet.class);
for (String s : source) {
Ranges item = new Ranges(s);
lengthToArrays.put(item.size(), item);
}
// then compact items of each length and emit compacted sets
for (Entry<Integer, Set<Ranges>> entry : lengthToArrays.keyValuesSet()) {
LinkedList<Ranges> compacted = compact(entry.getKey(), entry.getValue());
for (Ranges ranges : compacted) {
adder.add(ranges.start(), ranges.end(shorterPairs));
}
}
}
} }
|
public class class_name {
public static void compact(Set<String> source, Adder adder, boolean shorterPairs, boolean moreCompact) {
if (!moreCompact) {
String start = null;
String end = null;
int lastCp = 0;
int prefixLen = 0;
for (String s : source) {
if (start != null) { // We have something queued up
if (s.regionMatches(0, start, 0, prefixLen)) {
int currentCp = s.codePointAt(prefixLen);
if (currentCp == 1+lastCp && s.length() == prefixLen + Character.charCount(currentCp)) {
end = s; // depends on control dependency: [if], data = [none]
lastCp = currentCp; // depends on control dependency: [if], data = [none]
continue;
}
}
// We failed to find continuation. Add what we have and restart
adder.add(start, end == null ? null
: !shorterPairs ? end
: end.substring(prefixLen, end.length())); // depends on control dependency: [if], data = [(start]
}
// new possible range
start = s; // depends on control dependency: [for], data = [s]
end = null; // depends on control dependency: [for], data = [none]
lastCp = s.codePointBefore(s.length()); // depends on control dependency: [for], data = [s]
prefixLen = s.length() - Character.charCount(lastCp); // depends on control dependency: [for], data = [s]
}
adder.add(start, end == null ? null
: !shorterPairs ? end
: end.substring(prefixLen, end.length())); // depends on control dependency: [if], data = [none]
} else {
// not a fast algorithm, but ok for now
// TODO rewire to use the first (slower) algorithm to generate the ranges, then compact them from there.
// first sort by lengths
Relation<Integer,Ranges> lengthToArrays = Relation.of(new TreeMap<Integer,Set<Ranges>>(), TreeSet.class);
for (String s : source) {
Ranges item = new Ranges(s);
lengthToArrays.put(item.size(), item); // depends on control dependency: [for], data = [s]
}
// then compact items of each length and emit compacted sets
for (Entry<Integer, Set<Ranges>> entry : lengthToArrays.keyValuesSet()) {
LinkedList<Ranges> compacted = compact(entry.getKey(), entry.getValue());
for (Ranges ranges : compacted) {
adder.add(ranges.start(), ranges.end(shorterPairs)); // depends on control dependency: [for], data = [ranges]
}
}
}
} }
|
public class class_name {
public static @Nullable String getLibraryPath(String libName) throws IOException {
sSoSourcesLock.readLock().lock();
String libPath = null;
try {
if (sSoSources != null) {
for (int i = 0; libPath == null && i < sSoSources.length; ++i) {
SoSource currentSource = sSoSources[i];
libPath = currentSource.getLibraryPath(libName);
}
}
} finally {
sSoSourcesLock.readLock().unlock();
}
return libPath;
} }
|
public class class_name {
public static @Nullable String getLibraryPath(String libName) throws IOException {
sSoSourcesLock.readLock().lock();
String libPath = null;
try {
if (sSoSources != null) {
for (int i = 0; libPath == null && i < sSoSources.length; ++i) {
SoSource currentSource = sSoSources[i];
libPath = currentSource.getLibraryPath(libName); // depends on control dependency: [for], data = [none]
}
}
} finally {
sSoSourcesLock.readLock().unlock();
}
return libPath;
} }
|
public class class_name {
void toJSONString(final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId,
final boolean includeNullValuedFields, final int depth, final int indentWidth,
final StringBuilder buf) {
final boolean prettyPrint = indentWidth > 0;
final int n = items.size();
int numDisplayedFields;
if (includeNullValuedFields) {
numDisplayedFields = n;
} else {
numDisplayedFields = 0;
for (final Entry<String, Object> item : items) {
if (item.getValue() != null) {
numDisplayedFields++;
}
}
}
if (objectId == null && numDisplayedFields == 0) {
buf.append("{}");
} else {
buf.append(prettyPrint ? "{\n" : "{");
if (objectId != null) {
// id will be non-null if this object does not have an @Id field, but was referenced by
// another object (need to include ID_TAG)
if (prettyPrint) {
JSONUtils.indent(depth + 1, indentWidth, buf);
}
buf.append('"');
buf.append(JSONUtils.ID_KEY);
buf.append(prettyPrint ? "\": " : "\":");
JSONSerializer.jsonValToJSONString(objectId, jsonReferenceToId, includeNullValuedFields, depth + 1,
indentWidth, buf);
if (numDisplayedFields > 0) {
buf.append(',');
}
if (prettyPrint) {
buf.append('\n');
}
}
for (int i = 0, j = 0; i < n; i++) {
final Entry<String, Object> item = items.get(i);
final Object val = item.getValue();
if (val != null || includeNullValuedFields) {
final String key = item.getKey();
if (key == null) {
// Keys must be quoted, so the unquoted null value cannot be a key
// (Should not happen -- JSONParser.parseJSONObject checks for null keys)
throw new IllegalArgumentException("Cannot serialize JSON object with null key");
}
if (prettyPrint) {
JSONUtils.indent(depth + 1, indentWidth, buf);
}
buf.append('"');
JSONUtils.escapeJSONString(key, buf);
buf.append(prettyPrint ? "\": " : "\":");
JSONSerializer.jsonValToJSONString(val, jsonReferenceToId, includeNullValuedFields, depth + 1,
indentWidth, buf);
if (++j < numDisplayedFields) {
buf.append(',');
}
if (prettyPrint) {
buf.append('\n');
}
}
}
if (prettyPrint) {
JSONUtils.indent(depth, indentWidth, buf);
}
buf.append('}');
}
} }
|
public class class_name {
void toJSONString(final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId,
final boolean includeNullValuedFields, final int depth, final int indentWidth,
final StringBuilder buf) {
final boolean prettyPrint = indentWidth > 0;
final int n = items.size();
int numDisplayedFields;
if (includeNullValuedFields) {
numDisplayedFields = n; // depends on control dependency: [if], data = [none]
} else {
numDisplayedFields = 0; // depends on control dependency: [if], data = [none]
for (final Entry<String, Object> item : items) {
if (item.getValue() != null) {
numDisplayedFields++; // depends on control dependency: [if], data = [none]
}
}
}
if (objectId == null && numDisplayedFields == 0) {
buf.append("{}"); // depends on control dependency: [if], data = [none]
} else {
buf.append(prettyPrint ? "{\n" : "{"); // depends on control dependency: [if], data = [none]
if (objectId != null) {
// id will be non-null if this object does not have an @Id field, but was referenced by
// another object (need to include ID_TAG)
if (prettyPrint) {
JSONUtils.indent(depth + 1, indentWidth, buf); // depends on control dependency: [if], data = [none]
}
buf.append('"'); // depends on control dependency: [if], data = [none]
buf.append(JSONUtils.ID_KEY); // depends on control dependency: [if], data = [none]
buf.append(prettyPrint ? "\": " : "\":"); // depends on control dependency: [if], data = [none]
JSONSerializer.jsonValToJSONString(objectId, jsonReferenceToId, includeNullValuedFields, depth + 1,
indentWidth, buf); // depends on control dependency: [if], data = [none]
if (numDisplayedFields > 0) {
buf.append(','); // depends on control dependency: [if], data = [none]
}
if (prettyPrint) {
buf.append('\n'); // depends on control dependency: [if], data = [none]
}
}
for (int i = 0, j = 0; i < n; i++) {
final Entry<String, Object> item = items.get(i);
final Object val = item.getValue();
if (val != null || includeNullValuedFields) {
final String key = item.getKey();
if (key == null) {
// Keys must be quoted, so the unquoted null value cannot be a key
// (Should not happen -- JSONParser.parseJSONObject checks for null keys)
throw new IllegalArgumentException("Cannot serialize JSON object with null key");
}
if (prettyPrint) {
JSONUtils.indent(depth + 1, indentWidth, buf); // depends on control dependency: [if], data = [none]
}
buf.append('"'); // depends on control dependency: [if], data = [none]
JSONUtils.escapeJSONString(key, buf); // depends on control dependency: [if], data = [none]
buf.append(prettyPrint ? "\": " : "\":"); // depends on control dependency: [if], data = [none]
JSONSerializer.jsonValToJSONString(val, jsonReferenceToId, includeNullValuedFields, depth + 1,
indentWidth, buf); // depends on control dependency: [if], data = [none]
if (++j < numDisplayedFields) {
buf.append(','); // depends on control dependency: [if], data = [none]
}
if (prettyPrint) {
buf.append('\n'); // depends on control dependency: [if], data = [none]
}
}
}
if (prettyPrint) {
JSONUtils.indent(depth, indentWidth, buf); // depends on control dependency: [if], data = [none]
}
buf.append('}'); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
protected void configurePropertySources(ConfigurableEnvironment environment,
String[] args) {
MutablePropertySources sources = environment.getPropertySources();
if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
sources.addLast(
new MapPropertySource("defaultProperties", this.defaultProperties));
}
if (this.addCommandLineProperties && args.length > 0) {
String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
if (sources.contains(name)) {
PropertySource<?> source = sources.get(name);
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(new SimpleCommandLinePropertySource(
"springApplicationCommandLineArgs", args));
composite.addPropertySource(source);
sources.replace(name, composite);
}
else {
sources.addFirst(new SimpleCommandLinePropertySource(args));
}
}
} }
|
public class class_name {
protected void configurePropertySources(ConfigurableEnvironment environment,
String[] args) {
MutablePropertySources sources = environment.getPropertySources();
if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
sources.addLast(
new MapPropertySource("defaultProperties", this.defaultProperties)); // depends on control dependency: [if], data = [none]
}
if (this.addCommandLineProperties && args.length > 0) {
String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
if (sources.contains(name)) {
PropertySource<?> source = sources.get(name);
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(new SimpleCommandLinePropertySource(
"springApplicationCommandLineArgs", args)); // depends on control dependency: [if], data = [none]
composite.addPropertySource(source); // depends on control dependency: [if], data = [none]
sources.replace(name, composite); // depends on control dependency: [if], data = [none]
}
else {
sources.addFirst(new SimpleCommandLinePropertySource(args)); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
@SuppressWarnings("unchecked")
private void createErrorFile(Watcher watcher, WatchingException e) {
mojo.getLog().debug("Creating error file for '" + e.getMessage() + "' happening at " + e.getLine() + ":" + e
.getCharacter() + " of " + e.getFile() + ", created by watcher : " + watcher);
JSONObject obj = new JSONObject();
obj.put("message", e.getMessage());
if (watcher instanceof WatcherDelegate) {
obj.put("watcher", ((WatcherDelegate) watcher).getDelegate().getClass().getName());
} else {
obj.put("watcher", watcher.getClass().getName());
}
if (e.getFile() != null) {
obj.put("file", e.getFile().getAbsolutePath());
}
if (e.getLine() != -1) {
obj.put("line", e.getLine());
}
if (e.getCharacter() != -1) {
obj.put("character", e.getCharacter());
}
if (e.getCause() != null) {
obj.put("cause", e.getCause().getMessage());
}
if (e.getTitle() != null) {
obj.put("title", e.getTitle());
}
try {
FileUtils.writeStringToFile(getErrorFileForWatcher(watcher), obj.toJSONString(), false);
} catch (IOException e1) {
mojo.getLog().error("Cannot write the error file", e1);
}
} }
|
public class class_name {
@SuppressWarnings("unchecked")
private void createErrorFile(Watcher watcher, WatchingException e) {
mojo.getLog().debug("Creating error file for '" + e.getMessage() + "' happening at " + e.getLine() + ":" + e
.getCharacter() + " of " + e.getFile() + ", created by watcher : " + watcher);
JSONObject obj = new JSONObject();
obj.put("message", e.getMessage());
if (watcher instanceof WatcherDelegate) {
obj.put("watcher", ((WatcherDelegate) watcher).getDelegate().getClass().getName()); // depends on control dependency: [if], data = [none]
} else {
obj.put("watcher", watcher.getClass().getName()); // depends on control dependency: [if], data = [none]
}
if (e.getFile() != null) {
obj.put("file", e.getFile().getAbsolutePath()); // depends on control dependency: [if], data = [none]
}
if (e.getLine() != -1) {
obj.put("line", e.getLine()); // depends on control dependency: [if], data = [none]
}
if (e.getCharacter() != -1) {
obj.put("character", e.getCharacter()); // depends on control dependency: [if], data = [none]
}
if (e.getCause() != null) {
obj.put("cause", e.getCause().getMessage()); // depends on control dependency: [if], data = [none]
}
if (e.getTitle() != null) {
obj.put("title", e.getTitle()); // depends on control dependency: [if], data = [none]
}
try {
FileUtils.writeStringToFile(getErrorFileForWatcher(watcher), obj.toJSONString(), false); // depends on control dependency: [try], data = [none]
} catch (IOException e1) {
mojo.getLog().error("Cannot write the error file", e1);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public com.apptentive.android.sdk.model.CustomData toJson() {
try {
com.apptentive.android.sdk.model.CustomData ret = new com.apptentive.android.sdk.model.CustomData();
Set<String> keys = keySet();
for (String key : keys) {
ret.put(key, get(key));
}
return ret;
} catch (JSONException e) {
ApptentiveLog.e(e, "Exception while creating custom data");
logException(e);
}
return null;
} }
|
public class class_name {
public com.apptentive.android.sdk.model.CustomData toJson() {
try {
com.apptentive.android.sdk.model.CustomData ret = new com.apptentive.android.sdk.model.CustomData();
Set<String> keys = keySet();
for (String key : keys) {
ret.put(key, get(key)); // depends on control dependency: [for], data = [key]
}
return ret; // depends on control dependency: [try], data = [none]
} catch (JSONException e) {
ApptentiveLog.e(e, "Exception while creating custom data");
logException(e);
} // depends on control dependency: [catch], data = [none]
return null;
} }
|
public class class_name {
public static <T extends OutputStream> T pump(InputStream is, T os, boolean closeIn, boolean closeOut) throws IOException{
byte buff[] = new byte[1024];
int len;
Exception exception = null;
try{
while((len=is.read(buff))!=-1)
os.write(buff, 0, len);
}catch(Exception ex){
exception = ex;
}finally{
try{
try{
if(closeIn)
is.close();
}finally{
if(closeOut)
os.close();
}
}catch(IOException ex){
if(exception!=null)
ex.printStackTrace();
else
exception = ex;
}
}
if(exception instanceof IOException)
throw (IOException)exception;
else if(exception instanceof RuntimeException)
throw (RuntimeException)exception;
return os;
} }
|
public class class_name {
public static <T extends OutputStream> T pump(InputStream is, T os, boolean closeIn, boolean closeOut) throws IOException{
byte buff[] = new byte[1024];
int len;
Exception exception = null;
try{
while((len=is.read(buff))!=-1)
os.write(buff, 0, len);
}catch(Exception ex){
exception = ex;
}finally{
try{
try{
if(closeIn)
is.close();
}finally{
if(closeOut)
os.close();
}
}catch(IOException ex){
if(exception!=null)
ex.printStackTrace();
else
exception = ex;
} // depends on control dependency: [catch], data = [none]
}
if(exception instanceof IOException)
throw (IOException)exception;
else if(exception instanceof RuntimeException)
throw (RuntimeException)exception;
return os;
} }
|
public class class_name {
public static double max(double a, double b) {
if (a != a)
return a; // a is NaN
if ((a == 0.0d) &&
(b == 0.0d) &&
(Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) {
// Raw conversion ok since NaN can't map to -0.0.
return b;
}
return (a >= b) ? a : b;
} }
|
public class class_name {
public static double max(double a, double b) {
if (a != a)
return a; // a is NaN
if ((a == 0.0d) &&
(b == 0.0d) &&
(Double.doubleToRawLongBits(a) == negativeZeroDoubleBits)) {
// Raw conversion ok since NaN can't map to -0.0.
return b; // depends on control dependency: [if], data = [none]
}
return (a >= b) ? a : b;
} }
|
public class class_name {
public static int getSupervisorPortNum(Map conf, int sysCpuNum, Long physicalMemSize) {
double cpuWeight = ConfigExtension.getSupervisorSlotsPortCpuWeight(conf);
int cpuPortNum = (int) (sysCpuNum / cpuWeight);
if (cpuPortNum < 1) {
LOG.info("Invalid supervisor.slots.port.cpu.weight setting :" + cpuWeight + ", cpu cores:" + sysCpuNum);
cpuPortNum = 1;
}
Double memWeight = ConfigExtension.getSupervisorSlotsPortMemWeight(conf);
int memPortNum = Integer.MAX_VALUE;
if (physicalMemSize == null) {
LOG.info("Failed to get memory size");
} else {
LOG.debug("Get system memory size: " + physicalMemSize);
long workerMemSize = ConfigExtension.getMemSizePerWorker(conf);
memPortNum = (int) (physicalMemSize / (workerMemSize * memWeight));
if (memPortNum < 1) {
LOG.info("System memory is too small for Jstorm");
memPortNum = 1; // minimal port number set to 1 if memory is not enough
}
}
return Math.min(cpuPortNum, memPortNum);
} }
|
public class class_name {
public static int getSupervisorPortNum(Map conf, int sysCpuNum, Long physicalMemSize) {
double cpuWeight = ConfigExtension.getSupervisorSlotsPortCpuWeight(conf);
int cpuPortNum = (int) (sysCpuNum / cpuWeight);
if (cpuPortNum < 1) {
LOG.info("Invalid supervisor.slots.port.cpu.weight setting :" + cpuWeight + ", cpu cores:" + sysCpuNum); // depends on control dependency: [if], data = [none]
cpuPortNum = 1; // depends on control dependency: [if], data = [none]
}
Double memWeight = ConfigExtension.getSupervisorSlotsPortMemWeight(conf);
int memPortNum = Integer.MAX_VALUE;
if (physicalMemSize == null) {
LOG.info("Failed to get memory size");
} else {
LOG.debug("Get system memory size: " + physicalMemSize);
long workerMemSize = ConfigExtension.getMemSizePerWorker(conf);
memPortNum = (int) (physicalMemSize / (workerMemSize * memWeight));
if (memPortNum < 1) {
LOG.info("System memory is too small for Jstorm");
memPortNum = 1; // minimal port number set to 1 if memory is not enough
}
}
return Math.min(cpuPortNum, memPortNum);
} }
|
public class class_name {
public static double[] timesPlusTimesEquals(final double[] v1, final double s1, final double[] v2, final double s2) {
assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
for(int i = 0; i < v1.length; i++) {
v1[i] = v1[i] * s1 + v2[i] * s2;
}
return v1;
} }
|
public class class_name {
public static double[] timesPlusTimesEquals(final double[] v1, final double s1, final double[] v2, final double s2) {
assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
for(int i = 0; i < v1.length; i++) {
v1[i] = v1[i] * s1 + v2[i] * s2; // depends on control dependency: [for], data = [i]
}
return v1;
} }
|
public class class_name {
private String getCommitBody(List<BoxFileUploadSessionPart> parts, Map<String, String> attributes) {
JsonObject jsonObject = new JsonObject();
JsonArray array = new JsonArray();
for (BoxFileUploadSessionPart part: parts) {
JsonObject partObj = new JsonObject();
partObj.add("part_id", part.getPartId());
partObj.add("offset", part.getOffset());
partObj.add("size", part.getSize());
array.add(partObj);
}
jsonObject.add("parts", array);
if (attributes != null) {
JsonObject attrObj = new JsonObject();
for (String key: attributes.keySet()) {
attrObj.add(key, attributes.get(key));
}
jsonObject.add("attributes", attrObj);
}
return jsonObject.toString();
} }
|
public class class_name {
private String getCommitBody(List<BoxFileUploadSessionPart> parts, Map<String, String> attributes) {
JsonObject jsonObject = new JsonObject();
JsonArray array = new JsonArray();
for (BoxFileUploadSessionPart part: parts) {
JsonObject partObj = new JsonObject();
partObj.add("part_id", part.getPartId()); // depends on control dependency: [for], data = [part]
partObj.add("offset", part.getOffset()); // depends on control dependency: [for], data = [part]
partObj.add("size", part.getSize()); // depends on control dependency: [for], data = [part]
array.add(partObj); // depends on control dependency: [for], data = [part]
}
jsonObject.add("parts", array);
if (attributes != null) {
JsonObject attrObj = new JsonObject();
for (String key: attributes.keySet()) {
attrObj.add(key, attributes.get(key)); // depends on control dependency: [for], data = [key]
}
jsonObject.add("attributes", attrObj); // depends on control dependency: [if], data = [none]
}
return jsonObject.toString();
} }
|
public class class_name {
@SuppressWarnings("unchecked")
public static <E> E[] filter(E[] elems, Filter<E> filter) {
List<E> filtered = new ArrayList<E>();
for (E elem: elems) {
if (filter.accept(elem)) {
filtered.add(elem);
}
}
return (filtered.toArray((E[]) Array.newInstance(elems.getClass().getComponentType(), filtered.size())));
} }
|
public class class_name {
@SuppressWarnings("unchecked")
public static <E> E[] filter(E[] elems, Filter<E> filter) {
List<E> filtered = new ArrayList<E>();
for (E elem: elems) {
if (filter.accept(elem)) {
filtered.add(elem);
// depends on control dependency: [if], data = [none]
}
}
return (filtered.toArray((E[]) Array.newInstance(elems.getClass().getComponentType(), filtered.size())));
} }
|
public class class_name {
XSLTElementProcessor getProcessorFor(String uri, String localName)
{
XSLTElementProcessor elemDef = null; // return value
if (null == m_elements)
return null;
int n = m_elements.length;
int order = -1;
boolean multiAllowed = true;
for (int i = 0; i < n; i++)
{
XSLTElementDef def = m_elements[i];
// A "*" signals that the element allows literal result
// elements, so just assign the def, and continue to
// see if anything else matches.
if (def.m_name.equals("*"))
{
// Don't allow xsl elements
if (!equalsMayBeNullOrZeroLen(uri, Constants.S_XSLNAMESPACEURL))
{
elemDef = def.m_elementProcessor;
order = def.getOrder();
multiAllowed = def.getMultiAllowed();
}
}
else if (def.QNameEquals(uri, localName))
{
if (def.getRequired())
this.setRequiredFound(def.getName(), true);
order = def.getOrder();
multiAllowed = def.getMultiAllowed();
elemDef = def.m_elementProcessor;
break;
}
}
if (elemDef != null && this.isOrdered())
{
int lastOrder = getLastOrder();
if (order > lastOrder)
setLastOrder(order);
else if (order == lastOrder && !multiAllowed)
{
return null;
}
else if (order < lastOrder && order > 0)
{
return null;
}
}
return elemDef;
} }
|
public class class_name {
XSLTElementProcessor getProcessorFor(String uri, String localName)
{
XSLTElementProcessor elemDef = null; // return value
if (null == m_elements)
return null;
int n = m_elements.length;
int order = -1;
boolean multiAllowed = true;
for (int i = 0; i < n; i++)
{
XSLTElementDef def = m_elements[i];
// A "*" signals that the element allows literal result
// elements, so just assign the def, and continue to
// see if anything else matches.
if (def.m_name.equals("*"))
{
// Don't allow xsl elements
if (!equalsMayBeNullOrZeroLen(uri, Constants.S_XSLNAMESPACEURL))
{
elemDef = def.m_elementProcessor; // depends on control dependency: [if], data = [none]
order = def.getOrder(); // depends on control dependency: [if], data = [none]
multiAllowed = def.getMultiAllowed(); // depends on control dependency: [if], data = [none]
}
}
else if (def.QNameEquals(uri, localName))
{
if (def.getRequired())
this.setRequiredFound(def.getName(), true);
order = def.getOrder(); // depends on control dependency: [if], data = [none]
multiAllowed = def.getMultiAllowed(); // depends on control dependency: [if], data = [none]
elemDef = def.m_elementProcessor; // depends on control dependency: [if], data = [none]
break;
}
}
if (elemDef != null && this.isOrdered())
{
int lastOrder = getLastOrder();
if (order > lastOrder)
setLastOrder(order);
else if (order == lastOrder && !multiAllowed)
{
return null; // depends on control dependency: [if], data = [none]
}
else if (order < lastOrder && order > 0)
{
return null; // depends on control dependency: [if], data = [none]
}
}
return elemDef;
} }
|
public class class_name {
public boolean isImportingWicket() {
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
// First check if there is a wiring to any package of org.apache.wicket
List<BundleWire> importPackageWires = bundleWiring.getRequiredWires(OSGI_WIRING_PACKAGE_NAMESPACE);
for (BundleWire bundleWire : importPackageWires) {
BundleRequirement requirement = bundleWire.getRequirement();
String filter = requirement.getDirectives().get(FILTER_DIRECTIVE);
if (filter != null) {
Matcher matcher = PACKAGE_PATTERN_WICKET.matcher(filter);
if (matcher.find()) {
return true;
}
}
}
List<BundleWire> requireBundleWires = bundleWiring.getRequiredWires(OSGI_WIRING_BUNDLE_NAMESPACE);
if (!requireBundleWires.isEmpty()) {
// find all apache.wicket bundles and check if there are wirings...
Bundle[] bundles = bundleContext.paxBundleContext.getBundles();
for (Bundle bundle : bundles) {
String symbolicName = bundle.getSymbolicName();
if (symbolicName.startsWith(APACHE_WICKET_NAMESPACE)) {
Map<String, Object> map = createMapWithVersion(OSGI_WIRING_BUNDLE_NAMESPACE, symbolicName,
bundle.getVersion());
if (hasWireMatchingFilter(requireBundleWires, map)) {
return true;
}
}
}
}
return false;
} }
|
public class class_name {
public boolean isImportingWicket() {
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
// First check if there is a wiring to any package of org.apache.wicket
List<BundleWire> importPackageWires = bundleWiring.getRequiredWires(OSGI_WIRING_PACKAGE_NAMESPACE);
for (BundleWire bundleWire : importPackageWires) {
BundleRequirement requirement = bundleWire.getRequirement();
String filter = requirement.getDirectives().get(FILTER_DIRECTIVE);
if (filter != null) {
Matcher matcher = PACKAGE_PATTERN_WICKET.matcher(filter);
if (matcher.find()) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
List<BundleWire> requireBundleWires = bundleWiring.getRequiredWires(OSGI_WIRING_BUNDLE_NAMESPACE);
if (!requireBundleWires.isEmpty()) {
// find all apache.wicket bundles and check if there are wirings...
Bundle[] bundles = bundleContext.paxBundleContext.getBundles();
for (Bundle bundle : bundles) {
String symbolicName = bundle.getSymbolicName();
if (symbolicName.startsWith(APACHE_WICKET_NAMESPACE)) {
Map<String, Object> map = createMapWithVersion(OSGI_WIRING_BUNDLE_NAMESPACE, symbolicName,
bundle.getVersion());
if (hasWireMatchingFilter(requireBundleWires, map)) {
return true; // depends on control dependency: [if], data = [none]
}
}
}
}
return false;
} }
|
public class class_name {
public CountryCodeDataType.Enum getCountryCodeDataType(String countryCode) {
CountryCodeDataType.Enum countryCodeDataType = null;
CountryContract country = s2SLocationService.getCountryFromCode(countryCode);
if (country != null) {
StringBuilder countryDetail = new StringBuilder();
countryDetail.append(country.getAlternateCode());
countryDetail.append(": ");
countryDetail.append(country.getName().toUpperCase());
countryCodeDataType = CountryCodeDataType.Enum
.forString(countryDetail.toString());
}
return countryCodeDataType;
} }
|
public class class_name {
public CountryCodeDataType.Enum getCountryCodeDataType(String countryCode) {
CountryCodeDataType.Enum countryCodeDataType = null;
CountryContract country = s2SLocationService.getCountryFromCode(countryCode);
if (country != null) {
StringBuilder countryDetail = new StringBuilder();
countryDetail.append(country.getAlternateCode()); // depends on control dependency: [if], data = [(country]
countryDetail.append(": "); // depends on control dependency: [if], data = [none]
countryDetail.append(country.getName().toUpperCase()); // depends on control dependency: [if], data = [(country]
countryCodeDataType = CountryCodeDataType.Enum
.forString(countryDetail.toString()); // depends on control dependency: [if], data = [none]
}
return countryCodeDataType;
} }
|
public class class_name {
public void addGroupBy(String[] fieldNames)
{
for (int i = 0; i < fieldNames.length; i++)
{
addGroupBy(fieldNames[i]);
}
} }
|
public class class_name {
public void addGroupBy(String[] fieldNames)
{
for (int i = 0; i < fieldNames.length; i++)
{
addGroupBy(fieldNames[i]);
// depends on control dependency: [for], data = [i]
}
} }
|
public class class_name {
private EventConsumer findEventConsumerForSubscriberMethod(SubscriberInfo subscriberInfo, String callDescription) {
Method subscriberMethod = subscriberInfo.getSubscriberMethod();
Subscribe subscribeAnnotation = subscriberMethod.getAnnotation(Subscribe.class);
if (null == subscribeAnnotation) {
LOGGER.error(String.format("The subscriber method: %s is not annotated with @Subscribe. Ignoring %s call.",
subscriberMethod, callDescription));
return null;
}
CopyOnWriteArrayList<EventConsumer> eventConsumers = consumersBySubscriberClass.get(
subscriberMethod.getDeclaringClass());
if (null != eventConsumers) {
// Here what we are dealing with is the subscriber methods in a SINGLE class, so O(n) will suffice.
for (EventConsumer eventConsumer : eventConsumers) {
if (isTheSameSubscriber(subscriberInfo, eventConsumer)) {
return eventConsumer;
}
}
}
LOGGER.info(String.format("Subscriber: %s is not registered (or already removed). Ignoring %s call.",
subscriberMethod, callDescription));
return null;
} }
|
public class class_name {
private EventConsumer findEventConsumerForSubscriberMethod(SubscriberInfo subscriberInfo, String callDescription) {
Method subscriberMethod = subscriberInfo.getSubscriberMethod();
Subscribe subscribeAnnotation = subscriberMethod.getAnnotation(Subscribe.class);
if (null == subscribeAnnotation) {
LOGGER.error(String.format("The subscriber method: %s is not annotated with @Subscribe. Ignoring %s call.",
subscriberMethod, callDescription)); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
CopyOnWriteArrayList<EventConsumer> eventConsumers = consumersBySubscriberClass.get(
subscriberMethod.getDeclaringClass());
if (null != eventConsumers) {
// Here what we are dealing with is the subscriber methods in a SINGLE class, so O(n) will suffice.
for (EventConsumer eventConsumer : eventConsumers) {
if (isTheSameSubscriber(subscriberInfo, eventConsumer)) {
return eventConsumer; // depends on control dependency: [if], data = [none]
}
}
}
LOGGER.info(String.format("Subscriber: %s is not registered (or already removed). Ignoring %s call.",
subscriberMethod, callDescription));
return null;
} }
|
public class class_name {
@Override
public void handle(String chargingStationId, JsonObject commandObject, IdentityContext identityContext) throws UserIdentityUnauthorizedException {
ChargingStationId csId = new ChargingStationId(chargingStationId);
if (!commandAuthorizationService.isAuthorized(csId, identityContext.getUserIdentity(), AddChargingStationOpeningTimesCommand.class)) {
throw new UserIdentityUnauthorizedException(chargingStationId, identityContext.getUserIdentity(), AddChargingStationOpeningTimesCommand.class);
}
try {
ChargingStation chargingStation = repository.findOne(chargingStationId);
if (chargingStation != null && chargingStation.isAccepted()) {
AddChargingStationOpeningTimesApiCommand command = gson.fromJson(commandObject, AddChargingStationOpeningTimesApiCommand.class);
commandGateway.send(new AddChargingStationOpeningTimesCommand(csId, command.getOpeningTimes(), identityContext));
}
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException("Set charging station opening times command not able to parse the payload, is your JSON correctly formatted?", e);
}
} }
|
public class class_name {
@Override
public void handle(String chargingStationId, JsonObject commandObject, IdentityContext identityContext) throws UserIdentityUnauthorizedException {
ChargingStationId csId = new ChargingStationId(chargingStationId);
if (!commandAuthorizationService.isAuthorized(csId, identityContext.getUserIdentity(), AddChargingStationOpeningTimesCommand.class)) {
throw new UserIdentityUnauthorizedException(chargingStationId, identityContext.getUserIdentity(), AddChargingStationOpeningTimesCommand.class);
}
try {
ChargingStation chargingStation = repository.findOne(chargingStationId);
if (chargingStation != null && chargingStation.isAccepted()) {
AddChargingStationOpeningTimesApiCommand command = gson.fromJson(commandObject, AddChargingStationOpeningTimesApiCommand.class);
commandGateway.send(new AddChargingStationOpeningTimesCommand(csId, command.getOpeningTimes(), identityContext)); // depends on control dependency: [if], data = [none]
}
} catch (JsonSyntaxException e) {
throw new IllegalArgumentException("Set charging station opening times command not able to parse the payload, is your JSON correctly formatted?", e);
}
} }
|
public class class_name {
public final void draw() {
AffineTransform transform = new AffineTransform(this.transform);
transform.concatenate(getAlignmentTransform());
// draw the background box
this.graphics2d.setTransform(transform);
this.graphics2d.setColor(this.params.getBackgroundColor());
this.graphics2d.fillRect(0, 0, this.settings.getSize().width, this.settings.getSize().height);
//draw the labels
this.graphics2d.setColor(this.params.getFontColor());
drawLabels(transform, this.params.getOrientation(), this.params.getLabelRotation());
//sets the transformation for drawing the bar and do it
final AffineTransform lineTransform = new AffineTransform(transform);
setLineTranslate(lineTransform);
if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT ||
this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) {
final AffineTransform rotate = AffineTransform.getQuadrantRotateInstance(1);
lineTransform.concatenate(rotate);
}
this.graphics2d.setTransform(lineTransform);
this.graphics2d.setStroke(new BasicStroke(this.settings.getLineWidth()));
this.graphics2d.setColor(this.params.getColor());
drawBar();
} }
|
public class class_name {
public final void draw() {
AffineTransform transform = new AffineTransform(this.transform);
transform.concatenate(getAlignmentTransform());
// draw the background box
this.graphics2d.setTransform(transform);
this.graphics2d.setColor(this.params.getBackgroundColor());
this.graphics2d.fillRect(0, 0, this.settings.getSize().width, this.settings.getSize().height);
//draw the labels
this.graphics2d.setColor(this.params.getFontColor());
drawLabels(transform, this.params.getOrientation(), this.params.getLabelRotation());
//sets the transformation for drawing the bar and do it
final AffineTransform lineTransform = new AffineTransform(transform);
setLineTranslate(lineTransform);
if (this.params.getOrientation() == Orientation.VERTICAL_LABELS_LEFT ||
this.params.getOrientation() == Orientation.VERTICAL_LABELS_RIGHT) {
final AffineTransform rotate = AffineTransform.getQuadrantRotateInstance(1);
lineTransform.concatenate(rotate); // depends on control dependency: [if], data = [none]
}
this.graphics2d.setTransform(lineTransform);
this.graphics2d.setStroke(new BasicStroke(this.settings.getLineWidth()));
this.graphics2d.setColor(this.params.getColor());
drawBar();
} }
|
public class class_name {
private Credentials getCredentials(Stage.Context context, List<Stage.ConfigIssue> issues) {
Credentials credentials = null;
File credentialsFile;
if (Paths.get(path).isAbsolute()) {
credentialsFile = new File(path);
} else {
credentialsFile = new File(context.getResourcesDirectory(), path);
}
if (!credentialsFile.exists() || !credentialsFile.isFile()) {
LOG.error(GOOGLE_01.getMessage(), credentialsFile.getPath());
issues.add(context.createConfigIssue(
Groups.CREDENTIALS.name(), CONF_CREDENTIALS_CREDENTIALS_PROVIDER,
GOOGLE_01,
credentialsFile.getPath()
));
return null;
}
try (InputStream in = new FileInputStream(credentialsFile)) {
credentials = ServiceAccountCredentials.fromStream(in);
} catch (IOException | IllegalArgumentException e) {
LOG.error(GOOGLE_02.getMessage(), e);
issues.add(context.createConfigIssue(
Groups.CREDENTIALS.name(), CONF_CREDENTIALS_CREDENTIALS_PROVIDER,
GOOGLE_02
));
}
return credentials;
} }
|
public class class_name {
private Credentials getCredentials(Stage.Context context, List<Stage.ConfigIssue> issues) {
Credentials credentials = null;
File credentialsFile;
if (Paths.get(path).isAbsolute()) {
credentialsFile = new File(path); // depends on control dependency: [if], data = [none]
} else {
credentialsFile = new File(context.getResourcesDirectory(), path); // depends on control dependency: [if], data = [none]
}
if (!credentialsFile.exists() || !credentialsFile.isFile()) {
LOG.error(GOOGLE_01.getMessage(), credentialsFile.getPath()); // depends on control dependency: [if], data = [none]
issues.add(context.createConfigIssue(
Groups.CREDENTIALS.name(), CONF_CREDENTIALS_CREDENTIALS_PROVIDER,
GOOGLE_01,
credentialsFile.getPath()
)); // depends on control dependency: [if], data = [none]
return null; // depends on control dependency: [if], data = [none]
}
try (InputStream in = new FileInputStream(credentialsFile)) {
credentials = ServiceAccountCredentials.fromStream(in);
} catch (IOException | IllegalArgumentException e) {
LOG.error(GOOGLE_02.getMessage(), e);
issues.add(context.createConfigIssue(
Groups.CREDENTIALS.name(), CONF_CREDENTIALS_CREDENTIALS_PROVIDER,
GOOGLE_02
));
}
return credentials;
} }
|
public class class_name {
public Set<String> rangeByLexReverse(final LexRange lexRange) {
return doWithJedis(new JedisCallable<Set<String>>() {
@Override
public Set<String> call(Jedis jedis) {
if (lexRange.hasLimit()) {
return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse(), lexRange.offset(), lexRange.count());
} else {
return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse());
}
}
});
} }
|
public class class_name {
public Set<String> rangeByLexReverse(final LexRange lexRange) {
return doWithJedis(new JedisCallable<Set<String>>() {
@Override
public Set<String> call(Jedis jedis) {
if (lexRange.hasLimit()) {
return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse(), lexRange.offset(), lexRange.count()); // depends on control dependency: [if], data = [none]
} else {
return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse()); // depends on control dependency: [if], data = [none]
}
}
});
} }
|
public class class_name {
private synchronized void updateDeploymentMap(DigitalObject obj,
Connection c)
throws SQLException {
Set<RelationshipTuple> sDefs =
obj.getRelationships(Constants.MODEL.IS_DEPLOYMENT_OF, null);
Set<RelationshipTuple> models =
obj.getRelationships(Constants.MODEL.IS_CONTRACTOR_OF, null);
for (RelationshipTuple sDefTuple : sDefs) {
String sDef = sDefTuple.getObjectPID();
for (RelationshipTuple cModelTuple : models) {
String cModel = cModelTuple.getObjectPID();
addDeployment(cModel, sDef, obj, c);
}
}
} }
|
public class class_name {
private synchronized void updateDeploymentMap(DigitalObject obj,
Connection c)
throws SQLException {
Set<RelationshipTuple> sDefs =
obj.getRelationships(Constants.MODEL.IS_DEPLOYMENT_OF, null);
Set<RelationshipTuple> models =
obj.getRelationships(Constants.MODEL.IS_CONTRACTOR_OF, null);
for (RelationshipTuple sDefTuple : sDefs) {
String sDef = sDefTuple.getObjectPID();
for (RelationshipTuple cModelTuple : models) {
String cModel = cModelTuple.getObjectPID();
addDeployment(cModel, sDef, obj, c); // depends on control dependency: [for], data = [none]
}
}
} }
|
public class class_name {
public Map<String, String> applyAll(Iterable<String> keys)
{
if (keys == null) {
return Collections.emptyMap();
}
Map<String, String> map = new HashMap<>();
for (String key : keys) {
map.put(key, apply(key));
}
return map;
} }
|
public class class_name {
public Map<String, String> applyAll(Iterable<String> keys)
{
if (keys == null) {
return Collections.emptyMap(); // depends on control dependency: [if], data = [none]
}
Map<String, String> map = new HashMap<>();
for (String key : keys) {
map.put(key, apply(key)); // depends on control dependency: [for], data = [key]
}
return map;
} }
|
public class class_name {
public static URI addParams(
final URI uri, final Multimap<String, String> params, final Set<String> overrideParams) {
if (params == null || params.isEmpty()) {
return uri;
}
final String origTxt = uri.toString();
int queryStart = origTxt.indexOf('?');
final StringBuilder result = new StringBuilder();
if (queryStart < 0) {
int fragmentStart = origTxt.indexOf('#');
if (fragmentStart < 0) {
result.append(origTxt);
} else {
result.append(origTxt, 0, fragmentStart);
}
} else {
result.append(origTxt, 0, queryStart);
}
Map<String, Collection<String>> origParams = getParameters(uri).asMap();
boolean first = true;
for (Map.Entry<String, Collection<String>> param: params.asMap().entrySet()) {
final String key = param.getKey();
Collection<String> origList = origParams.remove(key);
if (origList != null && (overrideParams == null || !overrideParams.contains(key))) {
first = addParams(result, first, key, origList);
}
Collection<String> list = param.getValue();
first = addParams(result, first, key, list);
}
for (Map.Entry<String, Collection<String>> param: origParams.entrySet()) {
final String key = param.getKey();
Collection<String> list = param.getValue();
first = addParams(result, first, key, list);
}
if (uri.getFragment() != null) {
result.append('#').append(uri.getRawFragment());
}
try {
return new URI(result.toString());
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
}
} }
|
public class class_name {
public static URI addParams(
final URI uri, final Multimap<String, String> params, final Set<String> overrideParams) {
if (params == null || params.isEmpty()) {
return uri; // depends on control dependency: [if], data = [none]
}
final String origTxt = uri.toString();
int queryStart = origTxt.indexOf('?');
final StringBuilder result = new StringBuilder();
if (queryStart < 0) {
int fragmentStart = origTxt.indexOf('#');
if (fragmentStart < 0) {
result.append(origTxt); // depends on control dependency: [if], data = [none]
} else {
result.append(origTxt, 0, fragmentStart); // depends on control dependency: [if], data = [none]
}
} else {
result.append(origTxt, 0, queryStart); // depends on control dependency: [if], data = [none]
}
Map<String, Collection<String>> origParams = getParameters(uri).asMap();
boolean first = true;
for (Map.Entry<String, Collection<String>> param: params.asMap().entrySet()) {
final String key = param.getKey();
Collection<String> origList = origParams.remove(key);
if (origList != null && (overrideParams == null || !overrideParams.contains(key))) {
first = addParams(result, first, key, origList); // depends on control dependency: [if], data = [none]
}
Collection<String> list = param.getValue();
first = addParams(result, first, key, list); // depends on control dependency: [for], data = [none]
}
for (Map.Entry<String, Collection<String>> param: origParams.entrySet()) {
final String key = param.getKey();
Collection<String> list = param.getValue();
first = addParams(result, first, key, list); // depends on control dependency: [for], data = [none]
}
if (uri.getFragment() != null) {
result.append('#').append(uri.getRawFragment()); // depends on control dependency: [if], data = [none]
}
try {
return new URI(result.toString()); // depends on control dependency: [try], data = [none]
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
protected static boolean runRejectedTask(Runnable runnable, ThreadPoolExecutor executor) {
// Runs the task directly in the calling thread of the {@code execute} method,
// unless the executor has been shut down, in which case the task
// is discarded.
if (!executor.isShutdown()) {
runnable.run();
return true;
}
return false;
} }
|
public class class_name {
protected static boolean runRejectedTask(Runnable runnable, ThreadPoolExecutor executor) {
// Runs the task directly in the calling thread of the {@code execute} method,
// unless the executor has been shut down, in which case the task
// is discarded.
if (!executor.isShutdown()) {
runnable.run(); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} }
|
public class class_name {
public boolean add(ConceptMap answer, ConceptMap answerIndex){
Index ind = Index.of(answerIndex.vars());
if (ind.equals(index)) {
return indexedAnswers.put(answerIndex, answer);
}
throw new IllegalStateException("Illegal index: " + answerIndex + " indices: " + index);
} }
|
public class class_name {
public boolean add(ConceptMap answer, ConceptMap answerIndex){
Index ind = Index.of(answerIndex.vars());
if (ind.equals(index)) {
return indexedAnswers.put(answerIndex, answer); // depends on control dependency: [if], data = [none]
}
throw new IllegalStateException("Illegal index: " + answerIndex + " indices: " + index);
} }
|
public class class_name {
@Override
public boolean isConnected(final Connection _connection)
throws SQLException
{
boolean ret = false;
final StringBuilder cmd = new StringBuilder();
cmd.append(" SELECT version();");
PreparedStatement stmt = null;
stmt = _connection.prepareStatement(cmd.toString());
try {
final ResultSet resultset = stmt.executeQuery();
if (resultset.next()) {
final String str = resultset.getString(1);
ret = str.toUpperCase().contains("POSTGRESQL");
}
resultset.close();
} finally {
stmt.close();
}
return ret;
} }
|
public class class_name {
@Override
public boolean isConnected(final Connection _connection)
throws SQLException
{
boolean ret = false;
final StringBuilder cmd = new StringBuilder();
cmd.append(" SELECT version();");
PreparedStatement stmt = null;
stmt = _connection.prepareStatement(cmd.toString());
try {
final ResultSet resultset = stmt.executeQuery();
if (resultset.next()) {
final String str = resultset.getString(1);
ret = str.toUpperCase().contains("POSTGRESQL"); // depends on control dependency: [if], data = [none]
}
resultset.close();
} finally {
stmt.close();
}
return ret;
} }
|
public class class_name {
private String getIdent(BioPAXElement bpe) {
String ident = "----";
if(bpe instanceof pathway) {
ident = "-pw-";
} else if(bpe instanceof interaction) {
ident = "-in-";
} else if (bpe instanceof protein) {
ident = "-pr-";
} else if (bpe instanceof complex) {
ident = "-co-";
}
return ident;
} }
|
public class class_name {
private String getIdent(BioPAXElement bpe) {
String ident = "----";
if(bpe instanceof pathway) {
ident = "-pw-"; // depends on control dependency: [if], data = [none]
} else if(bpe instanceof interaction) {
ident = "-in-"; // depends on control dependency: [if], data = [none]
} else if (bpe instanceof protein) {
ident = "-pr-"; // depends on control dependency: [if], data = [none]
} else if (bpe instanceof complex) {
ident = "-co-"; // depends on control dependency: [if], data = [none]
}
return ident;
} }
|
public class class_name {
public static int setCharAt(char target[], int limit, int offset16, int char32) {
if (offset16 >= limit) {
throw new ArrayIndexOutOfBoundsException(offset16);
}
int count = 1;
char single = target[offset16];
if (isSurrogate(single)) {
// pairs of the surrogate with offset16 at the lead char found
if (isLeadSurrogate(single) && (target.length > offset16 + 1)
&& isTrailSurrogate(target[offset16 + 1])) {
count++;
} else {
// pairs of the surrogate with offset16 at the trail char
// found
if (isTrailSurrogate(single) && (offset16 > 0)
&& isLeadSurrogate(target[offset16 - 1])) {
offset16--;
count++;
}
}
}
String str = valueOf(char32);
int result = limit;
int strlength = str.length();
target[offset16] = str.charAt(0);
if (count == strlength) {
if (count == 2) {
target[offset16 + 1] = str.charAt(1);
}
} else {
// this is not exact match in space, we'll have to do some
// shifting
System.arraycopy(target, offset16 + count, target, offset16 + strlength, limit
- (offset16 + count));
if (count < strlength) {
// char32 is a supplementary character trying to squeeze into
// a non-supplementary space
target[offset16 + 1] = str.charAt(1);
result++;
if (result < target.length) {
target[result] = 0;
}
} else {
// char32 is a non-supplementary character trying to fill
// into a supplementary space
result--;
target[result] = 0;
}
}
return result;
} }
|
public class class_name {
public static int setCharAt(char target[], int limit, int offset16, int char32) {
if (offset16 >= limit) {
throw new ArrayIndexOutOfBoundsException(offset16);
}
int count = 1;
char single = target[offset16];
if (isSurrogate(single)) {
// pairs of the surrogate with offset16 at the lead char found
if (isLeadSurrogate(single) && (target.length > offset16 + 1)
&& isTrailSurrogate(target[offset16 + 1])) {
count++; // depends on control dependency: [if], data = [none]
} else {
// pairs of the surrogate with offset16 at the trail char
// found
if (isTrailSurrogate(single) && (offset16 > 0)
&& isLeadSurrogate(target[offset16 - 1])) {
offset16--; // depends on control dependency: [if], data = [none]
count++; // depends on control dependency: [if], data = [none]
}
}
}
String str = valueOf(char32);
int result = limit;
int strlength = str.length();
target[offset16] = str.charAt(0);
if (count == strlength) {
if (count == 2) {
target[offset16 + 1] = str.charAt(1); // depends on control dependency: [if], data = [none]
}
} else {
// this is not exact match in space, we'll have to do some
// shifting
System.arraycopy(target, offset16 + count, target, offset16 + strlength, limit
- (offset16 + count)); // depends on control dependency: [if], data = [none]
if (count < strlength) {
// char32 is a supplementary character trying to squeeze into
// a non-supplementary space
target[offset16 + 1] = str.charAt(1); // depends on control dependency: [if], data = [none]
result++; // depends on control dependency: [if], data = [none]
if (result < target.length) {
target[result] = 0; // depends on control dependency: [if], data = [none]
}
} else {
// char32 is a non-supplementary character trying to fill
// into a supplementary space
result--; // depends on control dependency: [if], data = [none]
target[result] = 0; // depends on control dependency: [if], data = [none]
}
}
return result;
} }
|
public class class_name {
public static BufferedImage checkCopy( BufferedImage original , BufferedImage output ) {
ColorModel cm = original.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
if( output == null || original.getWidth() != output.getWidth() || original.getHeight() != output.getHeight() ||
original.getType() != output.getType() ) {
WritableRaster raster = original.copyData(original.getRaster().createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
original.copyData(output.getRaster());
return output;
} }
|
public class class_name {
public static BufferedImage checkCopy( BufferedImage original , BufferedImage output ) {
ColorModel cm = original.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
if( output == null || original.getWidth() != output.getWidth() || original.getHeight() != output.getHeight() ||
original.getType() != output.getType() ) {
WritableRaster raster = original.copyData(original.getRaster().createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null); // depends on control dependency: [if], data = [none]
}
original.copyData(output.getRaster());
return output;
} }
|
public class class_name {
private void cacheShardValue(TableDefinition tableDef,
Integer shardNumber,
Date shardStart) {
// Get or create the app name -> table map
String appName = tableDef.getAppDef().getAppName();
Map<String, Map<Integer, Date>> tableShardNumberMap = m_appShardMap.get(appName);
if (tableShardNumberMap == null) {
tableShardNumberMap = new HashMap<String, Map<Integer,Date>>();
m_appShardMap.put(appName, tableShardNumberMap);
}
// Get or create the table name -> shard number map
String tableName = tableDef.getTableName();
Map<Integer, Date> shardNumberMap = tableShardNumberMap.get(tableName);
if (shardNumberMap == null) {
shardNumberMap = new HashMap<Integer, Date>();
tableShardNumberMap.put(tableName, shardNumberMap);
}
// Add the shard number -> start date
shardNumberMap.put(shardNumber, shardStart);
m_logger.debug("Sharding date for {}.{} shard #{} set to: {} ({})",
new Object[]{appName, tableName, shardNumber, shardStart.getTime(), Utils.formatDateUTC(shardStart)});
} }
|
public class class_name {
private void cacheShardValue(TableDefinition tableDef,
Integer shardNumber,
Date shardStart) {
// Get or create the app name -> table map
String appName = tableDef.getAppDef().getAppName();
Map<String, Map<Integer, Date>> tableShardNumberMap = m_appShardMap.get(appName);
if (tableShardNumberMap == null) {
tableShardNumberMap = new HashMap<String, Map<Integer,Date>>();
// depends on control dependency: [if], data = [none]
m_appShardMap.put(appName, tableShardNumberMap);
// depends on control dependency: [if], data = [none]
}
// Get or create the table name -> shard number map
String tableName = tableDef.getTableName();
Map<Integer, Date> shardNumberMap = tableShardNumberMap.get(tableName);
if (shardNumberMap == null) {
shardNumberMap = new HashMap<Integer, Date>();
// depends on control dependency: [if], data = [none]
tableShardNumberMap.put(tableName, shardNumberMap);
// depends on control dependency: [if], data = [none]
}
// Add the shard number -> start date
shardNumberMap.put(shardNumber, shardStart);
m_logger.debug("Sharding date for {}.{} shard #{} set to: {} ({})",
new Object[]{appName, tableName, shardNumber, shardStart.getTime(), Utils.formatDateUTC(shardStart)});
} }
|
public class class_name {
@Override
public void constructCache(DefaultSolverScope solverScope) {
cachedEntityMap = new TreeMap<>();
ScoreDirector scoreDirector = solverScope.getScoreDirector();
double probabilityWeightOffset = 0L;
for (Object entity : childEntitySelector) {
double probabilityWeight = probabilityWeightFactory.createProbabilityWeight(
scoreDirector, entity);
cachedEntityMap.put(probabilityWeightOffset, entity);
probabilityWeightOffset += probabilityWeight;
}
probabilityWeightTotal = probabilityWeightOffset;
} }
|
public class class_name {
@Override
public void constructCache(DefaultSolverScope solverScope) {
cachedEntityMap = new TreeMap<>();
ScoreDirector scoreDirector = solverScope.getScoreDirector();
double probabilityWeightOffset = 0L;
for (Object entity : childEntitySelector) {
double probabilityWeight = probabilityWeightFactory.createProbabilityWeight(
scoreDirector, entity);
cachedEntityMap.put(probabilityWeightOffset, entity); // depends on control dependency: [for], data = [entity]
probabilityWeightOffset += probabilityWeight; // depends on control dependency: [for], data = [none]
}
probabilityWeightTotal = probabilityWeightOffset;
} }
|
public class class_name {
private CmsPathTree<P, V> ensureNode(List<P> path) {
List<P> pathToConsume = Lists.newLinkedList(path);
CmsPathTree<P, V> lastExistingNode = findNodeInternal(pathToConsume);
CmsPathTree<P, V> currentNode = lastExistingNode;
for (P pathPart : pathToConsume) {
CmsPathTree<P, V> child = new CmsPathTree<P, V>();
currentNode.m_children.put(pathPart, child);
currentNode = child;
}
return currentNode;
} }
|
public class class_name {
private CmsPathTree<P, V> ensureNode(List<P> path) {
List<P> pathToConsume = Lists.newLinkedList(path);
CmsPathTree<P, V> lastExistingNode = findNodeInternal(pathToConsume);
CmsPathTree<P, V> currentNode = lastExistingNode;
for (P pathPart : pathToConsume) {
CmsPathTree<P, V> child = new CmsPathTree<P, V>();
currentNode.m_children.put(pathPart, child); // depends on control dependency: [for], data = [pathPart]
currentNode = child; // depends on control dependency: [for], data = [none]
}
return currentNode;
} }
|
public class class_name {
@Override
protected int msd(Double a, Double b) {
/*
* For this to work, arithmetic must be unsigned
*/
long ux = Double.doubleToLongBits(a);
long uy = Double.doubleToLongBits(b);
if (ux == uy) {
return -1;
}
double d = UnsignedUtils.unsignedLongToDouble(ux ^ uy);
return Math.getExponent(d);
} }
|
public class class_name {
@Override
protected int msd(Double a, Double b) {
/*
* For this to work, arithmetic must be unsigned
*/
long ux = Double.doubleToLongBits(a);
long uy = Double.doubleToLongBits(b);
if (ux == uy) {
return -1; // depends on control dependency: [if], data = [none]
}
double d = UnsignedUtils.unsignedLongToDouble(ux ^ uy);
return Math.getExponent(d);
} }
|
public class class_name {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext context = event.getApplicationContext();
if (isSpringBoot){
CrawlerProperties crawlerProperties = context.getBean(CrawlerProperties.class);
if (!crawlerProperties.isEnabled()){
logger.warn("{} is not enabled",Constants.SEIMI_CRAWLER_BOOTSTRAP_ENABLED);
return;
}
}
if (context != null) {
if (CollectionUtils.isEmpty(CrawlerCache.getCrawlers())) {
logger.info("Not find any crawler,may be you need to check.");
return;
}
workersPool = Executors.newFixedThreadPool(Constants.BASE_THREAD_NUM * Runtime.getRuntime().availableProcessors() * CrawlerCache.getCrawlers().size());
for (Class<? extends BaseSeimiCrawler> a : CrawlerCache.getCrawlers()) {
CrawlerModel crawlerModel = new CrawlerModel(a, context);
if (CrawlerCache.isExist(crawlerModel.getCrawlerName())) {
logger.error("Crawler:{} is repeated,please check", crawlerModel.getCrawlerName());
throw new SeimiInitExcepiton(StrFormatUtil.info("Crawler:{} is repeated,please check", crawlerModel.getCrawlerName()));
}
CrawlerCache.putCrawlerModel(crawlerModel.getCrawlerName(), crawlerModel);
}
for (Map.Entry<String, CrawlerModel> crawlerEntry : CrawlerCache.getCrawlerModelContext().entrySet()) {
for (int i = 0; i < Constants.BASE_THREAD_NUM * Runtime.getRuntime().availableProcessors(); i++) {
workersPool.execute(new SeimiProcessor(CrawlerCache.getInterceptors(), crawlerEntry.getValue()));
}
}
if (isSpringBoot){
CrawlerProperties crawlerProperties = context.getBean(CrawlerProperties.class);
String crawlerNames = crawlerProperties.getNames();
if (StringUtils.isBlank(crawlerNames)){
logger.info("Spring boot start [{}] as worker.",StringUtils.join(CrawlerCache.getCrawlerModelContext().keySet(),","));
}else {
String[] crawlers = crawlerNames.split(",");
for (String cn:crawlers){
CrawlerModel crawlerModel = CrawlerCache.getCrawlerModel(cn);
if (crawlerModel == null){
logger.warn("Crawler name = {} is not existent.",cn);
continue;
}
crawlerModel.startRequest();
}
}
//统一通用配置信息至 seimiConfig
SeimiConfig config = new SeimiConfig();
config.setBloomFilterExpectedInsertions(crawlerProperties.getBloomFilterExpectedInsertions());
config.setBloomFilterFalseProbability(crawlerProperties.getBloomFilterFalseProbability());
config.setSeimiAgentHost(crawlerProperties.getSeimiAgentHost());
config.setSeimiAgentPort(crawlerProperties.getSeimiAgentPort());
CrawlerCache.setConfig(config);
}
}
} }
|
public class class_name {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext context = event.getApplicationContext();
if (isSpringBoot){
CrawlerProperties crawlerProperties = context.getBean(CrawlerProperties.class);
if (!crawlerProperties.isEnabled()){
logger.warn("{} is not enabled",Constants.SEIMI_CRAWLER_BOOTSTRAP_ENABLED); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
if (context != null) {
if (CollectionUtils.isEmpty(CrawlerCache.getCrawlers())) {
logger.info("Not find any crawler,may be you need to check."); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
workersPool = Executors.newFixedThreadPool(Constants.BASE_THREAD_NUM * Runtime.getRuntime().availableProcessors() * CrawlerCache.getCrawlers().size()); // depends on control dependency: [if], data = [none]
for (Class<? extends BaseSeimiCrawler> a : CrawlerCache.getCrawlers()) {
CrawlerModel crawlerModel = new CrawlerModel(a, context);
if (CrawlerCache.isExist(crawlerModel.getCrawlerName())) {
logger.error("Crawler:{} is repeated,please check", crawlerModel.getCrawlerName());
throw new SeimiInitExcepiton(StrFormatUtil.info("Crawler:{} is repeated,please check", crawlerModel.getCrawlerName()));
}
CrawlerCache.putCrawlerModel(crawlerModel.getCrawlerName(), crawlerModel);
}
for (Map.Entry<String, CrawlerModel> crawlerEntry : CrawlerCache.getCrawlerModelContext().entrySet()) {
for (int i = 0; i < Constants.BASE_THREAD_NUM * Runtime.getRuntime().availableProcessors(); i++) {
workersPool.execute(new SeimiProcessor(CrawlerCache.getInterceptors(), crawlerEntry.getValue()));
}
}
if (isSpringBoot){
CrawlerProperties crawlerProperties = context.getBean(CrawlerProperties.class);
String crawlerNames = crawlerProperties.getNames();
if (StringUtils.isBlank(crawlerNames)){
logger.info("Spring boot start [{}] as worker.",StringUtils.join(CrawlerCache.getCrawlerModelContext().keySet(),","));
}else {
String[] crawlers = crawlerNames.split(",");
for (String cn:crawlers){
CrawlerModel crawlerModel = CrawlerCache.getCrawlerModel(cn);
if (crawlerModel == null){
logger.warn("Crawler name = {} is not existent.",cn);
continue;
}
crawlerModel.startRequest();
}
}
//统一通用配置信息至 seimiConfig
SeimiConfig config = new SeimiConfig();
config.setBloomFilterExpectedInsertions(crawlerProperties.getBloomFilterExpectedInsertions());
config.setBloomFilterFalseProbability(crawlerProperties.getBloomFilterFalseProbability());
config.setSeimiAgentHost(crawlerProperties.getSeimiAgentHost());
config.setSeimiAgentPort(crawlerProperties.getSeimiAgentPort());
CrawlerCache.setConfig(config);
}
}
} }
|
public class class_name {
void popStackToClose(String... elNames) {
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
stack.remove(pos);
if (inSorted(next.normalName(), elNames))
break;
}
} }
|
public class class_name {
void popStackToClose(String... elNames) {
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
stack.remove(pos); // depends on control dependency: [for], data = [pos]
if (inSorted(next.normalName(), elNames))
break;
}
} }
|
public class class_name {
@Override
public int intValue() {
if (Math.abs(amount) <= Integer.MAX_VALUE) {
return (int) amount;
}
throw new IllegalStateException("Amount of '" + amount + "' cannot be converted into an Integer.");
} }
|
public class class_name {
@Override
public int intValue() {
if (Math.abs(amount) <= Integer.MAX_VALUE) {
return (int) amount; // depends on control dependency: [if], data = [none]
}
throw new IllegalStateException("Amount of '" + amount + "' cannot be converted into an Integer.");
} }
|
public class class_name {
public static String getGraphVizString(DoubleLinkedPoiCategory rootNode) {
StringBuilder sb = new StringBuilder();
Stack<PoiCategory> stack = new Stack<>();
stack.push(rootNode);
DoubleLinkedPoiCategory currentNode;
sb.append("// dot test.dot -Tpng > test.png\r\n");
sb.append("digraph Categories {\r\n");
sb.append(" graph [\r\nrankdir = \"LR\"\r\n]\r\n\r\nnode [\r\nshape = \"plaintext\"\r\n]");
while (!stack.isEmpty()) {
currentNode = (DoubleLinkedPoiCategory) stack.pop();
for (PoiCategory childNode : currentNode.childCategories) {
stack.push(childNode);
sb.append("\t\"").append(currentNode.getTitle()).append(" (")
.append(currentNode.getID()).append(")").append("\" -> \"")
.append(childNode.getTitle()).append(" (").append(childNode.getID())
.append(")").append("\"\r\n");
}
}
sb.append("}\r\n");
return sb.toString();
} }
|
public class class_name {
public static String getGraphVizString(DoubleLinkedPoiCategory rootNode) {
StringBuilder sb = new StringBuilder();
Stack<PoiCategory> stack = new Stack<>();
stack.push(rootNode);
DoubleLinkedPoiCategory currentNode;
sb.append("// dot test.dot -Tpng > test.png\r\n");
sb.append("digraph Categories {\r\n");
sb.append(" graph [\r\nrankdir = \"LR\"\r\n]\r\n\r\nnode [\r\nshape = \"plaintext\"\r\n]");
while (!stack.isEmpty()) {
currentNode = (DoubleLinkedPoiCategory) stack.pop(); // depends on control dependency: [while], data = [none]
for (PoiCategory childNode : currentNode.childCategories) {
stack.push(childNode); // depends on control dependency: [for], data = [childNode]
sb.append("\t\"").append(currentNode.getTitle()).append(" (")
.append(currentNode.getID()).append(")").append("\" -> \"")
.append(childNode.getTitle()).append(" (").append(childNode.getID())
.append(")").append("\"\r\n"); // depends on control dependency: [for], data = [none]
}
}
sb.append("}\r\n");
return sb.toString();
} }
|
public class class_name {
@Deprecated
public TimeUnitFormat setNumberFormat(NumberFormat format) {
if (format == this.format) {
return this;
}
if (format == null) {
if (locale == null) {
isReady = false;
mf = mf.withLocale(ULocale.getDefault());
} else {
this.format = NumberFormat.getNumberInstance(locale);
mf = mf.withNumberFormat(this.format);
}
} else {
this.format = format;
mf = mf.withNumberFormat(this.format);
}
return this;
} }
|
public class class_name {
@Deprecated
public TimeUnitFormat setNumberFormat(NumberFormat format) {
if (format == this.format) {
return this; // depends on control dependency: [if], data = [none]
}
if (format == null) {
if (locale == null) {
isReady = false; // depends on control dependency: [if], data = [none]
mf = mf.withLocale(ULocale.getDefault()); // depends on control dependency: [if], data = [none]
} else {
this.format = NumberFormat.getNumberInstance(locale); // depends on control dependency: [if], data = [(locale]
mf = mf.withNumberFormat(this.format); // depends on control dependency: [if], data = [none]
}
} else {
this.format = format; // depends on control dependency: [if], data = [none]
mf = mf.withNumberFormat(this.format); // depends on control dependency: [if], data = [none]
}
return this;
} }
|
public class class_name {
public CopyObjectResponse copyObject(CopyObjectRequest request) {
checkNotNull(request, "request should not be null.");
assertStringNotNullOrEmpty(request.getSourceKey(), "object key should not be null or empty");
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.PUT);
String copySourceHeader = "/" + request.getSourceBucketName() + "/" + request.getSourceKey();
copySourceHeader = HttpUtils.normalizePath(copySourceHeader);
internalRequest.addHeader(Headers.BCE_COPY_SOURCE, copySourceHeader);
if (request.getETag() != null) {
internalRequest.addHeader(Headers.BCE_COPY_SOURCE_IF_MATCH,
"\"" + request.getETag() + "\"");
}
if (request.getNoneMatchETagConstraint() != null) {
internalRequest.addHeader(
Headers.BCE_COPY_SOURCE_IF_NONE_MATCH, "\"" + request.getNoneMatchETagConstraint() + "\"");
}
if (request.getUnmodifiedSinceConstraint() != null) {
internalRequest.addHeader(
Headers.BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE, request.getUnmodifiedSinceConstraint());
}
if (request.getModifiedSinceConstraint() != null) {
internalRequest.addHeader(
Headers.BCE_COPY_SOURCE_IF_MODIFIED_SINCE, request.getModifiedSinceConstraint());
}
if (request.getStorageClass() != null) {
internalRequest.addHeader(Headers.BCE_STORAGE_CLASS, request.getStorageClass());
}
ObjectMetadata newObjectMetadata = request.getNewObjectMetadata();
if (newObjectMetadata != null) {
internalRequest.addHeader(Headers.BCE_COPY_METADATA_DIRECTIVE, "replace");
populateRequestMetadata(internalRequest, newObjectMetadata);
} else {
internalRequest.addHeader(Headers.BCE_COPY_METADATA_DIRECTIVE, "copy");
}
this.setZeroContentLength(internalRequest);
CopyObjectResponseWithExceptionInfo intermidiateRes = this.invokeHttpClient(internalRequest,
CopyObjectResponseWithExceptionInfo.class);
// handle exception
if (intermidiateRes.getETag() == null
&& intermidiateRes.getLastModified() == null) {
if (intermidiateRes.getMessage() != null) {
BceServiceException bse = new BceServiceException(intermidiateRes.getMessage());
bse.setErrorCode(intermidiateRes.getCode());
bse.setRequestId(intermidiateRes.getRequestId());
if (bse.getErrorCode() == "InternalError") {
bse.setErrorType(ErrorType.Service);
} else {
bse.setErrorType(ErrorType.Client);
}
bse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
throw bse;
}
}
return (CopyObjectResponse) intermidiateRes;
} }
|
public class class_name {
public CopyObjectResponse copyObject(CopyObjectRequest request) {
checkNotNull(request, "request should not be null.");
assertStringNotNullOrEmpty(request.getSourceKey(), "object key should not be null or empty");
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.PUT);
String copySourceHeader = "/" + request.getSourceBucketName() + "/" + request.getSourceKey();
copySourceHeader = HttpUtils.normalizePath(copySourceHeader);
internalRequest.addHeader(Headers.BCE_COPY_SOURCE, copySourceHeader);
if (request.getETag() != null) {
internalRequest.addHeader(Headers.BCE_COPY_SOURCE_IF_MATCH,
"\"" + request.getETag() + "\""); // depends on control dependency: [if], data = [none]
}
if (request.getNoneMatchETagConstraint() != null) {
internalRequest.addHeader(
Headers.BCE_COPY_SOURCE_IF_NONE_MATCH, "\"" + request.getNoneMatchETagConstraint() + "\""); // depends on control dependency: [if], data = [none]
}
if (request.getUnmodifiedSinceConstraint() != null) {
internalRequest.addHeader(
Headers.BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE, request.getUnmodifiedSinceConstraint()); // depends on control dependency: [if], data = [none]
}
if (request.getModifiedSinceConstraint() != null) {
internalRequest.addHeader(
Headers.BCE_COPY_SOURCE_IF_MODIFIED_SINCE, request.getModifiedSinceConstraint()); // depends on control dependency: [if], data = [none]
}
if (request.getStorageClass() != null) {
internalRequest.addHeader(Headers.BCE_STORAGE_CLASS, request.getStorageClass()); // depends on control dependency: [if], data = [none]
}
ObjectMetadata newObjectMetadata = request.getNewObjectMetadata();
if (newObjectMetadata != null) {
internalRequest.addHeader(Headers.BCE_COPY_METADATA_DIRECTIVE, "replace"); // depends on control dependency: [if], data = [none]
populateRequestMetadata(internalRequest, newObjectMetadata); // depends on control dependency: [if], data = [none]
} else {
internalRequest.addHeader(Headers.BCE_COPY_METADATA_DIRECTIVE, "copy"); // depends on control dependency: [if], data = [none]
}
this.setZeroContentLength(internalRequest);
CopyObjectResponseWithExceptionInfo intermidiateRes = this.invokeHttpClient(internalRequest,
CopyObjectResponseWithExceptionInfo.class);
// handle exception
if (intermidiateRes.getETag() == null
&& intermidiateRes.getLastModified() == null) {
if (intermidiateRes.getMessage() != null) {
BceServiceException bse = new BceServiceException(intermidiateRes.getMessage());
bse.setErrorCode(intermidiateRes.getCode()); // depends on control dependency: [if], data = [none]
bse.setRequestId(intermidiateRes.getRequestId()); // depends on control dependency: [if], data = [none]
if (bse.getErrorCode() == "InternalError") {
bse.setErrorType(ErrorType.Service); // depends on control dependency: [if], data = [none]
} else {
bse.setErrorType(ErrorType.Client); // depends on control dependency: [if], data = [none]
}
bse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); // depends on control dependency: [if], data = [none]
throw bse;
}
}
return (CopyObjectResponse) intermidiateRes;
} }
|
public class class_name {
JCExpression annotationValue() {
int pos;
switch (token.kind) {
case MONKEYS_AT:
pos = token.pos;
nextToken();
return annotation(pos, Tag.ANNOTATION);
case LBRACE:
pos = token.pos;
accept(LBRACE);
ListBuffer<JCExpression> buf = new ListBuffer<>();
if (token.kind == COMMA) {
nextToken();
} else if (token.kind != RBRACE) {
buf.append(annotationValue());
while (token.kind == COMMA) {
nextToken();
if (token.kind == RBRACE) break;
buf.append(annotationValue());
}
}
accept(RBRACE);
return toP(F.at(pos).NewArray(null, List.nil(), buf.toList()));
default:
mode = EXPR;
return term1();
}
} }
|
public class class_name {
JCExpression annotationValue() {
int pos;
switch (token.kind) {
case MONKEYS_AT:
pos = token.pos;
nextToken();
return annotation(pos, Tag.ANNOTATION);
case LBRACE:
pos = token.pos;
accept(LBRACE);
ListBuffer<JCExpression> buf = new ListBuffer<>();
if (token.kind == COMMA) {
nextToken(); // depends on control dependency: [if], data = [none]
} else if (token.kind != RBRACE) {
buf.append(annotationValue()); // depends on control dependency: [if], data = [none]
while (token.kind == COMMA) {
nextToken(); // depends on control dependency: [while], data = [none]
if (token.kind == RBRACE) break;
buf.append(annotationValue()); // depends on control dependency: [while], data = [none]
}
}
accept(RBRACE);
return toP(F.at(pos).NewArray(null, List.nil(), buf.toList()));
default:
mode = EXPR;
return term1();
}
} }
|
public class class_name {
public List<String> getWorkplaceServers(CmsSSLMode filterMode) {
if (filterMode == null) {
return getWorkplaceServers();
}
List<String> ret = new ArrayList<String>();
for (String server : m_workplaceServers.keySet()) {
if (m_workplaceServers.get(server).equals(filterMode)) {
ret.add(server);
}
}
return ret;
} }
|
public class class_name {
public List<String> getWorkplaceServers(CmsSSLMode filterMode) {
if (filterMode == null) {
return getWorkplaceServers(); // depends on control dependency: [if], data = [none]
}
List<String> ret = new ArrayList<String>();
for (String server : m_workplaceServers.keySet()) {
if (m_workplaceServers.get(server).equals(filterMode)) {
ret.add(server); // depends on control dependency: [if], data = [none]
}
}
return ret;
} }
|
public class class_name {
@Override
public PolicyFinderResult findPolicy(EvaluationCtx context) {
try {
AbstractPolicy policy = m_policyManager.getPolicy(context);
if (policy == null) {
return new PolicyFinderResult();
}
return new PolicyFinderResult(policy);
} catch (TopLevelPolicyException tlpe) {
return new PolicyFinderResult(tlpe.getStatus());
} catch (PolicyIndexException pdme) {
if (logger.isDebugEnabled()) {
logger.debug("problem processing policy", pdme);
}
List<String> codes = new ArrayList<String>();
codes.add(Status.STATUS_PROCESSING_ERROR);
return new PolicyFinderResult(new Status(codes, pdme.getMessage()));
}
} }
|
public class class_name {
@Override
public PolicyFinderResult findPolicy(EvaluationCtx context) {
try {
AbstractPolicy policy = m_policyManager.getPolicy(context);
if (policy == null) {
return new PolicyFinderResult(); // depends on control dependency: [if], data = [none]
}
return new PolicyFinderResult(policy); // depends on control dependency: [try], data = [none]
} catch (TopLevelPolicyException tlpe) {
return new PolicyFinderResult(tlpe.getStatus());
} catch (PolicyIndexException pdme) { // depends on control dependency: [catch], data = [none]
if (logger.isDebugEnabled()) {
logger.debug("problem processing policy", pdme); // depends on control dependency: [if], data = [none]
}
List<String> codes = new ArrayList<String>();
codes.add(Status.STATUS_PROCESSING_ERROR);
return new PolicyFinderResult(new Status(codes, pdme.getMessage()));
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public void setItem(String itemName, Object value) {
if (value == null) {
setItem(itemName, (String) null);
} else {
@SuppressWarnings("unchecked")
ISerializer<Object> contextSerializer = (ISerializer<Object>) ContextSerializerRegistry.getInstance()
.get(value.getClass());
if (contextSerializer == null) {
throw new ContextException("No serializer found for type " + value.getClass().getName());
}
setItem(itemName, contextSerializer.serialize(value));
}
} }
|
public class class_name {
public void setItem(String itemName, Object value) {
if (value == null) {
setItem(itemName, (String) null); // depends on control dependency: [if], data = [null)]
} else {
@SuppressWarnings("unchecked")
ISerializer<Object> contextSerializer = (ISerializer<Object>) ContextSerializerRegistry.getInstance()
.get(value.getClass());
if (contextSerializer == null) {
throw new ContextException("No serializer found for type " + value.getClass().getName());
}
setItem(itemName, contextSerializer.serialize(value)); // depends on control dependency: [if], data = [(value]
}
} }
|
public class class_name {
static void addEncoding(final Request.Builder builder, final HttpExchange httpExchange) {
final String contentType = httpExchange.getRequestHeaders().getFirst("Content-Type");
if (contentType != null) {
final Matcher matcher = CHARSET_PATTERN.matcher(contentType);
if (matcher.matches()) {
try {
builder.encoding(Charset.forName(matcher.group(1)));
}
catch (UnsupportedCharsetException e) {
//just ignore, fallback encoding will be used instead
}
}
}
} }
|
public class class_name {
static void addEncoding(final Request.Builder builder, final HttpExchange httpExchange) {
final String contentType = httpExchange.getRequestHeaders().getFirst("Content-Type");
if (contentType != null) {
final Matcher matcher = CHARSET_PATTERN.matcher(contentType);
if (matcher.matches()) {
try {
builder.encoding(Charset.forName(matcher.group(1))); // depends on control dependency: [try], data = [none]
}
catch (UnsupportedCharsetException e) {
//just ignore, fallback encoding will be used instead
} // depends on control dependency: [catch], data = [none]
}
}
} }
|
public class class_name {
public JSONObject addUser(String image, String imageType, String groupId, String userId, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("image", image);
request.addBody("image_type", imageType);
request.addBody("group_id", groupId);
request.addBody("user_id", userId);
if (options != null) {
request.addBody(options);
}
request.setUri(FaceConsts.USER_ADD);
request.setBodyFormat(EBodyFormat.RAW_JSON);
postOperation(request);
return requestServer(request);
} }
|
public class class_name {
public JSONObject addUser(String image, String imageType, String groupId, String userId, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("image", image);
request.addBody("image_type", imageType);
request.addBody("group_id", groupId);
request.addBody("user_id", userId);
if (options != null) {
request.addBody(options); // depends on control dependency: [if], data = [(options]
}
request.setUri(FaceConsts.USER_ADD);
request.setBodyFormat(EBodyFormat.RAW_JSON);
postOperation(request);
return requestServer(request);
} }
|
public class class_name {
public Observable<ServiceResponse<List<VnetRouteInner>>> getRouteForVnetWithServiceResponseAsync(String resourceGroupName, String name, String vnetName, String routeName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (name == null) {
throw new IllegalArgumentException("Parameter name is required and cannot be null.");
}
if (vnetName == null) {
throw new IllegalArgumentException("Parameter vnetName is required and cannot be null.");
}
if (routeName == null) {
throw new IllegalArgumentException("Parameter routeName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.getRouteForVnet(resourceGroupName, name, vnetName, routeName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<VnetRouteInner>>>>() {
@Override
public Observable<ServiceResponse<List<VnetRouteInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<VnetRouteInner>> clientResponse = getRouteForVnetDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} }
|
public class class_name {
public Observable<ServiceResponse<List<VnetRouteInner>>> getRouteForVnetWithServiceResponseAsync(String resourceGroupName, String name, String vnetName, String routeName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (name == null) {
throw new IllegalArgumentException("Parameter name is required and cannot be null.");
}
if (vnetName == null) {
throw new IllegalArgumentException("Parameter vnetName is required and cannot be null.");
}
if (routeName == null) {
throw new IllegalArgumentException("Parameter routeName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.getRouteForVnet(resourceGroupName, name, vnetName, routeName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<VnetRouteInner>>>>() {
@Override
public Observable<ServiceResponse<List<VnetRouteInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<VnetRouteInner>> clientResponse = getRouteForVnetDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} }
|
public class class_name {
private static String buildErrorMsg(List<String> dependencies, String message) {
final StringBuilder buffer = new StringBuilder();
boolean isFirstElement = true;
for (String dependency : dependencies) {
if (!isFirstElement) {
buffer.append(", ");
}
// check if it is an instance of Artifact - add the gavc else append the object
buffer.append(dependency);
isFirstElement = false;
}
return String.format(message, buffer.toString());
} }
|
public class class_name {
private static String buildErrorMsg(List<String> dependencies, String message) {
final StringBuilder buffer = new StringBuilder();
boolean isFirstElement = true;
for (String dependency : dependencies) {
if (!isFirstElement) {
buffer.append(", "); // depends on control dependency: [if], data = [none]
}
// check if it is an instance of Artifact - add the gavc else append the object
buffer.append(dependency); // depends on control dependency: [for], data = [dependency]
isFirstElement = false; // depends on control dependency: [for], data = [none]
}
return String.format(message, buffer.toString());
} }
|
public class class_name {
private static boolean polygonRelateEnvelope_(Polygon polygon_a,
Envelope envelope_b, double tolerance, int relation,
ProgressTracker progress_tracker) {
if (polygonDisjointEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker)) {
if (relation == Relation.disjoint)
return true;
return false;
} else if (relation == Relation.disjoint) {
return false;
}
switch (relation) {
case Relation.within:
return polygonWithinEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
case Relation.contains:
return polygonContainsEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
case Relation.equals:
return polygonEqualsEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
case Relation.touches:
return polygonTouchesEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
case Relation.overlaps:
return polygonOverlapsEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
case Relation.crosses:
return polygonCrossesEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
default:
break; // warning fix
}
return false;
} }
|
public class class_name {
private static boolean polygonRelateEnvelope_(Polygon polygon_a,
Envelope envelope_b, double tolerance, int relation,
ProgressTracker progress_tracker) {
if (polygonDisjointEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker)) {
if (relation == Relation.disjoint)
return true;
return false; // depends on control dependency: [if], data = [none]
} else if (relation == Relation.disjoint) {
return false; // depends on control dependency: [if], data = [none]
}
switch (relation) {
case Relation.within:
return polygonWithinEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
case Relation.contains:
return polygonContainsEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
case Relation.equals:
return polygonEqualsEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
case Relation.touches:
return polygonTouchesEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
case Relation.overlaps:
return polygonOverlapsEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
case Relation.crosses:
return polygonCrossesEnvelope_(polygon_a, envelope_b, tolerance,
progress_tracker);
default:
break; // warning fix
}
return false;
} }
|
public class class_name {
static ItemIdValueImpl fromIri(String iri) {
int separator = iri.lastIndexOf('/') + 1;
try {
return new ItemIdValueImpl(iri.substring(separator), iri.substring(0, separator));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid Wikibase entity IRI: " + iri, e);
}
} }
|
public class class_name {
static ItemIdValueImpl fromIri(String iri) {
int separator = iri.lastIndexOf('/') + 1;
try {
return new ItemIdValueImpl(iri.substring(separator), iri.substring(0, separator)); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid Wikibase entity IRI: " + iri, e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private byte decideLanguage(int serverLanguage) {
//force UTF8mb4 if possible, UTF8 if not.
if (serverLanguage == 45 //utf8mb4_general_ci
|| serverLanguage == 46 //utf8mb4_bin
|| (serverLanguage >= 224 && serverLanguage <= 247)) {
return (byte) serverLanguage;
} else if (serverLanguage == 33 //utf8_general_ci
|| serverLanguage == 83 //utf8_bin
|| serverLanguage == 223 //utf8_general_mysql500_ci
|| (serverLanguage >= 192 && serverLanguage <= 215)) {
return (byte) serverLanguage;
}
if (getMajorServerVersion() == 5 && getMinorServerVersion() <= 1) {
return (byte) 33; //utf8_general_ci
}
return (byte) 224; //UTF8MB4_UNICODE_CI;
} }
|
public class class_name {
private byte decideLanguage(int serverLanguage) {
//force UTF8mb4 if possible, UTF8 if not.
if (serverLanguage == 45 //utf8mb4_general_ci
|| serverLanguage == 46 //utf8mb4_bin
|| (serverLanguage >= 224 && serverLanguage <= 247)) {
return (byte) serverLanguage; // depends on control dependency: [if], data = [none]
} else if (serverLanguage == 33 //utf8_general_ci
|| serverLanguage == 83 //utf8_bin
|| serverLanguage == 223 //utf8_general_mysql500_ci
|| (serverLanguage >= 192 && serverLanguage <= 215)) {
return (byte) serverLanguage; // depends on control dependency: [if], data = [none]
}
if (getMajorServerVersion() == 5 && getMinorServerVersion() <= 1) {
return (byte) 33; //utf8_general_ci // depends on control dependency: [if], data = [none]
}
return (byte) 224; //UTF8MB4_UNICODE_CI;
} }
|
public class class_name {
private static <T extends Comparable<? super T>>
void mergeSort( T[] arr, T[] tmpArr, int left, int right )
{
//recursive way
if ( left < right ) {
int center = ( left + right ) / 2;
mergeSort(arr, tmpArr, left, center);
mergeSort(arr, tmpArr, center + 1, right);
merge(arr, tmpArr, left, center + 1, right);
}
//loop instead
/* int len = 2, pos;
int rpos, offset, cut;
while ( len <= right ) {
pos = 0;
offset = len / 2;
while ( pos + len <= right ) {
rpos = pos + offset;
merge( arr, tmpArr, pos, rpos, rpos + offset - 1 );
pos += len;
}
//merge the rest
cut = pos + offset;
if ( cut <= right )
merge( arr, tmpArr, pos, cut, right );
len *= 2;
}
merge( arr, tmpArr, 0, len / 2, right );*/
} }
|
public class class_name {
private static <T extends Comparable<? super T>>
void mergeSort( T[] arr, T[] tmpArr, int left, int right )
{
//recursive way
if ( left < right ) {
int center = ( left + right ) / 2;
mergeSort(arr, tmpArr, left, center); // depends on control dependency: [if], data = [none]
mergeSort(arr, tmpArr, center + 1, right); // depends on control dependency: [if], data = [none]
merge(arr, tmpArr, left, center + 1, right);
}
//loop instead
/* int len = 2, pos;
int rpos, offset, cut;
while ( len <= right ) {
pos = 0;
offset = len / 2;
while ( pos + len <= right ) {
rpos = pos + offset;
merge( arr, tmpArr, pos, rpos, rpos + offset - 1 );
pos += len;
}
//merge the rest
cut = pos + offset;
if ( cut <= right )
merge( arr, tmpArr, pos, cut, right );
len *= 2;
}
merge( arr, tmpArr, 0, len / 2, right );*/
} }
|
public class class_name {
@Override
public final void shutdownNow(Status status) {
shutdown(status);
Collection<PendingStream> savedPendingStreams;
Runnable savedReportTransportTerminated;
synchronized (lock) {
savedPendingStreams = pendingStreams;
savedReportTransportTerminated = reportTransportTerminated;
reportTransportTerminated = null;
if (!pendingStreams.isEmpty()) {
pendingStreams = Collections.emptyList();
}
}
if (savedReportTransportTerminated != null) {
for (PendingStream stream : savedPendingStreams) {
stream.cancel(status);
}
syncContext.execute(savedReportTransportTerminated);
}
// If savedReportTransportTerminated == null, transportTerminated() has already been called in
// shutdown().
} }
|
public class class_name {
@Override
public final void shutdownNow(Status status) {
shutdown(status);
Collection<PendingStream> savedPendingStreams;
Runnable savedReportTransportTerminated;
synchronized (lock) {
savedPendingStreams = pendingStreams;
savedReportTransportTerminated = reportTransportTerminated;
reportTransportTerminated = null;
if (!pendingStreams.isEmpty()) {
pendingStreams = Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
}
if (savedReportTransportTerminated != null) {
for (PendingStream stream : savedPendingStreams) {
stream.cancel(status); // depends on control dependency: [for], data = [stream]
}
syncContext.execute(savedReportTransportTerminated); // depends on control dependency: [if], data = [(savedReportTransportTerminated]
}
// If savedReportTransportTerminated == null, transportTerminated() has already been called in
// shutdown().
} }
|
public class class_name {
public LongWritable getValueLongWritable(String label) {
HadoopObject o = getHadoopObject(VALUE, label, ObjectUtil.LONG, "Long");
if (o == null) {
return null;
}
return (LongWritable) o.getObject();
} }
|
public class class_name {
public LongWritable getValueLongWritable(String label) {
HadoopObject o = getHadoopObject(VALUE, label, ObjectUtil.LONG, "Long");
if (o == null) {
return null; // depends on control dependency: [if], data = [none]
}
return (LongWritable) o.getObject();
} }
|
public class class_name {
public static InputStream read( String path, ClassLoader classLoader, boolean useTLCL ) {
if (useTLCL) {
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
if (stream != null) {
return stream;
}
}
return classLoader != null ? classLoader.getResourceAsStream(path) : ResourceLookup.class.getResourceAsStream(path);
} }
|
public class class_name {
public static InputStream read( String path, ClassLoader classLoader, boolean useTLCL ) {
if (useTLCL) {
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
if (stream != null) {
return stream; // depends on control dependency: [if], data = [none]
}
}
return classLoader != null ? classLoader.getResourceAsStream(path) : ResourceLookup.class.getResourceAsStream(path);
} }
|
public class class_name {
public void setPublishRelatedResourcesMode(String publishRelatedResourcesMode) {
m_publishRelatedResourcesMode = CmsPublishRelatedResourcesMode.valueOf(publishRelatedResourcesMode);
if ((m_publishRelatedResourcesMode != null) && CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_PUBLISH_RELATED_RESOURCES_MODE_1,
m_publishRelatedResourcesMode.toString()));
}
} }
|
public class class_name {
public void setPublishRelatedResourcesMode(String publishRelatedResourcesMode) {
m_publishRelatedResourcesMode = CmsPublishRelatedResourcesMode.valueOf(publishRelatedResourcesMode);
if ((m_publishRelatedResourcesMode != null) && CmsLog.INIT.isInfoEnabled()) {
CmsLog.INIT.info(
Messages.get().getBundle().key(
Messages.INIT_PUBLISH_RELATED_RESOURCES_MODE_1,
m_publishRelatedResourcesMode.toString())); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private Set<String> resolveClass(String variableName, String text, Document document) {
Set<String> items = new LinkedHashSet<>();
FileObject fo = getFileObject(document);
ClassPath sourcePath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
ClassPath compilePath = ClassPath.getClassPath(fo, ClassPath.COMPILE);
ClassPath bootPath = ClassPath.getClassPath(fo, ClassPath.BOOT);
if (sourcePath == null) {
return items;
}
ClassPath cp = ClassPathSupport.createProxyClassPath(sourcePath, compilePath, bootPath);
MemberLookupResolver resolver = new MemberLookupResolver(text, cp);
Set<MemberLookupResult> results = resolver.performMemberLookup(StringUtils.defaultString(StringUtils.substringBeforeLast(variableName, "."), variableName));
for (MemberLookupResult result : results) {
Matcher m = GETTER_PATTERN.matcher(result.getMethodName());
if (m.matches() && m.groupCount() >= 2) {
items.add(result.getVariableName() + "." + WordUtils.uncapitalize(m.group(2)));
}
else {
items.add(result.getVariableName() + "." + WordUtils.uncapitalize(result.getMethodName()));
}
}
return items;
} }
|
public class class_name {
private Set<String> resolveClass(String variableName, String text, Document document) {
Set<String> items = new LinkedHashSet<>();
FileObject fo = getFileObject(document);
ClassPath sourcePath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
ClassPath compilePath = ClassPath.getClassPath(fo, ClassPath.COMPILE);
ClassPath bootPath = ClassPath.getClassPath(fo, ClassPath.BOOT);
if (sourcePath == null) {
return items; // depends on control dependency: [if], data = [none]
}
ClassPath cp = ClassPathSupport.createProxyClassPath(sourcePath, compilePath, bootPath);
MemberLookupResolver resolver = new MemberLookupResolver(text, cp);
Set<MemberLookupResult> results = resolver.performMemberLookup(StringUtils.defaultString(StringUtils.substringBeforeLast(variableName, "."), variableName));
for (MemberLookupResult result : results) {
Matcher m = GETTER_PATTERN.matcher(result.getMethodName());
if (m.matches() && m.groupCount() >= 2) {
items.add(result.getVariableName() + "." + WordUtils.uncapitalize(m.group(2))); // depends on control dependency: [if], data = [none]
}
else {
items.add(result.getVariableName() + "." + WordUtils.uncapitalize(result.getMethodName())); // depends on control dependency: [if], data = [none]
}
}
return items;
} }
|
public class class_name {
public static String hexEncode(final String data) {
try {
val result = Hex.encodeHex(data.getBytes(StandardCharsets.UTF_8));
return new String(result);
} catch (final Exception e) {
return null;
}
} }
|
public class class_name {
public static String hexEncode(final String data) {
try {
val result = Hex.encodeHex(data.getBytes(StandardCharsets.UTF_8));
return new String(result); // depends on control dependency: [try], data = [none]
} catch (final Exception e) {
return null;
} // depends on control dependency: [catch], data = [none]
} }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.