code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
---|---|
public class class_name {
public static URI addPathComponent(URI uri, String component) {
if (uri != null && component != null) try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
Optional.ofNullable(uri.getPath()).map(path -> join(path, component, '/')).orElse(component),
uri.getQuery(), uri.getFragment());
} catch (URISyntaxException use) {
throw new IllegalArgumentException("Could not add path component \"" + component + "\" to " + uri + ": "
+ use.getMessage(), use);
}
return uri;
} } | public class class_name {
public static URI addPathComponent(URI uri, String component) {
if (uri != null && component != null) try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
Optional.ofNullable(uri.getPath()).map(path -> join(path, component, '/')).orElse(component),
uri.getQuery(), uri.getFragment()); // depends on control dependency: [try], data = [none]
} catch (URISyntaxException use) {
throw new IllegalArgumentException("Could not add path component \"" + component + "\" to " + uri + ": "
+ use.getMessage(), use);
} // depends on control dependency: [catch], data = [none]
return uri;
} } |
public class class_name {
public boolean isMetBy(LocalProperties other) {
if (this.ordering != null) {
// we demand an ordering
return other.getOrdering() != null && this.ordering.isMetBy(other.getOrdering());
} else if (this.groupedFields != null) {
// check if the other fields are unique
if (other.getGroupedFields() != null && other.getGroupedFields().isValidUnorderedPrefix(this.groupedFields)) {
return true;
} else {
return other.areFieldsUnique(this.groupedFields);
}
} else {
return true;
}
} } | public class class_name {
public boolean isMetBy(LocalProperties other) {
if (this.ordering != null) {
// we demand an ordering
return other.getOrdering() != null && this.ordering.isMetBy(other.getOrdering()); // depends on control dependency: [if], data = [none]
} else if (this.groupedFields != null) {
// check if the other fields are unique
if (other.getGroupedFields() != null && other.getGroupedFields().isValidUnorderedPrefix(this.groupedFields)) {
return true; // depends on control dependency: [if], data = [none]
} else {
return other.areFieldsUnique(this.groupedFields); // depends on control dependency: [if], data = [none]
}
} else {
return true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@Override
public void run() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "run", Thread.currentThread().getName() + " " + this.in.getReadListener());
}
try {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Issuing the async read for the data");
}
if (_isc==null) {
_callback.complete(null);
} else {
//Call into the HttpInboundService context for the body data, passing in the callback and forcing
//the read to go asynchronous
//If there is data immediately available Channel will call the callback.complete before returning to this thread
_isc.getRequestBodyBuffer(_callback, true);
}
} catch (Exception e){
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "An exception occurred during the async read : " + e);
}
e.printStackTrace();
//There was a problem with the read so we should invoke their onError, since technically it's been set now
if(this.in.getReadListener()!= null)
this.in.getReadListener().onError(e);
} finally {
asyncContext.setReadListenerRunning(false);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "run", this.in.getReadListener());
}
} } | public class class_name {
@Override
public void run() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "run", Thread.currentThread().getName() + " " + this.in.getReadListener()); // depends on control dependency: [if], data = [none]
}
try {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Issuing the async read for the data"); // depends on control dependency: [if], data = [none]
}
if (_isc==null) {
_callback.complete(null); // depends on control dependency: [if], data = [null)]
} else {
//Call into the HttpInboundService context for the body data, passing in the callback and forcing
//the read to go asynchronous
//If there is data immediately available Channel will call the callback.complete before returning to this thread
_isc.getRequestBodyBuffer(_callback, true); // depends on control dependency: [if], data = [none]
}
} catch (Exception e){
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "An exception occurred during the async read : " + e); // depends on control dependency: [if], data = [none]
}
e.printStackTrace();
//There was a problem with the read so we should invoke their onError, since technically it's been set now
if(this.in.getReadListener()!= null)
this.in.getReadListener().onError(e);
} finally { // depends on control dependency: [catch], data = [none]
asyncContext.setReadListenerRunning(false);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "run", this.in.getReadListener()); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected Object session(Type type, String name) {
return parameter(type, name, new Function<String, Object>() {
public Object apply(String name) {
return context.session().getAttribute(name);
}
}, new Function<String, Collection<Object>>() {
@SuppressWarnings("unchecked")
public Collection<Object> apply(String name) {
HttpSession session = context.session();
Object attribute = session.getAttribute(name);
if (attribute instanceof Collection<?>) {
return (Collection<Object>) attribute;
}
Map<String, Object> map = new TreeMap<String, Object>();
for (Object object : Collections.list(session.getAttributeNames())) {
String key = (String) object;
if (key.startsWith(name + "[")) {
map.put(key, session.getAttribute(key));
}
}
return (map.isEmpty()) ? null : map.values();
}
});
} } | public class class_name {
protected Object session(Type type, String name) {
return parameter(type, name, new Function<String, Object>() {
public Object apply(String name) {
return context.session().getAttribute(name);
}
}, new Function<String, Collection<Object>>() {
@SuppressWarnings("unchecked")
public Collection<Object> apply(String name) {
HttpSession session = context.session();
Object attribute = session.getAttribute(name);
if (attribute instanceof Collection<?>) {
return (Collection<Object>) attribute; // depends on control dependency: [if], data = [)]
}
Map<String, Object> map = new TreeMap<String, Object>();
for (Object object : Collections.list(session.getAttributeNames())) {
String key = (String) object;
if (key.startsWith(name + "[")) {
map.put(key, session.getAttribute(key)); // depends on control dependency: [if], data = [none]
}
}
return (map.isEmpty()) ? null : map.values();
}
});
} } |
public class class_name {
public JsonObject prepare() {
if (channel != null) {
slackMessage.addProperty(CHANNEL, channel);
}
if (username != null) {
slackMessage.addProperty(USERNAME, username);
}
if (icon != null) {
if (icon.contains(HTTP)) {
slackMessage.addProperty(ICON_URL, icon);
} else {
slackMessage.addProperty(ICON_EMOJI, icon);
}
}
slackMessage.addProperty(UNFURL_MEDIA, unfurlMedia);
slackMessage.addProperty(UNFURL_LINKS, unfurlLinks);
slackMessage.addProperty(LINK_NAMES, linkNames);
if (text == null) {
throw new IllegalArgumentException("Missing Text field @ SlackMessage");
} else {
slackMessage.addProperty(TEXT, text);
}
if (!attach.isEmpty()) {
slackMessage.add(ATTACHMENTS, this.prepareAttach());
}
return slackMessage;
} } | public class class_name {
public JsonObject prepare() {
if (channel != null) {
slackMessage.addProperty(CHANNEL, channel); // depends on control dependency: [if], data = [none]
}
if (username != null) {
slackMessage.addProperty(USERNAME, username); // depends on control dependency: [if], data = [none]
}
if (icon != null) {
if (icon.contains(HTTP)) {
slackMessage.addProperty(ICON_URL, icon); // depends on control dependency: [if], data = [none]
} else {
slackMessage.addProperty(ICON_EMOJI, icon); // depends on control dependency: [if], data = [none]
}
}
slackMessage.addProperty(UNFURL_MEDIA, unfurlMedia);
slackMessage.addProperty(UNFURL_LINKS, unfurlLinks);
slackMessage.addProperty(LINK_NAMES, linkNames);
if (text == null) {
throw new IllegalArgumentException("Missing Text field @ SlackMessage");
} else {
slackMessage.addProperty(TEXT, text); // depends on control dependency: [if], data = [none]
}
if (!attach.isEmpty()) {
slackMessage.add(ATTACHMENTS, this.prepareAttach()); // depends on control dependency: [if], data = [none]
}
return slackMessage;
} } |
public class class_name {
@Override
public EClass getIfcAudioVisualApplianceType() {
if (ifcAudioVisualApplianceTypeEClass == null) {
ifcAudioVisualApplianceTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(30);
}
return ifcAudioVisualApplianceTypeEClass;
} } | public class class_name {
@Override
public EClass getIfcAudioVisualApplianceType() {
if (ifcAudioVisualApplianceTypeEClass == null) {
ifcAudioVisualApplianceTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(30);
// depends on control dependency: [if], data = [none]
}
return ifcAudioVisualApplianceTypeEClass;
} } |
public class class_name {
public int hash(char[] buffer, int offset, int length) {
int code = 0;
for (int i = 0; i < length; i++) {
code = code * 37 + buffer[offset + i];
}
return code & 0x7FFFFFF;
} } | public class class_name {
public int hash(char[] buffer, int offset, int length) {
int code = 0;
for (int i = 0; i < length; i++) {
code = code * 37 + buffer[offset + i]; // depends on control dependency: [for], data = [i]
}
return code & 0x7FFFFFF;
} } |
public class class_name {
public CharSequence matchesPattern(final CharSequence input, final String pattern) {
if (!Pattern.matches(pattern, input)) {
fail(String.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern));
}
return input;
} } | public class class_name {
public CharSequence matchesPattern(final CharSequence input, final String pattern) {
if (!Pattern.matches(pattern, input)) {
fail(String.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern)); // depends on control dependency: [if], data = [none]
}
return input;
} } |
public class class_name {
@Pure
@SuppressWarnings({"checkstyle:magicnumber", "checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity"})
public static String formatTime(double amount, TimeUnit unit) {
double amt;
double coef = 1.;
switch (unit) {
case DAYS:
coef = 86400.;
break;
case HOURS:
coef = 3600.;
break;
case MINUTES:
coef = 60.;
break;
case SECONDS:
break;
case MILLISECONDS:
coef = 1e-3;
break;
case MICROSECONDS:
coef = 1e-6;
break;
case NANOSECONDS:
coef = 1e-9;
break;
default:
throw new IllegalArgumentException();
}
// amount is in seconds
amt = amount * coef;
final StringBuilder text = new StringBuilder();
String centuries = ""; //$NON-NLS-1$
String years = ""; //$NON-NLS-1$
String days = ""; //$NON-NLS-1$
String hours = ""; //$NON-NLS-1$
String minutes = ""; //$NON-NLS-1$
String seconds = ""; //$NON-NLS-1$
long ah = 0;
long am = 0;
long as = 0;
int idx = 0;
if (amt >= 3153600000.) {
final long a = (long) Math.floor(amt / 3153600000.);
centuries = Locale.getString((a >= 2) ? "TIME_FORMAT_Cs" : "TIME_FORMAT_C", //$NON-NLS-1$ //$NON-NLS-2$
Long.toString(a));
amt -= a * 3153600000.;
text.append(centuries);
idx |= 32;
}
if (amt >= 31536000.) {
final long a = (long) Math.floor(amt / 31536000.);
years = Locale.getString((a >= 2) ? "TIME_FORMAT_Ys" : "TIME_FORMAT_Y", //$NON-NLS-1$ //$NON-NLS-2$
Long.toString(a));
amt -= a * 31536000.;
if (text.length() > 0) {
text.append(' ');
}
text.append(years);
idx |= 16;
}
if (amt >= 86400.) {
final long a = (long) Math.floor(amt / 86400.);
days = Locale.getString((a >= 2) ? "TIME_FORMAT_Ds" : "TIME_FORMAT_D", //$NON-NLS-1$ //$NON-NLS-2$
Long.toString(a));
amt -= a * 86400.;
if (text.length() > 0) {
text.append(' ');
}
text.append(days);
idx |= 8;
}
//-------------------
if (amt >= 3600.) {
ah = (long) Math.floor(amt / 3600.);
hours = Long.toString(ah);
if (ah < 10.) {
hours = "0" + hours; //$NON-NLS-1$
}
amt -= ah * 3600.;
idx |= 4;
}
if (amt >= 60.) {
am = (long) Math.floor(amt / 60.);
minutes = Long.toString(am);
if (am < 10.) {
minutes = "0" + minutes; //$NON-NLS-1$
}
amt -= am * 60.;
idx |= 2;
}
if (amt >= 0. || idx == 0) {
if (idx >= 8) {
as = (long) Math.floor(amt);
seconds = Long.toString(as);
} else {
final NumberFormat fmt = new DecimalFormat("#0.000"); //$NON-NLS-1$
seconds = fmt.format(amt);
}
idx |= 1;
}
if ((idx & 7) == 7) {
if (text.length() > 0) {
text.append(' ');
}
if (idx >= 8 && as > 0) {
if (as < 10.) {
seconds = "0" + seconds; //$NON-NLS-1$
}
} else if (idx < 8 && amt > 0. && amt < 10.) {
seconds = "0" + seconds; //$NON-NLS-1$
}
text.append(Locale.getString("TIME_FORMAT_HMS", hours, minutes, seconds)); //$NON-NLS-1$
} else {
if (ah > 0) {
if (text.length() > 0) {
text.append(' ');
}
text.append(Locale.getString((ah >= 2) ? "TIME_FORMAT_Hs" : "TIME_FORMAT_H", //$NON-NLS-1$ //$NON-NLS-2$
hours));
}
if (am > 0) {
if (text.length() > 0) {
text.append(' ');
}
text.append(Locale.getString((am >= 2) ? "TIME_FORMAT_Ms" : "TIME_FORMAT_M", //$NON-NLS-1$ //$NON-NLS-2$
minutes));
}
if (idx >= 8 && as > 0) {
if (text.length() > 0) {
text.append(' ');
}
text.append(Locale.getString((as >= 2) ? "TIME_FORMAT_Ss" : "TIME_FORMAT_S", //$NON-NLS-1$ //$NON-NLS-2$
seconds));
} else if (idx < 8 && amt > 0.) {
if (text.length() > 0) {
text.append(' ');
}
text.append(Locale.getString((amt >= 2.) ? "TIME_FORMAT_Ss" : "TIME_FORMAT_S", //$NON-NLS-1$ //$NON-NLS-2$
seconds));
}
}
return text.toString();
} } | public class class_name {
@Pure
@SuppressWarnings({"checkstyle:magicnumber", "checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity"})
public static String formatTime(double amount, TimeUnit unit) {
double amt;
double coef = 1.;
switch (unit) {
case DAYS:
coef = 86400.;
break;
case HOURS:
coef = 3600.;
break;
case MINUTES:
coef = 60.;
break;
case SECONDS:
break;
case MILLISECONDS:
coef = 1e-3;
break;
case MICROSECONDS:
coef = 1e-6;
break;
case NANOSECONDS:
coef = 1e-9;
break;
default:
throw new IllegalArgumentException();
}
// amount is in seconds
amt = amount * coef;
final StringBuilder text = new StringBuilder();
String centuries = ""; //$NON-NLS-1$
String years = ""; //$NON-NLS-1$
String days = ""; //$NON-NLS-1$
String hours = ""; //$NON-NLS-1$
String minutes = ""; //$NON-NLS-1$
String seconds = ""; //$NON-NLS-1$
long ah = 0;
long am = 0;
long as = 0;
int idx = 0;
if (amt >= 3153600000.) {
final long a = (long) Math.floor(amt / 3153600000.);
centuries = Locale.getString((a >= 2) ? "TIME_FORMAT_Cs" : "TIME_FORMAT_C", //$NON-NLS-1$ //$NON-NLS-2$
Long.toString(a)); // depends on control dependency: [if], data = [none]
amt -= a * 3153600000.; // depends on control dependency: [if], data = [none]
text.append(centuries); // depends on control dependency: [if], data = [none]
idx |= 32; // depends on control dependency: [if], data = [none]
}
if (amt >= 31536000.) {
final long a = (long) Math.floor(amt / 31536000.);
years = Locale.getString((a >= 2) ? "TIME_FORMAT_Ys" : "TIME_FORMAT_Y", //$NON-NLS-1$ //$NON-NLS-2$
Long.toString(a)); // depends on control dependency: [if], data = [none]
amt -= a * 31536000.; // depends on control dependency: [if], data = [none]
if (text.length() > 0) {
text.append(' '); // depends on control dependency: [if], data = [none]
}
text.append(years); // depends on control dependency: [if], data = [none]
idx |= 16; // depends on control dependency: [if], data = [none]
}
if (amt >= 86400.) {
final long a = (long) Math.floor(amt / 86400.);
days = Locale.getString((a >= 2) ? "TIME_FORMAT_Ds" : "TIME_FORMAT_D", //$NON-NLS-1$ //$NON-NLS-2$
Long.toString(a)); // depends on control dependency: [if], data = [none]
amt -= a * 86400.; // depends on control dependency: [if], data = [none]
if (text.length() > 0) {
text.append(' '); // depends on control dependency: [if], data = [none]
}
text.append(days); // depends on control dependency: [if], data = [none]
idx |= 8; // depends on control dependency: [if], data = [none]
}
//-------------------
if (amt >= 3600.) {
ah = (long) Math.floor(amt / 3600.); // depends on control dependency: [if], data = [(amt]
hours = Long.toString(ah); // depends on control dependency: [if], data = [none]
if (ah < 10.) {
hours = "0" + hours; //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
amt -= ah * 3600.; // depends on control dependency: [if], data = [none]
idx |= 4; // depends on control dependency: [if], data = [none]
}
if (amt >= 60.) {
am = (long) Math.floor(amt / 60.); // depends on control dependency: [if], data = [(amt]
minutes = Long.toString(am); // depends on control dependency: [if], data = [none]
if (am < 10.) {
minutes = "0" + minutes; //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
amt -= am * 60.; // depends on control dependency: [if], data = [none]
idx |= 2; // depends on control dependency: [if], data = [none]
}
if (amt >= 0. || idx == 0) {
if (idx >= 8) {
as = (long) Math.floor(amt); // depends on control dependency: [if], data = [none]
seconds = Long.toString(as); // depends on control dependency: [if], data = [none]
} else {
final NumberFormat fmt = new DecimalFormat("#0.000"); //$NON-NLS-1$
seconds = fmt.format(amt); // depends on control dependency: [if], data = [none]
}
idx |= 1; // depends on control dependency: [if], data = [none]
}
if ((idx & 7) == 7) {
if (text.length() > 0) {
text.append(' '); // depends on control dependency: [if], data = [none]
}
if (idx >= 8 && as > 0) {
if (as < 10.) {
seconds = "0" + seconds; //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
} else if (idx < 8 && amt > 0. && amt < 10.) {
seconds = "0" + seconds; //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
}
text.append(Locale.getString("TIME_FORMAT_HMS", hours, minutes, seconds)); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
} else {
if (ah > 0) {
if (text.length() > 0) {
text.append(' '); // depends on control dependency: [if], data = [none]
}
text.append(Locale.getString((ah >= 2) ? "TIME_FORMAT_Hs" : "TIME_FORMAT_H", //$NON-NLS-1$ //$NON-NLS-2$
hours)); // depends on control dependency: [if], data = [none]
}
if (am > 0) {
if (text.length() > 0) {
text.append(' '); // depends on control dependency: [if], data = [none]
}
text.append(Locale.getString((am >= 2) ? "TIME_FORMAT_Ms" : "TIME_FORMAT_M", //$NON-NLS-1$ //$NON-NLS-2$
minutes)); // depends on control dependency: [if], data = [none]
}
if (idx >= 8 && as > 0) {
if (text.length() > 0) {
text.append(' '); // depends on control dependency: [if], data = [none]
}
text.append(Locale.getString((as >= 2) ? "TIME_FORMAT_Ss" : "TIME_FORMAT_S", //$NON-NLS-1$ //$NON-NLS-2$
seconds)); // depends on control dependency: [if], data = [none]
} else if (idx < 8 && amt > 0.) {
if (text.length() > 0) {
text.append(' '); // depends on control dependency: [if], data = [none]
}
text.append(Locale.getString((amt >= 2.) ? "TIME_FORMAT_Ss" : "TIME_FORMAT_S", //$NON-NLS-1$ //$NON-NLS-2$
seconds)); // depends on control dependency: [if], data = [none]
}
}
return text.toString();
} } |
public class class_name {
public static Process launchVMWithClassPath(String classToLaunch, File[] classpath,
String... additionalParams) throws IOException {
final StringBuilder b = new StringBuilder();
for (final File f : classpath) {
if (b.length() > 0) {
b.append(File.pathSeparator);
}
b.append(f.getAbsolutePath());
}
return launchVMWithClassPath(classToLaunch, b.toString(), additionalParams);
} } | public class class_name {
public static Process launchVMWithClassPath(String classToLaunch, File[] classpath,
String... additionalParams) throws IOException {
final StringBuilder b = new StringBuilder();
for (final File f : classpath) {
if (b.length() > 0) {
b.append(File.pathSeparator); // depends on control dependency: [if], data = [none]
}
b.append(f.getAbsolutePath()); // depends on control dependency: [for], data = [f]
}
return launchVMWithClassPath(classToLaunch, b.toString(), additionalParams);
} } |
public class class_name {
private Context getContext(ExecutionContext executionContext) {
// Get context id.
HttpServletRequest request = executionContext.getActionBeanContext().getRequest();
String parameter = request.getParameter(ID_PARAMETER);
// Return context.
if (parameter != null) {
int id = Integer.parseInt(parameter, 16);
return contexts.get(id);
}
return null;
} } | public class class_name {
private Context getContext(ExecutionContext executionContext) {
// Get context id.
HttpServletRequest request = executionContext.getActionBeanContext().getRequest();
String parameter = request.getParameter(ID_PARAMETER);
// Return context.
if (parameter != null) {
int id = Integer.parseInt(parameter, 16);
return contexts.get(id); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public static Optional<Method> extractGetter(final Class<?> targetClass, final String propertyName, final Class<?> propertyType) {
final String methodName = "get" + Utils.capitalize(propertyName);
Method method;
try {
method = targetClass.getMethod(methodName);
} catch (NoSuchMethodException | SecurityException e) {
return Optional.empty();
}
method.setAccessible(true);
if(method.getParameterCount() > 0) {
return Optional.empty();
}
if(!method.getReturnType().equals(propertyType)) {
return Optional.empty();
}
return Optional.of(method);
} } | public class class_name {
public static Optional<Method> extractGetter(final Class<?> targetClass, final String propertyName, final Class<?> propertyType) {
final String methodName = "get" + Utils.capitalize(propertyName);
Method method;
try {
method = targetClass.getMethod(methodName);
// depends on control dependency: [try], data = [none]
} catch (NoSuchMethodException | SecurityException e) {
return Optional.empty();
}
// depends on control dependency: [catch], data = [none]
method.setAccessible(true);
if(method.getParameterCount() > 0) {
return Optional.empty();
// depends on control dependency: [if], data = [none]
}
if(!method.getReturnType().equals(propertyType)) {
return Optional.empty();
// depends on control dependency: [if], data = [none]
}
return Optional.of(method);
} } |
public class class_name {
public static Set<Stubbing> findStubbings(Iterable<?> mocks) {
Set<Stubbing> stubbings = new TreeSet<Stubbing>(new StubbingComparator());
for (Object mock : mocks) {
Collection<? extends Stubbing> fromSingleMock = new DefaultMockingDetails(mock).getStubbings();
stubbings.addAll(fromSingleMock);
}
return stubbings;
} } | public class class_name {
public static Set<Stubbing> findStubbings(Iterable<?> mocks) {
Set<Stubbing> stubbings = new TreeSet<Stubbing>(new StubbingComparator());
for (Object mock : mocks) {
Collection<? extends Stubbing> fromSingleMock = new DefaultMockingDetails(mock).getStubbings(); // depends on control dependency: [for], data = [mock]
stubbings.addAll(fromSingleMock); // depends on control dependency: [for], data = [none]
}
return stubbings;
} } |
public class class_name {
public synchronized void firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event event) {
PlaylistBasicChangeEvent pce = new PlaylistBasicChangeEvent(this, event);
for (PlaylistBasicChangeListener pcl : playlistListeners) {
pcl.playlistBasicChange(pce);
}
} } | public class class_name {
public synchronized void firePlaylistChangeEvent(PlaylistBasicChangeEvent.Event event) {
PlaylistBasicChangeEvent pce = new PlaylistBasicChangeEvent(this, event);
for (PlaylistBasicChangeListener pcl : playlistListeners) {
pcl.playlistBasicChange(pce); // depends on control dependency: [for], data = [pcl]
}
} } |
public class class_name {
public static void showKeyboardInDialog(Dialog dialog, EditText target) {
if (dialog == null || target == null) {
return;
}
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
target.requestFocus();
} } | public class class_name {
public static void showKeyboardInDialog(Dialog dialog, EditText target) {
if (dialog == null || target == null) {
return; // depends on control dependency: [if], data = [none]
}
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
target.requestFocus();
} } |
public class class_name {
private void ensureCapacity(int minCapacity) {
long currentCapacity = data.length;
if (minCapacity <= currentCapacity) {
return;
}
// increase capacity by at least ~50%
long expandedCapacity = Math.max(minCapacity, currentCapacity + (currentCapacity >> 1));
int newCapacity = (int) Math.min(MAX_ARRAY_SIZE, expandedCapacity);
if (newCapacity < minCapacity) {
// throw exception as unbounded arrays are not expected to fill
throw new RuntimeException("Requested array size " + minCapacity + " exceeds limit of " + MAX_ARRAY_SIZE);
}
data = Arrays.copyOf(data, newCapacity);
} } | public class class_name {
private void ensureCapacity(int minCapacity) {
long currentCapacity = data.length;
if (minCapacity <= currentCapacity) {
return; // depends on control dependency: [if], data = [none]
}
// increase capacity by at least ~50%
long expandedCapacity = Math.max(minCapacity, currentCapacity + (currentCapacity >> 1));
int newCapacity = (int) Math.min(MAX_ARRAY_SIZE, expandedCapacity);
if (newCapacity < minCapacity) {
// throw exception as unbounded arrays are not expected to fill
throw new RuntimeException("Requested array size " + minCapacity + " exceeds limit of " + MAX_ARRAY_SIZE);
}
data = Arrays.copyOf(data, newCapacity);
} } |
public class class_name {
public Set<ConstraintViolation> validate(DataSetInfo info) {
Set<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();
try {
if (info.isMandatory() && get(info.getDataSetNumber()) == null) {
errors.add(new ConstraintViolation(info, ConstraintViolation.MANDATORY_MISSING));
}
if (!info.isRepeatable() && getAll(info.getDataSetNumber()).size() > 1) {
errors.add(new ConstraintViolation(info, ConstraintViolation.REPEATABLE_REPEATED));
}
} catch (SerializationException e) {
errors.add(new ConstraintViolation(info, ConstraintViolation.INVALID_VALUE));
}
return errors;
} } | public class class_name {
public Set<ConstraintViolation> validate(DataSetInfo info) {
Set<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();
try {
if (info.isMandatory() && get(info.getDataSetNumber()) == null) {
errors.add(new ConstraintViolation(info, ConstraintViolation.MANDATORY_MISSING));
// depends on control dependency: [if], data = [none]
}
if (!info.isRepeatable() && getAll(info.getDataSetNumber()).size() > 1) {
errors.add(new ConstraintViolation(info, ConstraintViolation.REPEATABLE_REPEATED));
// depends on control dependency: [if], data = [none]
}
} catch (SerializationException e) {
errors.add(new ConstraintViolation(info, ConstraintViolation.INVALID_VALUE));
}
// depends on control dependency: [catch], data = [none]
return errors;
} } |
public class class_name {
@SuppressWarnings("unused")
private final void purgeBeanClasses(ClassLoader loader) {
Iterator<Class<?>> classes = cache.keySet().iterator();
while (classes.hasNext()) {
if (loader == classes.next().getClassLoader()) {
classes.remove();
}
}
} } | public class class_name {
@SuppressWarnings("unused")
private final void purgeBeanClasses(ClassLoader loader) {
Iterator<Class<?>> classes = cache.keySet().iterator();
while (classes.hasNext()) {
if (loader == classes.next().getClassLoader()) {
classes.remove(); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private static boolean subMatch(final String str, int soff, final byte[] m)
{
for(int k = 0; k < m.length; k++) {
if(str.charAt(soff++) != m[k]) {
return false;
}
}
return true;
} } | public class class_name {
private static boolean subMatch(final String str, int soff, final byte[] m)
{
for(int k = 0; k < m.length; k++) {
if(str.charAt(soff++) != m[k]) {
return false; // depends on control dependency: [if], data = [none]
}
}
return true;
} } |
public class class_name {
public Observable<ServiceResponse<Page<RemoteLoginInformationInner>>> listRemoteLoginInformationWithServiceResponseAsync(final String resourceGroupName, final String workspaceName, final String experimentName, final String jobName) {
return listRemoteLoginInformationSinglePageAsync(resourceGroupName, workspaceName, experimentName, jobName)
.concatMap(new Func1<ServiceResponse<Page<RemoteLoginInformationInner>>, Observable<ServiceResponse<Page<RemoteLoginInformationInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RemoteLoginInformationInner>>> call(ServiceResponse<Page<RemoteLoginInformationInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listRemoteLoginInformationNextWithServiceResponseAsync(nextPageLink));
}
});
} } | public class class_name {
public Observable<ServiceResponse<Page<RemoteLoginInformationInner>>> listRemoteLoginInformationWithServiceResponseAsync(final String resourceGroupName, final String workspaceName, final String experimentName, final String jobName) {
return listRemoteLoginInformationSinglePageAsync(resourceGroupName, workspaceName, experimentName, jobName)
.concatMap(new Func1<ServiceResponse<Page<RemoteLoginInformationInner>>, Observable<ServiceResponse<Page<RemoteLoginInformationInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RemoteLoginInformationInner>>> call(ServiceResponse<Page<RemoteLoginInformationInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page); // depends on control dependency: [if], data = [none]
}
return Observable.just(page).concatWith(listRemoteLoginInformationNextWithServiceResponseAsync(nextPageLink));
}
});
} } |
public class class_name {
private byte getHeaderType(final Header header, final Header lastHeader) {
//int lastFullTs = ((RTMPConnection) Red5.getConnectionLocal()).getState().getLastFullTimestampWritten(header.getChannelId());
if (lastHeader == null || header.getStreamId() != lastHeader.getStreamId() || header.getTimer() < lastHeader.getTimer()) {
// new header mark if header for another stream
return HEADER_NEW;
} else if (header.getSize() != lastHeader.getSize() || header.getDataType() != lastHeader.getDataType()) {
// same source header if last header data type or size differ
return HEADER_SAME_SOURCE;
} else if (header.getTimer() != lastHeader.getTimer()) {
// timer change marker if there's time gap between header time stamps
return HEADER_TIMER_CHANGE;
}
// continue encoding
return HEADER_CONTINUE;
} } | public class class_name {
private byte getHeaderType(final Header header, final Header lastHeader) {
//int lastFullTs = ((RTMPConnection) Red5.getConnectionLocal()).getState().getLastFullTimestampWritten(header.getChannelId());
if (lastHeader == null || header.getStreamId() != lastHeader.getStreamId() || header.getTimer() < lastHeader.getTimer()) {
// new header mark if header for another stream
return HEADER_NEW;
// depends on control dependency: [if], data = [none]
} else if (header.getSize() != lastHeader.getSize() || header.getDataType() != lastHeader.getDataType()) {
// same source header if last header data type or size differ
return HEADER_SAME_SOURCE;
// depends on control dependency: [if], data = [none]
} else if (header.getTimer() != lastHeader.getTimer()) {
// timer change marker if there's time gap between header time stamps
return HEADER_TIMER_CHANGE;
// depends on control dependency: [if], data = [none]
}
// continue encoding
return HEADER_CONTINUE;
} } |
public class class_name {
@Override
public List<Group> getAtomGroups(GroupType type){
List<Group> tmp = new ArrayList<>() ;
for (Group g : groups) {
if (g.getType().equals(type)) {
tmp.add(g);
}
}
return tmp ;
} } | public class class_name {
@Override
public List<Group> getAtomGroups(GroupType type){
List<Group> tmp = new ArrayList<>() ;
for (Group g : groups) {
if (g.getType().equals(type)) {
tmp.add(g); // depends on control dependency: [if], data = [none]
}
}
return tmp ;
} } |
public class class_name {
public static JettyConnector[] parseConnectors(String[] connectors) {
if (connectors == null) {
return null;
}
List<JettyConnector> array = new ArrayList<>();
for (String coonectorString : connectors) {
try {
array.add(JettyConnector.valueOf(coonectorString));
} catch (IllegalArgumentException e) {
//nothing to do here
}
}
return !array.isEmpty() ? array.toArray(new JettyConnector[array.size()]) : null;
} } | public class class_name {
public static JettyConnector[] parseConnectors(String[] connectors) {
if (connectors == null) {
return null; // depends on control dependency: [if], data = [none]
}
List<JettyConnector> array = new ArrayList<>();
for (String coonectorString : connectors) {
try {
array.add(JettyConnector.valueOf(coonectorString)); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException e) {
//nothing to do here
} // depends on control dependency: [catch], data = [none]
}
return !array.isEmpty() ? array.toArray(new JettyConnector[array.size()]) : null;
} } |
public class class_name {
@Override
public CPFriendlyURLEntry fetchByPrimaryKey(Serializable primaryKey) {
Serializable serializable = entityCache.getResult(CPFriendlyURLEntryModelImpl.ENTITY_CACHE_ENABLED,
CPFriendlyURLEntryImpl.class, primaryKey);
if (serializable == nullModel) {
return null;
}
CPFriendlyURLEntry cpFriendlyURLEntry = (CPFriendlyURLEntry)serializable;
if (cpFriendlyURLEntry == null) {
Session session = null;
try {
session = openSession();
cpFriendlyURLEntry = (CPFriendlyURLEntry)session.get(CPFriendlyURLEntryImpl.class,
primaryKey);
if (cpFriendlyURLEntry != null) {
cacheResult(cpFriendlyURLEntry);
}
else {
entityCache.putResult(CPFriendlyURLEntryModelImpl.ENTITY_CACHE_ENABLED,
CPFriendlyURLEntryImpl.class, primaryKey, nullModel);
}
}
catch (Exception e) {
entityCache.removeResult(CPFriendlyURLEntryModelImpl.ENTITY_CACHE_ENABLED,
CPFriendlyURLEntryImpl.class, primaryKey);
throw processException(e);
}
finally {
closeSession(session);
}
}
return cpFriendlyURLEntry;
} } | public class class_name {
@Override
public CPFriendlyURLEntry fetchByPrimaryKey(Serializable primaryKey) {
Serializable serializable = entityCache.getResult(CPFriendlyURLEntryModelImpl.ENTITY_CACHE_ENABLED,
CPFriendlyURLEntryImpl.class, primaryKey);
if (serializable == nullModel) {
return null; // depends on control dependency: [if], data = [none]
}
CPFriendlyURLEntry cpFriendlyURLEntry = (CPFriendlyURLEntry)serializable;
if (cpFriendlyURLEntry == null) {
Session session = null;
try {
session = openSession(); // depends on control dependency: [try], data = [none]
cpFriendlyURLEntry = (CPFriendlyURLEntry)session.get(CPFriendlyURLEntryImpl.class,
primaryKey); // depends on control dependency: [try], data = [none]
if (cpFriendlyURLEntry != null) {
cacheResult(cpFriendlyURLEntry); // depends on control dependency: [if], data = [(cpFriendlyURLEntry]
}
else {
entityCache.putResult(CPFriendlyURLEntryModelImpl.ENTITY_CACHE_ENABLED,
CPFriendlyURLEntryImpl.class, primaryKey, nullModel); // depends on control dependency: [if], data = [none]
}
}
catch (Exception e) {
entityCache.removeResult(CPFriendlyURLEntryModelImpl.ENTITY_CACHE_ENABLED,
CPFriendlyURLEntryImpl.class, primaryKey);
throw processException(e);
} // depends on control dependency: [catch], data = [none]
finally {
closeSession(session);
}
}
return cpFriendlyURLEntry;
} } |
public class class_name {
public static String getCustomerInfoWithEncrypt(Map<String,String> customerInfoMap,String accNo,String encoding) {
if(customerInfoMap.isEmpty())
return "{}";
StringBuffer sf = new StringBuffer("{");
//敏感信息加密域
StringBuffer encryptedInfoSb = new StringBuffer("");
for(Iterator<String> it = customerInfoMap.keySet().iterator(); it.hasNext();){
String key = it.next();
String value = customerInfoMap.get(key);
if(key.equals("phoneNo") || key.equals("cvn2") || key.equals("expired")){
encryptedInfoSb.append(key).append(SDKConstants.EQUAL).append(value).append(SDKConstants.AMPERSAND);
}else{
if(key.equals("pin")){
if(null == accNo || "".equals(accNo.trim())){
LogUtil.writeLog("送了密码(PIN),必须在getCustomerInfoWithEncrypt参数中上传卡号");
throw new RuntimeException("加密PIN没送卡号无法后续处理");
}else{
value = encryptPin(accNo,value,encoding);
}
}
sf.append(key).append(SDKConstants.EQUAL).append(value).append(SDKConstants.AMPERSAND);
}
}
if(!encryptedInfoSb.toString().equals("")){
encryptedInfoSb.setLength(encryptedInfoSb.length()-1);//去掉最后一个&符号
LogUtil.writeLog("组装的customerInfo encryptedInfo明文:"+ encryptedInfoSb.toString());
sf.append("encryptedInfo").append(SDKConstants.EQUAL).append(encryptData(encryptedInfoSb.toString(), encoding));
}else{
sf.setLength(sf.length()-1);
}
String customerInfo = sf.append("}").toString();
LogUtil.writeLog("组装的customerInfo明文:"+customerInfo);
try {
return new String(SecureUtil.base64Encode(sf.toString().getBytes(encoding)),encoding);
} catch (UnsupportedEncodingException e) {
LogUtil.writeErrorLog(e.getMessage(), e);
} catch (IOException e) {
LogUtil.writeErrorLog(e.getMessage(), e);
}
return customerInfo;
} } | public class class_name {
public static String getCustomerInfoWithEncrypt(Map<String,String> customerInfoMap,String accNo,String encoding) {
if(customerInfoMap.isEmpty())
return "{}";
StringBuffer sf = new StringBuffer("{");
//敏感信息加密域
StringBuffer encryptedInfoSb = new StringBuffer("");
for(Iterator<String> it = customerInfoMap.keySet().iterator(); it.hasNext();){
String key = it.next();
String value = customerInfoMap.get(key);
if(key.equals("phoneNo") || key.equals("cvn2") || key.equals("expired")){
encryptedInfoSb.append(key).append(SDKConstants.EQUAL).append(value).append(SDKConstants.AMPERSAND); // depends on control dependency: [if], data = [none]
}else{
if(key.equals("pin")){
if(null == accNo || "".equals(accNo.trim())){
LogUtil.writeLog("送了密码(PIN),必须在getCustomerInfoWithEncrypt参数中上传卡号"); // depends on control dependency: [if], data = [none]
throw new RuntimeException("加密PIN没送卡号无法后续处理");
}else{
value = encryptPin(accNo,value,encoding); // depends on control dependency: [if], data = [none]
}
}
sf.append(key).append(SDKConstants.EQUAL).append(value).append(SDKConstants.AMPERSAND); // depends on control dependency: [if], data = [none]
}
}
if(!encryptedInfoSb.toString().equals("")){
encryptedInfoSb.setLength(encryptedInfoSb.length()-1);//去掉最后一个&符号 // depends on control dependency: [if], data = [none]
LogUtil.writeLog("组装的customerInfo encryptedInfo明文:"+ encryptedInfoSb.toString()); // depends on control dependency: [if], data = [none]
sf.append("encryptedInfo").append(SDKConstants.EQUAL).append(encryptData(encryptedInfoSb.toString(), encoding)); // depends on control dependency: [if], data = [none]
}else{
sf.setLength(sf.length()-1); // depends on control dependency: [if], data = [none]
}
String customerInfo = sf.append("}").toString();
LogUtil.writeLog("组装的customerInfo明文:"+customerInfo);
try {
return new String(SecureUtil.base64Encode(sf.toString().getBytes(encoding)),encoding); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) {
LogUtil.writeErrorLog(e.getMessage(), e);
} catch (IOException e) { // depends on control dependency: [catch], data = [none]
LogUtil.writeErrorLog(e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
return customerInfo;
} } |
public class class_name {
@Override
public void emit(SinkFactory factory, Doc doc) {
logger.fine("Generating Java source based on " + doc.srcInfo);
final StringBuilder header = new StringBuilder();
header.append(ASTPrinter.printComments("", commentProcessor.leftAlign(doc.pkg.comments)));
header.append(doc.pkg.name.isEmpty() ? "" : ("package " + doc.pkg.name + ";\n\n"));
if (!doc.imports.isEmpty()) {
for (Imprt imp : doc.imports) {
header.append(ASTPrinter.printComments("", commentProcessor.leftAlign(imp.comments)));
header.append("import " + imp.name + ";\n");
}
header.append("\n");
}
final String version = new Version().getVersion();
header.append("/*\nThis file was generated based on " + doc.srcInfo + " using jADT version " + version + " http://jamesiry.github.com/jADT/ . Please do not modify directly.\n\n");
header.append("The source was parsed as: \n\n");
for (DataType dataType : doc.dataTypes) {
final Sink sink = factory.createSink(doc.pkg.name.isEmpty() ? dataType.name : doc.pkg.name + "." + dataType.name);
logger.info("Generating " + sink.getInfo());
try {
dataTypeEmitter.emit(sink, dataType, header.toString());
} finally {
sink.close();
}
}
} } | public class class_name {
@Override
public void emit(SinkFactory factory, Doc doc) {
logger.fine("Generating Java source based on " + doc.srcInfo);
final StringBuilder header = new StringBuilder();
header.append(ASTPrinter.printComments("", commentProcessor.leftAlign(doc.pkg.comments)));
header.append(doc.pkg.name.isEmpty() ? "" : ("package " + doc.pkg.name + ";\n\n"));
if (!doc.imports.isEmpty()) {
for (Imprt imp : doc.imports) {
header.append(ASTPrinter.printComments("", commentProcessor.leftAlign(imp.comments))); // depends on control dependency: [for], data = [imp]
header.append("import " + imp.name + ";\n"); // depends on control dependency: [for], data = [imp]
}
header.append("\n"); // depends on control dependency: [if], data = [none]
}
final String version = new Version().getVersion();
header.append("/*\nThis file was generated based on " + doc.srcInfo + " using jADT version " + version + " http://jamesiry.github.com/jADT/ . Please do not modify directly.\n\n");
header.append("The source was parsed as: \n\n");
for (DataType dataType : doc.dataTypes) {
final Sink sink = factory.createSink(doc.pkg.name.isEmpty() ? dataType.name : doc.pkg.name + "." + dataType.name);
logger.info("Generating " + sink.getInfo()); // depends on control dependency: [for], data = [none]
try {
dataTypeEmitter.emit(sink, dataType, header.toString()); // depends on control dependency: [try], data = [none]
} finally {
sink.close();
}
}
} } |
public class class_name {
boolean attemptClearSymbolIDValues()
{
boolean sidsRemain = false;
if (_fieldName != null)
{
_fieldId = UNKNOWN_SYMBOL_ID;
} else if (_fieldId > UNKNOWN_SYMBOL_ID)
{
// retaining the field SID, as it couldn't be cleared due to loss of context
// TODO - for SID handling consistency; this should attempt resolution first
sidsRemain = true;
}
if (_annotations != null)
{
for (int i = 0; i < _annotations.length; i++)
{
SymbolToken annotation = _annotations[i];
// _annotations may have nulls at the end.
if (annotation == null) break;
String text = annotation.getText();
// TODO - for SID handling consistency; this should attempt resolution first, not just drop entry
if (text != null && annotation.getSid() != UNKNOWN_SYMBOL_ID)
{
_annotations[i] =
newSymbolToken(text, UNKNOWN_SYMBOL_ID);
}
}
}
return !sidsRemain;
} } | public class class_name {
boolean attemptClearSymbolIDValues()
{
boolean sidsRemain = false;
if (_fieldName != null)
{
_fieldId = UNKNOWN_SYMBOL_ID; // depends on control dependency: [if], data = [none]
} else if (_fieldId > UNKNOWN_SYMBOL_ID)
{
// retaining the field SID, as it couldn't be cleared due to loss of context
// TODO - for SID handling consistency; this should attempt resolution first
sidsRemain = true; // depends on control dependency: [if], data = [none]
}
if (_annotations != null)
{
for (int i = 0; i < _annotations.length; i++)
{
SymbolToken annotation = _annotations[i];
// _annotations may have nulls at the end.
if (annotation == null) break;
String text = annotation.getText();
// TODO - for SID handling consistency; this should attempt resolution first, not just drop entry
if (text != null && annotation.getSid() != UNKNOWN_SYMBOL_ID)
{
_annotations[i] =
newSymbolToken(text, UNKNOWN_SYMBOL_ID); // depends on control dependency: [if], data = [none]
}
}
}
return !sidsRemain;
} } |
public class class_name {
public static long convertStringToFutureTimeMillis(String time) {
Calendar exp = Calendar.getInstance();
if (time.endsWith("H")) {
exp.add(Calendar.HOUR, Integer.valueOf(StringUtils.remove(time, 'H')));
} else if (time.endsWith("M")) {
exp.add(Calendar.MINUTE, Integer.valueOf(StringUtils.remove(time, 'M')));
} else if (time.endsWith("S")) {
exp.add(Calendar.MILLISECOND, Integer.valueOf(StringUtils.remove(time, 'S')) * 1000);
}
return exp.getTimeInMillis();
} } | public class class_name {
public static long convertStringToFutureTimeMillis(String time) {
Calendar exp = Calendar.getInstance();
if (time.endsWith("H")) {
exp.add(Calendar.HOUR, Integer.valueOf(StringUtils.remove(time, 'H')));
// depends on control dependency: [if], data = [none]
} else if (time.endsWith("M")) {
exp.add(Calendar.MINUTE, Integer.valueOf(StringUtils.remove(time, 'M')));
// depends on control dependency: [if], data = [none]
} else if (time.endsWith("S")) {
exp.add(Calendar.MILLISECOND, Integer.valueOf(StringUtils.remove(time, 'S')) * 1000);
// depends on control dependency: [if], data = [none]
}
return exp.getTimeInMillis();
} } |
public class class_name {
public FixedDelayBuilder<RetryBuilder<P>> fixedDelay() {
if (fixedDelay == null) {
fixedDelay = new FixedDelayBuilder<>(this, environmentBuilder);
}
return fixedDelay;
} } | public class class_name {
public FixedDelayBuilder<RetryBuilder<P>> fixedDelay() {
if (fixedDelay == null) {
fixedDelay = new FixedDelayBuilder<>(this, environmentBuilder); // depends on control dependency: [if], data = [none]
}
return fixedDelay;
} } |
public class class_name {
private Observable<Boolean> reconfigureBucket(final BucketConfig config) {
LOGGER.debug("Starting reconfiguration for bucket {}", config.name());
List<Observable<Boolean>> observables = new ArrayList<Observable<Boolean>>();
for (final NodeInfo nodeInfo : config.nodes()) {
final String alternate = nodeInfo.useAlternateNetwork();
final NetworkAddress altHost = alternate != null ? nodeInfo.alternateAddresses().get(alternate).hostname(): null;
Observable<Boolean> obs = addNode(nodeInfo.hostname(), altHost)
.flatMap(new Func1<LifecycleState, Observable<Map<ServiceType, Integer>>>() {
@Override
public Observable<Map<ServiceType, Integer>> call(final LifecycleState lifecycleState) {
Map<ServiceType, Integer> services;
if (alternate != null) {
AlternateAddress aa = nodeInfo.alternateAddresses().get(alternate);
services = environment.sslEnabled() ? aa.sslServices() : aa.services();
} else {
services = environment.sslEnabled() ? nodeInfo.sslServices() : nodeInfo.services();
}
return Observable.just(services);
}
}).flatMap(new Func1<Map<ServiceType, Integer>, Observable<AddServiceRequest>>() {
@Override
public Observable<AddServiceRequest> call(final Map<ServiceType, Integer> services) {
List<AddServiceRequest> requests = new ArrayList<AddServiceRequest>(services.size());
for (Map.Entry<ServiceType, Integer> service : services.entrySet()) {
requests.add(new AddServiceRequest(service.getKey(), config.name(), config.username(),
config.password(), service.getValue(), nodeInfo.hostname()));
}
return Observable.from(requests);
}
}).flatMap(new Func1<AddServiceRequest, Observable<Service>>() {
@Override
public Observable<Service> call(AddServiceRequest request) {
return addService(request);
}
}).last().map(new Func1<Service, Boolean>() {
@Override
public Boolean call(Service service) {
return true;
}
});
observables.add(obs);
}
return Observable.merge(observables).last();
} } | public class class_name {
private Observable<Boolean> reconfigureBucket(final BucketConfig config) {
LOGGER.debug("Starting reconfiguration for bucket {}", config.name());
List<Observable<Boolean>> observables = new ArrayList<Observable<Boolean>>();
for (final NodeInfo nodeInfo : config.nodes()) {
final String alternate = nodeInfo.useAlternateNetwork();
final NetworkAddress altHost = alternate != null ? nodeInfo.alternateAddresses().get(alternate).hostname(): null;
Observable<Boolean> obs = addNode(nodeInfo.hostname(), altHost)
.flatMap(new Func1<LifecycleState, Observable<Map<ServiceType, Integer>>>() {
@Override
public Observable<Map<ServiceType, Integer>> call(final LifecycleState lifecycleState) {
Map<ServiceType, Integer> services;
if (alternate != null) {
AlternateAddress aa = nodeInfo.alternateAddresses().get(alternate);
services = environment.sslEnabled() ? aa.sslServices() : aa.services(); // depends on control dependency: [if], data = [none]
} else {
services = environment.sslEnabled() ? nodeInfo.sslServices() : nodeInfo.services(); // depends on control dependency: [if], data = [none]
}
return Observable.just(services);
}
}).flatMap(new Func1<Map<ServiceType, Integer>, Observable<AddServiceRequest>>() {
@Override
public Observable<AddServiceRequest> call(final Map<ServiceType, Integer> services) {
List<AddServiceRequest> requests = new ArrayList<AddServiceRequest>(services.size());
for (Map.Entry<ServiceType, Integer> service : services.entrySet()) {
requests.add(new AddServiceRequest(service.getKey(), config.name(), config.username(),
config.password(), service.getValue(), nodeInfo.hostname())); // depends on control dependency: [for], data = [service]
}
return Observable.from(requests);
}
}).flatMap(new Func1<AddServiceRequest, Observable<Service>>() {
@Override
public Observable<Service> call(AddServiceRequest request) {
return addService(request);
}
}).last().map(new Func1<Service, Boolean>() {
@Override
public Boolean call(Service service) {
return true;
}
});
observables.add(obs); // depends on control dependency: [for], data = [none]
}
return Observable.merge(observables).last();
} } |
public class class_name {
public static char[] addToSortedCharArray(char[] a, char value) {
if(a == null || a.length == 0) {
return new char[] {value};
}
int insertionPochar = -java.util.Arrays.binarySearch(a, value) - 1;
if(insertionPochar < 0) {
throw new IllegalArgumentException(String.format("Element %d already exists in array", value));
}
char[] array = new char[a.length + 1];
if(insertionPochar > 0) {
System.arraycopy(a, 0, array, 0, insertionPochar);
}
array[insertionPochar] = value;
if(insertionPochar < a.length) {
System.arraycopy(a, insertionPochar, array, insertionPochar + 1, array.length - insertionPochar - 1);
}
return array;
} } | public class class_name {
public static char[] addToSortedCharArray(char[] a, char value) {
if(a == null || a.length == 0) {
return new char[] {value}; // depends on control dependency: [if], data = [none]
}
int insertionPochar = -java.util.Arrays.binarySearch(a, value) - 1;
if(insertionPochar < 0) {
throw new IllegalArgumentException(String.format("Element %d already exists in array", value));
}
char[] array = new char[a.length + 1];
if(insertionPochar > 0) {
System.arraycopy(a, 0, array, 0, insertionPochar); // depends on control dependency: [if], data = [none]
}
array[insertionPochar] = value;
if(insertionPochar < a.length) {
System.arraycopy(a, insertionPochar, array, insertionPochar + 1, array.length - insertionPochar - 1); // depends on control dependency: [if], data = [none]
}
return array;
} } |
public class class_name {
@DoesServiceRequest
public boolean createIfNotExists(FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException {
options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient);
this.getShare().assertNoSnapshot();
boolean exists = this.exists(true /* primaryOnly */, null /* accessCondition */, options, opContext);
if (exists) {
return false;
}
else {
try {
this.create(options, opContext);
return true;
}
catch (StorageException e) {
if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT
&& StorageErrorCodeStrings.RESOURCE_ALREADY_EXISTS.equals(e.getErrorCode())) {
return false;
}
else {
throw e;
}
}
}
} } | public class class_name {
@DoesServiceRequest
public boolean createIfNotExists(FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException {
options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient);
this.getShare().assertNoSnapshot();
boolean exists = this.exists(true /* primaryOnly */, null /* accessCondition */, options, opContext);
if (exists) {
return false;
}
else {
try {
this.create(options, opContext); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
}
catch (StorageException e) {
if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT
&& StorageErrorCodeStrings.RESOURCE_ALREADY_EXISTS.equals(e.getErrorCode())) {
return false; // depends on control dependency: [if], data = [none]
}
else {
throw e;
}
} // depends on control dependency: [catch], data = [none]
}
} } |
public class class_name {
boolean checkAvailablePush(Context context) {
int connectionStatus = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
if (connectionStatus == ConnectionResult.SUCCESS) {
log.i("Google Play Services are available on this device.");
return true;
} else {
if (GoogleApiAvailability.getInstance().isUserResolvableError(connectionStatus)) {
log.e("Google Play Services is probably not up to date. User recoverable Error Code is " + connectionStatus);
} else {
log.e("This device is not supported by Google Play Services.");
}
return false;
}
} } | public class class_name {
boolean checkAvailablePush(Context context) {
int connectionStatus = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
if (connectionStatus == ConnectionResult.SUCCESS) {
log.i("Google Play Services are available on this device."); // depends on control dependency: [if], data = [none]
return true; // depends on control dependency: [if], data = [none]
} else {
if (GoogleApiAvailability.getInstance().isUserResolvableError(connectionStatus)) {
log.e("Google Play Services is probably not up to date. User recoverable Error Code is " + connectionStatus); // depends on control dependency: [if], data = [none]
} else {
log.e("This device is not supported by Google Play Services."); // depends on control dependency: [if], data = [none]
}
return false; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
static Set<DriverEventCode> getEnabledDriverEventCodes(final String enabledLoggerEventCodes)
{
if (null == enabledLoggerEventCodes || "".equals(enabledLoggerEventCodes))
{
return EnumSet.noneOf(DriverEventCode.class);
}
final Set<DriverEventCode> eventCodeSet = new HashSet<>();
final String[] codeIds = enabledLoggerEventCodes.split(",");
for (final String codeId : codeIds)
{
switch (codeId)
{
case "all":
eventCodeSet.addAll(ALL_LOGGER_EVENT_CODES);
break;
case "admin":
eventCodeSet.addAll(ADMIN_ONLY_EVENT_CODES);
break;
default:
{
DriverEventCode code = null;
try
{
code = DriverEventCode.valueOf(codeId);
}
catch (final IllegalArgumentException ignore)
{
}
if (null == code)
{
try
{
code = DriverEventCode.get(Integer.parseInt(codeId));
}
catch (final IllegalArgumentException ignore)
{
}
}
if (null != code)
{
eventCodeSet.add(code);
}
else
{
System.err.println("unknown event code: " + codeId);
}
}
}
}
return eventCodeSet;
} } | public class class_name {
static Set<DriverEventCode> getEnabledDriverEventCodes(final String enabledLoggerEventCodes)
{
if (null == enabledLoggerEventCodes || "".equals(enabledLoggerEventCodes))
{
return EnumSet.noneOf(DriverEventCode.class); // depends on control dependency: [if], data = [none]
}
final Set<DriverEventCode> eventCodeSet = new HashSet<>();
final String[] codeIds = enabledLoggerEventCodes.split(",");
for (final String codeId : codeIds)
{
switch (codeId)
{
case "all":
eventCodeSet.addAll(ALL_LOGGER_EVENT_CODES);
break;
case "admin":
eventCodeSet.addAll(ADMIN_ONLY_EVENT_CODES);
break;
default:
{
DriverEventCode code = null;
try
{
code = DriverEventCode.valueOf(codeId); // depends on control dependency: [try], data = [none]
}
catch (final IllegalArgumentException ignore)
{
} // depends on control dependency: [catch], data = [none]
if (null == code)
{
try
{
code = DriverEventCode.get(Integer.parseInt(codeId)); // depends on control dependency: [try], data = [none]
}
catch (final IllegalArgumentException ignore)
{
} // depends on control dependency: [catch], data = [none]
}
if (null != code)
{
eventCodeSet.add(code); // depends on control dependency: [if], data = [code)]
}
else
{
System.err.println("unknown event code: " + codeId); // depends on control dependency: [if], data = [none]
}
}
}
}
return eventCodeSet;
} } |
public class class_name {
public static String pathToClassName(String path) {
path = path.replace('/', '.');
if (path.endsWith(CLASS_EXTENSION)) {
path = path.substring(0, path.length() - CLASS_EXTENSION.length());
}
return path;
} } | public class class_name {
public static String pathToClassName(String path) {
path = path.replace('/', '.');
if (path.endsWith(CLASS_EXTENSION)) {
path = path.substring(0, path.length() - CLASS_EXTENSION.length()); // depends on control dependency: [if], data = [none]
}
return path;
} } |
public class class_name {
public static void transformDocumentToXml(DomDocument document, StreamResult result) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
synchronized(document) {
transformer.transform(document.getDomSource(), result);
}
} catch (TransformerConfigurationException e) {
throw new ModelIoException("Unable to create a transformer for the model", e);
} catch (TransformerException e) {
throw new ModelIoException("Unable to transform model to xml", e);
}
} } | public class class_name {
public static void transformDocumentToXml(DomDocument document, StreamResult result) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try {
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // depends on control dependency: [try], data = [none]
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // depends on control dependency: [try], data = [none]
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
synchronized(document) {
transformer.transform(document.getDomSource(), result); // depends on control dependency: [try], data = [none]
}
} catch (TransformerConfigurationException e) {
throw new ModelIoException("Unable to create a transformer for the model", e);
} catch (TransformerException e) { // depends on control dependency: [catch], data = [none]
throw new ModelIoException("Unable to transform model to xml", e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public A_CmsReportThread retrieveThread(CmsUUID key) {
if (LOG.isDebugEnabled()) {
dumpThreads();
}
return m_threads.get(key);
} } | public class class_name {
public A_CmsReportThread retrieveThread(CmsUUID key) {
if (LOG.isDebugEnabled()) {
dumpThreads(); // depends on control dependency: [if], data = [none]
}
return m_threads.get(key);
} } |
public class class_name {
static void adjustPositionSet(
List<NodeInfo> order, Element positionSet, IntegrationResult result) {
Node nodeToMatch = positionSet.getFirstChild();
Element nodeToInsertBefore = positionSet.getOwnerDocument().createElement("INSERT_POINT");
positionSet.insertBefore(nodeToInsertBefore, nodeToMatch);
for (Iterator<NodeInfo> iter = order.iterator(); iter.hasNext(); ) {
NodeInfo ni = iter.next();
if (ni.getPositionDirective() != null) {
// found one check it against the current one in the position
// set to see if it is different. If so then indicate that
// something (the position set) has changed in the plf
if (ni.getPositionDirective() != nodeToMatch) result.setChangedPLF(true);
;
// now bump the insertion point forward prior to
// moving on to the next position node to be evaluated
if (nodeToMatch != null) nodeToMatch = nodeToMatch.getNextSibling();
// now insert it prior to insertion point
positionSet.insertBefore(ni.getPositionDirective(), nodeToInsertBefore);
}
}
// now for any left over after the insert point remove them.
int removeFails = 0; // avoid infinite loop, if stuck
while (nodeToInsertBefore.getNextSibling() != null && removeFails < 5) {
Node toRemove = nodeToInsertBefore.getNextSibling();
try {
toRemove.getParentNode().removeChild(toRemove);
} catch (DOMException de) {
LOG.error(
"DOM issue removing next child after insert point: {} -- {}",
toRemove.toString(),
de.getLocalizedMessage());
removeFails++;
}
}
// now remove the insertion point
if (nodeToInsertBefore.getParentNode() != null) {
nodeToInsertBefore.getParentNode().removeChild(nodeToInsertBefore);
}
} } | public class class_name {
static void adjustPositionSet(
List<NodeInfo> order, Element positionSet, IntegrationResult result) {
Node nodeToMatch = positionSet.getFirstChild();
Element nodeToInsertBefore = positionSet.getOwnerDocument().createElement("INSERT_POINT");
positionSet.insertBefore(nodeToInsertBefore, nodeToMatch);
for (Iterator<NodeInfo> iter = order.iterator(); iter.hasNext(); ) {
NodeInfo ni = iter.next();
if (ni.getPositionDirective() != null) {
// found one check it against the current one in the position
// set to see if it is different. If so then indicate that
// something (the position set) has changed in the plf
if (ni.getPositionDirective() != nodeToMatch) result.setChangedPLF(true);
;
// now bump the insertion point forward prior to
// moving on to the next position node to be evaluated
if (nodeToMatch != null) nodeToMatch = nodeToMatch.getNextSibling();
// now insert it prior to insertion point
positionSet.insertBefore(ni.getPositionDirective(), nodeToInsertBefore); // depends on control dependency: [if], data = [(ni.getPositionDirective()]
}
}
// now for any left over after the insert point remove them.
int removeFails = 0; // avoid infinite loop, if stuck
while (nodeToInsertBefore.getNextSibling() != null && removeFails < 5) {
Node toRemove = nodeToInsertBefore.getNextSibling();
try {
toRemove.getParentNode().removeChild(toRemove); // depends on control dependency: [try], data = [none]
} catch (DOMException de) {
LOG.error(
"DOM issue removing next child after insert point: {} -- {}",
toRemove.toString(),
de.getLocalizedMessage());
removeFails++;
} // depends on control dependency: [catch], data = [none]
}
// now remove the insertion point
if (nodeToInsertBefore.getParentNode() != null) {
nodeToInsertBefore.getParentNode().removeChild(nodeToInsertBefore); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public Space findSpace(float x, float y) {
for (int i=0;i<spaces.size();i++) {
Space space = getSpace(i);
if (space.contains(x,y)) {
return space;
}
}
return null;
} } | public class class_name {
public Space findSpace(float x, float y) {
for (int i=0;i<spaces.size();i++) {
Space space = getSpace(i);
if (space.contains(x,y)) {
return space; // depends on control dependency: [if], data = [none]
}
}
return null;
} } |
public class class_name {
@Override
public StreamOperatorStateContext streamOperatorStateContext(
@Nonnull OperatorID operatorID,
@Nonnull String operatorClassName,
@Nonnull KeyContext keyContext,
@Nullable TypeSerializer<?> keySerializer,
@Nonnull CloseableRegistry streamTaskCloseableRegistry,
@Nonnull MetricGroup metricGroup) throws Exception {
TaskInfo taskInfo = environment.getTaskInfo();
OperatorSubtaskDescriptionText operatorSubtaskDescription =
new OperatorSubtaskDescriptionText(
operatorID,
operatorClassName,
taskInfo.getIndexOfThisSubtask(),
taskInfo.getNumberOfParallelSubtasks());
final String operatorIdentifierText = operatorSubtaskDescription.toString();
final PrioritizedOperatorSubtaskState prioritizedOperatorSubtaskStates =
taskStateManager.prioritizedOperatorState(operatorID);
AbstractKeyedStateBackend<?> keyedStatedBackend = null;
OperatorStateBackend operatorStateBackend = null;
CloseableIterable<KeyGroupStatePartitionStreamProvider> rawKeyedStateInputs = null;
CloseableIterable<StatePartitionStreamProvider> rawOperatorStateInputs = null;
InternalTimeServiceManager<?> timeServiceManager;
try {
// -------------- Keyed State Backend --------------
keyedStatedBackend = keyedStatedBackend(
keySerializer,
operatorIdentifierText,
prioritizedOperatorSubtaskStates,
streamTaskCloseableRegistry,
metricGroup);
// -------------- Operator State Backend --------------
operatorStateBackend = operatorStateBackend(
operatorIdentifierText,
prioritizedOperatorSubtaskStates,
streamTaskCloseableRegistry);
// -------------- Raw State Streams --------------
rawKeyedStateInputs = rawKeyedStateInputs(
prioritizedOperatorSubtaskStates.getPrioritizedRawKeyedState().iterator());
streamTaskCloseableRegistry.registerCloseable(rawKeyedStateInputs);
rawOperatorStateInputs = rawOperatorStateInputs(
prioritizedOperatorSubtaskStates.getPrioritizedRawOperatorState().iterator());
streamTaskCloseableRegistry.registerCloseable(rawOperatorStateInputs);
// -------------- Internal Timer Service Manager --------------
timeServiceManager = internalTimeServiceManager(keyedStatedBackend, keyContext, rawKeyedStateInputs);
// -------------- Preparing return value --------------
return new StreamOperatorStateContextImpl(
prioritizedOperatorSubtaskStates.isRestored(),
operatorStateBackend,
keyedStatedBackend,
timeServiceManager,
rawOperatorStateInputs,
rawKeyedStateInputs);
} catch (Exception ex) {
// cleanup if something went wrong before results got published.
if (keyedStatedBackend != null) {
if (streamTaskCloseableRegistry.unregisterCloseable(keyedStatedBackend)) {
IOUtils.closeQuietly(keyedStatedBackend);
}
// release resource (e.g native resource)
keyedStatedBackend.dispose();
}
if (operatorStateBackend != null) {
if (streamTaskCloseableRegistry.unregisterCloseable(operatorStateBackend)) {
IOUtils.closeQuietly(operatorStateBackend);
}
operatorStateBackend.dispose();
}
if (streamTaskCloseableRegistry.unregisterCloseable(rawKeyedStateInputs)) {
IOUtils.closeQuietly(rawKeyedStateInputs);
}
if (streamTaskCloseableRegistry.unregisterCloseable(rawOperatorStateInputs)) {
IOUtils.closeQuietly(rawOperatorStateInputs);
}
throw new Exception("Exception while creating StreamOperatorStateContext.", ex);
}
} } | public class class_name {
@Override
public StreamOperatorStateContext streamOperatorStateContext(
@Nonnull OperatorID operatorID,
@Nonnull String operatorClassName,
@Nonnull KeyContext keyContext,
@Nullable TypeSerializer<?> keySerializer,
@Nonnull CloseableRegistry streamTaskCloseableRegistry,
@Nonnull MetricGroup metricGroup) throws Exception {
TaskInfo taskInfo = environment.getTaskInfo();
OperatorSubtaskDescriptionText operatorSubtaskDescription =
new OperatorSubtaskDescriptionText(
operatorID,
operatorClassName,
taskInfo.getIndexOfThisSubtask(),
taskInfo.getNumberOfParallelSubtasks());
final String operatorIdentifierText = operatorSubtaskDescription.toString();
final PrioritizedOperatorSubtaskState prioritizedOperatorSubtaskStates =
taskStateManager.prioritizedOperatorState(operatorID);
AbstractKeyedStateBackend<?> keyedStatedBackend = null;
OperatorStateBackend operatorStateBackend = null;
CloseableIterable<KeyGroupStatePartitionStreamProvider> rawKeyedStateInputs = null;
CloseableIterable<StatePartitionStreamProvider> rawOperatorStateInputs = null;
InternalTimeServiceManager<?> timeServiceManager;
try {
// -------------- Keyed State Backend --------------
keyedStatedBackend = keyedStatedBackend(
keySerializer,
operatorIdentifierText,
prioritizedOperatorSubtaskStates,
streamTaskCloseableRegistry,
metricGroup);
// -------------- Operator State Backend --------------
operatorStateBackend = operatorStateBackend(
operatorIdentifierText,
prioritizedOperatorSubtaskStates,
streamTaskCloseableRegistry);
// -------------- Raw State Streams --------------
rawKeyedStateInputs = rawKeyedStateInputs(
prioritizedOperatorSubtaskStates.getPrioritizedRawKeyedState().iterator());
streamTaskCloseableRegistry.registerCloseable(rawKeyedStateInputs);
rawOperatorStateInputs = rawOperatorStateInputs(
prioritizedOperatorSubtaskStates.getPrioritizedRawOperatorState().iterator());
streamTaskCloseableRegistry.registerCloseable(rawOperatorStateInputs);
// -------------- Internal Timer Service Manager --------------
timeServiceManager = internalTimeServiceManager(keyedStatedBackend, keyContext, rawKeyedStateInputs);
// -------------- Preparing return value --------------
return new StreamOperatorStateContextImpl(
prioritizedOperatorSubtaskStates.isRestored(),
operatorStateBackend,
keyedStatedBackend,
timeServiceManager,
rawOperatorStateInputs,
rawKeyedStateInputs);
} catch (Exception ex) {
// cleanup if something went wrong before results got published.
if (keyedStatedBackend != null) {
if (streamTaskCloseableRegistry.unregisterCloseable(keyedStatedBackend)) {
IOUtils.closeQuietly(keyedStatedBackend); // depends on control dependency: [if], data = [none]
}
// release resource (e.g native resource)
keyedStatedBackend.dispose(); // depends on control dependency: [if], data = [none]
}
if (operatorStateBackend != null) {
if (streamTaskCloseableRegistry.unregisterCloseable(operatorStateBackend)) {
IOUtils.closeQuietly(operatorStateBackend); // depends on control dependency: [if], data = [none]
}
operatorStateBackend.dispose(); // depends on control dependency: [if], data = [none]
}
if (streamTaskCloseableRegistry.unregisterCloseable(rawKeyedStateInputs)) {
IOUtils.closeQuietly(rawKeyedStateInputs); // depends on control dependency: [if], data = [none]
}
if (streamTaskCloseableRegistry.unregisterCloseable(rawOperatorStateInputs)) {
IOUtils.closeQuietly(rawOperatorStateInputs); // depends on control dependency: [if], data = [none]
}
throw new Exception("Exception while creating StreamOperatorStateContext.", ex);
}
} } |
public class class_name {
private static void quoteList(final Collection<String> coll, final StringBuilder buf) {
buf.append('[');
boolean first = true;
for (final String item : coll) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append('"');
for (int i = 0; i < item.length(); i++) {
final char c = item.charAt(i);
if (c == '"') {
buf.append("\\\"");
} else {
buf.append(c);
}
}
buf.append('"');
}
buf.append(']');
} } | public class class_name {
private static void quoteList(final Collection<String> coll, final StringBuilder buf) {
buf.append('[');
boolean first = true;
for (final String item : coll) {
if (first) {
first = false; // depends on control dependency: [if], data = [none]
} else {
buf.append(", "); // depends on control dependency: [if], data = [none]
}
buf.append('"'); // depends on control dependency: [for], data = [none]
for (int i = 0; i < item.length(); i++) {
final char c = item.charAt(i);
if (c == '"') {
buf.append("\\\""); // depends on control dependency: [if], data = [none]
} else {
buf.append(c); // depends on control dependency: [if], data = [(c]
}
}
buf.append('"'); // depends on control dependency: [for], data = [none]
}
buf.append(']');
} } |
public class class_name {
static public void registerFactory( FeatureType datatype, Class c) {
if (!(TypedDatasetFactoryIF.class.isAssignableFrom( c)))
throw new IllegalArgumentException("Class "+c.getName()+" must implement TypedDatasetFactoryIF");
// fail fast - check newInstance works
Object instance;
try {
instance = c.newInstance();
} catch (InstantiationException e) {
throw new IllegalArgumentException("CoordTransBuilderIF Class "+c.getName()+" cannot instantiate, probably need default Constructor");
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("CoordTransBuilderIF Class "+c.getName()+" is not accessible");
}
// user stuff gets put at top
if (userMode)
transformList.add( 0, new Factory( datatype, c, (TypedDatasetFactoryIF) instance));
else
transformList.add( new Factory( datatype, c, (TypedDatasetFactoryIF)instance));
} } | public class class_name {
static public void registerFactory( FeatureType datatype, Class c) {
if (!(TypedDatasetFactoryIF.class.isAssignableFrom( c)))
throw new IllegalArgumentException("Class "+c.getName()+" must implement TypedDatasetFactoryIF");
// fail fast - check newInstance works
Object instance;
try {
instance = c.newInstance(); // depends on control dependency: [try], data = [none]
} catch (InstantiationException e) {
throw new IllegalArgumentException("CoordTransBuilderIF Class "+c.getName()+" cannot instantiate, probably need default Constructor");
} catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none]
throw new IllegalArgumentException("CoordTransBuilderIF Class "+c.getName()+" is not accessible");
} // depends on control dependency: [catch], data = [none]
// user stuff gets put at top
if (userMode)
transformList.add( 0, new Factory( datatype, c, (TypedDatasetFactoryIF) instance));
else
transformList.add( new Factory( datatype, c, (TypedDatasetFactoryIF)instance));
} } |
public class class_name {
private void handleGroupChannel(JsonNode jsonChannel) {
long channelId = jsonChannel.get("id").asLong();
api.getGroupChannelById(channelId).map(GroupChannelImpl.class::cast).ifPresent(channel -> {
String oldName = channel.getName().orElseThrow(AssertionError::new);
String newName = jsonChannel.get("name").asText();
if (!Objects.equals(oldName, newName)) {
channel.setName(newName);
GroupChannelChangeNameEvent event =
new GroupChannelChangeNameEventImpl(channel, newName, oldName);
api.getEventDispatcher().dispatchGroupChannelChangeNameEvent(
api, Collections.singleton(channel), channel.getMembers(), event);
}
});
} } | public class class_name {
private void handleGroupChannel(JsonNode jsonChannel) {
long channelId = jsonChannel.get("id").asLong();
api.getGroupChannelById(channelId).map(GroupChannelImpl.class::cast).ifPresent(channel -> {
String oldName = channel.getName().orElseThrow(AssertionError::new);
String newName = jsonChannel.get("name").asText();
if (!Objects.equals(oldName, newName)) {
channel.setName(newName); // depends on control dependency: [if], data = [none]
GroupChannelChangeNameEvent event =
new GroupChannelChangeNameEventImpl(channel, newName, oldName);
api.getEventDispatcher().dispatchGroupChannelChangeNameEvent(
api, Collections.singleton(channel), channel.getMembers(), event); // depends on control dependency: [if], data = [none]
}
});
} } |
public class class_name {
public synchronized DirectoryScanner setExcludes(String[] excludes) {
if (excludes == null) {
this.excludes = null;
} else {
this.excludes = new String[excludes.length];
for (int i = 0; i < excludes.length; i++) {
this.excludes[i] = normalizePattern(excludes[i]);
}
}
return this;
} } | public class class_name {
public synchronized DirectoryScanner setExcludes(String[] excludes) {
if (excludes == null) {
this.excludes = null; // depends on control dependency: [if], data = [none]
} else {
this.excludes = new String[excludes.length]; // depends on control dependency: [if], data = [none]
for (int i = 0; i < excludes.length; i++) {
this.excludes[i] = normalizePattern(excludes[i]); // depends on control dependency: [for], data = [i]
}
}
return this;
} } |
public class class_name {
protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) {
try {
if (file == null) {
throw new IllegalArgumentException("File must not be null!");
}
CmsLock lock = cms.getLock(file);
CmsUser user = cms.getRequestContext().getCurrentUser();
boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject()
&& (lock.isOwnedBy(user) || lock.isLockableBy(user))
&& cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT);
boolean isReadOnly = !canWrite;
boolean isFolder = file.isFolder();
boolean isRoot = file.getRootPath().length() <= 1;
Set<Action> aas = new LinkedHashSet<Action>();
addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot);
addAction(aas, Action.CAN_GET_PROPERTIES, true);
addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly);
addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot);
addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot);
if (isFolder) {
addAction(aas, Action.CAN_GET_DESCENDANTS, true);
addAction(aas, Action.CAN_GET_CHILDREN, true);
addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot);
addAction(aas, Action.CAN_GET_FOLDER_TREE, true);
addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly);
addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly);
addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly);
} else {
addAction(aas, Action.CAN_GET_CONTENT_STREAM, true);
addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly);
addAction(aas, Action.CAN_GET_ALL_VERSIONS, true);
}
AllowableActionsImpl result = new AllowableActionsImpl();
result.setAllowableActions(aas);
return result;
} catch (CmsException e) {
handleCmsException(e);
return null;
}
} } | public class class_name {
protected AllowableActions collectAllowableActions(CmsObject cms, CmsResource file) {
try {
if (file == null) {
throw new IllegalArgumentException("File must not be null!");
}
CmsLock lock = cms.getLock(file);
CmsUser user = cms.getRequestContext().getCurrentUser();
boolean canWrite = !cms.getRequestContext().getCurrentProject().isOnlineProject()
&& (lock.isOwnedBy(user) || lock.isLockableBy(user))
&& cms.hasPermissions(file, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.DEFAULT);
boolean isReadOnly = !canWrite;
boolean isFolder = file.isFolder();
boolean isRoot = file.getRootPath().length() <= 1;
Set<Action> aas = new LinkedHashSet<Action>();
addAction(aas, Action.CAN_GET_OBJECT_PARENTS, !isRoot);
// depends on control dependency: [try], data = [none]
addAction(aas, Action.CAN_GET_PROPERTIES, true);
// depends on control dependency: [try], data = [none]
addAction(aas, Action.CAN_UPDATE_PROPERTIES, !isReadOnly);
// depends on control dependency: [try], data = [none]
addAction(aas, Action.CAN_MOVE_OBJECT, !isReadOnly && !isRoot);
// depends on control dependency: [try], data = [none]
addAction(aas, Action.CAN_DELETE_OBJECT, !isReadOnly && !isRoot);
// depends on control dependency: [try], data = [none]
if (isFolder) {
addAction(aas, Action.CAN_GET_DESCENDANTS, true);
// depends on control dependency: [if], data = [none]
addAction(aas, Action.CAN_GET_CHILDREN, true);
// depends on control dependency: [if], data = [none]
addAction(aas, Action.CAN_GET_FOLDER_PARENT, !isRoot);
// depends on control dependency: [if], data = [none]
addAction(aas, Action.CAN_GET_FOLDER_TREE, true);
// depends on control dependency: [if], data = [none]
addAction(aas, Action.CAN_CREATE_DOCUMENT, !isReadOnly);
// depends on control dependency: [if], data = [none]
addAction(aas, Action.CAN_CREATE_FOLDER, !isReadOnly);
// depends on control dependency: [if], data = [none]
addAction(aas, Action.CAN_DELETE_TREE, !isReadOnly);
// depends on control dependency: [if], data = [none]
} else {
addAction(aas, Action.CAN_GET_CONTENT_STREAM, true);
// depends on control dependency: [if], data = [none]
addAction(aas, Action.CAN_SET_CONTENT_STREAM, !isReadOnly);
// depends on control dependency: [if], data = [none]
addAction(aas, Action.CAN_GET_ALL_VERSIONS, true);
// depends on control dependency: [if], data = [none]
}
AllowableActionsImpl result = new AllowableActionsImpl();
result.setAllowableActions(aas);
// depends on control dependency: [try], data = [none]
return result;
// depends on control dependency: [try], data = [none]
} catch (CmsException e) {
handleCmsException(e);
return null;
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static <T> T readObjectFromFile(String file, Class<T> clazz, boolean printException) {
final FileInputStream fileIn;
try {
fileIn = new FileInputStream(file);
} catch (Exception e) {
printException(e, printException);
return null;
}
final BufferedInputStream bufferedIn = new BufferedInputStream(fileIn);
final ObjectInputStream objIn;
try {
objIn = new ObjectInputStream(bufferedIn);
} catch (Exception e) {
printException(e, printException);
closeInputStream(fileIn, printException);
return null;
}
final Object ret;
try {
ret = objIn.readObject();
} catch (Exception e) {
printException(e, printException);
closeInputStream(objIn, printException); // objIn.close() also closes fileIn
return null;
}
closeInputStream(objIn, printException); // objIn.close() also closes fileIn
return clazz.cast(ret);
} } | public class class_name {
public static <T> T readObjectFromFile(String file, Class<T> clazz, boolean printException) {
final FileInputStream fileIn;
try {
fileIn = new FileInputStream(file);
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
printException(e, printException);
return null;
}
// depends on control dependency: [catch], data = [none]
final BufferedInputStream bufferedIn = new BufferedInputStream(fileIn);
final ObjectInputStream objIn;
try {
objIn = new ObjectInputStream(bufferedIn);
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
printException(e, printException);
closeInputStream(fileIn, printException);
return null;
}
// depends on control dependency: [catch], data = [none]
final Object ret;
try {
ret = objIn.readObject();
// depends on control dependency: [try], data = [none]
} catch (Exception e) {
printException(e, printException);
closeInputStream(objIn, printException); // objIn.close() also closes fileIn
return null;
}
// depends on control dependency: [catch], data = [none]
closeInputStream(objIn, printException); // objIn.close() also closes fileIn
return clazz.cast(ret);
} } |
public class class_name {
boolean allowsValue(String str, ValidationContext vc) {
try {
getValue(str, vc);
return true;
}
catch (DatatypeException e) {
return false;
}
} } | public class class_name {
boolean allowsValue(String str, ValidationContext vc) {
try {
getValue(str, vc); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
}
catch (DatatypeException e) {
return false;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private int[] doLabel( int[] data, int width, int height ) {
int nextlabel = 1;
int nbs[] = new int[4];
int nbls[] = new int[4];
// Get size of image and make 1d_arrays
int d_w = width;
int d_h = height;
int[] dest_1d = new int[d_w * d_h];
// the most labels there can be is 1/2 of the points
// in checkerboard
int[] labels = new int[d_w * d_h / 2];
int result = 0;
// labelsValid = false; // only set to true once we've complete the task
// initialise labels
for( int i = 0; i < labels.length; i++ )
labels[i] = i;
int count;
// now Label the image
for( int i = 0; i < data.length; i++ ) {
int src1rgb = data[i] & 0x000000ff;
if (src1rgb == 0) {
result = 0; // nothing here
} else {
// The 4 visited neighbours
nbs[0] = getNeighbours(data, i, -1, 0, d_w, d_h);
nbs[1] = getNeighbours(data, i, 0, -1, d_w, d_h);
nbs[2] = getNeighbours(data, i, -1, -1, d_w, d_h);
nbs[3] = getNeighbours(data, i, 1, -1, d_w, d_h);
// Their corresponding labels
nbls[0] = getNeighbourd(dest_1d, i, -1, 0, d_w, d_h);
nbls[1] = getNeighbourd(dest_1d, i, 0, -1, d_w, d_h);
nbls[2] = getNeighbourd(dest_1d, i, -1, -1, d_w, d_h);
nbls[3] = getNeighbourd(dest_1d, i, 1, -1, d_w, d_h);
// label the point
if ((nbs[0] == nbs[1]) && (nbs[1] == nbs[2]) && (nbs[2] == nbs[3]) && (nbs[0] == 0)) {
// all neighbours are 0 so gives this point a new label
result = nextlabel;
nextlabel++;
} else { // one or more neighbours have already got labels
count = 0;
int found = -1;
for( int j = 0; j < 4; j++ ) {
if (nbs[j] != 0) {
count += 1;
found = j;
}
}
if (count == 1) {
// only one neighbour has a label, so assign the same label to this.
result = nbls[found];
} else {
// more than 1 neighbour has a label
result = nbls[found];
// Equivalence the connected points
for( int j = 0; j < 4; j++ ) {
if ((nbls[j] != 0) && (nbls[j] != result)) {
associate(nbls[j], result, labels);
}
}
}
}
}
dest_1d[i] = result;
}
// reduce labels ie 76=23=22=3 -> 76=3
// done in reverse order to preserve sorting
for( int i = labels.length - 1; i > 0; i-- ) {
labels[i] = reduce(i, labels);
}
/*now labels will look something like 1=1 2=2 3=2 4=2 5=5.. 76=5 77=5
this needs to be condensed down again, so that there is no wasted
space eg in the above, the labels 3 and 4 are not used instead it jumps
to 5.
*/
int condensed[] = new int[nextlabel]; // cant be more than nextlabel labels
count = 0;
for( int i = 0; i < nextlabel; i++ ) {
if (i == labels[i])
condensed[i] = count++;
}
// Record the number of labels
int numberOfLabels = count - 1;
// now run back through our preliminary results, replacing the raw label
// with the reduced and condensed one, and do the scaling and offsets too
// Now generate an array of colours which will be used to label the image
int[] labelColors = new int[numberOfLabels + 1];
// Variable used to check if the color generated is acceptable
// boolean acceptColor = false;
for( int i = 0; i < labelColors.length; i++ ) {
// acceptColor = false;
// while( !acceptColor ) {
// double tmp = Math.random();
// labelColors[i] = (int) (tmp * 16777215);
// if (((labelColors[i] & 0x000000ff) < 200) && (((labelColors[i] & 0x0000ff00) >> 8) <
// 64) && (((labelColors[i] & 0x00ff0000) >> 16) < 64)) {
// // Color to be rejected so don't set acceptColor
// } else {
// acceptColor = true;
// }
// }
// if (i == 0)
// labelColors[i] = 0;
labelColors[i] = i;
}
for( int i = 0; i < data.length; i++ ) {
result = condensed[labels[dest_1d[i]]];
// result = (int) ( scale * (float) result + oset );
// truncate if necessary
// if( result > 255 ) result = 255;
// if( result < 0 ) result = 0;
// produce grayscale
// dest_1d[i] = 0xff000000 | (result + (result << 16) + (result << 8));
dest_1d[i] = labelColors[result];// + 0xff000000;
}
// labelsValid = true; // only set to true now we've complete the task
return dest_1d;
} } | public class class_name {
private int[] doLabel( int[] data, int width, int height ) {
int nextlabel = 1;
int nbs[] = new int[4];
int nbls[] = new int[4];
// Get size of image and make 1d_arrays
int d_w = width;
int d_h = height;
int[] dest_1d = new int[d_w * d_h];
// the most labels there can be is 1/2 of the points
// in checkerboard
int[] labels = new int[d_w * d_h / 2];
int result = 0;
// labelsValid = false; // only set to true once we've complete the task
// initialise labels
for( int i = 0; i < labels.length; i++ )
labels[i] = i;
int count;
// now Label the image
for( int i = 0; i < data.length; i++ ) {
int src1rgb = data[i] & 0x000000ff;
if (src1rgb == 0) {
result = 0; // nothing here // depends on control dependency: [if], data = [none]
} else {
// The 4 visited neighbours
nbs[0] = getNeighbours(data, i, -1, 0, d_w, d_h); // depends on control dependency: [if], data = [none]
nbs[1] = getNeighbours(data, i, 0, -1, d_w, d_h); // depends on control dependency: [if], data = [none]
nbs[2] = getNeighbours(data, i, -1, -1, d_w, d_h); // depends on control dependency: [if], data = [none]
nbs[3] = getNeighbours(data, i, 1, -1, d_w, d_h); // depends on control dependency: [if], data = [none]
// Their corresponding labels
nbls[0] = getNeighbourd(dest_1d, i, -1, 0, d_w, d_h); // depends on control dependency: [if], data = [none]
nbls[1] = getNeighbourd(dest_1d, i, 0, -1, d_w, d_h); // depends on control dependency: [if], data = [none]
nbls[2] = getNeighbourd(dest_1d, i, -1, -1, d_w, d_h); // depends on control dependency: [if], data = [none]
nbls[3] = getNeighbourd(dest_1d, i, 1, -1, d_w, d_h); // depends on control dependency: [if], data = [none]
// label the point
if ((nbs[0] == nbs[1]) && (nbs[1] == nbs[2]) && (nbs[2] == nbs[3]) && (nbs[0] == 0)) {
// all neighbours are 0 so gives this point a new label
result = nextlabel; // depends on control dependency: [if], data = [none]
nextlabel++; // depends on control dependency: [if], data = [none]
} else { // one or more neighbours have already got labels
count = 0; // depends on control dependency: [if], data = [none]
int found = -1;
for( int j = 0; j < 4; j++ ) {
if (nbs[j] != 0) {
count += 1; // depends on control dependency: [if], data = [none]
found = j; // depends on control dependency: [if], data = [none]
}
}
if (count == 1) {
// only one neighbour has a label, so assign the same label to this.
result = nbls[found]; // depends on control dependency: [if], data = [none]
} else {
// more than 1 neighbour has a label
result = nbls[found]; // depends on control dependency: [if], data = [none]
// Equivalence the connected points
for( int j = 0; j < 4; j++ ) {
if ((nbls[j] != 0) && (nbls[j] != result)) {
associate(nbls[j], result, labels); // depends on control dependency: [if], data = [none]
}
}
}
}
}
dest_1d[i] = result; // depends on control dependency: [for], data = [i]
}
// reduce labels ie 76=23=22=3 -> 76=3
// done in reverse order to preserve sorting
for( int i = labels.length - 1; i > 0; i-- ) {
labels[i] = reduce(i, labels); // depends on control dependency: [for], data = [i]
}
/*now labels will look something like 1=1 2=2 3=2 4=2 5=5.. 76=5 77=5
this needs to be condensed down again, so that there is no wasted
space eg in the above, the labels 3 and 4 are not used instead it jumps
to 5.
*/
int condensed[] = new int[nextlabel]; // cant be more than nextlabel labels
count = 0;
for( int i = 0; i < nextlabel; i++ ) {
if (i == labels[i])
condensed[i] = count++;
}
// Record the number of labels
int numberOfLabels = count - 1;
// now run back through our preliminary results, replacing the raw label
// with the reduced and condensed one, and do the scaling and offsets too
// Now generate an array of colours which will be used to label the image
int[] labelColors = new int[numberOfLabels + 1];
// Variable used to check if the color generated is acceptable
// boolean acceptColor = false;
for( int i = 0; i < labelColors.length; i++ ) {
// acceptColor = false;
// while( !acceptColor ) {
// double tmp = Math.random();
// labelColors[i] = (int) (tmp * 16777215);
// if (((labelColors[i] & 0x000000ff) < 200) && (((labelColors[i] & 0x0000ff00) >> 8) <
// 64) && (((labelColors[i] & 0x00ff0000) >> 16) < 64)) {
// // Color to be rejected so don't set acceptColor
// } else {
// acceptColor = true;
// }
// }
// if (i == 0)
// labelColors[i] = 0;
labelColors[i] = i; // depends on control dependency: [for], data = [i]
}
for( int i = 0; i < data.length; i++ ) {
result = condensed[labels[dest_1d[i]]]; // depends on control dependency: [for], data = [i]
// result = (int) ( scale * (float) result + oset );
// truncate if necessary
// if( result > 255 ) result = 255;
// if( result < 0 ) result = 0;
// produce grayscale
// dest_1d[i] = 0xff000000 | (result + (result << 16) + (result << 8));
dest_1d[i] = labelColors[result];// + 0xff000000; // depends on control dependency: [for], data = [i]
}
// labelsValid = true; // only set to true now we've complete the task
return dest_1d;
} } |
public class class_name {
public Block withEntityTypes(String... entityTypes) {
if (this.entityTypes == null) {
setEntityTypes(new java.util.ArrayList<String>(entityTypes.length));
}
for (String ele : entityTypes) {
this.entityTypes.add(ele);
}
return this;
} } | public class class_name {
public Block withEntityTypes(String... entityTypes) {
if (this.entityTypes == null) {
setEntityTypes(new java.util.ArrayList<String>(entityTypes.length)); // depends on control dependency: [if], data = [none]
}
for (String ele : entityTypes) {
this.entityTypes.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
private void sendPending() {
while (outstanding.get() < concurrency) {
final TopicQueue queue = pendingTopics.poll();
if (queue == null) {
return;
}
queue.pending = false;
final int sent = queue.sendBatch();
// Did we send a whole batch? Then there might be more messages in the queue. Mark as pending again.
if (sent == batchSize) {
queue.pending = true;
pendingTopics.offer(queue);
}
}
} } | public class class_name {
private void sendPending() {
while (outstanding.get() < concurrency) {
final TopicQueue queue = pendingTopics.poll();
if (queue == null) {
return; // depends on control dependency: [if], data = [none]
}
queue.pending = false; // depends on control dependency: [while], data = [none]
final int sent = queue.sendBatch();
// Did we send a whole batch? Then there might be more messages in the queue. Mark as pending again.
if (sent == batchSize) {
queue.pending = true; // depends on control dependency: [if], data = [none]
pendingTopics.offer(queue); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
private void checkPoint(Collidable objectA, Map<Point, Set<Collidable>> acceptedElements, Point point)
{
final Set<Collidable> others = acceptedElements.get(point);
for (final Collidable objectB : others)
{
if (objectA != objectB)
{
final List<Collision> collisions = objectA.collide(objectB);
for (final Collision collision : collisions)
{
toNotify.add(new Collided(objectA, objectB, collision));
}
}
}
} } | public class class_name {
private void checkPoint(Collidable objectA, Map<Point, Set<Collidable>> acceptedElements, Point point)
{
final Set<Collidable> others = acceptedElements.get(point);
for (final Collidable objectB : others)
{
if (objectA != objectB)
{
final List<Collision> collisions = objectA.collide(objectB);
for (final Collision collision : collisions)
{
toNotify.add(new Collided(objectA, objectB, collision)); // depends on control dependency: [for], data = [collision]
}
}
}
} } |
public class class_name {
public int getInteger(String name, int defaultValue) {
try {
String value = getString(name, null);
if (!StringUtils.isNullOrEmpty(value)) {
return Integer.parseInt(value.trim());
}
} catch (NumberFormatException e) {
log.warn("Failed to parse integer for " + name + USING_DEFAULT_OF
+ defaultValue);
}
return defaultValue;
} } | public class class_name {
public int getInteger(String name, int defaultValue) {
try {
String value = getString(name, null);
if (!StringUtils.isNullOrEmpty(value)) {
return Integer.parseInt(value.trim()); // depends on control dependency: [if], data = [none]
}
} catch (NumberFormatException e) {
log.warn("Failed to parse integer for " + name + USING_DEFAULT_OF
+ defaultValue);
} // depends on control dependency: [catch], data = [none]
return defaultValue;
} } |
public class class_name {
@Override
public Collection<Symptom> detect(Collection<Measurement> measurements) {
publishingMetrics.executeDetectorIncr(BACK_PRESSURE_DETECTOR);
Collection<Symptom> result = new ArrayList<>();
Instant now = context.checkpoint();
MeasurementsTable bpMetrics
= MeasurementsTable.of(measurements).type(METRIC_BACK_PRESSURE.text());
for (String component : bpMetrics.uniqueComponents()) {
double compBackPressure = bpMetrics.component(component).sum();
if (compBackPressure > noiseFilterMillis) {
LOG.info(String.format("Detected component back-pressure for %s, total back pressure is %f",
component, compBackPressure));
List<String> addresses = Collections.singletonList(component);
result.add(new Symptom(SYMPTOM_COMP_BACK_PRESSURE.text(), now, addresses));
}
}
for (String instance : bpMetrics.uniqueInstances()) {
double totalBP = bpMetrics.instance(instance).sum();
if (totalBP > noiseFilterMillis) {
LOG.info(String.format("Detected instance back-pressure for %s, total back pressure is %f",
instance, totalBP));
List<String> addresses = Collections.singletonList(instance);
result.add(new Symptom(SYMPTOM_INSTANCE_BACK_PRESSURE.text(), now, addresses));
}
}
return result;
} } | public class class_name {
@Override
public Collection<Symptom> detect(Collection<Measurement> measurements) {
publishingMetrics.executeDetectorIncr(BACK_PRESSURE_DETECTOR);
Collection<Symptom> result = new ArrayList<>();
Instant now = context.checkpoint();
MeasurementsTable bpMetrics
= MeasurementsTable.of(measurements).type(METRIC_BACK_PRESSURE.text());
for (String component : bpMetrics.uniqueComponents()) {
double compBackPressure = bpMetrics.component(component).sum();
if (compBackPressure > noiseFilterMillis) {
LOG.info(String.format("Detected component back-pressure for %s, total back pressure is %f",
component, compBackPressure)); // depends on control dependency: [if], data = [none]
List<String> addresses = Collections.singletonList(component);
result.add(new Symptom(SYMPTOM_COMP_BACK_PRESSURE.text(), now, addresses)); // depends on control dependency: [if], data = [none]
}
}
for (String instance : bpMetrics.uniqueInstances()) {
double totalBP = bpMetrics.instance(instance).sum();
if (totalBP > noiseFilterMillis) {
LOG.info(String.format("Detected instance back-pressure for %s, total back pressure is %f",
instance, totalBP)); // depends on control dependency: [if], data = [none]
List<String> addresses = Collections.singletonList(instance);
result.add(new Symptom(SYMPTOM_INSTANCE_BACK_PRESSURE.text(), now, addresses)); // depends on control dependency: [if], data = [none]
}
}
return result;
} } |
public class class_name {
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
ExitStatus status = stepExecution.getExitStatus();
List<String> errors = getErrors();
if (errors.isEmpty()) {
try {
RestoreStatus newStatus = RestoreStatus.TRANSFER_TO_DURACLOUD_COMPLETE;
restoreManager.transitionRestoreStatus(restorationId, newStatus, "");
// restore the snapshot props file to the data directory.
restoreFile(new File(this.watchDir.getParentFile(), Constants.SNAPSHOT_PROPS_FILENAME),
watchDir.getParentFile());
return status.and(ExitStatus.COMPLETED);
} catch (Exception e) {
String message = "failed to transition restore status: " + e.getMessage();
log.error(message, e);
return status.and(ExitStatus.FAILED).addExitDescription(message);
}
} else {
status = status.and(ExitStatus.FAILED);
status.addExitDescription("Transfer to DuraCloud failed: " +
errors.size() + " items failed.");
for (String error : errors) {
status.addExitDescription(error);
}
resetContextState();
return status;
}
} } | public class class_name {
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
ExitStatus status = stepExecution.getExitStatus();
List<String> errors = getErrors();
if (errors.isEmpty()) {
try {
RestoreStatus newStatus = RestoreStatus.TRANSFER_TO_DURACLOUD_COMPLETE;
restoreManager.transitionRestoreStatus(restorationId, newStatus, ""); // depends on control dependency: [try], data = [none]
// restore the snapshot props file to the data directory.
restoreFile(new File(this.watchDir.getParentFile(), Constants.SNAPSHOT_PROPS_FILENAME),
watchDir.getParentFile()); // depends on control dependency: [try], data = [none]
return status.and(ExitStatus.COMPLETED); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
String message = "failed to transition restore status: " + e.getMessage();
log.error(message, e);
return status.and(ExitStatus.FAILED).addExitDescription(message);
} // depends on control dependency: [catch], data = [none]
} else {
status = status.and(ExitStatus.FAILED); // depends on control dependency: [if], data = [none]
status.addExitDescription("Transfer to DuraCloud failed: " +
errors.size() + " items failed."); // depends on control dependency: [if], data = [none]
for (String error : errors) {
status.addExitDescription(error); // depends on control dependency: [for], data = [error]
}
resetContextState(); // depends on control dependency: [if], data = [none]
return status; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void put_device_attribute_property(Database database, String deviceName, DbAttribute[] attr)
throws DevFailed {
if (!database.isAccess_checked()) checkAccess(database);
DeviceData argIn = new DeviceData();
try {
// value is an array
argIn.insert(ApiUtil.toStringArray(deviceName, attr, 2));
command_inout(database, "DbPutDeviceAttributeProperty2", argIn);
} catch (DevFailed e) {
if (e.errors[0].reason.equals("API_CommandNotFound")) {
// Value is just one element
argIn.insert(ApiUtil.toStringArray(deviceName, attr, 1));
command_inout(database, "DbPutDeviceAttributeProperty", argIn);
} else
throw e;
}
} } | public class class_name {
public void put_device_attribute_property(Database database, String deviceName, DbAttribute[] attr)
throws DevFailed {
if (!database.isAccess_checked()) checkAccess(database);
DeviceData argIn = new DeviceData();
try {
// value is an array
argIn.insert(ApiUtil.toStringArray(deviceName, attr, 2));
command_inout(database, "DbPutDeviceAttributeProperty2", argIn);
} catch (DevFailed e) {
if (e.errors[0].reason.equals("API_CommandNotFound")) {
// Value is just one element
argIn.insert(ApiUtil.toStringArray(deviceName, attr, 1)); // depends on control dependency: [if], data = [none]
command_inout(database, "DbPutDeviceAttributeProperty", argIn); // depends on control dependency: [if], data = [none]
} else
throw e;
}
} } |
public class class_name {
private static Properties loadPropsFromResource(String resourceName, boolean failOnResourceNotFoundOrNotLoaded) {
Properties props = new Properties();
InputStream resource = PropertyLoaderFromResource.class.getResourceAsStream(resourceName);
boolean resourceNotFound = (resource == null);
if(resourceNotFound) {
if(failOnResourceNotFoundOrNotLoaded) {
throw new ConfigException("resource " + resourceName + " not found");
} else {
// if the resource is not found, return an empty Properties
logger.warn("Skipping resource " + resourceName + ": file not found.");
return props;
}
}
try {
props.load(resource);
} catch (IOException e) {
if(failOnResourceNotFoundOrNotLoaded)
throw new ConfigException("Cannot load properties from " + resourceName, e);
else
logger.warn("Cannot load properties from " + resourceName + ": " + e.getMessage());
}
return props;
} } | public class class_name {
private static Properties loadPropsFromResource(String resourceName, boolean failOnResourceNotFoundOrNotLoaded) {
Properties props = new Properties();
InputStream resource = PropertyLoaderFromResource.class.getResourceAsStream(resourceName);
boolean resourceNotFound = (resource == null);
if(resourceNotFound) {
if(failOnResourceNotFoundOrNotLoaded) {
throw new ConfigException("resource " + resourceName + " not found");
} else {
// if the resource is not found, return an empty Properties
logger.warn("Skipping resource " + resourceName + ": file not found."); // depends on control dependency: [if], data = [none]
return props; // depends on control dependency: [if], data = [none]
}
}
try {
props.load(resource); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
if(failOnResourceNotFoundOrNotLoaded)
throw new ConfigException("Cannot load properties from " + resourceName, e);
else
logger.warn("Cannot load properties from " + resourceName + ": " + e.getMessage());
} // depends on control dependency: [catch], data = [none]
return props;
} } |
public class class_name {
@Override
public void close() {
//at the moment the only thing that might need to happen is to stop the timeout...
//however, if execution has completed normally and as designed, the timeout will already be stopped
//one day there might be more things that need closing
if (this.timeout != null) {
this.timeout.stop();
}
metricRecorder.recordTimeoutExecutionTime(System.nanoTime() - startTime);
this.closed = true;
} } | public class class_name {
@Override
public void close() {
//at the moment the only thing that might need to happen is to stop the timeout...
//however, if execution has completed normally and as designed, the timeout will already be stopped
//one day there might be more things that need closing
if (this.timeout != null) {
this.timeout.stop(); // depends on control dependency: [if], data = [none]
}
metricRecorder.recordTimeoutExecutionTime(System.nanoTime() - startTime);
this.closed = true;
} } |
public class class_name {
public ClientStats getStatsForProcedure(String procedureName) {
Map<Long, Map<String, ClientStats>> complete = getCompleteStats();
List<ClientStats> statsForProc = new ArrayList<ClientStats>();
for (Entry<Long, Map<String, ClientStats>> e : complete.entrySet()) {
ClientStats procStats = e.getValue().get(procedureName);
if (procStats != null) {
statsForProc.add(procStats);
}
}
if (statsForProc.size() == 0) {
return null;
}
return ClientStats.merge(statsForProc);
} } | public class class_name {
public ClientStats getStatsForProcedure(String procedureName) {
Map<Long, Map<String, ClientStats>> complete = getCompleteStats();
List<ClientStats> statsForProc = new ArrayList<ClientStats>();
for (Entry<Long, Map<String, ClientStats>> e : complete.entrySet()) {
ClientStats procStats = e.getValue().get(procedureName);
if (procStats != null) {
statsForProc.add(procStats); // depends on control dependency: [if], data = [(procStats]
}
}
if (statsForProc.size() == 0) {
return null; // depends on control dependency: [if], data = [none]
}
return ClientStats.merge(statsForProc);
} } |
public class class_name {
public static Integer toInteger(Object v) {
if (v == null) {
return null;
}
if (v instanceof Boolean) {
return ((Boolean) v) ? 1 : 0;
}
return ((Number) v).intValue();
} } | public class class_name {
public static Integer toInteger(Object v) {
if (v == null) {
return null; // depends on control dependency: [if], data = [none]
}
if (v instanceof Boolean) {
return ((Boolean) v) ? 1 : 0; // depends on control dependency: [if], data = [none]
}
return ((Number) v).intValue();
} } |
public class class_name {
public void setCompanyName(java.util.Collection<StringFilter> companyName) {
if (companyName == null) {
this.companyName = null;
return;
}
this.companyName = new java.util.ArrayList<StringFilter>(companyName);
} } | public class class_name {
public void setCompanyName(java.util.Collection<StringFilter> companyName) {
if (companyName == null) {
this.companyName = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.companyName = new java.util.ArrayList<StringFilter>(companyName);
} } |
public class class_name {
public void setCommandExecutor(ActionCommandExecutor commandExecutor) {
if (ObjectUtils.nullSafeEquals(this.commandExecutor, commandExecutor)) {
return;
}
if (commandExecutor == null) {
detachCommandExecutor();
}
else {
if (this.commandExecutor instanceof GuardedActionCommandExecutor) {
unsubscribeFromGuardedCommandDelegate();
}
this.commandExecutor = commandExecutor;
attachCommandExecutor();
}
} } | public class class_name {
public void setCommandExecutor(ActionCommandExecutor commandExecutor) {
if (ObjectUtils.nullSafeEquals(this.commandExecutor, commandExecutor)) {
return; // depends on control dependency: [if], data = [none]
}
if (commandExecutor == null) {
detachCommandExecutor(); // depends on control dependency: [if], data = [none]
}
else {
if (this.commandExecutor instanceof GuardedActionCommandExecutor) {
unsubscribeFromGuardedCommandDelegate(); // depends on control dependency: [if], data = [none]
}
this.commandExecutor = commandExecutor; // depends on control dependency: [if], data = [none]
attachCommandExecutor(); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static void pause(long delay)
{
try
{
Thread.sleep(delay);
}
catch (@SuppressWarnings("unused") final InterruptedException exception)
{
Thread.currentThread().interrupt();
}
} } | public class class_name {
public static void pause(long delay)
{
try
{
Thread.sleep(delay);
// depends on control dependency: [try], data = [none]
}
catch (@SuppressWarnings("unused") final InterruptedException exception)
{
Thread.currentThread().interrupt();
}
// depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public void marshall(BulkDeploymentMetrics bulkDeploymentMetrics, ProtocolMarshaller protocolMarshaller) {
if (bulkDeploymentMetrics == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(bulkDeploymentMetrics.getInvalidInputRecords(), INVALIDINPUTRECORDS_BINDING);
protocolMarshaller.marshall(bulkDeploymentMetrics.getRecordsProcessed(), RECORDSPROCESSED_BINDING);
protocolMarshaller.marshall(bulkDeploymentMetrics.getRetryAttempts(), RETRYATTEMPTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(BulkDeploymentMetrics bulkDeploymentMetrics, ProtocolMarshaller protocolMarshaller) {
if (bulkDeploymentMetrics == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(bulkDeploymentMetrics.getInvalidInputRecords(), INVALIDINPUTRECORDS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(bulkDeploymentMetrics.getRecordsProcessed(), RECORDSPROCESSED_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(bulkDeploymentMetrics.getRetryAttempts(), RETRYATTEMPTS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static AsciiString of(CharSequence name) {
if (name instanceof AsciiString) {
return of((AsciiString) name);
}
final String lowerCased = Ascii.toLowerCase(requireNonNull(name, "name"));
final AsciiString cached = map.get(lowerCased);
return cached != null ? cached : AsciiString.cached(lowerCased);
} } | public class class_name {
public static AsciiString of(CharSequence name) {
if (name instanceof AsciiString) {
return of((AsciiString) name); // depends on control dependency: [if], data = [none]
}
final String lowerCased = Ascii.toLowerCase(requireNonNull(name, "name"));
final AsciiString cached = map.get(lowerCased);
return cached != null ? cached : AsciiString.cached(lowerCased);
} } |
public class class_name {
public static List<Method> getPublicMethod(Class<?> clz) {
Method[] methods = clz.getMethods();
List<Method> ret = new ArrayList<Method>();
for (Method method : methods) {
boolean isPublic = Modifier.isPublic(method.getModifiers());
boolean isNotObjectClass = method.getDeclaringClass() != Object.class;
if (isPublic && isNotObjectClass) {
ret.add(method);
}
}
return ret;
} } | public class class_name {
public static List<Method> getPublicMethod(Class<?> clz) {
Method[] methods = clz.getMethods();
List<Method> ret = new ArrayList<Method>();
for (Method method : methods) {
boolean isPublic = Modifier.isPublic(method.getModifiers());
boolean isNotObjectClass = method.getDeclaringClass() != Object.class;
if (isPublic && isNotObjectClass) {
ret.add(method); // depends on control dependency: [if], data = [none]
}
}
return ret;
} } |
public class class_name {
public static long getDirLogicalSize(List<FileStatus> lfs) {
long totalSize = 0L;
if (null == lfs) {
return totalSize;
}
for (FileStatus fsStat : lfs) {
totalSize += fsStat.getLen();
}
return totalSize;
} } | public class class_name {
public static long getDirLogicalSize(List<FileStatus> lfs) {
long totalSize = 0L;
if (null == lfs) {
return totalSize; // depends on control dependency: [if], data = [none]
}
for (FileStatus fsStat : lfs) {
totalSize += fsStat.getLen(); // depends on control dependency: [for], data = [fsStat]
}
return totalSize;
} } |
public class class_name {
private RSAPublicKey getKeyForUser(String userName) throws KeyNotFoundException {
RSAPublicKey key = null;
for (final KeyProvider keyProvider : keyProviders) {
try {
key = keyProvider.getKey(userName);
break;
} catch (KeyNotFoundException e) {
// that's fine, try the next provider
}
}
if (key == null) {
throw new KeyNotFoundException();
}
return key;
} } | public class class_name {
private RSAPublicKey getKeyForUser(String userName) throws KeyNotFoundException {
RSAPublicKey key = null;
for (final KeyProvider keyProvider : keyProviders) {
try {
key = keyProvider.getKey(userName); // depends on control dependency: [try], data = [none]
break;
} catch (KeyNotFoundException e) {
// that's fine, try the next provider
} // depends on control dependency: [catch], data = [none]
}
if (key == null) {
throw new KeyNotFoundException();
}
return key;
} } |
public class class_name {
public void marshall(DisassociateConnectionFromLagRequest disassociateConnectionFromLagRequest, ProtocolMarshaller protocolMarshaller) {
if (disassociateConnectionFromLagRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(disassociateConnectionFromLagRequest.getConnectionId(), CONNECTIONID_BINDING);
protocolMarshaller.marshall(disassociateConnectionFromLagRequest.getLagId(), LAGID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DisassociateConnectionFromLagRequest disassociateConnectionFromLagRequest, ProtocolMarshaller protocolMarshaller) {
if (disassociateConnectionFromLagRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(disassociateConnectionFromLagRequest.getConnectionId(), CONNECTIONID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(disassociateConnectionFromLagRequest.getLagId(), LAGID_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 Converter<?, NetworkRequest> requestConverter(Type type, Annotation[] annotations) {
checkNotNull(type, "type == null");
checkNotNull(annotations, "annotations == null");
for (int i = 0, count = converters.size(); i < count; i++) {
Converter<?, NetworkRequest> converter =
converters.get(i).toRequest(type, annotations);
if (converter != null) {
return converter;
}
}
StringBuilder builder = new StringBuilder("Could not locate Request converter for ")
.append(type)
.append(". Tried:");
for (Factory converterFactory : converters) {
builder.append("\n * ").append(converterFactory.getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
} } | public class class_name {
public Converter<?, NetworkRequest> requestConverter(Type type, Annotation[] annotations) {
checkNotNull(type, "type == null");
checkNotNull(annotations, "annotations == null");
for (int i = 0, count = converters.size(); i < count; i++) {
Converter<?, NetworkRequest> converter =
converters.get(i).toRequest(type, annotations);
if (converter != null) {
return converter; // depends on control dependency: [if], data = [none]
}
}
StringBuilder builder = new StringBuilder("Could not locate Request converter for ")
.append(type)
.append(". Tried:");
for (Factory converterFactory : converters) {
builder.append("\n * ").append(converterFactory.getClass().getName()); // depends on control dependency: [for], data = [converterFactory]
}
throw new IllegalArgumentException(builder.toString());
} } |
public class class_name {
protected void writePackageFiles(QualifiedName name, String lineSeparator,
IExtraLanguageGeneratorContext context) {
final IFileSystemAccess2 fsa = context.getFileSystemAccess();
final String outputConfiguration = getOutputConfigurationName();
QualifiedName libraryName = null;
for (final String segment : name.skipLast(1).getSegments()) {
if (libraryName == null) {
libraryName = QualifiedName.create(segment, LIBRARY_FILENAME);
} else {
libraryName = libraryName.append(segment).append(LIBRARY_FILENAME);
}
final String fileName = toFilename(libraryName);
if (!fsa.isFile(fileName)) {
final String content = PYTHON_FILE_HEADER + lineSeparator
+ getGenerationComment(context) + lineSeparator
+ LIBRARY_CONTENT;
if (Strings.isEmpty(outputConfiguration)) {
fsa.generateFile(fileName, content);
} else {
fsa.generateFile(fileName, outputConfiguration, content);
}
}
libraryName = libraryName.skipLast(1);
}
} } | public class class_name {
protected void writePackageFiles(QualifiedName name, String lineSeparator,
IExtraLanguageGeneratorContext context) {
final IFileSystemAccess2 fsa = context.getFileSystemAccess();
final String outputConfiguration = getOutputConfigurationName();
QualifiedName libraryName = null;
for (final String segment : name.skipLast(1).getSegments()) {
if (libraryName == null) {
libraryName = QualifiedName.create(segment, LIBRARY_FILENAME); // depends on control dependency: [if], data = [none]
} else {
libraryName = libraryName.append(segment).append(LIBRARY_FILENAME); // depends on control dependency: [if], data = [none]
}
final String fileName = toFilename(libraryName);
if (!fsa.isFile(fileName)) {
final String content = PYTHON_FILE_HEADER + lineSeparator
+ getGenerationComment(context) + lineSeparator
+ LIBRARY_CONTENT;
if (Strings.isEmpty(outputConfiguration)) {
fsa.generateFile(fileName, content); // depends on control dependency: [if], data = [none]
} else {
fsa.generateFile(fileName, outputConfiguration, content); // depends on control dependency: [if], data = [none]
}
}
libraryName = libraryName.skipLast(1); // depends on control dependency: [for], data = [none]
}
} } |
public class class_name {
void emitMinusOne(int tc) {
if (tc == LONGcode) {
items.makeImmediateItem(syms.longType, Long.valueOf(-1)).load();
} else {
code.emitop0(iconst_m1);
}
} } | public class class_name {
void emitMinusOne(int tc) {
if (tc == LONGcode) {
items.makeImmediateItem(syms.longType, Long.valueOf(-1)).load(); // depends on control dependency: [if], data = [none]
} else {
code.emitop0(iconst_m1); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void marshall(ImportSourceCredentialsRequest importSourceCredentialsRequest, ProtocolMarshaller protocolMarshaller) {
if (importSourceCredentialsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(importSourceCredentialsRequest.getUsername(), USERNAME_BINDING);
protocolMarshaller.marshall(importSourceCredentialsRequest.getToken(), TOKEN_BINDING);
protocolMarshaller.marshall(importSourceCredentialsRequest.getServerType(), SERVERTYPE_BINDING);
protocolMarshaller.marshall(importSourceCredentialsRequest.getAuthType(), AUTHTYPE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(ImportSourceCredentialsRequest importSourceCredentialsRequest, ProtocolMarshaller protocolMarshaller) {
if (importSourceCredentialsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(importSourceCredentialsRequest.getUsername(), USERNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(importSourceCredentialsRequest.getToken(), TOKEN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(importSourceCredentialsRequest.getServerType(), SERVERTYPE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(importSourceCredentialsRequest.getAuthType(), AUTHTYPE_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static short getShort(MemorySegment[] segments, int offset) {
if (inFirstSegment(segments, offset, 2)) {
return segments[0].getShort(offset);
} else {
return getShortMultiSegments(segments, offset);
}
} } | public class class_name {
public static short getShort(MemorySegment[] segments, int offset) {
if (inFirstSegment(segments, offset, 2)) {
return segments[0].getShort(offset); // depends on control dependency: [if], data = [none]
} else {
return getShortMultiSegments(segments, offset); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private ImageMetaData readImageMetaData() {
InputStream inputStream = null;
ImageMetaData metaData = null;
try {
inputStream = getInputStream();
metaData = BitmapUtil.decodeDimensionsAndColorSpace(inputStream);
mColorSpace = metaData.getColorSpace();
Pair<Integer, Integer> dimensions = metaData.getDimensions();
if (dimensions != null) {
mWidth = dimensions.first;
mHeight = dimensions.second;
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// Head in the sand
}
}
}
return metaData;
} } | public class class_name {
private ImageMetaData readImageMetaData() {
InputStream inputStream = null;
ImageMetaData metaData = null;
try {
inputStream = getInputStream(); // depends on control dependency: [try], data = [none]
metaData = BitmapUtil.decodeDimensionsAndColorSpace(inputStream); // depends on control dependency: [try], data = [none]
mColorSpace = metaData.getColorSpace(); // depends on control dependency: [try], data = [none]
Pair<Integer, Integer> dimensions = metaData.getDimensions();
if (dimensions != null) {
mWidth = dimensions.first; // depends on control dependency: [if], data = [none]
mHeight = dimensions.second; // depends on control dependency: [if], data = [none]
}
} finally {
if (inputStream != null) {
try {
inputStream.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
// Head in the sand
} // depends on control dependency: [catch], data = [none]
}
}
return metaData;
} } |
public class class_name {
protected int marshalMessagesToSameDestination(Address dest, Message[] buf, final int start_index, final int end_index,
int max_bundle_size) throws Exception {
int num_msgs=0, bytes=0;
for(int i=start_index; i != end_index; i=increment(i)) {
Message msg=buf[i];
if(msg != null && msg != NULL_MSG && Objects.equals(dest, msg.dest())) {
long msg_size=msg.size();
if(bytes + msg_size > max_bundle_size)
break;
bytes+=msg_size;
num_msgs++;
buf[i]=NULL_MSG;
msg.writeToNoAddrs(msg.src(), output, transport.getId());
}
}
return num_msgs;
} } | public class class_name {
protected int marshalMessagesToSameDestination(Address dest, Message[] buf, final int start_index, final int end_index,
int max_bundle_size) throws Exception {
int num_msgs=0, bytes=0;
for(int i=start_index; i != end_index; i=increment(i)) {
Message msg=buf[i];
if(msg != null && msg != NULL_MSG && Objects.equals(dest, msg.dest())) {
long msg_size=msg.size();
if(bytes + msg_size > max_bundle_size)
break;
bytes+=msg_size; // depends on control dependency: [if], data = [none]
num_msgs++; // depends on control dependency: [if], data = [none]
buf[i]=NULL_MSG; // depends on control dependency: [if], data = [none]
msg.writeToNoAddrs(msg.src(), output, transport.getId()); // depends on control dependency: [if], data = [(msg]
}
}
return num_msgs;
} } |
public class class_name {
public JimfsPath createPath(@Nullable Name root, Iterable<Name> names) {
ImmutableList<Name> nameList = ImmutableList.copyOf(Iterables.filter(names, NOT_EMPTY));
if (root == null && nameList.isEmpty()) {
// ensure the canonical empty path (one empty string name) is used rather than a path with
// no root and no names
return emptyPath();
}
return createPathInternal(root, nameList);
} } | public class class_name {
public JimfsPath createPath(@Nullable Name root, Iterable<Name> names) {
ImmutableList<Name> nameList = ImmutableList.copyOf(Iterables.filter(names, NOT_EMPTY));
if (root == null && nameList.isEmpty()) {
// ensure the canonical empty path (one empty string name) is used rather than a path with
// no root and no names
return emptyPath(); // depends on control dependency: [if], data = [none]
}
return createPathInternal(root, nameList);
} } |
public class class_name {
static public List<String> breakUpCommand(String command) throws Exception{
try {
List<String> commandTokens = new Vector<String>();
StringBuilder currentToken = null;
boolean isTokenQuoted = false;
StringReader sr = new StringReader(command);
int b = sr.read();
while( b >= 0 ){
char c = (char)b;
if( null == currentToken ){
// At token is not in progress
// Skipping spaces
if( ' ' == c || '\t' == c ){
} else if( '"' == c ) {
// Starting a quoted token
currentToken = new StringBuilder();
//currentToken.append(c);
isTokenQuoted = true;
} else {
// Starting a non-quoted token
currentToken = new StringBuilder();
currentToken.append(c);
isTokenQuoted = false;
}
} else if( isTokenQuoted ) {
// A quoted token is in progress. It ends with a quote
if( '"' == c ){
//currentToken.append(c);
String token = currentToken.toString();
currentToken = null;
commandTokens.add(token);
} else {
// Continuation
currentToken.append(c);
}
} else {
// A non-quoted token is in progress. It ends with a space
if( ' ' == c || '\t' == c ){
String token = currentToken.toString();
currentToken = null;
commandTokens.add(token);
} else {
// Continuation
currentToken.append(c);
}
}
b = sr.read();
}
if( null != currentToken ){
String token = currentToken.toString();
commandTokens.add(token);
}
return commandTokens;
} catch (IOException e) {
throw new Exception("Error while breaking up command into tokens: "+command,e);
}
} } | public class class_name {
static public List<String> breakUpCommand(String command) throws Exception{
try {
List<String> commandTokens = new Vector<String>();
StringBuilder currentToken = null;
boolean isTokenQuoted = false;
StringReader sr = new StringReader(command);
int b = sr.read();
while( b >= 0 ){
char c = (char)b;
if( null == currentToken ){
// At token is not in progress
// Skipping spaces
if( ' ' == c || '\t' == c ){
} else if( '"' == c ) {
// Starting a quoted token
currentToken = new StringBuilder(); // depends on control dependency: [if], data = [none]
//currentToken.append(c);
isTokenQuoted = true; // depends on control dependency: [if], data = [none]
} else {
// Starting a non-quoted token
currentToken = new StringBuilder(); // depends on control dependency: [if], data = [none]
currentToken.append(c); // depends on control dependency: [if], data = [none]
isTokenQuoted = false; // depends on control dependency: [if], data = [none]
}
} else if( isTokenQuoted ) {
// A quoted token is in progress. It ends with a quote
if( '"' == c ){
//currentToken.append(c);
String token = currentToken.toString();
currentToken = null; // depends on control dependency: [if], data = [none]
commandTokens.add(token); // depends on control dependency: [if], data = [none]
} else {
// Continuation
currentToken.append(c); // depends on control dependency: [if], data = [none]
}
} else {
// A non-quoted token is in progress. It ends with a space
if( ' ' == c || '\t' == c ){
String token = currentToken.toString();
currentToken = null; // depends on control dependency: [if], data = [none]
commandTokens.add(token); // depends on control dependency: [if], data = [none]
} else {
// Continuation
currentToken.append(c); // depends on control dependency: [if], data = [none]
}
}
b = sr.read();
}
if( null != currentToken ){
String token = currentToken.toString();
commandTokens.add(token);
}
return commandTokens;
} catch (IOException e) {
throw new Exception("Error while breaking up command into tokens: "+command,e);
}
} } |
public class class_name {
public static List<List<String>> convertWritableInputToString(List<List<Writable>> stringInput,Schema schema) {
List<List<String>> ret = new ArrayList<>();
List<List<String>> timeStepAdd = new ArrayList<>();
for(int j = 0; j < stringInput.size(); j++) {
List<Writable> record = stringInput.get(j);
List<String> recordAdd = new ArrayList<>();
for(int k = 0; k < record.size(); k++) {
recordAdd.add(record.get(k).toString());
}
timeStepAdd.add(recordAdd);
}
return ret;
} } | public class class_name {
public static List<List<String>> convertWritableInputToString(List<List<Writable>> stringInput,Schema schema) {
List<List<String>> ret = new ArrayList<>();
List<List<String>> timeStepAdd = new ArrayList<>();
for(int j = 0; j < stringInput.size(); j++) {
List<Writable> record = stringInput.get(j);
List<String> recordAdd = new ArrayList<>();
for(int k = 0; k < record.size(); k++) {
recordAdd.add(record.get(k).toString()); // depends on control dependency: [for], data = [k]
}
timeStepAdd.add(recordAdd); // depends on control dependency: [for], data = [none]
}
return ret;
} } |
public class class_name {
@Override
public void visitClassContext(ClassContext clsContext) {
try {
stack = new OpcodeStack();
clsVersion = clsContext.getJavaClass().getMajor();
unendedZLIBs = new HashMap<>();
super.visitClassContext(clsContext);
} finally {
unendedZLIBs = null;
stack = null;
}
} } | public class class_name {
@Override
public void visitClassContext(ClassContext clsContext) {
try {
stack = new OpcodeStack(); // depends on control dependency: [try], data = [none]
clsVersion = clsContext.getJavaClass().getMajor(); // depends on control dependency: [try], data = [none]
unendedZLIBs = new HashMap<>(); // depends on control dependency: [try], data = [none]
super.visitClassContext(clsContext); // depends on control dependency: [try], data = [none]
} finally {
unendedZLIBs = null;
stack = null;
}
} } |
public class class_name {
public static String getBaseDir() {
// 'basedir' is set by Maven Surefire. It always points to the current subproject,
// even in reactor builds.
String baseDir = System.getProperty("basedir");
// if 'basedir' is not set, try the current directory
if (baseDir == null) {
baseDir = System.getProperty("user.dir");
}
return baseDir;
} } | public class class_name {
public static String getBaseDir() {
// 'basedir' is set by Maven Surefire. It always points to the current subproject,
// even in reactor builds.
String baseDir = System.getProperty("basedir");
// if 'basedir' is not set, try the current directory
if (baseDir == null) {
baseDir = System.getProperty("user.dir"); // depends on control dependency: [if], data = [none]
}
return baseDir;
} } |
public class class_name {
public static List<ReflectedInfo> getExposedFieldInfo(final Class<?> clazz) {
List<ReflectedInfo> results = null;
try {
results = fieldInfoCache.get(clazz, new Callable<List<ReflectedInfo>>() {
/**
* This method is called if the value is not found in the cache. This
* is where the real reflection work is done.
*/
public List<ReflectedInfo> call() throws Exception {
List<ReflectedInfo> exposed = new ArrayList<ReflectedInfo>();
for (Method m : clazz.getMethods()) {
if(isIgnored(m)) {
continue;
}
boolean methodIsSirenProperty = m.getAnnotation(Siren4JProperty.class) != null;
String methodAnnotationName = extractEffectiveName(m, null);
if (ReflectionUtils.isGetter(m)) {
Field f = getGetterField(m);
if(f != null && isIgnored(f)) {
continue;
}
if (f != null) {
String fieldAnnotationName = extractEffectiveName(f, null);
String effectiveName = (String)findFirstNonNull(
Arrays.asList(fieldAnnotationName, methodAnnotationName, f.getName()).iterator()
);
exposed.add(
new ReflectedInfo(f, m, ReflectionUtils.getSetter(clazz, f), effectiveName)
);
} else if(methodIsSirenProperty) {// looks like we have getter not backed by field
exposed.add(
ReflectedInfoBuilder.aReflectedInfo().
withGetter(m).
withEffectiveName(extractEffectiveName(m, stripGetterPrefix(m.getName()))).
build()
);
}
} else if(methodIsSirenProperty) {
exposed.add(
ReflectedInfoBuilder.aReflectedInfo().
withGetter(m).
withEffectiveName(extractEffectiveName(m, m.getName())).
build()
);
}
}
return exposed;
}
});
} catch (ExecutionException e) {
throw new Siren4JRuntimeException(e);
}
return results;
} } | public class class_name {
public static List<ReflectedInfo> getExposedFieldInfo(final Class<?> clazz) {
List<ReflectedInfo> results = null;
try {
results = fieldInfoCache.get(clazz, new Callable<List<ReflectedInfo>>() {
/**
* This method is called if the value is not found in the cache. This
* is where the real reflection work is done.
*/
public List<ReflectedInfo> call() throws Exception {
List<ReflectedInfo> exposed = new ArrayList<ReflectedInfo>();
for (Method m : clazz.getMethods()) {
if(isIgnored(m)) {
continue;
}
boolean methodIsSirenProperty = m.getAnnotation(Siren4JProperty.class) != null;
String methodAnnotationName = extractEffectiveName(m, null);
if (ReflectionUtils.isGetter(m)) {
Field f = getGetterField(m);
if(f != null && isIgnored(f)) {
continue;
}
if (f != null) {
String fieldAnnotationName = extractEffectiveName(f, null);
String effectiveName = (String)findFirstNonNull(
Arrays.asList(fieldAnnotationName, methodAnnotationName, f.getName()).iterator()
);
exposed.add(
new ReflectedInfo(f, m, ReflectionUtils.getSetter(clazz, f), effectiveName)
);
// depends on control dependency: [if], data = [none]
} else if(methodIsSirenProperty) {// looks like we have getter not backed by field
exposed.add(
ReflectedInfoBuilder.aReflectedInfo().
withGetter(m).
withEffectiveName(extractEffectiveName(m, stripGetterPrefix(m.getName()))).
build()
);
// depends on control dependency: [if], data = [none]
}
} else if(methodIsSirenProperty) {
exposed.add(
ReflectedInfoBuilder.aReflectedInfo().
withGetter(m).
withEffectiveName(extractEffectiveName(m, m.getName())).
build()
);
}
}
return exposed;
}
});
// depends on control dependency: [try], data = [none]
} catch (ExecutionException e) {
throw new Siren4JRuntimeException(e);
}
// depends on control dependency: [catch], data = [none]
return results;
} } |
public class class_name {
JCTree attribSpeculative(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
final JCTree newTree = new TreeCopier<Object>(make).copy(tree);
Env<AttrContext> speculativeEnv = env.dup(newTree, env.info.dup(env.info.scope.dupUnshared()));
speculativeEnv.info.scope.owner = env.info.scope.owner;
Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
new Log.DeferredDiagnosticHandler(log, new Filter<JCDiagnostic>() {
public boolean accepts(final JCDiagnostic d) {
class PosScanner extends TreeScanner {
boolean found = false;
@Override
public void scan(JCTree tree) {
if (tree != null &&
tree.pos() == d.getDiagnosticPosition()) {
found = true;
}
super.scan(tree);
}
};
PosScanner posScanner = new PosScanner();
posScanner.scan(newTree);
return posScanner.found;
}
});
try {
attr.attribTree(newTree, speculativeEnv, resultInfo);
unenterScanner.scan(newTree);
return newTree;
} finally {
unenterScanner.scan(newTree);
log.popDiagnosticHandler(deferredDiagnosticHandler);
}
} } | public class class_name {
JCTree attribSpeculative(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
final JCTree newTree = new TreeCopier<Object>(make).copy(tree);
Env<AttrContext> speculativeEnv = env.dup(newTree, env.info.dup(env.info.scope.dupUnshared()));
speculativeEnv.info.scope.owner = env.info.scope.owner;
Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
new Log.DeferredDiagnosticHandler(log, new Filter<JCDiagnostic>() {
public boolean accepts(final JCDiagnostic d) {
class PosScanner extends TreeScanner {
boolean found = false;
@Override
public void scan(JCTree tree) {
if (tree != null &&
tree.pos() == d.getDiagnosticPosition()) {
found = true; // depends on control dependency: [if], data = [none]
}
super.scan(tree);
}
};
PosScanner posScanner = new PosScanner();
posScanner.scan(newTree);
return posScanner.found;
}
});
try {
attr.attribTree(newTree, speculativeEnv, resultInfo); // depends on control dependency: [try], data = [none]
unenterScanner.scan(newTree); // depends on control dependency: [try], data = [none]
return newTree; // depends on control dependency: [try], data = [none]
} finally {
unenterScanner.scan(newTree);
log.popDiagnosticHandler(deferredDiagnosticHandler);
}
} } |
public class class_name {
public final void start() {
if (isStarted()) return;
if (getContext() == null) {
throw new IllegalStateException("context not set");
}
if (shouldStart()) {
getContext().getScheduledExecutorService().execute(getRunnableTask());
started = true;
}
} } | public class class_name {
public final void start() {
if (isStarted()) return;
if (getContext() == null) {
throw new IllegalStateException("context not set");
}
if (shouldStart()) {
getContext().getScheduledExecutorService().execute(getRunnableTask()); // depends on control dependency: [if], data = [none]
started = true; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public void respawn(int index) {
configurationRwLock.writeLock().lock();
try {
if (index >= 0 && index < servers.length) {
servers[index].startup();
}
rebalance();
} finally {
Info.incrementConfigRevision();
configurationRwLock.writeLock().unlock();
}
} } | public class class_name {
public void respawn(int index) {
configurationRwLock.writeLock().lock();
try {
if (index >= 0 && index < servers.length) {
servers[index].startup(); // depends on control dependency: [if], data = [none]
}
rebalance(); // depends on control dependency: [try], data = [none]
} finally {
Info.incrementConfigRevision();
configurationRwLock.writeLock().unlock();
}
} } |
public class class_name {
public KQueueDatagramChannelConfig setReusePort(boolean reusePort) {
try {
((KQueueDatagramChannel) channel).socket.setReusePort(reusePort);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} } | public class class_name {
public KQueueDatagramChannelConfig setReusePort(boolean reusePort) {
try {
((KQueueDatagramChannel) channel).socket.setReusePort(reusePort); // depends on control dependency: [try], data = [none]
return this; // depends on control dependency: [try], data = [none]
} catch (IOException e) {
throw new ChannelException(e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
private static SQLTransform getTransform(TypeName typeName) {
if (typeName.isPrimitive()) {
return getPrimitiveTransform(typeName);
}
if (typeName instanceof ArrayTypeName) {
ArrayTypeName typeNameArray = (ArrayTypeName) typeName;
TypeName componentTypeName = typeNameArray.componentType;
if (TypeUtility.isEquals(componentTypeName, Byte.TYPE.toString())) {
return new ByteArraySQLTransform();
} else {
return new ArraySQLTransform();
}
} else if (typeName instanceof ParameterizedTypeName) {
ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
if (TypeUtility.isList(parameterizedTypeName)) {
return new ListSQLTransformation();
} else if (TypeUtility.isSet(parameterizedTypeName)) {
return new SetSQLTransformation();
} else if (TypeUtility.isMap(parameterizedTypeName)) {
return new MapSQLTransformation();
}
}
String name = typeName.toString();
if (name.startsWith("java.lang")) {
return getLanguageTransform(typeName);
}
if (name.startsWith("java.util")) {
return getUtilTransform(typeName);
}
if (name.startsWith("java.math")) {
return getMathTransform(typeName);
}
if (name.startsWith("java.net")) {
return getNetTransform(typeName);
}
if (name.startsWith("java.sql")) {
return getSqlTransform(typeName);
}
if (TypeUtility.isEnum(typeName)) {
return new EnumSQLTransform(typeName);
}
return new ObjectSQLTransform();
} } | public class class_name {
private static SQLTransform getTransform(TypeName typeName) {
if (typeName.isPrimitive()) {
return getPrimitiveTransform(typeName); // depends on control dependency: [if], data = [none]
}
if (typeName instanceof ArrayTypeName) {
ArrayTypeName typeNameArray = (ArrayTypeName) typeName;
TypeName componentTypeName = typeNameArray.componentType;
if (TypeUtility.isEquals(componentTypeName, Byte.TYPE.toString())) {
return new ByteArraySQLTransform(); // depends on control dependency: [if], data = [none]
} else {
return new ArraySQLTransform(); // depends on control dependency: [if], data = [none]
}
} else if (typeName instanceof ParameterizedTypeName) {
ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
if (TypeUtility.isList(parameterizedTypeName)) {
return new ListSQLTransformation(); // depends on control dependency: [if], data = [none]
} else if (TypeUtility.isSet(parameterizedTypeName)) {
return new SetSQLTransformation(); // depends on control dependency: [if], data = [none]
} else if (TypeUtility.isMap(parameterizedTypeName)) {
return new MapSQLTransformation(); // depends on control dependency: [if], data = [none]
}
}
String name = typeName.toString();
if (name.startsWith("java.lang")) {
return getLanguageTransform(typeName);
}
if (name.startsWith("java.util")) {
return getUtilTransform(typeName);
}
if (name.startsWith("java.math")) {
return getMathTransform(typeName);
}
if (name.startsWith("java.net")) {
return getNetTransform(typeName);
}
if (name.startsWith("java.sql")) {
return getSqlTransform(typeName);
}
if (TypeUtility.isEnum(typeName)) {
return new EnumSQLTransform(typeName);
}
return new ObjectSQLTransform();
} } |
public class class_name {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, int highlightColor) {
Context ctx = inflater.getContext();
View view = inflater.inflate(R.layout.navdrawer_item, container, false);
ImageView iconView = ButterKnife.findById(view, R.id.icon);
TextView titleView = ButterKnife.findById(view, R.id.title);
TextView badgeView = ButterKnife.findById(view, R.id.badge);
// Set the textResId
FontLoader.apply(titleView, Face.ROBOTO_MEDIUM);
titleView.setText(textResId);
// Set the iconResId, if provided
iconView.setVisibility(iconResId > 0 ? View.VISIBLE : View.GONE);
if(iconResId > 0)
iconView.setImageResource(iconResId);
// configure its appearance according to whether or not it's selected
titleView.setTextColor(selected ?
highlightColor :
UIUtils.getColorAttr(ctx, android.R.attr.textColorPrimary));
iconView.setColorFilter(selected ?
highlightColor :
ctx.getResources().getColor(R.color.navdrawer_icon_tint));
// Setup the badge view
if(badge != null) {
Drawable badgeBackground = DrawableCompat
.wrap(ctx.getResources().getDrawable(R.drawable.badge));
DrawableCompat.setTint(badgeBackground, badge.getColor());
badgeView.setBackground(badgeBackground);
badgeView.setTextColor(badge.getTextColor());
badgeView.setText(badge.getText());
badgeView.setVisibility(View.VISIBLE);
}
return view;
} } | public class class_name {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, int highlightColor) {
Context ctx = inflater.getContext();
View view = inflater.inflate(R.layout.navdrawer_item, container, false);
ImageView iconView = ButterKnife.findById(view, R.id.icon);
TextView titleView = ButterKnife.findById(view, R.id.title);
TextView badgeView = ButterKnife.findById(view, R.id.badge);
// Set the textResId
FontLoader.apply(titleView, Face.ROBOTO_MEDIUM);
titleView.setText(textResId);
// Set the iconResId, if provided
iconView.setVisibility(iconResId > 0 ? View.VISIBLE : View.GONE);
if(iconResId > 0)
iconView.setImageResource(iconResId);
// configure its appearance according to whether or not it's selected
titleView.setTextColor(selected ?
highlightColor :
UIUtils.getColorAttr(ctx, android.R.attr.textColorPrimary));
iconView.setColorFilter(selected ?
highlightColor :
ctx.getResources().getColor(R.color.navdrawer_icon_tint));
// Setup the badge view
if(badge != null) {
Drawable badgeBackground = DrawableCompat
.wrap(ctx.getResources().getDrawable(R.drawable.badge));
DrawableCompat.setTint(badgeBackground, badge.getColor()); // depends on control dependency: [if], data = [(badge]
badgeView.setBackground(badgeBackground); // depends on control dependency: [if], data = [(badge]
badgeView.setTextColor(badge.getTextColor()); // depends on control dependency: [if], data = [(badge]
badgeView.setText(badge.getText()); // depends on control dependency: [if], data = [(badge]
badgeView.setVisibility(View.VISIBLE); // depends on control dependency: [if], data = [none]
}
return view;
} } |
public class class_name {
public String getNamespaceForPrefix(String prefix,
org.w3c.dom.Node namespaceContext) {
Node parent = namespaceContext;
String namespace = null;
if (prefix.equals("xml")) {
namespace = S_XMLNAMESPACEURI;
} else {
int type;
while ((null != parent) && (null == namespace)
&& (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
|| (type == Node.ENTITY_REFERENCE_NODE))) {
if (type == Node.ELEMENT_NODE) {
NamedNodeMap nnm = parent.getAttributes();
for (int i = 0; i < nnm.getLength(); i++) {
Node attr = nnm.item(i);
String aname = attr.getNodeName();
boolean isPrefix = aname.startsWith("xmlns:");
if (isPrefix || aname.equals("xmlns")) {
int index = aname.indexOf(':');
String p =isPrefix ?aname.substring(index + 1) :"";
if (p.equals(prefix)) {
namespace = attr.getNodeValue();
break;
}
}
}
}
parent = parent.getParentNode();
}
}
return namespace;
} } | public class class_name {
public String getNamespaceForPrefix(String prefix,
org.w3c.dom.Node namespaceContext) {
Node parent = namespaceContext;
String namespace = null;
if (prefix.equals("xml")) {
namespace = S_XMLNAMESPACEURI; // depends on control dependency: [if], data = [none]
} else {
int type;
while ((null != parent) && (null == namespace)
&& (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
|| (type == Node.ENTITY_REFERENCE_NODE))) {
if (type == Node.ELEMENT_NODE) {
NamedNodeMap nnm = parent.getAttributes();
for (int i = 0; i < nnm.getLength(); i++) {
Node attr = nnm.item(i);
String aname = attr.getNodeName();
boolean isPrefix = aname.startsWith("xmlns:");
if (isPrefix || aname.equals("xmlns")) {
int index = aname.indexOf(':');
String p =isPrefix ?aname.substring(index + 1) :"";
if (p.equals(prefix)) {
namespace = attr.getNodeValue(); // depends on control dependency: [if], data = [none]
break;
}
}
}
}
parent = parent.getParentNode(); // depends on control dependency: [while], data = [none]
}
}
return namespace;
} } |
public class class_name {
protected final void verifyFieldType(short id, String name, Collection<FieldMetadata> fields, ThriftCatalog catalog)
{
boolean isSupportedType = true;
for (FieldMetadata field : fields) {
if (!catalog.isSupportedStructFieldType(field.getJavaType())) {
metadataErrors.addError("Thrift class '%s' field '%s(%s)' type '%s' is not a supported Java type", structName, name, id, TypeToken.of(field.getJavaType()));
isSupportedType = false;
// only report the error once
break;
}
}
// fields must have the same type
if (isSupportedType) {
Set<ThriftTypeReference> types = new HashSet<>();
for (FieldMetadata field : fields) {
types.add(catalog.getFieldThriftTypeReference(field));
}
if (types.size() > 1) {
metadataErrors.addError("Thrift class '%s' field '%s(%s)' has multiple types: %s", structName, name, id, types);
}
}
} } | public class class_name {
protected final void verifyFieldType(short id, String name, Collection<FieldMetadata> fields, ThriftCatalog catalog)
{
boolean isSupportedType = true;
for (FieldMetadata field : fields) {
if (!catalog.isSupportedStructFieldType(field.getJavaType())) {
metadataErrors.addError("Thrift class '%s' field '%s(%s)' type '%s' is not a supported Java type", structName, name, id, TypeToken.of(field.getJavaType()));
isSupportedType = false;
// only report the error once
break;
}
}
// fields must have the same type
if (isSupportedType) {
Set<ThriftTypeReference> types = new HashSet<>();
for (FieldMetadata field : fields) {
types.add(catalog.getFieldThriftTypeReference(field));
}
if (types.size() > 1) {
metadataErrors.addError("Thrift class '%s' field '%s(%s)' has multiple types: %s", structName, name, id, types); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
public Observable<ServiceResponse<Boolean>> checkNameExistsWithServiceResponseAsync(String accountName) {
if (accountName == null) {
throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.checkNameExists(accountName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<Void>, Observable<ServiceResponse<Boolean>>>() {
@Override
public Observable<ServiceResponse<Boolean>> call(Response<Void> response) {
try {
ServiceResponse<Boolean> clientResponse = checkNameExistsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} } | public class class_name {
public Observable<ServiceResponse<Boolean>> checkNameExistsWithServiceResponseAsync(String accountName) {
if (accountName == null) {
throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.checkNameExists(accountName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<Void>, Observable<ServiceResponse<Boolean>>>() {
@Override
public Observable<ServiceResponse<Boolean>> call(Response<Void> response) {
try {
ServiceResponse<Boolean> clientResponse = checkNameExistsDelegate(response);
return Observable.just(clientResponse); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
return Observable.error(t);
} // depends on control dependency: [catch], data = [none]
}
});
} } |
public class class_name {
public boolean setMetadata(int iid, Object metaData) {
if (iid < 0 || iid > loadCounter) {
System.out.println("Internal id " + iid + " is out of range!");
return false;
}
MetaDataEntity mde = new MetaDataEntity(iid, metaData);
PrimaryIndex<Integer, MetaDataEntity> primaryIndex = iidToMetadataDB.getPrimaryIndex(Integer.class,
MetaDataEntity.class);
if (primaryIndex.contains(iid)) {
primaryIndex.put(null, mde);
return true;
} else {
return false;
}
} } | public class class_name {
public boolean setMetadata(int iid, Object metaData) {
if (iid < 0 || iid > loadCounter) {
System.out.println("Internal id " + iid + " is out of range!");
// depends on control dependency: [if], data = [none]
return false;
// depends on control dependency: [if], data = [none]
}
MetaDataEntity mde = new MetaDataEntity(iid, metaData);
PrimaryIndex<Integer, MetaDataEntity> primaryIndex = iidToMetadataDB.getPrimaryIndex(Integer.class,
MetaDataEntity.class);
if (primaryIndex.contains(iid)) {
primaryIndex.put(null, mde);
// depends on control dependency: [if], data = [none]
return true;
// depends on control dependency: [if], data = [none]
} else {
return false;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@NullSafe
public static boolean containsDigits(String value) {
for (char chr : toCharArray(value)) {
if (Character.isDigit(chr)) {
return true;
}
}
return false;
} } | public class class_name {
@NullSafe
public static boolean containsDigits(String value) {
for (char chr : toCharArray(value)) {
if (Character.isDigit(chr)) {
return true; // depends on control dependency: [if], data = [none]
}
}
return false;
} } |
public class class_name {
private IcsListPopupWindow getListPopupWindow() {
if (mListPopupWindow == null) {
mListPopupWindow = new IcsListPopupWindow(getContext());
mListPopupWindow.setAdapter(mAdapter);
mListPopupWindow.setAnchorView(ActivityChooserView.this);
mListPopupWindow.setModal(true);
mListPopupWindow.setOnItemClickListener(mCallbacks);
mListPopupWindow.setOnDismissListener(mCallbacks);
}
return mListPopupWindow;
} } | public class class_name {
private IcsListPopupWindow getListPopupWindow() {
if (mListPopupWindow == null) {
mListPopupWindow = new IcsListPopupWindow(getContext()); // depends on control dependency: [if], data = [none]
mListPopupWindow.setAdapter(mAdapter); // depends on control dependency: [if], data = [none]
mListPopupWindow.setAnchorView(ActivityChooserView.this); // depends on control dependency: [if], data = [none]
mListPopupWindow.setModal(true); // depends on control dependency: [if], data = [none]
mListPopupWindow.setOnItemClickListener(mCallbacks); // depends on control dependency: [if], data = [none]
mListPopupWindow.setOnDismissListener(mCallbacks); // depends on control dependency: [if], data = [none]
}
return mListPopupWindow;
} } |
public class class_name {
public StreamSource getTransformerStream(String strDocument)
{
StreamSource source = null;
if (strDocument.indexOf(':') == -1)
{ // See if it is a file name
try { // First try it as a filename
FileReader reader = new FileReader(strDocument);
if (reader != null)
source = new StreamSource(reader);
} catch (IOException ex) {
source = null;
}
}
if (source == null)
{
try {
URL url = new URL(strDocument);
InputStream is = url.openStream();
source = new StreamSource(is);
} catch (IOException ex) {
source = null;
}
}
return source;
} } | public class class_name {
public StreamSource getTransformerStream(String strDocument)
{
StreamSource source = null;
if (strDocument.indexOf(':') == -1)
{ // See if it is a file name
try { // First try it as a filename
FileReader reader = new FileReader(strDocument);
if (reader != null)
source = new StreamSource(reader);
} catch (IOException ex) {
source = null;
} // depends on control dependency: [catch], data = [none]
}
if (source == null)
{
try {
URL url = new URL(strDocument);
InputStream is = url.openStream();
source = new StreamSource(is); // depends on control dependency: [try], data = [none]
} catch (IOException ex) {
source = null;
} // depends on control dependency: [catch], data = [none]
}
return source;
} } |
public class class_name {
public void addComment(String tag, String comment) {
String nt = normaliseTag(tag);
if(! comments.containsKey(nt)) {
comments.put(nt, new ArrayList<String>());
}
comments.get(nt).add(comment);
} } | public class class_name {
public void addComment(String tag, String comment) {
String nt = normaliseTag(tag);
if(! comments.containsKey(nt)) {
comments.put(nt, new ArrayList<String>()); // depends on control dependency: [if], data = [none]
}
comments.get(nt).add(comment);
} } |
public class class_name {
public synchronized void merge(BloomFilter filter) {
if (!this.matchesAll() && !filter.matchesAll()) {
checkArgument(filter.data.length == this.data.length &&
filter.hashFuncs == this.hashFuncs &&
filter.nTweak == this.nTweak);
for (int i = 0; i < data.length; i++)
this.data[i] |= filter.data[i];
} else {
this.data = new byte[] {(byte) 0xff};
}
} } | public class class_name {
public synchronized void merge(BloomFilter filter) {
if (!this.matchesAll() && !filter.matchesAll()) {
checkArgument(filter.data.length == this.data.length &&
filter.hashFuncs == this.hashFuncs &&
filter.nTweak == this.nTweak); // depends on control dependency: [if], data = [none]
for (int i = 0; i < data.length; i++)
this.data[i] |= filter.data[i];
} else {
this.data = new byte[] {(byte) 0xff}; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected TypeName[] createTypeVariables(
TypeName extractedType, String extractVariableName, int extractArity) {
List<TypeName> typeVariables = new ArrayList<>();
typeVariables.add(extractedType);
if (extractArity > 0) {
typeVariables.addAll(
IntStream.rangeClosed(1, extractArity)
.mapToObj(j -> TypeVariableName.get(extractVariableName + j))
.collect(Collectors.toList()));
}
return typeVariables.toArray(new TypeName[typeVariables.size()]);
} } | public class class_name {
protected TypeName[] createTypeVariables(
TypeName extractedType, String extractVariableName, int extractArity) {
List<TypeName> typeVariables = new ArrayList<>();
typeVariables.add(extractedType);
if (extractArity > 0) {
typeVariables.addAll(
IntStream.rangeClosed(1, extractArity)
.mapToObj(j -> TypeVariableName.get(extractVariableName + j))
.collect(Collectors.toList())); // depends on control dependency: [if], data = [none]
}
return typeVariables.toArray(new TypeName[typeVariables.size()]);
} } |
public class class_name {
@SuppressWarnings("unchecked")
public static List<EntityPlayerMP> getPlayersWatchingChunk(WorldServer world, int x, int z)
{
if (playersWatchingChunk == null)
return new ArrayList<>();
try
{
PlayerChunkMapEntry entry = world.getPlayerChunkMap().getEntry(x, z);
if (entry == null)
return Lists.newArrayList();
return (List<EntityPlayerMP>) playersWatchingChunk.get(entry);
}
catch (ReflectiveOperationException e)
{
MalisisCore.log.info("Failed to get players watching chunk :", e);
return new ArrayList<>();
}
} } | public class class_name {
@SuppressWarnings("unchecked")
public static List<EntityPlayerMP> getPlayersWatchingChunk(WorldServer world, int x, int z)
{
if (playersWatchingChunk == null)
return new ArrayList<>();
try
{
PlayerChunkMapEntry entry = world.getPlayerChunkMap().getEntry(x, z);
if (entry == null)
return Lists.newArrayList();
return (List<EntityPlayerMP>) playersWatchingChunk.get(entry); // depends on control dependency: [try], data = [none]
}
catch (ReflectiveOperationException e)
{
MalisisCore.log.info("Failed to get players watching chunk :", e);
return new ArrayList<>();
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@Override
public EClass getIfcFlowTerminal() {
if (ifcFlowTerminalEClass == null) {
ifcFlowTerminalEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(290);
}
return ifcFlowTerminalEClass;
} } | public class class_name {
@Override
public EClass getIfcFlowTerminal() {
if (ifcFlowTerminalEClass == null) {
ifcFlowTerminalEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(290);
// depends on control dependency: [if], data = [none]
}
return ifcFlowTerminalEClass;
} } |
public class class_name {
public GroupAsa[] getGroupAsas() {
TreeMap<ResidueNumber, GroupAsa> asas = new TreeMap<>();
double[] asasPerAtom = calculateAsas();
for (int i=0;i<atomCoords.length;i++) {
Group g = atoms[i].getGroup();
if (!asas.containsKey(g.getResidueNumber())) {
GroupAsa groupAsa = new GroupAsa(g);
groupAsa.addAtomAsaU(asasPerAtom[i]);
asas.put(g.getResidueNumber(), groupAsa);
} else {
GroupAsa groupAsa = asas.get(g.getResidueNumber());
groupAsa.addAtomAsaU(asasPerAtom[i]);
}
}
return asas.values().toArray(new GroupAsa[asas.size()]);
} } | public class class_name {
public GroupAsa[] getGroupAsas() {
TreeMap<ResidueNumber, GroupAsa> asas = new TreeMap<>();
double[] asasPerAtom = calculateAsas();
for (int i=0;i<atomCoords.length;i++) {
Group g = atoms[i].getGroup();
if (!asas.containsKey(g.getResidueNumber())) {
GroupAsa groupAsa = new GroupAsa(g);
groupAsa.addAtomAsaU(asasPerAtom[i]); // depends on control dependency: [if], data = [none]
asas.put(g.getResidueNumber(), groupAsa); // depends on control dependency: [if], data = [none]
} else {
GroupAsa groupAsa = asas.get(g.getResidueNumber());
groupAsa.addAtomAsaU(asasPerAtom[i]); // depends on control dependency: [if], data = [none]
}
}
return asas.values().toArray(new GroupAsa[asas.size()]);
} } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.