code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
public OGCPoint getPoint(DeferredObject[] args) {
OGCGeometry geometry = getGeometry(args);
if (geometry instanceof OGCPoint) {
return (OGCPoint)geometry;
} else {
return null;
}
} } | public class class_name {
public OGCPoint getPoint(DeferredObject[] args) {
OGCGeometry geometry = getGeometry(args);
if (geometry instanceof OGCPoint) {
return (OGCPoint)geometry;
// depends on control dependency: [if], data = [none]
} else {
return null;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void addEmitEventCall(ExecutableElement originalMethod,
MethodSpec.Builder proxyMethodBuilder, String methodCallParameters) {
String methodName = "$emit";
if (methodCallParameters != null && !"".equals(methodCallParameters)) {
proxyMethodBuilder.addStatement("vue().$L($S, $L)",
methodName,
methodToEventName(originalMethod),
methodCallParameters);
} else {
proxyMethodBuilder.addStatement("vue().$L($S)",
methodName,
methodToEventName(originalMethod));
}
} } | public class class_name {
private void addEmitEventCall(ExecutableElement originalMethod,
MethodSpec.Builder proxyMethodBuilder, String methodCallParameters) {
String methodName = "$emit";
if (methodCallParameters != null && !"".equals(methodCallParameters)) {
proxyMethodBuilder.addStatement("vue().$L($S, $L)",
methodName,
methodToEventName(originalMethod),
methodCallParameters); // depends on control dependency: [if], data = [none]
} else {
proxyMethodBuilder.addStatement("vue().$L($S)",
methodName,
methodToEventName(originalMethod)); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static String getClassSignature(String[] interfaces, String className, String apiName) {
StringBuilder signature;
signature = new StringBuilder("<Z::" + XsdSupportingStructure.elementTypeDesc + ">" + JAVA_OBJECT_DESC);
if (interfaces != null){
for (String anInterface : interfaces) {
signature.append("L")
.append(getFullClassTypeName(anInterface, apiName))
.append("<L")
.append(getFullClassTypeName(className, apiName))
.append("<TZ;>;TZ;>;");
}
}
return signature.toString();
} } | public class class_name {
static String getClassSignature(String[] interfaces, String className, String apiName) {
StringBuilder signature;
signature = new StringBuilder("<Z::" + XsdSupportingStructure.elementTypeDesc + ">" + JAVA_OBJECT_DESC);
if (interfaces != null){
for (String anInterface : interfaces) {
signature.append("L")
.append(getFullClassTypeName(anInterface, apiName))
.append("<L")
.append(getFullClassTypeName(className, apiName))
.append("<TZ;>;TZ;>;"); // depends on control dependency: [for], data = [none] // depends on control dependency: [for], data = [none]
}
}
return signature.toString();
} } |
public class class_name {
public static boolean isValidJavaPackage(String packageName) {
if (isBlank(packageName)) {
return false;
}
final String[] parts = packageName.split("\\.");
for (String part : parts) {
if (!isValidJavaIdentifier(part)) {
return false;
}
}
return true;
} } | public class class_name {
public static boolean isValidJavaPackage(String packageName) {
if (isBlank(packageName)) {
return false; // depends on control dependency: [if], data = [none]
}
final String[] parts = packageName.split("\\.");
for (String part : parts) {
if (!isValidJavaIdentifier(part)) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public ProgressStyle setIndeterminate(boolean value){
if(mProgressStyle == HORIZONTAL) {
mProgress.setIndeterminate(value);
mProgressText.setVisibility(value ? View.GONE : View.VISIBLE);
mProgressMax.setVisibility(value ? View.GONE : View.VISIBLE);
}
return this;
} } | public class class_name {
public ProgressStyle setIndeterminate(boolean value){
if(mProgressStyle == HORIZONTAL) {
mProgress.setIndeterminate(value); // depends on control dependency: [if], data = [none]
mProgressText.setVisibility(value ? View.GONE : View.VISIBLE); // depends on control dependency: [if], data = [none]
mProgressMax.setVisibility(value ? View.GONE : View.VISIBLE); // depends on control dependency: [if], data = [none]
}
return this;
} } |
public class class_name {
private static IDisconfUpdatePipeline getIDisconfUpdatePipelineInstance(
Class<IDisconfUpdatePipeline> disconfUpdateServiceClass,
Registry registry) {
Object iDisconfUpdate = registry.getFirstByType(disconfUpdateServiceClass, true);
if (iDisconfUpdate == null) {
return null;
}
return (IDisconfUpdatePipeline) iDisconfUpdate;
} } | public class class_name {
private static IDisconfUpdatePipeline getIDisconfUpdatePipelineInstance(
Class<IDisconfUpdatePipeline> disconfUpdateServiceClass,
Registry registry) {
Object iDisconfUpdate = registry.getFirstByType(disconfUpdateServiceClass, true);
if (iDisconfUpdate == null) {
return null; // depends on control dependency: [if], data = [none]
}
return (IDisconfUpdatePipeline) iDisconfUpdate;
} } |
public class class_name {
public Drawable decideIcon(Context ctx, int iconColor, boolean tint, int paddingDp) {
Drawable icon = getIcon();
if (mIIcon != null) {
icon = new IconicsDrawable(ctx, mIIcon).color(iconColor).sizeDp(24).paddingDp(paddingDp);
} else if (getIconRes() != -1) {
icon = AppCompatResources.getDrawable(ctx, getIconRes());
} else if (getUri() != null) {
try {
InputStream inputStream = ctx.getContentResolver().openInputStream(getUri());
icon = Drawable.createFromStream(inputStream, getUri().toString());
} catch (FileNotFoundException e) {
//no need to handle this
}
}
//if we got an icon AND we have auto tinting enabled AND it is no IIcon, tint it ;)
if (icon != null && tint && mIIcon == null) {
icon = icon.mutate();
icon.setColorFilter(iconColor, PorterDuff.Mode.SRC_IN);
}
return icon;
} } | public class class_name {
public Drawable decideIcon(Context ctx, int iconColor, boolean tint, int paddingDp) {
Drawable icon = getIcon();
if (mIIcon != null) {
icon = new IconicsDrawable(ctx, mIIcon).color(iconColor).sizeDp(24).paddingDp(paddingDp); // depends on control dependency: [if], data = [none]
} else if (getIconRes() != -1) {
icon = AppCompatResources.getDrawable(ctx, getIconRes()); // depends on control dependency: [if], data = [none]
} else if (getUri() != null) {
try {
InputStream inputStream = ctx.getContentResolver().openInputStream(getUri());
icon = Drawable.createFromStream(inputStream, getUri().toString()); // depends on control dependency: [try], data = [none]
} catch (FileNotFoundException e) {
//no need to handle this
} // depends on control dependency: [catch], data = [none]
}
//if we got an icon AND we have auto tinting enabled AND it is no IIcon, tint it ;)
if (icon != null && tint && mIIcon == null) {
icon = icon.mutate(); // depends on control dependency: [if], data = [none]
icon.setColorFilter(iconColor, PorterDuff.Mode.SRC_IN); // depends on control dependency: [if], data = [none]
}
return icon;
} } |
public class class_name {
public void marshall(ImagePermissions imagePermissions, ProtocolMarshaller protocolMarshaller) {
if (imagePermissions == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(imagePermissions.getAllowFleet(), ALLOWFLEET_BINDING);
protocolMarshaller.marshall(imagePermissions.getAllowImageBuilder(), ALLOWIMAGEBUILDER_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ImagePermissions imagePermissions, ProtocolMarshaller protocolMarshaller) {
if (imagePermissions == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(imagePermissions.getAllowFleet(), ALLOWFLEET_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(imagePermissions.getAllowImageBuilder(), ALLOWIMAGEBUILDER_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private synchronized void compareProgress(List<Long> processIds) {
if (CollectionUtils.isEmpty(processIds) == false) {
Long minProcessId = processIds.get(0);
// 对比一下progress中的记录,如果小于当前最小的processId,直接删除内存中的记录
// 因为发生跨机器调用或者出现restart指令,对应的process记录不会被删除
for (Long processId : progress.keySet()) {
if (processId < minProcessId) {
progress.remove(processId);
}
}
}
} } | public class class_name {
private synchronized void compareProgress(List<Long> processIds) {
if (CollectionUtils.isEmpty(processIds) == false) {
Long minProcessId = processIds.get(0);
// 对比一下progress中的记录,如果小于当前最小的processId,直接删除内存中的记录
// 因为发生跨机器调用或者出现restart指令,对应的process记录不会被删除
for (Long processId : progress.keySet()) {
if (processId < minProcessId) {
progress.remove(processId); // depends on control dependency: [if], data = [(processId]
}
}
}
} } |
public class class_name {
public boolean add(final Process process) {
synchronized (processes) {
// if this list is empty, register the shutdown hook
if (processes.size() == 0) {
try {
if(shutDownHookExecuted) {
throw new IllegalStateException();
}
addShutdownHook();
}
// kill the process now if the JVM is currently shutting down
catch (IllegalStateException e) {
destroy(process);
}
}
processes.addElement(process);
return processes.contains(process);
}
} } | public class class_name {
public boolean add(final Process process) {
synchronized (processes) {
// if this list is empty, register the shutdown hook
if (processes.size() == 0) {
try {
if(shutDownHookExecuted) {
throw new IllegalStateException();
}
addShutdownHook(); // depends on control dependency: [try], data = [none]
}
// kill the process now if the JVM is currently shutting down
catch (IllegalStateException e) {
destroy(process);
} // depends on control dependency: [catch], data = [none]
}
processes.addElement(process);
return processes.contains(process);
}
} } |
public class class_name {
public static void putString(IoBuffer buf, String string) {
final byte[] encoded = encodeString(string);
if (encoded.length < AMF.LONG_STRING_LENGTH) {
// write unsigned short
buf.put((byte) ((encoded.length >> 8) & 0xff));
buf.put((byte) (encoded.length & 0xff));
} else {
buf.putInt(encoded.length);
}
buf.put(encoded);
} } | public class class_name {
public static void putString(IoBuffer buf, String string) {
final byte[] encoded = encodeString(string);
if (encoded.length < AMF.LONG_STRING_LENGTH) {
// write unsigned short
buf.put((byte) ((encoded.length >> 8) & 0xff)); // depends on control dependency: [if], data = [(encoded.length]
buf.put((byte) (encoded.length & 0xff)); // depends on control dependency: [if], data = [(encoded.length]
} else {
buf.putInt(encoded.length); // depends on control dependency: [if], data = [(encoded.length]
}
buf.put(encoded);
} } |
public class class_name {
public void checkCacheMode(Boolean boolShouldBeCached)
{
try {
boolean bCurrentlyCached = (this.getRemoteTableType(CachedRemoteTable.class) != null);
if ((this.getRecord().getOpenMode() & DBConstants.OPEN_CACHE_RECORDS) == DBConstants.OPEN_CACHE_RECORDS)
boolShouldBeCached = Boolean.TRUE;
// if ((this.getRecord().getOpenMode() & DBConstants.OPEN_READ_ONLY) == DBConstants.OPEN_READ_ONLY);
// bShouldBeCached = true;
if ((this.getRecord().getOpenMode() & DBConstants.OPEN_DONT_CACHE) == DBConstants.OPEN_DONT_CACHE)
boolShouldBeCached = Boolean.FALSE;
if (boolShouldBeCached == null)
return; // Not specified, Don't change.
if ((!bCurrentlyCached) && (boolShouldBeCached.booleanValue()))
{ // Add a cache
Utility.getLogger().info("Cache ON: " + this.getRecord().getTableNames(false));
this.setRemoteTable(new CachedRemoteTable(m_tableRemote));
}
else if ((bCurrentlyCached) && (!boolShouldBeCached.booleanValue()))
{ // Remove the cache
Utility.getLogger().info("Cache OFF: " + this.getRecord().getTableNames(false));
// RemoteTable tableRemote = this.getRemoteTableType(org.jbundle.model.Remote.class);
RemoteTable tableRemote = this.getRemoteTableType(CachedRemoteTable.class).getRemoteTableType(null);
((CachedRemoteTable)m_tableRemote).setRemoteTable(null);
((CachedRemoteTable)m_tableRemote).free();
this.setRemoteTable(tableRemote);
}
} catch (RemoteException ex) {
// Never for this usage
}
} } | public class class_name {
public void checkCacheMode(Boolean boolShouldBeCached)
{
try {
boolean bCurrentlyCached = (this.getRemoteTableType(CachedRemoteTable.class) != null);
if ((this.getRecord().getOpenMode() & DBConstants.OPEN_CACHE_RECORDS) == DBConstants.OPEN_CACHE_RECORDS)
boolShouldBeCached = Boolean.TRUE;
// if ((this.getRecord().getOpenMode() & DBConstants.OPEN_READ_ONLY) == DBConstants.OPEN_READ_ONLY);
// bShouldBeCached = true;
if ((this.getRecord().getOpenMode() & DBConstants.OPEN_DONT_CACHE) == DBConstants.OPEN_DONT_CACHE)
boolShouldBeCached = Boolean.FALSE;
if (boolShouldBeCached == null)
return; // Not specified, Don't change.
if ((!bCurrentlyCached) && (boolShouldBeCached.booleanValue()))
{ // Add a cache
Utility.getLogger().info("Cache ON: " + this.getRecord().getTableNames(false)); // depends on control dependency: [if], data = [none]
this.setRemoteTable(new CachedRemoteTable(m_tableRemote)); // depends on control dependency: [if], data = [none]
}
else if ((bCurrentlyCached) && (!boolShouldBeCached.booleanValue()))
{ // Remove the cache
Utility.getLogger().info("Cache OFF: " + this.getRecord().getTableNames(false)); // depends on control dependency: [if], data = [none]
// RemoteTable tableRemote = this.getRemoteTableType(org.jbundle.model.Remote.class);
RemoteTable tableRemote = this.getRemoteTableType(CachedRemoteTable.class).getRemoteTableType(null);
((CachedRemoteTable)m_tableRemote).setRemoteTable(null); // depends on control dependency: [if], data = [none]
((CachedRemoteTable)m_tableRemote).free(); // depends on control dependency: [if], data = [none]
this.setRemoteTable(tableRemote); // depends on control dependency: [if], data = [none]
}
} catch (RemoteException ex) {
// Never for this usage
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static int getMonomerCountFromMonomerNotation(MonomerNotation monomerNotation) {
int multiply;
try {
multiply = Integer.parseInt(monomerNotation.getCount());
if (multiply < 1) {
multiply = 1;
}
} catch (NumberFormatException e) {
multiply = 1;
}
if (monomerNotation instanceof MonomerNotationGroup) {
return 1 * multiply;
}
if (monomerNotation instanceof MonomerNotationList) {
int count = 0;
for (MonomerNotation unit : ((MonomerNotationList) monomerNotation).getListofMonomerUnits()) {
count += getMonomerCountFromMonomerNotation(unit);
}
return count * multiply;
}
if (monomerNotation instanceof MonomerNotationUnitRNA) {
int count = 0;
for (MonomerNotationUnit unit : ((MonomerNotationUnitRNA) monomerNotation).getContents()) {
count += getMonomerCountFromMonomerNotation(unit);
}
return count * multiply;
}
return 1 * multiply;
} } | public class class_name {
private static int getMonomerCountFromMonomerNotation(MonomerNotation monomerNotation) {
int multiply;
try {
multiply = Integer.parseInt(monomerNotation.getCount());
// depends on control dependency: [try], data = [none]
if (multiply < 1) {
multiply = 1;
// depends on control dependency: [if], data = [none]
}
} catch (NumberFormatException e) {
multiply = 1;
}
// depends on control dependency: [catch], data = [none]
if (monomerNotation instanceof MonomerNotationGroup) {
return 1 * multiply;
// depends on control dependency: [if], data = [none]
}
if (monomerNotation instanceof MonomerNotationList) {
int count = 0;
for (MonomerNotation unit : ((MonomerNotationList) monomerNotation).getListofMonomerUnits()) {
count += getMonomerCountFromMonomerNotation(unit);
// depends on control dependency: [for], data = [unit]
}
return count * multiply;
// depends on control dependency: [if], data = [none]
}
if (monomerNotation instanceof MonomerNotationUnitRNA) {
int count = 0;
for (MonomerNotationUnit unit : ((MonomerNotationUnitRNA) monomerNotation).getContents()) {
count += getMonomerCountFromMonomerNotation(unit);
// depends on control dependency: [for], data = [unit]
}
return count * multiply;
// depends on control dependency: [if], data = [none]
}
return 1 * multiply;
} } |
public class class_name {
public void addDataId(Object dataId) {
if (lock == SET) {
throw new IllegalStateException("EntryInfo is locked");
}
if (dataId != null && !dataId.equals("")) {
dataIds.add(dataId);
}
} } | public class class_name {
public void addDataId(Object dataId) {
if (lock == SET) {
throw new IllegalStateException("EntryInfo is locked");
}
if (dataId != null && !dataId.equals("")) {
dataIds.add(dataId); // depends on control dependency: [if], data = [(dataId]
}
} } |
public class class_name {
@Override
public Collection<CopyableFile> filter(FileSystem sourceFs, FileSystem targetFs,
Collection<CopyableFile> copyableFiles) {
Iterator<CopyableFile> cfIterator = copyableFiles.iterator();
ImmutableList.Builder<CopyableFile> filtered = ImmutableList.builder();
while (cfIterator.hasNext()) {
CopyableFile cf = cfIterator.next();
Path readyFilePath = PathUtils.addExtension(cf.getOrigin().getPath(), READY_EXTENSION);
try {
if (sourceFs.exists(readyFilePath)) {
filtered.add(cf);
} else {
log.info(String.format("Removing %s as the .ready file is not found", cf.getOrigin().getPath()));
}
} catch (IOException e) {
log.warn(String.format("Removing %s as the .ready file can not be read. Exception %s",
cf.getOrigin().getPath(), e.getMessage()));
}
}
return filtered.build();
} } | public class class_name {
@Override
public Collection<CopyableFile> filter(FileSystem sourceFs, FileSystem targetFs,
Collection<CopyableFile> copyableFiles) {
Iterator<CopyableFile> cfIterator = copyableFiles.iterator();
ImmutableList.Builder<CopyableFile> filtered = ImmutableList.builder();
while (cfIterator.hasNext()) {
CopyableFile cf = cfIterator.next();
Path readyFilePath = PathUtils.addExtension(cf.getOrigin().getPath(), READY_EXTENSION);
try {
if (sourceFs.exists(readyFilePath)) {
filtered.add(cf); // depends on control dependency: [if], data = [none]
} else {
log.info(String.format("Removing %s as the .ready file is not found", cf.getOrigin().getPath())); // depends on control dependency: [if], data = [none]
}
} catch (IOException e) {
log.warn(String.format("Removing %s as the .ready file can not be read. Exception %s",
cf.getOrigin().getPath(), e.getMessage()));
} // depends on control dependency: [catch], data = [none]
}
return filtered.build();
} } |
public class class_name {
public void validate () {
formInvalid = false;
errorMsgText = null;
for (CheckedButtonWrapper wrapper : buttons) {
if (wrapper.button.isChecked() != wrapper.mustBeChecked) {
wrapper.setButtonStateInvalid(true);
} else {
wrapper.setButtonStateInvalid(false);
}
}
for (CheckedButtonWrapper wrapper : buttons) {
if (treatDisabledFieldsAsValid && wrapper.button.isDisabled()) {
continue;
}
if (wrapper.button.isChecked() != wrapper.mustBeChecked) {
errorMsgText = wrapper.errorMsg;
formInvalid = true;
break;
}
}
for (VisValidatableTextField field : fields) {
field.validateInput();
}
for (VisValidatableTextField field : fields) {
if (treatDisabledFieldsAsValid && field.isDisabled()) {
continue;
}
if (field.isInputValid() == false) {
Array<InputValidator> validators = field.getValidators();
for (InputValidator v : validators) {
if (v instanceof FormInputValidator == false) {
throw new IllegalStateException("Fields validated by FormValidator cannot have validators not added using FormValidator methods. " +
"Are you adding validators to field manually?");
}
FormInputValidator validator = (FormInputValidator) v;
if (validator.getLastResult() == false) {
if (!(validator.isHideErrorOnEmptyInput() && field.getText().equals(""))) {
errorMsgText = validator.getErrorMsg();
}
formInvalid = true;
break;
}
}
break;
}
}
updateWidgets();
} } | public class class_name {
public void validate () {
formInvalid = false;
errorMsgText = null;
for (CheckedButtonWrapper wrapper : buttons) {
if (wrapper.button.isChecked() != wrapper.mustBeChecked) {
wrapper.setButtonStateInvalid(true); // depends on control dependency: [if], data = [none]
} else {
wrapper.setButtonStateInvalid(false); // depends on control dependency: [if], data = [none]
}
}
for (CheckedButtonWrapper wrapper : buttons) {
if (treatDisabledFieldsAsValid && wrapper.button.isDisabled()) {
continue;
}
if (wrapper.button.isChecked() != wrapper.mustBeChecked) {
errorMsgText = wrapper.errorMsg; // depends on control dependency: [if], data = [none]
formInvalid = true; // depends on control dependency: [if], data = [none]
break;
}
}
for (VisValidatableTextField field : fields) {
field.validateInput(); // depends on control dependency: [for], data = [field]
}
for (VisValidatableTextField field : fields) {
if (treatDisabledFieldsAsValid && field.isDisabled()) {
continue;
}
if (field.isInputValid() == false) {
Array<InputValidator> validators = field.getValidators();
for (InputValidator v : validators) {
if (v instanceof FormInputValidator == false) {
throw new IllegalStateException("Fields validated by FormValidator cannot have validators not added using FormValidator methods. " +
"Are you adding validators to field manually?");
}
FormInputValidator validator = (FormInputValidator) v;
if (validator.getLastResult() == false) {
if (!(validator.isHideErrorOnEmptyInput() && field.getText().equals(""))) {
errorMsgText = validator.getErrorMsg(); // depends on control dependency: [if], data = [none]
}
formInvalid = true; // depends on control dependency: [if], data = [none]
break;
}
}
break;
}
}
updateWidgets();
} } |
public class class_name {
protected boolean
isWholeCompound(DapStructure dstruct)
{
int processed = 0;
List<DapVariable> fields = dstruct.getFields();
for(DapVariable field : fields) {
// not contractable if this field has non-original dimensions
Segment seg = findSegment(field);
if(seg == null)
break; // this compound is not whole
List<Slice> slices = seg.slices;
if(slices != null) {
for(Slice slice : slices) {
if(slice.isConstrained())
break;
}
}
DapType base = field.getBaseType();
if(base.getTypeSort().isCompound()) {
if(!isWholeCompound((DapStructure) base))
break; // this compound is not whole
}
processed++;
}
return (processed == fields.size());
} } | public class class_name {
protected boolean
isWholeCompound(DapStructure dstruct)
{
int processed = 0;
List<DapVariable> fields = dstruct.getFields();
for(DapVariable field : fields) {
// not contractable if this field has non-original dimensions
Segment seg = findSegment(field);
if(seg == null)
break; // this compound is not whole
List<Slice> slices = seg.slices;
if(slices != null) {
for(Slice slice : slices) {
if(slice.isConstrained())
break;
}
}
DapType base = field.getBaseType();
if(base.getTypeSort().isCompound()) {
if(!isWholeCompound((DapStructure) base))
break; // this compound is not whole
}
processed++; // depends on control dependency: [for], data = [none]
}
return (processed == fields.size());
} } |
public class class_name {
private AstStrList parseStringList() {
ArrayList<String> strs = new ArrayList<>(10);
while (isQuote(skipWS())) {
strs.add(string());
if (skipWS() == ',') eatChar(',');
}
return new AstStrList(strs);
} } | public class class_name {
private AstStrList parseStringList() {
ArrayList<String> strs = new ArrayList<>(10);
while (isQuote(skipWS())) {
strs.add(string()); // depends on control dependency: [while], data = [none]
if (skipWS() == ',') eatChar(',');
}
return new AstStrList(strs);
} } |
public class class_name {
public Set<String> getAttributeNamesSkipId() {
if (attributeNamesNoId == null) {//no one cares about unfortunate multi-threading timing with 2 instances created
//if someone does, use DCL with volatile
Set<String> attributesNames = new CaseInsensitiveSet(getAttributeNames());
attributesNames.remove(getIdName());
attributeNamesNoId = attributesNames;
}
return attributeNamesNoId;
} } | public class class_name {
public Set<String> getAttributeNamesSkipId() {
if (attributeNamesNoId == null) {//no one cares about unfortunate multi-threading timing with 2 instances created
//if someone does, use DCL with volatile
Set<String> attributesNames = new CaseInsensitiveSet(getAttributeNames());
attributesNames.remove(getIdName()); // depends on control dependency: [if], data = [none]
attributeNamesNoId = attributesNames; // depends on control dependency: [if], data = [none]
}
return attributeNamesNoId;
} } |
public class class_name {
public static String hash(String password) {
String result = null;
if (password != null) {
// Generate a random salt:
String salt = Generate.salt();
// Hash the password:
byte[] hash = hash(password, salt);
// Concatenate the salt and hash:
byte[] concatenated = ArrayUtils.addAll(ByteArray.fromBase64(salt), hash);
// Base-64 encode the result:
result = ByteArray.toBase64(concatenated);
}
return result;
} } | public class class_name {
public static String hash(String password) {
String result = null;
if (password != null) {
// Generate a random salt:
String salt = Generate.salt();
// Hash the password:
byte[] hash = hash(password, salt);
// Concatenate the salt and hash:
byte[] concatenated = ArrayUtils.addAll(ByteArray.fromBase64(salt), hash);
// Base-64 encode the result:
result = ByteArray.toBase64(concatenated); // depends on control dependency: [if], data = [none]
}
return result;
} } |
public class class_name {
public DirEntry insert(RecordId dataRecordId) {
// search range must be a constant
if (!searchRange.isSingleValue())
throw new IllegalStateException();
// ccMgr.modifyLeafBlock(currentPage.currentBlk());
currentSlot++;
SearchKey searchKey = searchRange.asSearchKey();
insert(currentSlot, searchKey, dataRecordId);
/*
* If the inserted key is less than the key stored in the overflow
* blocks, split this block to make sure that the key of the first
* record in every block will be the same as the key of records in
* the overflow blocks.
*/
if (currentSlot == 0 && getOverflowFlag(currentPage) != -1 &&
!getKey(currentPage, 1, keyType.length()).equals(searchKey)) {
SearchKey splitKey = getKey(currentPage, 1, keyType.length());
long newBlkNum = currentPage.split(1,
new long[] { getOverflowFlag(currentPage),
getSiblingFlag(currentPage) });
setOverflowFlag(currentPage, -1);
setSiblingFlag(currentPage, newBlkNum);
return new DirEntry(splitKey, newBlkNum);
}
if (!currentPage.isFull())
return null;
/*
* If this block is full, then split the block and return the directory
* entry of the new block.
*/
SearchKey firstKey = getKey(currentPage, 0, keyType.length());
SearchKey lastKey = getKey(currentPage, currentPage.getNumRecords() - 1,
keyType.length());
if (lastKey.equals(firstKey)) {
/*
* If all of the records in the page have the same key, then the
* block does not split; instead, all but one of the records are
* placed into an overflow block.
*/
long overflowFlag = (getOverflowFlag(currentPage) == -1) ?
currentPage.currentBlk().number() : getOverflowFlag(currentPage);
long newBlkNum = currentPage.split(1, new long[] { overflowFlag, -1 });
setOverflowFlag(currentPage, newBlkNum);
return null;
} else {
int splitPos = currentPage.getNumRecords() / 2;
SearchKey splitKey = getKey(currentPage, splitPos, keyType.length());
// records having the same key must be in the same block
if (splitKey.equals(firstKey)) {
// move right, looking for a different key
while (getKey(currentPage, splitPos, keyType.length()).equals(splitKey))
splitPos++;
splitKey = getKey(currentPage, splitPos, keyType.length());
} else {
// move left, looking for first entry having that key
while (getKey(currentPage, splitPos - 1, keyType.length())
.equals(splitKey))
splitPos--;
}
// split the block
long newBlkNum = currentPage.split(splitPos, new long[] { -1,
getSiblingFlag(currentPage) });
setSiblingFlag(currentPage, newBlkNum);
return new DirEntry(splitKey, newBlkNum);
}
} } | public class class_name {
public DirEntry insert(RecordId dataRecordId) {
// search range must be a constant
if (!searchRange.isSingleValue())
throw new IllegalStateException();
// ccMgr.modifyLeafBlock(currentPage.currentBlk());
currentSlot++;
SearchKey searchKey = searchRange.asSearchKey();
insert(currentSlot, searchKey, dataRecordId);
/*
* If the inserted key is less than the key stored in the overflow
* blocks, split this block to make sure that the key of the first
* record in every block will be the same as the key of records in
* the overflow blocks.
*/
if (currentSlot == 0 && getOverflowFlag(currentPage) != -1 &&
!getKey(currentPage, 1, keyType.length()).equals(searchKey)) {
SearchKey splitKey = getKey(currentPage, 1, keyType.length());
long newBlkNum = currentPage.split(1,
new long[] { getOverflowFlag(currentPage),
getSiblingFlag(currentPage) });
setOverflowFlag(currentPage, -1);
// depends on control dependency: [if], data = [none]
setSiblingFlag(currentPage, newBlkNum);
// depends on control dependency: [if], data = [none]
return new DirEntry(splitKey, newBlkNum);
// depends on control dependency: [if], data = [none]
}
if (!currentPage.isFull())
return null;
/*
* If this block is full, then split the block and return the directory
* entry of the new block.
*/
SearchKey firstKey = getKey(currentPage, 0, keyType.length());
SearchKey lastKey = getKey(currentPage, currentPage.getNumRecords() - 1,
keyType.length());
if (lastKey.equals(firstKey)) {
/*
* If all of the records in the page have the same key, then the
* block does not split; instead, all but one of the records are
* placed into an overflow block.
*/
long overflowFlag = (getOverflowFlag(currentPage) == -1) ?
currentPage.currentBlk().number() : getOverflowFlag(currentPage);
long newBlkNum = currentPage.split(1, new long[] { overflowFlag, -1 });
setOverflowFlag(currentPage, newBlkNum);
// depends on control dependency: [if], data = [none]
return null;
// depends on control dependency: [if], data = [none]
} else {
int splitPos = currentPage.getNumRecords() / 2;
SearchKey splitKey = getKey(currentPage, splitPos, keyType.length());
// records having the same key must be in the same block
if (splitKey.equals(firstKey)) {
// move right, looking for a different key
while (getKey(currentPage, splitPos, keyType.length()).equals(splitKey))
splitPos++;
splitKey = getKey(currentPage, splitPos, keyType.length());
// depends on control dependency: [if], data = [none]
} else {
// move left, looking for first entry having that key
while (getKey(currentPage, splitPos - 1, keyType.length())
.equals(splitKey))
splitPos--;
}
// split the block
long newBlkNum = currentPage.split(splitPos, new long[] { -1,
getSiblingFlag(currentPage) });
setSiblingFlag(currentPage, newBlkNum);
// depends on control dependency: [if], data = [none]
return new DirEntry(splitKey, newBlkNum);
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public ParseResult parse(Reader reader, AttributeSource parent)
throws IOException {
ParseResult res = new ParseResult();
// get MtasUpdateRequestProcessorResult
StringBuilder sb = new StringBuilder();
char[] buf = new char[128];
int cnt;
while ((cnt = reader.read(buf)) > 0) {
sb.append(buf, 0, cnt);
}
Iterator<MtasUpdateRequestProcessorResultItem> iterator;
try (
MtasUpdateRequestProcessorResultReader result = new MtasUpdateRequestProcessorResultReader(
sb.toString());) {
iterator = result.getIterator();
if (iterator != null && iterator.hasNext()) {
res.str = result.getStoredStringValue();
res.bin = result.getStoredBinValue();
} else {
res.str = null;
res.bin = null;
result.close();
return res;
}
parent.clearAttributes();
while (iterator.hasNext()) {
MtasUpdateRequestProcessorResultItem item = iterator.next();
if (item.tokenTerm != null) {
CharTermAttribute catt = parent.addAttribute(CharTermAttribute.class);
catt.append(item.tokenTerm);
}
if (item.tokenFlags != null) {
FlagsAttribute flags = parent.addAttribute(FlagsAttribute.class);
flags.setFlags(item.tokenFlags);
}
if (item.tokenPosIncr != null) {
PositionIncrementAttribute patt = parent
.addAttribute(PositionIncrementAttribute.class);
patt.setPositionIncrement(item.tokenPosIncr);
}
if (item.tokenPayload != null) {
PayloadAttribute p = parent.addAttribute(PayloadAttribute.class);
p.setPayload(new BytesRef(item.tokenPayload));
}
if (item.tokenOffsetStart != null && item.tokenOffsetEnd != null) {
OffsetAttribute offset = parent.addAttribute(OffsetAttribute.class);
offset.setOffset(item.tokenOffsetStart, item.tokenOffsetEnd);
}
// capture state and add to result
State state = parent.captureState();
res.states.add(state.clone());
// reset for reuse
parent.clearAttributes();
}
} catch (IOException e) {
// ignore
log.debug(e);
}
return res;
} } | public class class_name {
@Override
public ParseResult parse(Reader reader, AttributeSource parent)
throws IOException {
ParseResult res = new ParseResult();
// get MtasUpdateRequestProcessorResult
StringBuilder sb = new StringBuilder();
char[] buf = new char[128];
int cnt;
while ((cnt = reader.read(buf)) > 0) {
sb.append(buf, 0, cnt);
}
Iterator<MtasUpdateRequestProcessorResultItem> iterator;
try (
MtasUpdateRequestProcessorResultReader result = new MtasUpdateRequestProcessorResultReader(
sb.toString());) {
iterator = result.getIterator();
if (iterator != null && iterator.hasNext()) {
res.str = result.getStoredStringValue(); // depends on control dependency: [if], data = [none]
res.bin = result.getStoredBinValue(); // depends on control dependency: [if], data = [none]
} else {
res.str = null; // depends on control dependency: [if], data = [none]
res.bin = null; // depends on control dependency: [if], data = [none]
result.close(); // depends on control dependency: [if], data = [none]
return res; // depends on control dependency: [if], data = [none]
}
parent.clearAttributes();
while (iterator.hasNext()) {
MtasUpdateRequestProcessorResultItem item = iterator.next();
if (item.tokenTerm != null) {
CharTermAttribute catt = parent.addAttribute(CharTermAttribute.class);
catt.append(item.tokenTerm); // depends on control dependency: [if], data = [(item.tokenTerm]
}
if (item.tokenFlags != null) {
FlagsAttribute flags = parent.addAttribute(FlagsAttribute.class);
flags.setFlags(item.tokenFlags); // depends on control dependency: [if], data = [(item.tokenFlags]
}
if (item.tokenPosIncr != null) {
PositionIncrementAttribute patt = parent
.addAttribute(PositionIncrementAttribute.class);
patt.setPositionIncrement(item.tokenPosIncr); // depends on control dependency: [if], data = [(item.tokenPosIncr]
}
if (item.tokenPayload != null) {
PayloadAttribute p = parent.addAttribute(PayloadAttribute.class);
p.setPayload(new BytesRef(item.tokenPayload)); // depends on control dependency: [if], data = [(item.tokenPayload]
}
if (item.tokenOffsetStart != null && item.tokenOffsetEnd != null) {
OffsetAttribute offset = parent.addAttribute(OffsetAttribute.class);
offset.setOffset(item.tokenOffsetStart, item.tokenOffsetEnd); // depends on control dependency: [if], data = [(item.tokenOffsetStart]
}
// capture state and add to result
State state = parent.captureState();
res.states.add(state.clone()); // depends on control dependency: [while], data = [none]
// reset for reuse
parent.clearAttributes(); // depends on control dependency: [while], data = [none]
}
} catch (IOException e) {
// ignore
log.debug(e);
}
return res;
} } |
public class class_name {
public boolean isStarving(long now) {
double starvingShare = getShare() * shareStarvingRatio;
if (getGranted() >= Math.ceil(starvingShare)) {
lastTimeAboveStarvingShare = now;
}
if (getGranted() >= Math.min(getShare(), getMinimum())) {
lastTimeAboveMinimum = now;
}
if (now - lastPreemptTime < getMinPreemptPeriod()) {
// Prevent duplicate preemption
return false;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Pool:" + getName() +
" lastTimeAboveMinimum:" + lastTimeAboveMinimum +
" lastTimeAboveStarvingShare:" + lastTimeAboveStarvingShare +
" minimumStarvingTime:" + getMinimumStarvingTime(now) +
" shareStarvingTime:" + getShareStarvingTime(now) +
" starvingTime:" + getStarvingTime(now));
}
if (getMinimumStarvingTime(now) >= 0) {
LOG.info("Pool:" + getName() + " for type:" + getType() +
" is starving min:" + getMinimum() +
" granted:" + getGranted());
lastPreemptTime = now;
return true;
}
if (getShareStarvingTime(now) >= 0) {
LOG.info("Pool:" + getName() + " for type:" + getType() +
" is starving share:" + getShare() +
" starvingRatio:" + shareStarvingRatio +
" starvingShare:" + starvingShare +
" granted:" + getGranted());
lastPreemptTime = now;
return true;
}
return false;
} } | public class class_name {
public boolean isStarving(long now) {
double starvingShare = getShare() * shareStarvingRatio;
if (getGranted() >= Math.ceil(starvingShare)) {
lastTimeAboveStarvingShare = now; // depends on control dependency: [if], data = [none]
}
if (getGranted() >= Math.min(getShare(), getMinimum())) {
lastTimeAboveMinimum = now; // depends on control dependency: [if], data = [none]
}
if (now - lastPreemptTime < getMinPreemptPeriod()) {
// Prevent duplicate preemption
return false; // depends on control dependency: [if], data = [none]
}
if (LOG.isDebugEnabled()) {
LOG.debug("Pool:" + getName() +
" lastTimeAboveMinimum:" + lastTimeAboveMinimum +
" lastTimeAboveStarvingShare:" + lastTimeAboveStarvingShare +
" minimumStarvingTime:" + getMinimumStarvingTime(now) +
" shareStarvingTime:" + getShareStarvingTime(now) +
" starvingTime:" + getStarvingTime(now)); // depends on control dependency: [if], data = [none]
}
if (getMinimumStarvingTime(now) >= 0) {
LOG.info("Pool:" + getName() + " for type:" + getType() +
" is starving min:" + getMinimum() +
" granted:" + getGranted()); // depends on control dependency: [if], data = [none]
lastPreemptTime = now; // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
if (getShareStarvingTime(now) >= 0) {
LOG.info("Pool:" + getName() + " for type:" + getType() +
" is starving share:" + getShare() +
" starvingRatio:" + shareStarvingRatio +
" starvingShare:" + starvingShare +
" granted:" + getGranted()); // depends on control dependency: [if], data = [none]
lastPreemptTime = now; // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public byte getStatus(final int id, final String path) {
if (FileDownloader.getImpl().isServiceConnected()) {
return FileDownloader.getImpl().getStatus(id, path);
}
if (path != null && new File(path).exists()) {
return FileDownloadStatus.completed;
}
final ConnectSubscriber subscriber = new ConnectSubscriber() {
private byte mValue;
@Override
public void connected() {
mValue = FileDownloader.getImpl().getStatus(id, path);
}
@Override
public Object getValue() {
return mValue;
}
};
wait(subscriber);
return (byte) subscriber.getValue();
} } | public class class_name {
public byte getStatus(final int id, final String path) {
if (FileDownloader.getImpl().isServiceConnected()) {
return FileDownloader.getImpl().getStatus(id, path); // depends on control dependency: [if], data = [none]
}
if (path != null && new File(path).exists()) {
return FileDownloadStatus.completed; // depends on control dependency: [if], data = [none]
}
final ConnectSubscriber subscriber = new ConnectSubscriber() {
private byte mValue;
@Override
public void connected() {
mValue = FileDownloader.getImpl().getStatus(id, path);
}
@Override
public Object getValue() {
return mValue;
}
};
wait(subscriber);
return (byte) subscriber.getValue();
} } |
public class class_name {
public void setFaceIds(java.util.Collection<String> faceIds) {
if (faceIds == null) {
this.faceIds = null;
return;
}
this.faceIds = new java.util.ArrayList<String>(faceIds);
} } | public class class_name {
public void setFaceIds(java.util.Collection<String> faceIds) {
if (faceIds == null) {
this.faceIds = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.faceIds = new java.util.ArrayList<String>(faceIds);
} } |
public class class_name {
private static String[] splitRange(final String str) {
if(StringUtils.isBlank(str)) {
return new String[]{""};
}
return str.split(RANGE_PATTERN);
} } | public class class_name {
private static String[] splitRange(final String str) {
if(StringUtils.isBlank(str)) {
return new String[]{""}; // depends on control dependency: [if], data = [none]
}
return str.split(RANGE_PATTERN);
} } |
public class class_name {
protected static void calculateSelectivityCoeffs(List<DoubleObjPair<DAFile>> daFiles, NumberVector query, double epsilon) {
final int dimensions = query.getDimensionality();
double[] lowerVals = new double[dimensions];
double[] upperVals = new double[dimensions];
VectorApproximation queryApprox = calculatePartialApproximation(null, query, daFiles);
for(int i = 0; i < dimensions; i++) {
final double val = query.doubleValue(i);
lowerVals[i] = val - epsilon;
upperVals[i] = val + epsilon;
}
DoubleVector lowerEpsilon = DoubleVector.wrap(lowerVals);
VectorApproximation lowerEpsilonPartitions = calculatePartialApproximation(null, lowerEpsilon, daFiles);
DoubleVector upperEpsilon = DoubleVector.wrap(upperVals);
VectorApproximation upperEpsilonPartitions = calculatePartialApproximation(null, upperEpsilon, daFiles);
for(int i = 0; i < daFiles.size(); i++) {
int coeff = (queryApprox.getApproximation(i) - lowerEpsilonPartitions.getApproximation(i)) + (upperEpsilonPartitions.getApproximation(i) - queryApprox.getApproximation(i)) + 1;
daFiles.get(i).first = coeff;
}
} } | public class class_name {
protected static void calculateSelectivityCoeffs(List<DoubleObjPair<DAFile>> daFiles, NumberVector query, double epsilon) {
final int dimensions = query.getDimensionality();
double[] lowerVals = new double[dimensions];
double[] upperVals = new double[dimensions];
VectorApproximation queryApprox = calculatePartialApproximation(null, query, daFiles);
for(int i = 0; i < dimensions; i++) {
final double val = query.doubleValue(i);
lowerVals[i] = val - epsilon; // depends on control dependency: [for], data = [i]
upperVals[i] = val + epsilon; // depends on control dependency: [for], data = [i]
}
DoubleVector lowerEpsilon = DoubleVector.wrap(lowerVals);
VectorApproximation lowerEpsilonPartitions = calculatePartialApproximation(null, lowerEpsilon, daFiles);
DoubleVector upperEpsilon = DoubleVector.wrap(upperVals);
VectorApproximation upperEpsilonPartitions = calculatePartialApproximation(null, upperEpsilon, daFiles);
for(int i = 0; i < daFiles.size(); i++) {
int coeff = (queryApprox.getApproximation(i) - lowerEpsilonPartitions.getApproximation(i)) + (upperEpsilonPartitions.getApproximation(i) - queryApprox.getApproximation(i)) + 1;
daFiles.get(i).first = coeff; // depends on control dependency: [for], data = [i]
}
} } |
public class class_name {
public int checkCurrentCacheIsPhysical(Object data) throws DBException, RemoteException
{
int iErrorCode = Constants.NORMAL_RETURN;
Object objTargetRow = m_objCurrentCacheRecord;
if (objTargetRow != NONE)
{
if (m_mapCache != null)
{
int iTargetRow = ((Integer)objTargetRow).intValue();
int iCurrentPhysicalRecord = ((Integer)m_objCurrentPhysicalRecord).intValue();
if (iTargetRow != iCurrentPhysicalRecord)
{ // Current cached record has not been read... read it.
try {
if (m_bhtGet)
data = m_tableRemote.get(iTargetRow, 1);
else
{
//x Object dataRecord = m_mapCache.get(iTargetRow);
//x if (dataRecord instanceof Vector)
//x {
//x Object bookmark = ((Vector)dataRecord).get(0);
//x data = m_tableRemote.doSetHandle(bookmark, " *", 0);
//x }
throw new DBException("Can't update: Only read-only grid tables can be cached"); // Never (A moveNext is never updated)
}
if (data instanceof Vector)
m_objCurrentPhysicalRecord = objTargetRow; // Always
} catch (RemoteException ex) {
throw ex;
}
}
if (data != null)
if (data instanceof Vector)
m_mapCache.set(iTargetRow, data); // Make sure the cache matches the actual
m_objCurrentCacheRecord = objTargetRow;
}
if (m_htCache != null)
{
if (!objTargetRow.equals(m_objCurrentPhysicalRecord))
{ // Current cached record has not been read... read it.
try {
data = m_tableRemote.seek(Constants.EQUALS, Constants.OPEN_NORMAL | Constants.OPEN_DONT_UPDATE_LAST_READ, Constants.PRIMARY_KEY, null, objTargetRow);
if (data instanceof Vector)
{
m_objCurrentPhysicalRecord = objTargetRow; // Always
// Don't check the data, since the client doesn't handle mergeToCurrent (This should never happen, since I pass the OPEN_DONT_UPDATE_LAST_READ)
// Object oldData = m_htCache.get(objTargetRow); // Get the old copy
// if ((oldData != null) && (!oldData.equals(data)))
// iErrorCode = Constants.INVALID_RECORD; // Must have changed from the last time I read it.
}
else
iErrorCode = Constants.INVALID_RECORD; // Must have been deleted
} catch (RemoteException ex) {
throw ex;
}
}
if (data != null)
if (data instanceof Vector)
m_htCache.put(objTargetRow, data); // Make sure the cache matches the actual
m_objCurrentCacheRecord = objTargetRow;
}
}
return iErrorCode;
} } | public class class_name {
public int checkCurrentCacheIsPhysical(Object data) throws DBException, RemoteException
{
int iErrorCode = Constants.NORMAL_RETURN;
Object objTargetRow = m_objCurrentCacheRecord;
if (objTargetRow != NONE)
{
if (m_mapCache != null)
{
int iTargetRow = ((Integer)objTargetRow).intValue();
int iCurrentPhysicalRecord = ((Integer)m_objCurrentPhysicalRecord).intValue();
if (iTargetRow != iCurrentPhysicalRecord)
{ // Current cached record has not been read... read it.
try {
if (m_bhtGet)
data = m_tableRemote.get(iTargetRow, 1);
else
{
//x Object dataRecord = m_mapCache.get(iTargetRow);
//x if (dataRecord instanceof Vector)
//x {
//x Object bookmark = ((Vector)dataRecord).get(0);
//x data = m_tableRemote.doSetHandle(bookmark, " *", 0);
//x }
throw new DBException("Can't update: Only read-only grid tables can be cached"); // Never (A moveNext is never updated)
}
if (data instanceof Vector)
m_objCurrentPhysicalRecord = objTargetRow; // Always
} catch (RemoteException ex) {
throw ex;
}
}
if (data != null)
if (data instanceof Vector)
m_mapCache.set(iTargetRow, data); // Make sure the cache matches the actual
m_objCurrentCacheRecord = objTargetRow;
}
if (m_htCache != null)
{
if (!objTargetRow.equals(m_objCurrentPhysicalRecord))
{ // Current cached record has not been read... read it.
try {
data = m_tableRemote.seek(Constants.EQUALS, Constants.OPEN_NORMAL | Constants.OPEN_DONT_UPDATE_LAST_READ, Constants.PRIMARY_KEY, null, objTargetRow);
if (data instanceof Vector)
{
m_objCurrentPhysicalRecord = objTargetRow; // Always
// Don't check the data, since the client doesn't handle mergeToCurrent (This should never happen, since I pass the OPEN_DONT_UPDATE_LAST_READ)
// Object oldData = m_htCache.get(objTargetRow); // Get the old copy
// if ((oldData != null) && (!oldData.equals(data)))
// iErrorCode = Constants.INVALID_RECORD; // Must have changed from the last time I read it.
}
else
iErrorCode = Constants.INVALID_RECORD; // Must have been deleted
} catch (RemoteException ex) {
throw ex;
}
}
if (data != null)
if (data instanceof Vector)
m_htCache.put(objTargetRow, data); // Make sure the cache matches the actual
m_objCurrentCacheRecord = objTargetRow; // depends on control dependency: [if], data = [none]
}
}
return iErrorCode;
} } |
public class class_name {
protected boolean hasValidVersionSpecified( EnforcerRuleHelper helper, Plugin source, List<PluginWrapper> pluginWrappers )
{
boolean found = false;
boolean status = false;
for ( PluginWrapper plugin : pluginWrappers )
{
// find the matching plugin entry
if ( source.getArtifactId().equals( plugin.getArtifactId() )
&& source.getGroupId().equals( plugin.getGroupId() ) )
{
found = true;
// found the entry. now see if the version is specified
String version = plugin.getVersion();
try
{
version = (String) helper.evaluate( version );
}
catch ( ExpressionEvaluationException e )
{
return false;
}
if ( StringUtils.isNotEmpty( version ) && !StringUtils.isWhitespace( version ) )
{
if ( banRelease && version.equals( "RELEASE" ) )
{
return false;
}
if ( banLatest && version.equals( "LATEST" ) )
{
return false;
}
if ( banSnapshots && isSnapshot( version ) )
{
return false;
}
// the version was specified and not
// banned. It's ok. Keep looking through the list to make
// sure it's not using a banned version somewhere else.
status = true;
if ( !banRelease && !banLatest && !banSnapshots )
{
// no need to keep looking
break;
}
}
}
}
if ( !found )
{
log.debug( "plugin " + source.getGroupId() + ":" + source.getArtifactId() + " not found" );
}
return status;
} } | public class class_name {
protected boolean hasValidVersionSpecified( EnforcerRuleHelper helper, Plugin source, List<PluginWrapper> pluginWrappers )
{
boolean found = false;
boolean status = false;
for ( PluginWrapper plugin : pluginWrappers )
{
// find the matching plugin entry
if ( source.getArtifactId().equals( plugin.getArtifactId() )
&& source.getGroupId().equals( plugin.getGroupId() ) )
{
found = true; // depends on control dependency: [if], data = [none]
// found the entry. now see if the version is specified
String version = plugin.getVersion();
try
{
version = (String) helper.evaluate( version ); // depends on control dependency: [try], data = [none]
}
catch ( ExpressionEvaluationException e )
{
return false;
} // depends on control dependency: [catch], data = [none]
if ( StringUtils.isNotEmpty( version ) && !StringUtils.isWhitespace( version ) )
{
if ( banRelease && version.equals( "RELEASE" ) )
{
return false; // depends on control dependency: [if], data = [none]
}
if ( banLatest && version.equals( "LATEST" ) )
{
return false; // depends on control dependency: [if], data = [none]
}
if ( banSnapshots && isSnapshot( version ) )
{
return false; // depends on control dependency: [if], data = [none]
}
// the version was specified and not
// banned. It's ok. Keep looking through the list to make
// sure it's not using a banned version somewhere else.
status = true; // depends on control dependency: [if], data = [none]
if ( !banRelease && !banLatest && !banSnapshots )
{
// no need to keep looking
break;
}
}
}
}
if ( !found )
{
log.debug( "plugin " + source.getGroupId() + ":" + source.getArtifactId() + " not found" ); // depends on control dependency: [if], data = [none]
}
return status;
} } |
public class class_name {
private void applyWait(int emptyTimes) {
int newEmptyTimes = emptyTimes > maxEmptyTimes ? maxEmptyTimes : emptyTimes;
if (emptyTimes <= 3) { // 3次以内
Thread.yield();
} else { // 超过3次,最多只sleep 10ms
LockSupport.parkNanos(1000 * 1000L * newEmptyTimes);
}
} } | public class class_name {
private void applyWait(int emptyTimes) {
int newEmptyTimes = emptyTimes > maxEmptyTimes ? maxEmptyTimes : emptyTimes;
if (emptyTimes <= 3) { // 3次以内
Thread.yield(); // depends on control dependency: [if], data = [none]
} else { // 超过3次,最多只sleep 10ms
LockSupport.parkNanos(1000 * 1000L * newEmptyTimes); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public InviteUsersResult withInvites(Invite... invites) {
if (this.invites == null) {
setInvites(new java.util.ArrayList<Invite>(invites.length));
}
for (Invite ele : invites) {
this.invites.add(ele);
}
return this;
} } | public class class_name {
public InviteUsersResult withInvites(Invite... invites) {
if (this.invites == null) {
setInvites(new java.util.ArrayList<Invite>(invites.length)); // depends on control dependency: [if], data = [none]
}
for (Invite ele : invites) {
this.invites.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
@Override
public void init() {
String packageName = getCommands().get(getCommand());
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String path = packageName.replace('.', '/');
URL url = null;
try {
final Enumeration<URL> urls = classLoader.getResources(path);
while (urls.hasMoreElements()) {
url = urls.nextElement();
int index = url.toExternalForm().lastIndexOf(path);
url = new URL(url.toExternalForm().substring(0, index));
}
} catch (IOException e) {
throw new InitializationException("", e);
}
db = new AnnotationDB();
db.setScanClassAnnotations(true);
db.setScanMethodAnnotations(true);
try {
db.scanArchives(url);
} catch (IOException e) {
throw new InitializationException("", e);
}
} } | public class class_name {
@Override
public void init() {
String packageName = getCommands().get(getCommand());
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String path = packageName.replace('.', '/');
URL url = null;
try {
final Enumeration<URL> urls = classLoader.getResources(path);
while (urls.hasMoreElements()) {
url = urls.nextElement(); // depends on control dependency: [while], data = [none]
int index = url.toExternalForm().lastIndexOf(path);
url = new URL(url.toExternalForm().substring(0, index)); // depends on control dependency: [while], data = [none]
}
} catch (IOException e) {
throw new InitializationException("", e);
} // depends on control dependency: [catch], data = [none]
db = new AnnotationDB();
db.setScanClassAnnotations(true);
db.setScanMethodAnnotations(true);
try {
db.scanArchives(url); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new InitializationException("", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private void applyUserAgent(PutMediaRequest request, Request<PutMediaRequest> marshalled) {
if (!marshalled.getHeaders().containsKey("User-Agent")) {
marshalled.addHeader("User-Agent",
RuntimeHttpUtils.getUserAgent(new ClientConfiguration(),
request.getRequestClientOptions()
.getClientMarker(RequestClientOptions.Marker.USER_AGENT)));
}
} } | public class class_name {
private void applyUserAgent(PutMediaRequest request, Request<PutMediaRequest> marshalled) {
if (!marshalled.getHeaders().containsKey("User-Agent")) {
marshalled.addHeader("User-Agent",
RuntimeHttpUtils.getUserAgent(new ClientConfiguration(),
request.getRequestClientOptions()
.getClientMarker(RequestClientOptions.Marker.USER_AGENT))); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static String extractNameFromSchema(String schema, String schemaName, String fallbackName) {
String resolvedName = null;
if (schema != null) {
// if we have an array type we need to recurse into it
int startIdx = 0;
String type = extractTopItem("type", schema, startIdx);
if (type != null && type.equalsIgnoreCase("array")) {
int itemsIdx = schema.indexOf("\"items\"");
if (itemsIdx != -1) {
startIdx = itemsIdx + 7;
}
// lets check if we have a ref
String ref = extractTopItem("$ref", schema, startIdx);
if (ref != null) {
logger.info("Loading referenced schema " + ref);
ref = ref.replace("classpath:", "");
try {
schema = IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream(ref), "UTF-8");
startIdx = 0; // reset pointer since we recursed into
// schema
} catch (IOException e) {
logger.info("Erro Loading referenced schema " + ref, e);
}
}
}
// check if javaType can give us exact name
String javaType = extractTopItem("javaType", schema, startIdx);
if (StringUtils.hasText(javaType)) {
// do stuff to it
int dotIdx = javaType.lastIndexOf(".");
if (dotIdx > -1) {
javaType = javaType.substring(dotIdx + 1);
}
resolvedName = javaType;
} else {
String id = extractTopItem("id", schema, startIdx);
if (StringUtils.hasText(id)) {
// do stuff to it
if (id.startsWith("urn:") && ((id.lastIndexOf(":") + 1) < id.length())) {
id = id.substring(id.lastIndexOf(":") + 1);
} else if (id.startsWith(JSON_SCHEMA_IDENT)) {
if (id.length() > (JSON_SCHEMA_IDENT.length() + 3)) {
id = id.substring(JSON_SCHEMA_IDENT.length());
}
}
resolvedName = StringUtils.capitalize(id);
}
if (!NamingHelper.isValidJavaClassName(resolvedName)) {
if (NamingHelper.isValidJavaClassName(schemaName)) {
return StringUtils.capitalize(schemaName); // try schema
// name
} else {
resolvedName = fallbackName; // fallback to generated
}
}
}
}
return resolvedName;
} } | public class class_name {
public static String extractNameFromSchema(String schema, String schemaName, String fallbackName) {
String resolvedName = null;
if (schema != null) {
// if we have an array type we need to recurse into it
int startIdx = 0;
String type = extractTopItem("type", schema, startIdx);
if (type != null && type.equalsIgnoreCase("array")) {
int itemsIdx = schema.indexOf("\"items\"");
if (itemsIdx != -1) {
startIdx = itemsIdx + 7; // depends on control dependency: [if], data = [none]
}
// lets check if we have a ref
String ref = extractTopItem("$ref", schema, startIdx);
if (ref != null) {
logger.info("Loading referenced schema " + ref); // depends on control dependency: [if], data = [none]
ref = ref.replace("classpath:", ""); // depends on control dependency: [if], data = [none]
try {
schema = IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream(ref), "UTF-8"); // depends on control dependency: [try], data = [none]
startIdx = 0; // reset pointer since we recursed into // depends on control dependency: [try], data = [none]
// schema
} catch (IOException e) {
logger.info("Erro Loading referenced schema " + ref, e);
} // depends on control dependency: [catch], data = [none]
}
}
// check if javaType can give us exact name
String javaType = extractTopItem("javaType", schema, startIdx);
if (StringUtils.hasText(javaType)) {
// do stuff to it
int dotIdx = javaType.lastIndexOf(".");
if (dotIdx > -1) {
javaType = javaType.substring(dotIdx + 1); // depends on control dependency: [if], data = [(dotIdx]
}
resolvedName = javaType; // depends on control dependency: [if], data = [none]
} else {
String id = extractTopItem("id", schema, startIdx);
if (StringUtils.hasText(id)) {
// do stuff to it
if (id.startsWith("urn:") && ((id.lastIndexOf(":") + 1) < id.length())) {
id = id.substring(id.lastIndexOf(":") + 1); // depends on control dependency: [if], data = [none]
} else if (id.startsWith(JSON_SCHEMA_IDENT)) {
if (id.length() > (JSON_SCHEMA_IDENT.length() + 3)) {
id = id.substring(JSON_SCHEMA_IDENT.length()); // depends on control dependency: [if], data = [none]
}
}
resolvedName = StringUtils.capitalize(id); // depends on control dependency: [if], data = [none]
}
if (!NamingHelper.isValidJavaClassName(resolvedName)) {
if (NamingHelper.isValidJavaClassName(schemaName)) {
return StringUtils.capitalize(schemaName); // try schema // depends on control dependency: [if], data = [none]
// name
} else {
resolvedName = fallbackName; // fallback to generated // depends on control dependency: [if], data = [none]
}
}
}
}
return resolvedName;
} } |
public class class_name {
public boolean isActive(final org.apache.tools.ant.Project p) {
if (this.value == null) {
return false;
}
if (this.ifCond != null && p.getProperty(this.ifCond) == null) {
return false;
} else if (this.unlessCond != null && p.getProperty(this.unlessCond) != null) {
return false;
}
return true;
} } | public class class_name {
public boolean isActive(final org.apache.tools.ant.Project p) {
if (this.value == null) {
return false; // depends on control dependency: [if], data = [none]
}
if (this.ifCond != null && p.getProperty(this.ifCond) == null) {
return false; // depends on control dependency: [if], data = [none]
} else if (this.unlessCond != null && p.getProperty(this.unlessCond) != null) {
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
private void performInsertEOLogic(EngineeringObjectModelWrapper model) {
for (Field field : model.getForeignKeyFields()) {
mergeEngineeringObjectWithReferencedModel(field, model);
}
} } | public class class_name {
private void performInsertEOLogic(EngineeringObjectModelWrapper model) {
for (Field field : model.getForeignKeyFields()) {
mergeEngineeringObjectWithReferencedModel(field, model); // depends on control dependency: [for], data = [field]
}
} } |
public class class_name {
private void connected(final MemcachedNode node) {
assert node.getChannel().isConnected() : "Not connected.";
int rt = node.getReconnectCount();
node.connected();
for (ConnectionObserver observer : connObservers) {
observer.connectionEstablished(node.getSocketAddress(), rt);
}
} } | public class class_name {
private void connected(final MemcachedNode node) {
assert node.getChannel().isConnected() : "Not connected.";
int rt = node.getReconnectCount();
node.connected();
for (ConnectionObserver observer : connObservers) {
observer.connectionEstablished(node.getSocketAddress(), rt); // depends on control dependency: [for], data = [observer]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
public String generateDocumentId(String databaseName, Object entity) {
Class<?> clazz = entity.getClass();
for (Tuple<Class, BiFunction<String, Object, String>> listOfRegisteredIdConvention : _listOfRegisteredIdConventions) {
if (listOfRegisteredIdConvention.first.isAssignableFrom(clazz)) {
return listOfRegisteredIdConvention.second.apply(databaseName, entity);
}
}
return _documentIdGenerator.apply(databaseName, entity);
} } | public class class_name {
@SuppressWarnings("unchecked")
public String generateDocumentId(String databaseName, Object entity) {
Class<?> clazz = entity.getClass();
for (Tuple<Class, BiFunction<String, Object, String>> listOfRegisteredIdConvention : _listOfRegisteredIdConventions) {
if (listOfRegisteredIdConvention.first.isAssignableFrom(clazz)) {
return listOfRegisteredIdConvention.second.apply(databaseName, entity); // depends on control dependency: [if], data = [none]
}
}
return _documentIdGenerator.apply(databaseName, entity);
} } |
public class class_name {
public char match(String str1, String str2) {
if (null == str1 || null == str2 || 0 == str1.length() || 0 == str2.length()) {
return IMappingElement.IDK;
}
String[] grams1 = generateNGrams(str1, gramlength);
String[] grams2 = generateNGrams(str2, gramlength);
int count = 0;
for (String aGrams1 : grams1)
for (String aGrams2 : grams2) {
if (aGrams1.equals(aGrams2)) {
count++;
break;
}
}
float sim = (float) 2 * count / (grams1.length + grams2.length); // Dice-Coefficient
if (threshold <= sim) {
return IMappingElement.EQUIVALENCE;
} else {
return IMappingElement.IDK;
}
} } | public class class_name {
public char match(String str1, String str2) {
if (null == str1 || null == str2 || 0 == str1.length() || 0 == str2.length()) {
return IMappingElement.IDK;
// depends on control dependency: [if], data = [none]
}
String[] grams1 = generateNGrams(str1, gramlength);
String[] grams2 = generateNGrams(str2, gramlength);
int count = 0;
for (String aGrams1 : grams1)
for (String aGrams2 : grams2) {
if (aGrams1.equals(aGrams2)) {
count++;
// depends on control dependency: [if], data = [none]
break;
}
}
float sim = (float) 2 * count / (grams1.length + grams2.length); // Dice-Coefficient
if (threshold <= sim) {
return IMappingElement.EQUIVALENCE;
// depends on control dependency: [if], data = [none]
} else {
return IMappingElement.IDK;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void updateGalleryData(CmsContainerPageGalleryData galleryData, boolean viewChanged) {
if (m_dialog != null) {
if (viewChanged) {
m_dialog.removeFromParent();
m_dialog = null;
} else {
m_dialog.updateGalleryData(galleryData.getGalleryData());
}
}
m_galleryData = galleryData.getGalleryData();
m_search = galleryData.getGallerySearch();
} } | public class class_name {
public void updateGalleryData(CmsContainerPageGalleryData galleryData, boolean viewChanged) {
if (m_dialog != null) {
if (viewChanged) {
m_dialog.removeFromParent(); // depends on control dependency: [if], data = [none]
m_dialog = null; // depends on control dependency: [if], data = [none]
} else {
m_dialog.updateGalleryData(galleryData.getGalleryData()); // depends on control dependency: [if], data = [none]
}
}
m_galleryData = galleryData.getGalleryData();
m_search = galleryData.getGallerySearch();
} } |
public class class_name {
private static void formalTypeParameter(Result sb, TypeParameterElement typeParameter) throws IOException
{
sb.append(typeParameter.getSimpleName());
List<? extends TypeMirror> bounds = typeParameter.getBounds();
if (!bounds.isEmpty())
{
TypeMirror tm = bounds.get(0);
if (TypeKind.DECLARED == tm.getKind())
{
DeclaredType dt = (DeclaredType) tm;
if (ElementKind.CLASS != dt.asElement().getKind())
{
sb.append(':');
}
}
}
for (TypeMirror bound : bounds)
{
sb.append(':');
fieldTypeSignature(sb, bound);
}
} } | public class class_name {
private static void formalTypeParameter(Result sb, TypeParameterElement typeParameter) throws IOException
{
sb.append(typeParameter.getSimpleName());
List<? extends TypeMirror> bounds = typeParameter.getBounds();
if (!bounds.isEmpty())
{
TypeMirror tm = bounds.get(0);
if (TypeKind.DECLARED == tm.getKind())
{
DeclaredType dt = (DeclaredType) tm;
if (ElementKind.CLASS != dt.asElement().getKind())
{
sb.append(':'); // depends on control dependency: [if], data = [none]
}
}
}
for (TypeMirror bound : bounds)
{
sb.append(':');
fieldTypeSignature(sb, bound);
}
} } |
public class class_name {
public void setParameter(String name, Object value)
{
if (value == null) {
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_SET_PARAM_VALUE, new Object[]{name}));
}
if (null == m_params)
{
m_params = new Hashtable();
}
m_params.put(name, value);
} } | public class class_name {
public void setParameter(String name, Object value)
{
if (value == null) {
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_SET_PARAM_VALUE, new Object[]{name}));
}
if (null == m_params)
{
m_params = new Hashtable(); // depends on control dependency: [if], data = [none]
}
m_params.put(name, value);
} } |
public class class_name {
@Override
public Date getNextStart(long base, int prevRawOffset, int prevDSTSavings, boolean inclusive) {
int[] fields = Grego.timeToFields(base, null);
int year = fields[0];
if (year < startYear) {
return getFirstStart(prevRawOffset, prevDSTSavings);
}
Date d = getStartInYear(year, prevRawOffset, prevDSTSavings);
if (d != null && (d.getTime() < base || (!inclusive && (d.getTime() == base)))) {
d = getStartInYear(year + 1, prevRawOffset, prevDSTSavings);
}
return d;
} } | public class class_name {
@Override
public Date getNextStart(long base, int prevRawOffset, int prevDSTSavings, boolean inclusive) {
int[] fields = Grego.timeToFields(base, null);
int year = fields[0];
if (year < startYear) {
return getFirstStart(prevRawOffset, prevDSTSavings); // depends on control dependency: [if], data = [none]
}
Date d = getStartInYear(year, prevRawOffset, prevDSTSavings);
if (d != null && (d.getTime() < base || (!inclusive && (d.getTime() == base)))) {
d = getStartInYear(year + 1, prevRawOffset, prevDSTSavings); // depends on control dependency: [if], data = [none]
}
return d;
} } |
public class class_name {
public void marshall(BatchCreatePartitionRequest batchCreatePartitionRequest, ProtocolMarshaller protocolMarshaller) {
if (batchCreatePartitionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchCreatePartitionRequest.getCatalogId(), CATALOGID_BINDING);
protocolMarshaller.marshall(batchCreatePartitionRequest.getDatabaseName(), DATABASENAME_BINDING);
protocolMarshaller.marshall(batchCreatePartitionRequest.getTableName(), TABLENAME_BINDING);
protocolMarshaller.marshall(batchCreatePartitionRequest.getPartitionInputList(), PARTITIONINPUTLIST_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(BatchCreatePartitionRequest batchCreatePartitionRequest, ProtocolMarshaller protocolMarshaller) {
if (batchCreatePartitionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchCreatePartitionRequest.getCatalogId(), CATALOGID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchCreatePartitionRequest.getDatabaseName(), DATABASENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchCreatePartitionRequest.getTableName(), TABLENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchCreatePartitionRequest.getPartitionInputList(), PARTITIONINPUTLIST_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public ClassGraph blacklistClasspathElementsContainingResourcePath(final String... resourcePaths) {
for (final String resourcePath : resourcePaths) {
final String resourcePathNormalized = WhiteBlackList.normalizePath(resourcePath);
scanSpec.classpathElementResourcePathWhiteBlackList.addToBlacklist(resourcePathNormalized);
}
return this;
} } | public class class_name {
public ClassGraph blacklistClasspathElementsContainingResourcePath(final String... resourcePaths) {
for (final String resourcePath : resourcePaths) {
final String resourcePathNormalized = WhiteBlackList.normalizePath(resourcePath);
scanSpec.classpathElementResourcePathWhiteBlackList.addToBlacklist(resourcePathNormalized); // depends on control dependency: [for], data = [resourcePath]
}
return this;
} } |
public class class_name {
private void put(String name, BeanDefine beanDefine) {
if (pool.put(name, beanDefine) != null) {
log.warn("Duplicated Bean: {}", name);
}
} } | public class class_name {
private void put(String name, BeanDefine beanDefine) {
if (pool.put(name, beanDefine) != null) {
log.warn("Duplicated Bean: {}", name); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Service
public BulkResponse terminate(List<String> workflowIds, String reason) {
BulkResponse bulkResponse = new BulkResponse();
for (String workflowId : workflowIds) {
try {
workflowExecutor.terminateWorkflow(workflowId, reason);
bulkResponse.appendSuccessResponse(workflowId);
} catch (Exception e) {
LOGGER.error("bulk terminate exception, workflowId {}, message: {} ",workflowId, e.getMessage(), e);
bulkResponse.appendFailedResponse(workflowId, e.getMessage());
}
}
return bulkResponse;
} } | public class class_name {
@Service
public BulkResponse terminate(List<String> workflowIds, String reason) {
BulkResponse bulkResponse = new BulkResponse();
for (String workflowId : workflowIds) {
try {
workflowExecutor.terminateWorkflow(workflowId, reason); // depends on control dependency: [try], data = [none]
bulkResponse.appendSuccessResponse(workflowId); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
LOGGER.error("bulk terminate exception, workflowId {}, message: {} ",workflowId, e.getMessage(), e);
bulkResponse.appendFailedResponse(workflowId, e.getMessage());
} // depends on control dependency: [catch], data = [none]
}
return bulkResponse;
} } |
public class class_name {
public long ping(final Connection connection) throws DevFailed {
long result = 0;
final int maxRetries = connection.transparent_reconnection ? 1 : 0;
int nbRetries = 0;
boolean retry;
do {
try {
result = doPing(connection);
retry = false;
} catch (final DevFailed e) {
if (nbRetries < maxRetries) {
retry = true;
} else {
throw e;
}
nbRetries++;
}
} while (retry);
return result;
} } | public class class_name {
public long ping(final Connection connection) throws DevFailed {
long result = 0;
final int maxRetries = connection.transparent_reconnection ? 1 : 0;
int nbRetries = 0;
boolean retry;
do {
try {
result = doPing(connection); // depends on control dependency: [try], data = [none]
retry = false; // depends on control dependency: [try], data = [none]
} catch (final DevFailed e) {
if (nbRetries < maxRetries) {
retry = true; // depends on control dependency: [if], data = [none]
} else {
throw e;
}
nbRetries++;
} // depends on control dependency: [catch], data = [none]
} while (retry);
return result;
} } |
public class class_name {
protected void cleanup() {
int closed = 0;
SendBuffer buffer;
synchronized (buffers) {
int buffersToClose = buffers.size() - maxConnections;
if (buffersToClose < 1) {
return;
}
Iterator<SendBuffer> i = buffers.values().iterator();
while (i.hasNext()) {
buffer = i.next();
if (buffer.tryToClose()) {
i.remove();
closed++;
if (closed >= buffersToClose) {
return;
}
}
}
}
} } | public class class_name {
protected void cleanup() {
int closed = 0;
SendBuffer buffer;
synchronized (buffers) {
int buffersToClose = buffers.size() - maxConnections;
if (buffersToClose < 1) {
return;
// depends on control dependency: [if], data = [none]
}
Iterator<SendBuffer> i = buffers.values().iterator();
while (i.hasNext()) {
buffer = i.next();
// depends on control dependency: [while], data = [none]
if (buffer.tryToClose()) {
i.remove();
// depends on control dependency: [if], data = [none]
closed++;
// depends on control dependency: [if], data = [none]
if (closed >= buffersToClose) {
return;
// depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
@Override
protected MessageFormat resolveCode(String code, Locale locale)
{
String ret = null;
String country = locale.getCountry();
String language = locale.getLanguage();
String variant = locale.getVariant();
logger.debug("Code {} Initial locale {}",code,locale.toString());
Locale thisLocale = null;
if (!StringUtils.isEmpty(variant))
{
thisLocale = new Locale(language,country,variant);
Map<String,String> m = m_map.get(thisLocale);
if (m != null)
{
ret = m.get(code);
}
logger.debug("tried locale {} result: {}",thisLocale.toString(),ret);
}
if (ret == null)
{
if (!StringUtils.isEmpty(country))
{
thisLocale = new Locale(language,country);
Map<String,String> m = m_map.get(thisLocale);
if (m != null)
{
ret = m.get(code);
}
logger.debug("tried locale {} result: {}",thisLocale.toString(),ret);
}
}
if (ret == null)
{
if (!StringUtils.isEmpty(language))
{
thisLocale = new Locale(language);
Map<String,String> m = m_map.get(thisLocale);
if (m != null)
{
ret = m.get(code);
}
logger.debug("tried locale {} result: {}",thisLocale.toString(),ret);
}
}
if (ret == null)
{
thisLocale = Locale.getDefault();
Map<String,String> m = m_map.get(thisLocale);
if (m != null)
{
ret = m.get(code);
}
logger.debug("tried locale {} result: {}",thisLocale.toString(),ret);
}
if (ret == null)
{
return null;
}
return new MessageFormat(ret, locale);
} } | public class class_name {
@Override
protected MessageFormat resolveCode(String code, Locale locale)
{
String ret = null;
String country = locale.getCountry();
String language = locale.getLanguage();
String variant = locale.getVariant();
logger.debug("Code {} Initial locale {}",code,locale.toString());
Locale thisLocale = null;
if (!StringUtils.isEmpty(variant))
{
thisLocale = new Locale(language,country,variant); // depends on control dependency: [if], data = [none]
Map<String,String> m = m_map.get(thisLocale);
if (m != null)
{
ret = m.get(code); // depends on control dependency: [if], data = [none]
}
logger.debug("tried locale {} result: {}",thisLocale.toString(),ret); // depends on control dependency: [if], data = [none]
}
if (ret == null)
{
if (!StringUtils.isEmpty(country))
{
thisLocale = new Locale(language,country); // depends on control dependency: [if], data = [none]
Map<String,String> m = m_map.get(thisLocale);
if (m != null)
{
ret = m.get(code); // depends on control dependency: [if], data = [none]
}
logger.debug("tried locale {} result: {}",thisLocale.toString(),ret); // depends on control dependency: [if], data = [none]
}
}
if (ret == null)
{
if (!StringUtils.isEmpty(language))
{
thisLocale = new Locale(language); // depends on control dependency: [if], data = [none]
Map<String,String> m = m_map.get(thisLocale);
if (m != null)
{
ret = m.get(code); // depends on control dependency: [if], data = [none]
}
logger.debug("tried locale {} result: {}",thisLocale.toString(),ret); // depends on control dependency: [if], data = [none]
}
}
if (ret == null)
{
thisLocale = Locale.getDefault(); // depends on control dependency: [if], data = [none]
Map<String,String> m = m_map.get(thisLocale);
if (m != null)
{
ret = m.get(code); // depends on control dependency: [if], data = [none]
}
logger.debug("tried locale {} result: {}",thisLocale.toString(),ret); // depends on control dependency: [if], data = [none]
}
if (ret == null)
{
return null; // depends on control dependency: [if], data = [none]
}
return new MessageFormat(ret, locale);
} } |
public class class_name {
public static boolean sanityCheck(int flags) {
doCheck(flags, ConformanceFlags.CHECKED | ConformanceFlags.UNCHECKED);
if ((flags & ConformanceFlags.UNCHECKED) == 0) {
doCheck(flags, ConformanceFlags.CHECK_RESULTS);
} else if ((flags & (ConformanceFlags.SEALED | ConformanceFlags.CHECK_RESULTS)) != 0) {
throw new IllegalArgumentException("Invalid flags: " + toString(flags));
}
return true;
} } | public class class_name {
public static boolean sanityCheck(int flags) {
doCheck(flags, ConformanceFlags.CHECKED | ConformanceFlags.UNCHECKED);
if ((flags & ConformanceFlags.UNCHECKED) == 0) {
doCheck(flags, ConformanceFlags.CHECK_RESULTS); // depends on control dependency: [if], data = [none]
} else if ((flags & (ConformanceFlags.SEALED | ConformanceFlags.CHECK_RESULTS)) != 0) {
throw new IllegalArgumentException("Invalid flags: " + toString(flags));
}
return true;
} } |
public class class_name {
public static boolean validateIdCard15(String idCard) {
if (idCard.length() != CHINA_ID_MIN_LENGTH) {
return false;
}
if (isNum(idCard)) {
String proCode = idCard.substring(0, 2);
if (cityCodes.get(proCode) == null) {
return false;
}
String birthCode = idCard.substring(6, 12);
Date birthDate = null;
try {
birthDate = new SimpleDateFormat("yy").parse(birthCode.substring(0, 2));
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
if (birthDate != null) {
cal.setTime(birthDate);
}
if (!valiDate(cal.get(Calendar.YEAR), Integer.valueOf(birthCode.substring(2, 4)),
Integer.valueOf(birthCode.substring(4, 6)))) {
return false;
}
} else {
return false;
}
return true;
} } | public class class_name {
public static boolean validateIdCard15(String idCard) {
if (idCard.length() != CHINA_ID_MIN_LENGTH) {
return false; // depends on control dependency: [if], data = [none]
}
if (isNum(idCard)) {
String proCode = idCard.substring(0, 2);
if (cityCodes.get(proCode) == null) {
return false; // depends on control dependency: [if], data = [none]
}
String birthCode = idCard.substring(6, 12);
Date birthDate = null;
try {
birthDate = new SimpleDateFormat("yy").parse(birthCode.substring(0, 2)); // depends on control dependency: [try], data = [none]
} catch (ParseException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
Calendar cal = Calendar.getInstance();
if (birthDate != null) {
cal.setTime(birthDate); // depends on control dependency: [if], data = [(birthDate]
}
if (!valiDate(cal.get(Calendar.YEAR), Integer.valueOf(birthCode.substring(2, 4)),
Integer.valueOf(birthCode.substring(4, 6)))) {
return false; // depends on control dependency: [if], data = [none]
}
} else {
return false; // depends on control dependency: [if], data = [none]
}
return true;
} } |
public class class_name {
public static BundleContext getBundleContext(Class<?> clazz) {
BundleContext context = null; //we'll return null if not running inside an OSGi framework (e.g. unit test)
if (FrameworkState.isValid()) {
Bundle bundle = FrameworkUtil.getBundle(clazz);
if (bundle != null) {
context = bundle.getBundleContext();
}
}
return context;
} } | public class class_name {
public static BundleContext getBundleContext(Class<?> clazz) {
BundleContext context = null; //we'll return null if not running inside an OSGi framework (e.g. unit test)
if (FrameworkState.isValid()) {
Bundle bundle = FrameworkUtil.getBundle(clazz);
if (bundle != null) {
context = bundle.getBundleContext(); // depends on control dependency: [if], data = [none]
}
}
return context;
} } |
public class class_name {
public static void track(Window window) {
Preferences prefs = node().node("Windows");
String bounds = prefs.get(window.getName() + ".bounds", null);
if (bounds != null) {
Rectangle rect = (Rectangle) ConverterRegistry.instance().convert(
Rectangle.class, bounds);
window.setBounds(rect);
}
window.addComponentListener(WINDOW_DIMENSIONS);
} } | public class class_name {
public static void track(Window window) {
Preferences prefs = node().node("Windows");
String bounds = prefs.get(window.getName() + ".bounds", null);
if (bounds != null) {
Rectangle rect = (Rectangle) ConverterRegistry.instance().convert(
Rectangle.class, bounds);
window.setBounds(rect); // depends on control dependency: [if], data = [none]
}
window.addComponentListener(WINDOW_DIMENSIONS);
} } |
public class class_name {
protected void processSelectBody(SelectBody selectBody, int level) {
if (selectBody instanceof PlainSelect) {
processPlainSelect((PlainSelect) selectBody, level + 1);
} else if (selectBody instanceof WithItem) {
WithItem withItem = (WithItem) selectBody;
if (withItem.getSelectBody() != null) {
processSelectBody(withItem.getSelectBody(), level + 1);
}
} else {
SetOperationList operationList = (SetOperationList) selectBody;
if (operationList.getSelects() != null && operationList.getSelects().size() > 0) {
List<SelectBody> plainSelects = operationList.getSelects();
for (SelectBody plainSelect : plainSelects) {
processSelectBody(plainSelect, level + 1);
}
}
}
} } | public class class_name {
protected void processSelectBody(SelectBody selectBody, int level) {
if (selectBody instanceof PlainSelect) {
processPlainSelect((PlainSelect) selectBody, level + 1); // depends on control dependency: [if], data = [none]
} else if (selectBody instanceof WithItem) {
WithItem withItem = (WithItem) selectBody;
if (withItem.getSelectBody() != null) {
processSelectBody(withItem.getSelectBody(), level + 1); // depends on control dependency: [if], data = [(withItem.getSelectBody()]
}
} else {
SetOperationList operationList = (SetOperationList) selectBody;
if (operationList.getSelects() != null && operationList.getSelects().size() > 0) {
List<SelectBody> plainSelects = operationList.getSelects();
for (SelectBody plainSelect : plainSelects) {
processSelectBody(plainSelect, level + 1); // depends on control dependency: [for], data = [plainSelect]
}
}
}
} } |
public class class_name {
private boolean isRunningOutOfMemory() {
StorageLevel level = raft.getStorage().storageLevel();
if (level == StorageLevel.MEMORY || level == StorageLevel.MAPPED) {
long freeMemory = raft.getStorage().statistics().getFreeMemory();
long totalMemory = raft.getStorage().statistics().getTotalMemory();
if (freeMemory > 0 && totalMemory > 0) {
return freeMemory / (double) totalMemory < raft.getStorage().freeMemoryBuffer();
}
}
return false;
} } | public class class_name {
private boolean isRunningOutOfMemory() {
StorageLevel level = raft.getStorage().storageLevel();
if (level == StorageLevel.MEMORY || level == StorageLevel.MAPPED) {
long freeMemory = raft.getStorage().statistics().getFreeMemory();
long totalMemory = raft.getStorage().statistics().getTotalMemory();
if (freeMemory > 0 && totalMemory > 0) {
return freeMemory / (double) totalMemory < raft.getStorage().freeMemoryBuffer(); // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
public List<TargetRelationship> getRelatedLevelRelationships() {
final ArrayList<TargetRelationship> relationships = new ArrayList<TargetRelationship>();
for (final TargetRelationship relationship : levelRelationships) {
if (relationship.getType() == RelationshipType.REFER_TO) {
relationships.add(relationship);
}
}
return relationships;
} } | public class class_name {
public List<TargetRelationship> getRelatedLevelRelationships() {
final ArrayList<TargetRelationship> relationships = new ArrayList<TargetRelationship>();
for (final TargetRelationship relationship : levelRelationships) {
if (relationship.getType() == RelationshipType.REFER_TO) {
relationships.add(relationship); // depends on control dependency: [if], data = [none]
}
}
return relationships;
} } |
public class class_name {
public void drawArc(float x1, float y1, float width, float height,
int segments, float start, float end) {
predraw();
TextureImpl.bindNone();
currentColor.bind();
while (end < start) {
end += 360;
}
float cx = x1 + (width / 2.0f);
float cy = y1 + (height / 2.0f);
LSR.start();
int step = 360 / segments;
for (int a = (int) start; a < (int) (end + step); a += step) {
float ang = a;
if (ang > end) {
ang = end;
}
float x = (float) (cx + (FastTrig.cos(Math.toRadians(ang)) * width / 2.0f));
float y = (float) (cy + (FastTrig.sin(Math.toRadians(ang)) * height / 2.0f));
LSR.vertex(x,y);
}
LSR.end();
postdraw();
} } | public class class_name {
public void drawArc(float x1, float y1, float width, float height,
int segments, float start, float end) {
predraw();
TextureImpl.bindNone();
currentColor.bind();
while (end < start) {
end += 360;
// depends on control dependency: [while], data = [none]
}
float cx = x1 + (width / 2.0f);
float cy = y1 + (height / 2.0f);
LSR.start();
int step = 360 / segments;
for (int a = (int) start; a < (int) (end + step); a += step) {
float ang = a;
if (ang > end) {
ang = end;
// depends on control dependency: [if], data = [none]
}
float x = (float) (cx + (FastTrig.cos(Math.toRadians(ang)) * width / 2.0f));
float y = (float) (cy + (FastTrig.sin(Math.toRadians(ang)) * height / 2.0f));
LSR.vertex(x,y);
// depends on control dependency: [for], data = [none]
}
LSR.end();
postdraw();
} } |
public class class_name {
protected BeanDefinition lookupBeanDefinitions(final BeanReferences beanReferences) {
final int total = beanReferences.size();
for (int i = 0; i < total; i++) {
final String name = beanReferences.name(i);
BeanDefinition beanDefinition = lookupBeanDefinition(name);
if (beanDefinition != null) {
return beanDefinition;
}
}
return null;
} } | public class class_name {
protected BeanDefinition lookupBeanDefinitions(final BeanReferences beanReferences) {
final int total = beanReferences.size();
for (int i = 0; i < total; i++) {
final String name = beanReferences.name(i);
BeanDefinition beanDefinition = lookupBeanDefinition(name);
if (beanDefinition != null) {
return beanDefinition; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
public Download resumeDownload(PersistableDownload persistableDownload) {
assertParameterNotNull(persistableDownload,
"PausedDownload is mandatory to resume a download.");
GetObjectRequest request = new GetObjectRequest(
persistableDownload.getBucketName(), persistableDownload.getKey(),
persistableDownload.getVersionId());
if (persistableDownload.getRange() != null
&& persistableDownload.getRange().length == 2) {
long[] range = persistableDownload.getRange();
request.setRange(range[0], range[1]);
}
request.setRequesterPays(persistableDownload.isRequesterPays());
request.setResponseHeaders(persistableDownload.getResponseHeaders());
return doDownload(request, new File(persistableDownload.getFile()), null, null,
APPEND_MODE, 0,
persistableDownload);
} } | public class class_name {
public Download resumeDownload(PersistableDownload persistableDownload) {
assertParameterNotNull(persistableDownload,
"PausedDownload is mandatory to resume a download.");
GetObjectRequest request = new GetObjectRequest(
persistableDownload.getBucketName(), persistableDownload.getKey(),
persistableDownload.getVersionId());
if (persistableDownload.getRange() != null
&& persistableDownload.getRange().length == 2) {
long[] range = persistableDownload.getRange();
request.setRange(range[0], range[1]); // depends on control dependency: [if], data = [none]
}
request.setRequesterPays(persistableDownload.isRequesterPays());
request.setResponseHeaders(persistableDownload.getResponseHeaders());
return doDownload(request, new File(persistableDownload.getFile()), null, null,
APPEND_MODE, 0,
persistableDownload);
} } |
public class class_name {
private void asyncGetGlobalCapabilitities(final String[] domains,
final String interfaceName,
Collection<DiscoveryEntryWithMetaInfo> localDiscoveryEntries2,
long discoveryTimeout,
final CapabilitiesCallback capabilitiesCallback) {
final Collection<DiscoveryEntryWithMetaInfo> localDiscoveryEntries = localDiscoveryEntries2 == null
? new LinkedList<DiscoveryEntryWithMetaInfo>()
: localDiscoveryEntries2;
globalCapabilitiesDirectoryClient.lookup(new Callback<List<GlobalDiscoveryEntry>>() {
@Override
public void onSuccess(List<GlobalDiscoveryEntry> globalDiscoverEntries) {
if (globalDiscoverEntries != null) {
registerIncomingEndpoints(globalDiscoverEntries);
globalDiscoveryEntryCache.add(globalDiscoverEntries);
Collection<DiscoveryEntryWithMetaInfo> allDisoveryEntries = new ArrayList<DiscoveryEntryWithMetaInfo>(globalDiscoverEntries.size()
+ localDiscoveryEntries.size());
allDisoveryEntries.addAll(CapabilityUtils.convertToDiscoveryEntryWithMetaInfoList(false,
globalDiscoverEntries));
allDisoveryEntries.addAll(localDiscoveryEntries);
capabilitiesCallback.processCapabilitiesReceived(allDisoveryEntries);
} else {
capabilitiesCallback.onError(new NullPointerException("Received capabilities are null"));
}
}
@Override
public void onFailure(JoynrRuntimeException exception) {
capabilitiesCallback.onError(exception);
}
}, domains, interfaceName, discoveryTimeout);
} } | public class class_name {
private void asyncGetGlobalCapabilitities(final String[] domains,
final String interfaceName,
Collection<DiscoveryEntryWithMetaInfo> localDiscoveryEntries2,
long discoveryTimeout,
final CapabilitiesCallback capabilitiesCallback) {
final Collection<DiscoveryEntryWithMetaInfo> localDiscoveryEntries = localDiscoveryEntries2 == null
? new LinkedList<DiscoveryEntryWithMetaInfo>()
: localDiscoveryEntries2;
globalCapabilitiesDirectoryClient.lookup(new Callback<List<GlobalDiscoveryEntry>>() {
@Override
public void onSuccess(List<GlobalDiscoveryEntry> globalDiscoverEntries) {
if (globalDiscoverEntries != null) {
registerIncomingEndpoints(globalDiscoverEntries); // depends on control dependency: [if], data = [(globalDiscoverEntries]
globalDiscoveryEntryCache.add(globalDiscoverEntries); // depends on control dependency: [if], data = [(globalDiscoverEntries]
Collection<DiscoveryEntryWithMetaInfo> allDisoveryEntries = new ArrayList<DiscoveryEntryWithMetaInfo>(globalDiscoverEntries.size()
+ localDiscoveryEntries.size());
allDisoveryEntries.addAll(CapabilityUtils.convertToDiscoveryEntryWithMetaInfoList(false,
globalDiscoverEntries)); // depends on control dependency: [if], data = [none]
allDisoveryEntries.addAll(localDiscoveryEntries); // depends on control dependency: [if], data = [none]
capabilitiesCallback.processCapabilitiesReceived(allDisoveryEntries); // depends on control dependency: [if], data = [none]
} else {
capabilitiesCallback.onError(new NullPointerException("Received capabilities are null")); // depends on control dependency: [if], data = [none]
}
}
@Override
public void onFailure(JoynrRuntimeException exception) {
capabilitiesCallback.onError(exception);
}
}, domains, interfaceName, discoveryTimeout);
} } |
public class class_name {
protected void initialize(final UUID _commandUUID,
final String _openerId)
throws CacheReloadException
{
this.openerId = _openerId;
if (_commandUUID != null) {
final AbstractCommand command = getCommand(_commandUUID);
this.cmdUUID = command.getUUID();
setMode(command.getTargetMode());
this.target = command.getTarget();
this.submit = command.isSubmit();
if (command.getTargetSearch() != null && !(this instanceof UIMenuItem)) {
this.callingCmdUUID = this.cmdUUID;
this.cmdUUID = command.getTargetSearch().getDefaultCommand().getUUID();
setMode(TargetMode.SEARCH);
if (command.hasEvents(EventType.UI_COMMAND_EXECUTE)) {
this.submit = true;
}
}
}
} } | public class class_name {
protected void initialize(final UUID _commandUUID,
final String _openerId)
throws CacheReloadException
{
this.openerId = _openerId;
if (_commandUUID != null) {
final AbstractCommand command = getCommand(_commandUUID);
this.cmdUUID = command.getUUID();
setMode(command.getTargetMode());
this.target = command.getTarget();
this.submit = command.isSubmit();
if (command.getTargetSearch() != null && !(this instanceof UIMenuItem)) {
this.callingCmdUUID = this.cmdUUID;
this.cmdUUID = command.getTargetSearch().getDefaultCommand().getUUID();
setMode(TargetMode.SEARCH);
if (command.hasEvents(EventType.UI_COMMAND_EXECUTE)) {
this.submit = true; // depends on control dependency: [if], data = [none]
}
}
}
} } |
public class class_name {
@Override
public EClass getIfcMeasureValue() {
if (ifcMeasureValueEClass == null) {
ifcMeasureValueEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1141);
}
return ifcMeasureValueEClass;
} } | public class class_name {
@Override
public EClass getIfcMeasureValue() {
if (ifcMeasureValueEClass == null) {
ifcMeasureValueEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1141);
// depends on control dependency: [if], data = [none]
}
return ifcMeasureValueEClass;
} } |
public class class_name {
@VisibleForTesting
Path getWindowsPythonPath() {
String cloudSdkPython = System.getenv("CLOUDSDK_PYTHON");
if (cloudSdkPython != null) {
Path cloudSdkPythonPath = Paths.get(cloudSdkPython);
if (Files.exists(cloudSdkPythonPath)) {
return cloudSdkPythonPath;
} else {
throw new InvalidPathException(cloudSdkPython, "python binary not in specified location");
}
}
Path pythonPath = getPath().resolve(WINDOWS_BUNDLED_PYTHON);
if (Files.exists(pythonPath)) {
return pythonPath;
} else {
return Paths.get("python");
}
} } | public class class_name {
@VisibleForTesting
Path getWindowsPythonPath() {
String cloudSdkPython = System.getenv("CLOUDSDK_PYTHON");
if (cloudSdkPython != null) {
Path cloudSdkPythonPath = Paths.get(cloudSdkPython);
if (Files.exists(cloudSdkPythonPath)) {
return cloudSdkPythonPath; // depends on control dependency: [if], data = [none]
} else {
throw new InvalidPathException(cloudSdkPython, "python binary not in specified location");
}
}
Path pythonPath = getPath().resolve(WINDOWS_BUNDLED_PYTHON);
if (Files.exists(pythonPath)) {
return pythonPath; // depends on control dependency: [if], data = [none]
} else {
return Paths.get("python"); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static <T> List<List<T>> split(final List<T> list, final int count) {
List<List<T>> subIdLists = CollectUtils.newArrayList();
if (list.size() < count) {
subIdLists.add(list);
} else {
int i = 0;
while (i < list.size()) {
int end = i + count;
if (end > list.size()) {
end = list.size();
}
subIdLists.add(list.subList(i, end));
i += count;
}
}
return subIdLists;
} } | public class class_name {
public static <T> List<List<T>> split(final List<T> list, final int count) {
List<List<T>> subIdLists = CollectUtils.newArrayList();
if (list.size() < count) {
subIdLists.add(list); // depends on control dependency: [if], data = [none]
} else {
int i = 0;
while (i < list.size()) {
int end = i + count;
if (end > list.size()) {
end = list.size(); // depends on control dependency: [if], data = [none]
}
subIdLists.add(list.subList(i, end)); // depends on control dependency: [while], data = [(i]
i += count; // depends on control dependency: [while], data = [none]
}
}
return subIdLists;
} } |
public class class_name {
public Enumeration getResponses() throws MalformedElementException {
final Element firstResponse = getFirstChild(root, "response"); //$NON-NLS-1$
ensureNotNull(Policy.bind("ensure.missingResponseElmt"), firstResponse); //$NON-NLS-1$
Enumeration e = new Enumeration() {
Element currentResponse = firstResponse;
public boolean hasMoreElements() {
return currentResponse != null;
}
public Object nextElement() {
if (!hasMoreElements())
throw new NoSuchElementException();
ResponseBody responseBody = null;
try {
responseBody = new ResponseBody(currentResponse);
} catch (MalformedElementException ex) {
Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$
}
currentResponse = getTwin(currentResponse, true);
return responseBody;
}
};
return e;
} } | public class class_name {
public Enumeration getResponses() throws MalformedElementException {
final Element firstResponse = getFirstChild(root, "response"); //$NON-NLS-1$
ensureNotNull(Policy.bind("ensure.missingResponseElmt"), firstResponse); //$NON-NLS-1$
Enumeration e = new Enumeration() {
Element currentResponse = firstResponse;
public boolean hasMoreElements() {
return currentResponse != null;
}
public Object nextElement() {
if (!hasMoreElements())
throw new NoSuchElementException();
ResponseBody responseBody = null;
try {
responseBody = new ResponseBody(currentResponse); // depends on control dependency: [try], data = [none]
} catch (MalformedElementException ex) {
Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$
}
currentResponse = getTwin(currentResponse, true);
return responseBody;
} // depends on control dependency: [catch], data = [none]
};
return e;
} } |
public class class_name {
public void stop() {
try {
this.monitor.stop();
} catch( final Exception e ) {
this.logger.warning("Cannot stop template watcher");
Utils.logException(this.logger, e);
}
} } | public class class_name {
public void stop() {
try {
this.monitor.stop(); // depends on control dependency: [try], data = [none]
} catch( final Exception e ) {
this.logger.warning("Cannot stop template watcher");
Utils.logException(this.logger, e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public DomainQueryResult execute() {
DomainQueryResult ret = new DomainQueryResult(this);
Object so = this.queryExecutor.getMappingInfo().getInternalDomainAccess().getSyncObject();
if (so != null) {
synchronized (so) {
this.queryExecutor.execute();
}
} else
this.queryExecutor.execute();
return ret;
} } | public class class_name {
public DomainQueryResult execute() {
DomainQueryResult ret = new DomainQueryResult(this);
Object so = this.queryExecutor.getMappingInfo().getInternalDomainAccess().getSyncObject();
if (so != null) {
synchronized (so) { // depends on control dependency: [if], data = [(so]
this.queryExecutor.execute();
}
} else
this.queryExecutor.execute();
return ret;
} } |
public class class_name {
private static boolean missingFormatArgs(String value) {
try {
Formatter.check(value);
} catch (MissingFormatArgumentException e) {
return true;
} catch (Exception ignored) {
// we don't care about other errors (it isn't supposed to be a format string)
}
return false;
} } | public class class_name {
private static boolean missingFormatArgs(String value) {
try {
Formatter.check(value); // depends on control dependency: [try], data = [none]
} catch (MissingFormatArgumentException e) {
return true;
} catch (Exception ignored) { // depends on control dependency: [catch], data = [none]
// we don't care about other errors (it isn't supposed to be a format string)
} // depends on control dependency: [catch], data = [none]
return false;
} } |
public class class_name {
private Object exctractJsonifiedValue(ObjectToJsonConverter pConverter, Object pValue, Stack<String> pPathParts)
throws AttributeNotFoundException {
if (pValue.getClass().isPrimitive() || FINAL_CLASSES.contains(pValue.getClass()) || pValue instanceof JSONAware) {
// No further diving, use these directly
return pValue;
} else {
// For the rest we build up a JSON map with the attributes as keys and the value are
List<String> attributes = extractBeanAttributes(pValue);
if (attributes.size() > 0) {
return extractBeanValues(pConverter, pValue, pPathParts, attributes);
} else {
// No further attributes, return string representation
return pValue.toString();
}
}
} } | public class class_name {
private Object exctractJsonifiedValue(ObjectToJsonConverter pConverter, Object pValue, Stack<String> pPathParts)
throws AttributeNotFoundException {
if (pValue.getClass().isPrimitive() || FINAL_CLASSES.contains(pValue.getClass()) || pValue instanceof JSONAware) {
// No further diving, use these directly
return pValue;
} else {
// For the rest we build up a JSON map with the attributes as keys and the value are
List<String> attributes = extractBeanAttributes(pValue);
if (attributes.size() > 0) {
return extractBeanValues(pConverter, pValue, pPathParts, attributes); // depends on control dependency: [if], data = [none]
} else {
// No further attributes, return string representation
return pValue.toString(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private int removeTagByName(List<TagReference> tags, String tagName) {
List<TagReference> removeTags = new ArrayList<>();
for (TagReference tag : tags) {
if (Objects.equals(tagName, tag.getName())) {
removeTags.add(tag);
}
}
tags.removeAll(removeTags);
return removeTags.size();
} } | public class class_name {
private int removeTagByName(List<TagReference> tags, String tagName) {
List<TagReference> removeTags = new ArrayList<>();
for (TagReference tag : tags) {
if (Objects.equals(tagName, tag.getName())) {
removeTags.add(tag); // depends on control dependency: [if], data = [none]
}
}
tags.removeAll(removeTags);
return removeTags.size();
} } |
public class class_name {
@SuppressWarnings({"rawtypes", "unchecked"})
public static BsonDocument asBsonDocument(final Object document, final CodecRegistry codecRegistry) {
if (document == null) {
return null;
}
if (document instanceof BsonDocument) {
return (BsonDocument) document;
} else {
return new BsonDocumentWrapper(document, codecRegistry.get(document.getClass()));
}
} } | public class class_name {
@SuppressWarnings({"rawtypes", "unchecked"})
public static BsonDocument asBsonDocument(final Object document, final CodecRegistry codecRegistry) {
if (document == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (document instanceof BsonDocument) {
return (BsonDocument) document; // depends on control dependency: [if], data = [none]
} else {
return new BsonDocumentWrapper(document, codecRegistry.get(document.getClass())); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Conditionals addIfMatch(Tag tag) {
Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE));
Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH));
List<Tag> match = new ArrayList<>(this.match);
if (tag == null) {
tag = Tag.ALL;
}
if (Tag.ALL.equals(tag)) {
match.clear();
}
if (!match.contains(Tag.ALL)) {
if (!match.contains(tag)) {
match.add(tag);
}
}
else {
throw new IllegalArgumentException("Tag ALL already in the list");
}
return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince);
} } | public class class_name {
public Conditionals addIfMatch(Tag tag) {
Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE));
Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_NONE_MATCH));
List<Tag> match = new ArrayList<>(this.match);
if (tag == null) {
tag = Tag.ALL; // depends on control dependency: [if], data = [none]
}
if (Tag.ALL.equals(tag)) {
match.clear(); // depends on control dependency: [if], data = [none]
}
if (!match.contains(Tag.ALL)) {
if (!match.contains(tag)) {
match.add(tag); // depends on control dependency: [if], data = [none]
}
}
else {
throw new IllegalArgumentException("Tag ALL already in the list");
}
return new Conditionals(Collections.unmodifiableList(match), empty(), Optional.empty(), unModifiedSince);
} } |
public class class_name {
private void checkSQL(MethodDeclaration method, AnnotationProcessorEnvironment env) {
final JdbcControl.SQL methodSQL = method.getAnnotation(JdbcControl.SQL.class);
if (methodSQL == null) {
return;
}
//
// check for empty SQL statement member
//
if (methodSQL.statement() == null || methodSQL.statement().length() == 0) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.empty.statement", method.getSimpleName()));
return;
}
//
// Make sure maxrows is not set to some negative number other than -1
//
int maxRows = methodSQL.maxRows();
if (maxRows < JdbcControl.MAXROWS_ALL) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.bad.maxrows", method.getSimpleName(),maxRows));
return;
}
//
//
// parse the SQL
//
//
SqlParser _p = new SqlParser();
SqlStatement _statement;
try {
_statement = _p.parse(methodSQL.statement());
} catch (ControlException ce) {
env.getMessager().printError(method.getPosition(), getResourceString("jdbccontrol.bad.parse",
method.getSimpleName(),
ce.toString()));
return;
}
//
// Check that the any statement element params (delimited by '{' and '}' can be
// matched to method parameter names. NOTE: This check is only valid on non-compiled files,
// once compiled to a class file method parameter names are replaced with 'arg0', 'arg1', etc.
// and cannot be used for this check.
//
try {
ParameterChecker.checkReflectionParameters(_statement, method);
} catch (ControlException e) {
env.getMessager().printError(method.getPosition(), e.getMessage());
return;
}
//
// check for case of generatedKeyColumns being set, when getGeneratedKeys is not set to true
//
final boolean getGeneratedKeys = methodSQL.getGeneratedKeys();
final String[] generatedKeyColumnNames = methodSQL.generatedKeyColumnNames();
final int[] generatedKeyIndexes = methodSQL.generatedKeyColumnIndexes();
if (!getGeneratedKeys && (generatedKeyColumnNames.length != 0 || generatedKeyIndexes.length != 0)) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.genkeys", method.getSimpleName()));
return;
}
//
// check that both generatedKeyColumnNames and generatedKeyColumnIndexes are not set
//
if (generatedKeyColumnNames.length > 0 && generatedKeyIndexes.length > 0) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.genkeycolumns", method.getSimpleName()));
return;
}
//
// batch update methods must return int[]
//
final boolean batchUpdate = methodSQL.batchUpdate();
final TypeMirror returnType = method.getReturnType();
if (batchUpdate) {
if (returnType instanceof ArrayType) {
final TypeMirror aType = ((ArrayType) returnType).getComponentType();
if (aType instanceof PrimitiveType == false
|| ((PrimitiveType) aType).getKind() != PrimitiveType.Kind.INT) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.batchupdate", method.getSimpleName()));
return;
}
} else if (returnType instanceof VoidType == false) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.batchupdate", method.getSimpleName()));
return;
}
}
//
// iterator type check match
//
if (returnType instanceof InterfaceType) {
String iName = ((InterfaceType) returnType).getDeclaration().getQualifiedName();
if ("java.util.Iterator".equals(iName)) {
String iteratorClassName = null;
try {
// this should always except
methodSQL.iteratorElementType();
} catch (MirroredTypeException mte) {
iteratorClassName = mte.getQualifiedName();
}
if ("org.apache.beehive.controls.system.jdbc.JdbcControl.UndefinedIteratorType".equals(iteratorClassName)) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.iterator.returntype",
method.getSimpleName()));
return;
}
}
}
//
// scrollable result set check
//
final JdbcControl.ScrollType scrollable = methodSQL.scrollableResultSet();
switch (scrollable) {
case SCROLL_INSENSITIVE:
case SCROLL_SENSITIVE:
case SCROLL_INSENSITIVE_UPDATABLE:
case SCROLL_SENSITIVE_UPDATABLE:
case FORWARD_ONLY_UPDATABLE:
String typeName = null;
if (returnType instanceof DeclaredType) {
typeName = ((DeclaredType) returnType).getDeclaration().getQualifiedName();
}
if (typeName == null || !"java.sql.ResultSet".equals(typeName)) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.scrollresultset",
method.getSimpleName()));
return;
}
case FORWARD_ONLY:
default:
break;
}
return;
} } | public class class_name {
private void checkSQL(MethodDeclaration method, AnnotationProcessorEnvironment env) {
final JdbcControl.SQL methodSQL = method.getAnnotation(JdbcControl.SQL.class);
if (methodSQL == null) {
return; // depends on control dependency: [if], data = [none]
}
//
// check for empty SQL statement member
//
if (methodSQL.statement() == null || methodSQL.statement().length() == 0) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.empty.statement", method.getSimpleName())); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
//
// Make sure maxrows is not set to some negative number other than -1
//
int maxRows = methodSQL.maxRows();
if (maxRows < JdbcControl.MAXROWS_ALL) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.bad.maxrows", method.getSimpleName(),maxRows)); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
//
//
// parse the SQL
//
//
SqlParser _p = new SqlParser();
SqlStatement _statement;
try {
_statement = _p.parse(methodSQL.statement()); // depends on control dependency: [try], data = [none]
} catch (ControlException ce) {
env.getMessager().printError(method.getPosition(), getResourceString("jdbccontrol.bad.parse",
method.getSimpleName(),
ce.toString()));
return;
} // depends on control dependency: [catch], data = [none]
//
// Check that the any statement element params (delimited by '{' and '}' can be
// matched to method parameter names. NOTE: This check is only valid on non-compiled files,
// once compiled to a class file method parameter names are replaced with 'arg0', 'arg1', etc.
// and cannot be used for this check.
//
try {
ParameterChecker.checkReflectionParameters(_statement, method); // depends on control dependency: [try], data = [none]
} catch (ControlException e) {
env.getMessager().printError(method.getPosition(), e.getMessage());
return;
} // depends on control dependency: [catch], data = [none]
//
// check for case of generatedKeyColumns being set, when getGeneratedKeys is not set to true
//
final boolean getGeneratedKeys = methodSQL.getGeneratedKeys();
final String[] generatedKeyColumnNames = methodSQL.generatedKeyColumnNames();
final int[] generatedKeyIndexes = methodSQL.generatedKeyColumnIndexes();
if (!getGeneratedKeys && (generatedKeyColumnNames.length != 0 || generatedKeyIndexes.length != 0)) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.genkeys", method.getSimpleName())); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
//
// check that both generatedKeyColumnNames and generatedKeyColumnIndexes are not set
//
if (generatedKeyColumnNames.length > 0 && generatedKeyIndexes.length > 0) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.genkeycolumns", method.getSimpleName())); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
//
// batch update methods must return int[]
//
final boolean batchUpdate = methodSQL.batchUpdate();
final TypeMirror returnType = method.getReturnType();
if (batchUpdate) {
if (returnType instanceof ArrayType) {
final TypeMirror aType = ((ArrayType) returnType).getComponentType();
if (aType instanceof PrimitiveType == false
|| ((PrimitiveType) aType).getKind() != PrimitiveType.Kind.INT) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.batchupdate", method.getSimpleName())); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
} else if (returnType instanceof VoidType == false) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.batchupdate", method.getSimpleName())); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
//
// iterator type check match
//
if (returnType instanceof InterfaceType) {
String iName = ((InterfaceType) returnType).getDeclaration().getQualifiedName();
if ("java.util.Iterator".equals(iName)) {
String iteratorClassName = null;
try {
// this should always except
methodSQL.iteratorElementType(); // depends on control dependency: [try], data = [none]
} catch (MirroredTypeException mte) {
iteratorClassName = mte.getQualifiedName();
} // depends on control dependency: [catch], data = [none]
if ("org.apache.beehive.controls.system.jdbc.JdbcControl.UndefinedIteratorType".equals(iteratorClassName)) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.iterator.returntype",
method.getSimpleName())); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
}
}
//
// scrollable result set check
//
final JdbcControl.ScrollType scrollable = methodSQL.scrollableResultSet();
switch (scrollable) {
case SCROLL_INSENSITIVE:
case SCROLL_SENSITIVE:
case SCROLL_INSENSITIVE_UPDATABLE:
case SCROLL_SENSITIVE_UPDATABLE:
case FORWARD_ONLY_UPDATABLE:
String typeName = null;
if (returnType instanceof DeclaredType) {
typeName = ((DeclaredType) returnType).getDeclaration().getQualifiedName(); // depends on control dependency: [if], data = [none]
}
if (typeName == null || !"java.sql.ResultSet".equals(typeName)) {
env.getMessager().printError(method.getPosition(),
getResourceString("jdbccontrol.scrollresultset",
method.getSimpleName())); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
case FORWARD_ONLY:
default:
break;
}
return;
} } |
public class class_name {
public final EObject entryRuleJvmParameterizedTypeReference() throws RecognitionException {
EObject current = null;
EObject iv_ruleJvmParameterizedTypeReference = null;
try {
// InternalXbase.g:5598:70: (iv_ruleJvmParameterizedTypeReference= ruleJvmParameterizedTypeReference EOF )
// InternalXbase.g:5599:2: iv_ruleJvmParameterizedTypeReference= ruleJvmParameterizedTypeReference EOF
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getJvmParameterizedTypeReferenceRule());
}
pushFollow(FOLLOW_1);
iv_ruleJvmParameterizedTypeReference=ruleJvmParameterizedTypeReference();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current =iv_ruleJvmParameterizedTypeReference;
}
match(input,EOF,FOLLOW_2); if (state.failed) return current;
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } | public class class_name {
public final EObject entryRuleJvmParameterizedTypeReference() throws RecognitionException {
EObject current = null;
EObject iv_ruleJvmParameterizedTypeReference = null;
try {
// InternalXbase.g:5598:70: (iv_ruleJvmParameterizedTypeReference= ruleJvmParameterizedTypeReference EOF )
// InternalXbase.g:5599:2: iv_ruleJvmParameterizedTypeReference= ruleJvmParameterizedTypeReference EOF
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getJvmParameterizedTypeReferenceRule()); // depends on control dependency: [if], data = [none]
}
pushFollow(FOLLOW_1);
iv_ruleJvmParameterizedTypeReference=ruleJvmParameterizedTypeReference();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current =iv_ruleJvmParameterizedTypeReference; // depends on control dependency: [if], data = [none]
}
match(input,EOF,FOLLOW_2); if (state.failed) return current;
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} } |
public class class_name {
public String getResult() {
String res;
CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(m_siteRoot);
if (site == null) {
res = CmsVaadinUtils.getMessageText(Messages.GUI_DATABASEAPP_STATS_RESULTS_ROOT_1, new Integer(m_count));
} else {
res = CmsVaadinUtils.getMessageText(
Messages.GUI_DATABASEAPP_STATS_RESULTS_2,
site.getTitle(),
new Integer(m_count));
}
return res;
} } | public class class_name {
public String getResult() {
String res;
CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(m_siteRoot);
if (site == null) {
res = CmsVaadinUtils.getMessageText(Messages.GUI_DATABASEAPP_STATS_RESULTS_ROOT_1, new Integer(m_count)); // depends on control dependency: [if], data = [none]
} else {
res = CmsVaadinUtils.getMessageText(
Messages.GUI_DATABASEAPP_STATS_RESULTS_2,
site.getTitle(),
new Integer(m_count)); // depends on control dependency: [if], data = [none]
}
return res;
} } |
public class class_name {
private List<Object> buildMetadataArgs(
String line,
String paramName,
String[] defaultValues) {
final List<Object> list = new ArrayList<>();
final String[][] ret = sqlLine.splitCompound(line);
String[] compound;
if (ret == null || ret.length != 2) {
if (defaultValues[defaultValues.length - 1] == null) {
throw new IllegalArgumentException(
sqlLine.loc("arg-usage",
ret == null || ret.length == 0 ? "" : ret[0][0], paramName));
}
compound = new String[0];
} else {
compound = ret[1];
}
if (compound.length <= defaultValues.length) {
list.addAll(
Arrays.asList(defaultValues).subList(
0, defaultValues.length - compound.length));
list.addAll(Arrays.asList(compound));
} else {
list.addAll(
Arrays.asList(compound).subList(0, defaultValues.length));
}
return list;
} } | public class class_name {
private List<Object> buildMetadataArgs(
String line,
String paramName,
String[] defaultValues) {
final List<Object> list = new ArrayList<>();
final String[][] ret = sqlLine.splitCompound(line);
String[] compound;
if (ret == null || ret.length != 2) {
if (defaultValues[defaultValues.length - 1] == null) {
throw new IllegalArgumentException(
sqlLine.loc("arg-usage",
ret == null || ret.length == 0 ? "" : ret[0][0], paramName));
}
compound = new String[0]; // depends on control dependency: [if], data = [none]
} else {
compound = ret[1]; // depends on control dependency: [if], data = [none]
}
if (compound.length <= defaultValues.length) {
list.addAll(
Arrays.asList(defaultValues).subList(
0, defaultValues.length - compound.length)); // depends on control dependency: [if], data = [none]
list.addAll(Arrays.asList(compound)); // depends on control dependency: [if], data = [none]
} else {
list.addAll(
Arrays.asList(compound).subList(0, defaultValues.length)); // depends on control dependency: [if], data = [none]
}
return list;
} } |
public class class_name {
@SuppressWarnings("rawtypes")
public boolean contains(Class exType) {
if (exType == null) {
return false;
}
if (exType.isInstance(this)) {
return true;
}
Throwable cause = getCause();
if (cause == this) {
return false;
}
if (cause instanceof NestedException) {
return ((NestedException) cause).contains(exType);
} else {
while (cause != null) {
if (exType.isInstance(cause)) {
return true;
}
if (cause.getCause() == cause) {
break;
}
cause = cause.getCause();
}
return false;
}
} } | public class class_name {
@SuppressWarnings("rawtypes")
public boolean contains(Class exType) {
if (exType == null) {
return false; // depends on control dependency: [if], data = [none]
}
if (exType.isInstance(this)) {
return true; // depends on control dependency: [if], data = [none]
}
Throwable cause = getCause();
if (cause == this) {
return false; // depends on control dependency: [if], data = [none]
}
if (cause instanceof NestedException) {
return ((NestedException) cause).contains(exType); // depends on control dependency: [if], data = [none]
} else {
while (cause != null) {
if (exType.isInstance(cause)) {
return true; // depends on control dependency: [if], data = [none]
}
if (cause.getCause() == cause) {
break;
}
cause = cause.getCause(); // depends on control dependency: [while], data = [none]
}
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public int getRow() {
if(_currentRow != null) {
int row = _currentRow.intValue();
/* if the row is out of range, simply adjust to the last row */
if(_dataSetSize != null && (row > _dataSetSize.intValue()))
row = _dataSetSize.intValue();
if(row % getPageSize() != 0) {
int adjustedPage = row - (row % getPageSize());
return adjustedPage;
}
else return row;
}
else return DEFAULT_ROW;
} } | public class class_name {
public int getRow() {
if(_currentRow != null) {
int row = _currentRow.intValue();
/* if the row is out of range, simply adjust to the last row */
if(_dataSetSize != null && (row > _dataSetSize.intValue()))
row = _dataSetSize.intValue();
if(row % getPageSize() != 0) {
int adjustedPage = row - (row % getPageSize());
return adjustedPage; // depends on control dependency: [if], data = [none]
}
else return row;
}
else return DEFAULT_ROW;
} } |
public class class_name {
public static boolean beginOrJoinTransaction()
{
boolean newTransaction = false;
try {
newTransaction = userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION;
if (newTransaction) {
userTransaction.begin();
}
}
catch (Exception e) {
throw new RuntimeException("Unable to start transaction.", e);
}
return newTransaction;
} } | public class class_name {
public static boolean beginOrJoinTransaction()
{
boolean newTransaction = false;
try {
newTransaction = userTransaction.getStatus() == Status.STATUS_NO_TRANSACTION; // depends on control dependency: [try], data = [none]
if (newTransaction) {
userTransaction.begin(); // depends on control dependency: [if], data = [none]
}
}
catch (Exception e) {
throw new RuntimeException("Unable to start transaction.", e);
} // depends on control dependency: [catch], data = [none]
return newTransaction;
} } |
public class class_name {
public final void additiveExpression() throws RecognitionException {
int additiveExpression_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 122) ) { return; }
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1188:5: ( multiplicativeExpression ( ( '+' | '-' ) multiplicativeExpression )* )
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1188:9: multiplicativeExpression ( ( '+' | '-' ) multiplicativeExpression )*
{
pushFollow(FOLLOW_multiplicativeExpression_in_additiveExpression5410);
multiplicativeExpression();
state._fsp--;
if (state.failed) return;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1188:34: ( ( '+' | '-' ) multiplicativeExpression )*
loop154:
while (true) {
int alt154=2;
int LA154_0 = input.LA(1);
if ( (LA154_0==40||LA154_0==44) ) {
alt154=1;
}
switch (alt154) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1188:36: ( '+' | '-' ) multiplicativeExpression
{
if ( input.LA(1)==40||input.LA(1)==44 ) {
input.consume();
state.errorRecovery=false;
state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
pushFollow(FOLLOW_multiplicativeExpression_in_additiveExpression5422);
multiplicativeExpression();
state._fsp--;
if (state.failed) return;
}
break;
default :
break loop154;
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
if ( state.backtracking>0 ) { memoize(input, 122, additiveExpression_StartIndex); }
}
} } | public class class_name {
public final void additiveExpression() throws RecognitionException {
int additiveExpression_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 122) ) { return; } // depends on control dependency: [if], data = [none]
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1188:5: ( multiplicativeExpression ( ( '+' | '-' ) multiplicativeExpression )* )
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1188:9: multiplicativeExpression ( ( '+' | '-' ) multiplicativeExpression )*
{
pushFollow(FOLLOW_multiplicativeExpression_in_additiveExpression5410);
multiplicativeExpression();
state._fsp--;
if (state.failed) return;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1188:34: ( ( '+' | '-' ) multiplicativeExpression )*
loop154:
while (true) {
int alt154=2;
int LA154_0 = input.LA(1);
if ( (LA154_0==40||LA154_0==44) ) {
alt154=1; // depends on control dependency: [if], data = [none]
}
switch (alt154) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1188:36: ( '+' | '-' ) multiplicativeExpression
{
if ( input.LA(1)==40||input.LA(1)==44 ) {
input.consume(); // depends on control dependency: [if], data = [none]
state.errorRecovery=false; // depends on control dependency: [if], data = [none]
state.failed=false; // depends on control dependency: [if], data = [none]
}
else {
if (state.backtracking>0) {state.failed=true; return;} // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
pushFollow(FOLLOW_multiplicativeExpression_in_additiveExpression5422);
multiplicativeExpression();
state._fsp--;
if (state.failed) return;
}
break;
default :
break loop154;
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
if ( state.backtracking>0 ) { memoize(input, 122, additiveExpression_StartIndex); } // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public boolean hasNext() {
if(done) return false;
if(cachedNext != null) {
return true;
}
while(inner.hasNext()) {
String tmp = inner.next();
if(tmp.startsWith(prefix)) {
cachedNext = tmp;
return true;
} else if(tmp.compareTo(prefix) > 0) {
done = true;
return false;
}
}
return false;
} } | public class class_name {
public boolean hasNext() {
if(done) return false;
if(cachedNext != null) {
return true; // depends on control dependency: [if], data = [none]
}
while(inner.hasNext()) {
String tmp = inner.next();
if(tmp.startsWith(prefix)) {
cachedNext = tmp; // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
} else if(tmp.compareTo(prefix) > 0) {
done = true; // depends on control dependency: [if], data = [none]
return false; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
private void initialize() {
if (locale == null) {
locale = ULocale.getDefault(Category.FORMAT);
}
if (formatData == null) {
formatData = new DateFormatSymbols(locale);
}
if (calendar == null) {
calendar = Calendar.getInstance(locale);
}
if (numberFormat == null) {
NumberingSystem ns = NumberingSystem.getInstance(locale);
if (ns.isAlgorithmic()) {
numberFormat = NumberFormat.getInstance(locale);
} else {
String digitString = ns.getDescription();
String nsName = ns.getName();
// Use a NumberFormat optimized for date formatting
numberFormat = new DateNumberFormat(locale, digitString, nsName);
}
}
// Note: deferring calendar calculation until when we really need it.
// Instead, we just record time of construction for backward compatibility.
defaultCenturyBase = System.currentTimeMillis();
setLocale(calendar.getLocale(ULocale.VALID_LOCALE ), calendar.getLocale(ULocale.ACTUAL_LOCALE));
initLocalZeroPaddingNumberFormat();
if (override != null) {
initNumberFormatters(locale);
}
parsePattern();
} } | public class class_name {
private void initialize() {
if (locale == null) {
locale = ULocale.getDefault(Category.FORMAT); // depends on control dependency: [if], data = [none]
}
if (formatData == null) {
formatData = new DateFormatSymbols(locale); // depends on control dependency: [if], data = [none]
}
if (calendar == null) {
calendar = Calendar.getInstance(locale); // depends on control dependency: [if], data = [none]
}
if (numberFormat == null) {
NumberingSystem ns = NumberingSystem.getInstance(locale);
if (ns.isAlgorithmic()) {
numberFormat = NumberFormat.getInstance(locale); // depends on control dependency: [if], data = [none]
} else {
String digitString = ns.getDescription();
String nsName = ns.getName();
// Use a NumberFormat optimized for date formatting
numberFormat = new DateNumberFormat(locale, digitString, nsName); // depends on control dependency: [if], data = [none]
}
}
// Note: deferring calendar calculation until when we really need it.
// Instead, we just record time of construction for backward compatibility.
defaultCenturyBase = System.currentTimeMillis();
setLocale(calendar.getLocale(ULocale.VALID_LOCALE ), calendar.getLocale(ULocale.ACTUAL_LOCALE));
initLocalZeroPaddingNumberFormat();
if (override != null) {
initNumberFormatters(locale); // depends on control dependency: [if], data = [none]
}
parsePattern();
} } |
public class class_name {
@UiHandler("m_seriesCheckBox")
void onSeriesChange(ValueChangeEvent<Boolean> event) {
if (handleChange()) {
m_controller.setIsSeries(event.getValue());
}
} } | public class class_name {
@UiHandler("m_seriesCheckBox")
void onSeriesChange(ValueChangeEvent<Boolean> event) {
if (handleChange()) {
m_controller.setIsSeries(event.getValue()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void put(double val) {
if(this.n == 0) {
n = 1.;
min = max = sum = val;
m2 = m3 = m4 = 0;
return;
}
final double nn = this.n + 1.0;
final double deltan = val * n - sum;
final double delta_nn = deltan / (n * nn);
final double delta_nn2 = delta_nn * delta_nn;
final double inc = deltan * delta_nn;
// Update values:
m4 += inc * delta_nn2 * (nn * (nn - 3.) + 3.) + 6. * delta_nn2 * m2 - 4. * delta_nn * m3;
m3 += inc * delta_nn * (nn - 2) - 3. * delta_nn * m2;
m2 += inc;
sum += val;
n = nn;
min = Math.min(min, val);
max = Math.max(max, val);
} } | public class class_name {
@Override
public void put(double val) {
if(this.n == 0) {
n = 1.; // depends on control dependency: [if], data = [none]
min = max = sum = val; // depends on control dependency: [if], data = [none]
m2 = m3 = m4 = 0; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
final double nn = this.n + 1.0;
final double deltan = val * n - sum;
final double delta_nn = deltan / (n * nn);
final double delta_nn2 = delta_nn * delta_nn;
final double inc = deltan * delta_nn;
// Update values:
m4 += inc * delta_nn2 * (nn * (nn - 3.) + 3.) + 6. * delta_nn2 * m2 - 4. * delta_nn * m3;
m3 += inc * delta_nn * (nn - 2) - 3. * delta_nn * m2;
m2 += inc;
sum += val;
n = nn;
min = Math.min(min, val);
max = Math.max(max, val);
} } |
public class class_name {
void onItemsChanged(boolean structureChanged) {
if (!mPreventDispatchingItemsChanged) {
if (structureChanged) {
mIsVisibleItemsStale = true;
mIsActionItemsStale = true;
}
dispatchPresenterUpdate(structureChanged);
} else {
mItemsChangedWhileDispatchPrevented = true;
}
} } | public class class_name {
void onItemsChanged(boolean structureChanged) {
if (!mPreventDispatchingItemsChanged) {
if (structureChanged) {
mIsVisibleItemsStale = true; // depends on control dependency: [if], data = [none]
mIsActionItemsStale = true; // depends on control dependency: [if], data = [none]
}
dispatchPresenterUpdate(structureChanged); // depends on control dependency: [if], data = [none]
} else {
mItemsChangedWhileDispatchPrevented = true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void addRule(ElementSelector elementSelector, Action action) {
action.setContext(context);
List<Action> a4p = rules.get(elementSelector);
if (a4p == null) {
a4p = new ArrayList<Action>();
rules.put(elementSelector, a4p);
}
a4p.add(action);
} } | public class class_name {
public void addRule(ElementSelector elementSelector, Action action) {
action.setContext(context);
List<Action> a4p = rules.get(elementSelector);
if (a4p == null) {
a4p = new ArrayList<Action>(); // depends on control dependency: [if], data = [none]
rules.put(elementSelector, a4p); // depends on control dependency: [if], data = [none]
}
a4p.add(action);
} } |
public class class_name {
public static byte[] decodeHex(final String value) {
// if string length is odd then throw exception
if (value.length() % 2 != 0) {
throw new NumberFormatException("odd number of characters in hex string");
}
byte[] bytes = new byte[value.length() / 2];
for (int i = 0; i < value.length(); i += 2) {
bytes[i / 2] = (byte) Integer.parseInt(value.substring(i, i + 2), 16);
}
return bytes;
} } | public class class_name {
public static byte[] decodeHex(final String value) {
// if string length is odd then throw exception
if (value.length() % 2 != 0) {
throw new NumberFormatException("odd number of characters in hex string");
}
byte[] bytes = new byte[value.length() / 2];
for (int i = 0; i < value.length(); i += 2) {
bytes[i / 2] = (byte) Integer.parseInt(value.substring(i, i + 2), 16); // depends on control dependency: [for], data = [i]
}
return bytes;
} } |
public class class_name {
private <R> R tryTwice(Supplier<R> action) {
try {
return action.get();
} catch (UnknownIndexException e) {
waitForIndexToBeStable();
try {
return action.get();
} catch (UnknownIndexException e1) {
throw new MolgenisDataException(
format(
"Error executing query, index for entity type '%s' with id '%s' does not exist",
getEntityType().getLabel(), getEntityType().getId()));
}
}
} } | public class class_name {
private <R> R tryTwice(Supplier<R> action) {
try {
return action.get(); // depends on control dependency: [try], data = [none]
} catch (UnknownIndexException e) {
waitForIndexToBeStable();
try {
return action.get(); // depends on control dependency: [try], data = [none]
} catch (UnknownIndexException e1) {
throw new MolgenisDataException(
format(
"Error executing query, index for entity type '%s' with id '%s' does not exist",
getEntityType().getLabel(), getEntityType().getId()));
} // depends on control dependency: [catch], data = [none]
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
synchronized void execute(File root, Runnable task) {
if (executors == null) {
throw new RuntimeException("AsyncDiskService is already shutdown");
}
ThreadPoolExecutor executor = executors.get(root);
if (executor == null) {
throw new RuntimeException("Cannot find root " + root
+ " for execution of task " + task);
} else {
executor.execute(task);
}
} } | public class class_name {
synchronized void execute(File root, Runnable task) {
if (executors == null) {
throw new RuntimeException("AsyncDiskService is already shutdown");
}
ThreadPoolExecutor executor = executors.get(root);
if (executor == null) {
throw new RuntimeException("Cannot find root " + root
+ " for execution of task " + task);
} else {
executor.execute(task); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected HeartbeatResponse transmitHeartBeat(
InterTrackerProtocol jobClient, short heartbeatResponseId,
TaskTrackerStatus status) throws IOException {
//
// Check if we should ask for a new Task
//
boolean askForNewTask;
long localMinSpaceStart;
synchronized (this) {
askForNewTask =
((status.countOccupiedMapSlots() < maxMapSlots ||
status.countOccupiedReduceSlots() < maxReduceSlots) &&
acceptNewTasks);
localMinSpaceStart = minSpaceStart;
}
if (askForNewTask) {
checkLocalDirs(getLocalDirsFromConf(fConf));
askForNewTask = enoughFreeSpace(localMinSpaceStart);
gatherResourceStatus(status);
}
//add node health information
TaskTrackerHealthStatus healthStatus = status.getHealthStatus();
synchronized (this) {
if (healthChecker != null) {
healthChecker.setHealthStatus(healthStatus);
} else {
healthStatus.setNodeHealthy(true);
healthStatus.setLastReported(0L);
healthStatus.setHealthReport("");
}
}
//
// Xmit the heartbeat
//
HeartbeatResponse heartbeatResponse = jobClient.heartbeat(status,
justStarted,
justInited,
askForNewTask,
heartbeatResponseId);
synchronized (this) {
for (TaskStatus taskStatus : status.getTaskReports()) {
if (taskStatus.getRunState() != TaskStatus.State.RUNNING &&
taskStatus.getRunState() != TaskStatus.State.UNASSIGNED &&
taskStatus.getRunState() != TaskStatus.State.COMMIT_PENDING &&
!taskStatus.inTaskCleanupPhase()) {
if (taskStatus.getIsMap()) {
mapTotal--;
} else {
reduceTotal--;
}
try {
myInstrumentation.completeTask(taskStatus.getTaskID());
} catch (MetricsException me) {
LOG.warn("Caught: " + StringUtils.stringifyException(me));
}
removeRunningTask(taskStatus.getTaskID());
//
// When the task attempt has entered the finished state
// we log the counters to task log for future use
// load the counters into Scuba, Scriber and Hive
//
if (fConf.getBoolean(LOG_FINISHED_TASK_COUNTERS, true)) {
// for log format, 0 means json, else means name and value pair
String logHeader = "TaskCountersLogged " + taskStatus.getTaskID() + " " +
taskStatus.getFinishTime()/1000 + " ";
if (fConf.getInt(FINISHED_TASK_COUNTERS_LOG_FORMAT, 0) == 0) {
LOG.warn(
logHeader + taskStatus.getCounters().makeJsonString());
} else {
LOG.warn(
logHeader + taskStatus.getCounters().makeCompactString());
}
}
}
}
// Clear transient status information which should only
// be sent once to the JobTracker
for (TaskInProgress tip: runningTasks.values()) {
tip.getStatus().clearStatus();
}
}
return heartbeatResponse;
} } | public class class_name {
protected HeartbeatResponse transmitHeartBeat(
InterTrackerProtocol jobClient, short heartbeatResponseId,
TaskTrackerStatus status) throws IOException {
//
// Check if we should ask for a new Task
//
boolean askForNewTask;
long localMinSpaceStart;
synchronized (this) {
askForNewTask =
((status.countOccupiedMapSlots() < maxMapSlots ||
status.countOccupiedReduceSlots() < maxReduceSlots) &&
acceptNewTasks);
localMinSpaceStart = minSpaceStart;
}
if (askForNewTask) {
checkLocalDirs(getLocalDirsFromConf(fConf));
askForNewTask = enoughFreeSpace(localMinSpaceStart);
gatherResourceStatus(status);
}
//add node health information
TaskTrackerHealthStatus healthStatus = status.getHealthStatus();
synchronized (this) {
if (healthChecker != null) {
healthChecker.setHealthStatus(healthStatus); // depends on control dependency: [if], data = [none]
} else {
healthStatus.setNodeHealthy(true); // depends on control dependency: [if], data = [none]
healthStatus.setLastReported(0L); // depends on control dependency: [if], data = [none]
healthStatus.setHealthReport(""); // depends on control dependency: [if], data = [none]
}
}
//
// Xmit the heartbeat
//
HeartbeatResponse heartbeatResponse = jobClient.heartbeat(status,
justStarted,
justInited,
askForNewTask,
heartbeatResponseId);
synchronized (this) {
for (TaskStatus taskStatus : status.getTaskReports()) {
if (taskStatus.getRunState() != TaskStatus.State.RUNNING &&
taskStatus.getRunState() != TaskStatus.State.UNASSIGNED &&
taskStatus.getRunState() != TaskStatus.State.COMMIT_PENDING &&
!taskStatus.inTaskCleanupPhase()) {
if (taskStatus.getIsMap()) {
mapTotal--; // depends on control dependency: [if], data = [none]
} else {
reduceTotal--; // depends on control dependency: [if], data = [none]
}
try {
myInstrumentation.completeTask(taskStatus.getTaskID()); // depends on control dependency: [try], data = [none]
} catch (MetricsException me) {
LOG.warn("Caught: " + StringUtils.stringifyException(me));
} // depends on control dependency: [catch], data = [none]
removeRunningTask(taskStatus.getTaskID()); // depends on control dependency: [if], data = [none]
//
// When the task attempt has entered the finished state
// we log the counters to task log for future use
// load the counters into Scuba, Scriber and Hive
//
if (fConf.getBoolean(LOG_FINISHED_TASK_COUNTERS, true)) {
// for log format, 0 means json, else means name and value pair
String logHeader = "TaskCountersLogged " + taskStatus.getTaskID() + " " +
taskStatus.getFinishTime()/1000 + " ";
if (fConf.getInt(FINISHED_TASK_COUNTERS_LOG_FORMAT, 0) == 0) {
LOG.warn(
logHeader + taskStatus.getCounters().makeJsonString()); // depends on control dependency: [if], data = [none]
} else {
LOG.warn(
logHeader + taskStatus.getCounters().makeCompactString()); // depends on control dependency: [if], data = [none]
}
}
}
}
// Clear transient status information which should only
// be sent once to the JobTracker
for (TaskInProgress tip: runningTasks.values()) {
tip.getStatus().clearStatus(); // depends on control dependency: [for], data = [tip]
}
}
return heartbeatResponse;
} } |
public class class_name {
public EClass getIfc2DCompositeCurve() {
if (ifc2DCompositeCurveEClass == null) {
ifc2DCompositeCurveEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(1);
}
return ifc2DCompositeCurveEClass;
} } | public class class_name {
public EClass getIfc2DCompositeCurve() {
if (ifc2DCompositeCurveEClass == null) {
ifc2DCompositeCurveEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(1);
// depends on control dependency: [if], data = [none]
}
return ifc2DCompositeCurveEClass;
} } |
public class class_name {
@Override
public EClass getIfcBuilding() {
if (ifcBuildingEClass == null) {
ifcBuildingEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(57);
}
return ifcBuildingEClass;
} } | public class class_name {
@Override
public EClass getIfcBuilding() {
if (ifcBuildingEClass == null) {
ifcBuildingEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(57);
// depends on control dependency: [if], data = [none]
}
return ifcBuildingEClass;
} } |
public class class_name {
public boolean addFailOverListener(FailOverListener localListener) {
if (logger.isDebugEnabled()) {
logger.debug("Adding local listener " + localListener);
}
for(FailOverListener failOverListener : failOverListeners) {
if (failOverListener.getBaseFqn().getFqn().equals(localListener.getBaseFqn().getFqn())) {
return false;
}
}
return failOverListeners.add(localListener);
} } | public class class_name {
public boolean addFailOverListener(FailOverListener localListener) {
if (logger.isDebugEnabled()) {
logger.debug("Adding local listener " + localListener); // depends on control dependency: [if], data = [none]
}
for(FailOverListener failOverListener : failOverListeners) {
if (failOverListener.getBaseFqn().getFqn().equals(localListener.getBaseFqn().getFqn())) {
return false; // depends on control dependency: [if], data = [none]
}
}
return failOverListeners.add(localListener);
} } |
public class class_name {
private static MethodHandle selectNumberTransformer(Class param, Object arg) {
param = TypeHelper.getWrapperClass(param);
if (param == Byte.class) {
return TO_BYTE;
} else if (param == Character.class || param == Integer.class) {
return TO_INT;
} else if (param == Long.class) {
return TO_LONG;
} else if (param == Float.class) {
return TO_FLOAT;
} else if (param == Double.class) {
return TO_DOUBLE;
} else if (param == BigInteger.class) {
return TO_BIG_INT;
} else if (param == BigDecimal.class) {
if (arg instanceof Double) {
return DOUBLE_TO_BIG_DEC;
} else if (arg instanceof Long) {
return LONG_TO_BIG_DEC;
} else if (arg instanceof BigInteger) {
return BIG_INT_TO_BIG_DEC;
} else {
return DOUBLE_TO_BIG_DEC_WITH_CONVERSION;
}
} else if (param == Short.class) {
return TO_SHORT;
} else {
return null;
}
} } | public class class_name {
private static MethodHandle selectNumberTransformer(Class param, Object arg) {
param = TypeHelper.getWrapperClass(param);
if (param == Byte.class) {
return TO_BYTE; // depends on control dependency: [if], data = [none]
} else if (param == Character.class || param == Integer.class) {
return TO_INT; // depends on control dependency: [if], data = [none]
} else if (param == Long.class) {
return TO_LONG; // depends on control dependency: [if], data = [none]
} else if (param == Float.class) {
return TO_FLOAT; // depends on control dependency: [if], data = [none]
} else if (param == Double.class) {
return TO_DOUBLE; // depends on control dependency: [if], data = [none]
} else if (param == BigInteger.class) {
return TO_BIG_INT; // depends on control dependency: [if], data = [none]
} else if (param == BigDecimal.class) {
if (arg instanceof Double) {
return DOUBLE_TO_BIG_DEC; // depends on control dependency: [if], data = [none]
} else if (arg instanceof Long) {
return LONG_TO_BIG_DEC; // depends on control dependency: [if], data = [none]
} else if (arg instanceof BigInteger) {
return BIG_INT_TO_BIG_DEC; // depends on control dependency: [if], data = [none]
} else {
return DOUBLE_TO_BIG_DEC_WITH_CONVERSION; // depends on control dependency: [if], data = [none]
}
} else if (param == Short.class) {
return TO_SHORT; // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private static void flattenCategories(List<Category> flatList, List<Category> categories) {
categories.forEach(category -> {
flatList.add(category);
List<Category> children = category.getChildren();
if (children != null) {
flattenCategories(flatList, children);
}
});
} } | public class class_name {
private static void flattenCategories(List<Category> flatList, List<Category> categories) {
categories.forEach(category -> {
flatList.add(category);
List<Category> children = category.getChildren();
if (children != null) {
flattenCategories(flatList, children); // depends on control dependency: [if], data = [none]
}
});
} } |
public class class_name {
public JSONObject exportConfigurationAndProfile(String oldExport) {
try {
BasicNameValuePair[] params = {
new BasicNameValuePair("oldExport", oldExport)
};
String url = BASE_BACKUP_PROFILE + "/" + uriEncode(this._profileName) + "/" + this._clientId;
return new JSONObject(doGet(url, new BasicNameValuePair[]{}));
} catch (Exception e) {
return new JSONObject();
}
} } | public class class_name {
public JSONObject exportConfigurationAndProfile(String oldExport) {
try {
BasicNameValuePair[] params = {
new BasicNameValuePair("oldExport", oldExport)
};
String url = BASE_BACKUP_PROFILE + "/" + uriEncode(this._profileName) + "/" + this._clientId;
return new JSONObject(doGet(url, new BasicNameValuePair[]{})); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
return new JSONObject();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static LinePolar2D_F64 polar( List<Point2D_F64> points , double weights[] , LinePolar2D_F64 ret ) {
final int N = points.size();
double totalWeight = 0;
for( int i = 0; i < N; i++ ) {
totalWeight += weights[i];
}
if( totalWeight == 0 )
return null;
if( ret == null )
ret = new LinePolar2D_F64();
double meanX = 0;
double meanY = 0;
for( int i = 0; i < N; i++ ) {
Point2D_F64 p = points.get(i);
double w = weights[i];
meanX += w*p.x;
meanY += w*p.y;
}
meanX /= totalWeight;
meanY /= totalWeight;
double top = 0;
double bottom = 0;
for( int i = 0; i < N; i++ ) {
Point2D_F64 p = points.get(i);
double w = weights[i];
double dx = meanX - p.x;
double dy = meanY - p.y;
top += w*dx*dy;
bottom += w*(dy*dy - dx*dx);
}
top /= totalWeight;
bottom /= totalWeight;
ret.angle = Math.atan2(-2.0*top , bottom)/2.0;
ret.distance = (double)( meanX*Math.cos(ret.angle) + meanY*Math.sin(ret.angle));
return ret;
} } | public class class_name {
public static LinePolar2D_F64 polar( List<Point2D_F64> points , double weights[] , LinePolar2D_F64 ret ) {
final int N = points.size();
double totalWeight = 0;
for( int i = 0; i < N; i++ ) {
totalWeight += weights[i]; // depends on control dependency: [for], data = [i]
}
if( totalWeight == 0 )
return null;
if( ret == null )
ret = new LinePolar2D_F64();
double meanX = 0;
double meanY = 0;
for( int i = 0; i < N; i++ ) {
Point2D_F64 p = points.get(i);
double w = weights[i];
meanX += w*p.x; // depends on control dependency: [for], data = [none]
meanY += w*p.y; // depends on control dependency: [for], data = [none]
}
meanX /= totalWeight;
meanY /= totalWeight;
double top = 0;
double bottom = 0;
for( int i = 0; i < N; i++ ) {
Point2D_F64 p = points.get(i);
double w = weights[i];
double dx = meanX - p.x;
double dy = meanY - p.y;
top += w*dx*dy; // depends on control dependency: [for], data = [none]
bottom += w*(dy*dy - dx*dx); // depends on control dependency: [for], data = [none]
}
top /= totalWeight;
bottom /= totalWeight;
ret.angle = Math.atan2(-2.0*top , bottom)/2.0;
ret.distance = (double)( meanX*Math.cos(ret.angle) + meanY*Math.sin(ret.angle));
return ret;
} } |
public class class_name {
public static GeometryFactory init() {
try {
GeometryFactory theGeometryFactory = (GeometryFactory) EPackage.Registry.INSTANCE.getEFactory(GeometryPackage.eNS_URI);
if (theGeometryFactory != null) {
return theGeometryFactory;
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new GeometryFactoryImpl();
} } | public class class_name {
public static GeometryFactory init() {
try {
GeometryFactory theGeometryFactory = (GeometryFactory) EPackage.Registry.INSTANCE.getEFactory(GeometryPackage.eNS_URI);
if (theGeometryFactory != null) {
return theGeometryFactory;
// depends on control dependency: [if], data = [none]
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
// depends on control dependency: [catch], data = [none]
return new GeometryFactoryImpl();
} } |
public class class_name {
private Collection<TestClassResults> flattenResults(List<ISuite> suites)
{
Map<IClass, TestClassResults> flattenedResults = new HashMap<IClass, TestClassResults>();
for (ISuite suite : suites)
{
for (ISuiteResult suiteResult : suite.getResults().values())
{
// Failed and skipped configuration methods are treated as test failures.
organiseByClass(suiteResult.getTestContext().getFailedConfigurations().getAllResults(), flattenedResults);
organiseByClass(suiteResult.getTestContext().getSkippedConfigurations().getAllResults(), flattenedResults);
// Successful configuration methods are not included.
organiseByClass(suiteResult.getTestContext().getFailedTests().getAllResults(), flattenedResults);
organiseByClass(suiteResult.getTestContext().getSkippedTests().getAllResults(), flattenedResults);
organiseByClass(suiteResult.getTestContext().getPassedTests().getAllResults(), flattenedResults);
}
}
return flattenedResults.values();
} } | public class class_name {
private Collection<TestClassResults> flattenResults(List<ISuite> suites)
{
Map<IClass, TestClassResults> flattenedResults = new HashMap<IClass, TestClassResults>();
for (ISuite suite : suites)
{
for (ISuiteResult suiteResult : suite.getResults().values())
{
// Failed and skipped configuration methods are treated as test failures.
organiseByClass(suiteResult.getTestContext().getFailedConfigurations().getAllResults(), flattenedResults); // depends on control dependency: [for], data = [suiteResult]
organiseByClass(suiteResult.getTestContext().getSkippedConfigurations().getAllResults(), flattenedResults); // depends on control dependency: [for], data = [suiteResult]
// Successful configuration methods are not included.
organiseByClass(suiteResult.getTestContext().getFailedTests().getAllResults(), flattenedResults); // depends on control dependency: [for], data = [suiteResult]
organiseByClass(suiteResult.getTestContext().getSkippedTests().getAllResults(), flattenedResults); // depends on control dependency: [for], data = [suiteResult]
organiseByClass(suiteResult.getTestContext().getPassedTests().getAllResults(), flattenedResults); // depends on control dependency: [for], data = [suiteResult]
}
}
return flattenedResults.values();
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.