code
stringlengths 130
281k
| code_dependency
stringlengths 182
306k
|
|---|---|
public class class_name {
public String getDataContainerId(boolean forceRefresh) throws SettingsBuildingException,
InterruptedException, IOException {
final Map<String, File> pluginFiles = getPluginFiles();
String dataContainerId = null;
String dataContainerImage = null;
LOG.debug("Checking whether data-container exist...");
final List<Container> containers = getDockerCli().listContainersCmd().withShowAll(true).exec();
OUTER:
for (Container container : containers) {
final String[] names = container.getNames();
for (String name : names) {
// docker adds "/" before container name
if (name.equals("/" + DATA_CONTAINER_NAME)) {
dataContainerId = container.getId();
dataContainerImage = container.getImage();
LOG.debug("Data container exists {}, based on image {}", dataContainerId, dataContainerImage);
break OUTER;
}
}
}
final String dataImage = getDataImage(forceRefresh, pluginFiles, DATA_IMAGE);
final boolean dataImagesEquals = dataImage.equals(dataContainerImage);
LOG.debug("Data image is the same: {}", dataImagesEquals);
if (nonNull(dataContainerId) && (forceRefresh || !dataImagesEquals)) {
LOG.info("Removing data-container. ForceRefresh: {}", forceRefresh);
try {
getDockerCli().removeContainerCmd(dataContainerId)
.withForce(true) // force is not good
.withRemoveVolumes(true)
.exec();
} catch (NotFoundException ignored) {
}
dataContainerId = null;
}
if (isNull(dataContainerId)) {
LOG.debug("Data container doesn't exist, creating...");
final CreateContainerResponse containerResponse = getDockerCli().createContainerCmd(dataImage)
.withName(DATA_CONTAINER_NAME)
.withCmd("/bin/true")
.exec();
dataContainerId = containerResponse.getId();
}
if (isNull(dataContainerId)) {
throw new IllegalStateException("Container id can't be null.");
}
getDockerCli().inspectContainerCmd(dataContainerId).exec().getId();
LOG.debug("Data containerId: '{}'", dataContainerId);
return dataContainerId;
} }
|
public class class_name {
public String getDataContainerId(boolean forceRefresh) throws SettingsBuildingException,
InterruptedException, IOException {
final Map<String, File> pluginFiles = getPluginFiles();
String dataContainerId = null;
String dataContainerImage = null;
LOG.debug("Checking whether data-container exist...");
final List<Container> containers = getDockerCli().listContainersCmd().withShowAll(true).exec();
OUTER:
for (Container container : containers) {
final String[] names = container.getNames();
for (String name : names) {
// docker adds "/" before container name
if (name.equals("/" + DATA_CONTAINER_NAME)) {
dataContainerId = container.getId(); // depends on control dependency: [if], data = [none]
dataContainerImage = container.getImage(); // depends on control dependency: [if], data = [none]
LOG.debug("Data container exists {}, based on image {}", dataContainerId, dataContainerImage); // depends on control dependency: [if], data = [none]
break OUTER;
}
}
}
final String dataImage = getDataImage(forceRefresh, pluginFiles, DATA_IMAGE);
final boolean dataImagesEquals = dataImage.equals(dataContainerImage);
LOG.debug("Data image is the same: {}", dataImagesEquals);
if (nonNull(dataContainerId) && (forceRefresh || !dataImagesEquals)) {
LOG.info("Removing data-container. ForceRefresh: {}", forceRefresh);
try {
getDockerCli().removeContainerCmd(dataContainerId)
.withForce(true) // force is not good
.withRemoveVolumes(true)
.exec(); // depends on control dependency: [try], data = [none]
} catch (NotFoundException ignored) {
} // depends on control dependency: [catch], data = [none]
dataContainerId = null;
}
if (isNull(dataContainerId)) {
LOG.debug("Data container doesn't exist, creating...");
final CreateContainerResponse containerResponse = getDockerCli().createContainerCmd(dataImage)
.withName(DATA_CONTAINER_NAME)
.withCmd("/bin/true")
.exec();
dataContainerId = containerResponse.getId();
}
if (isNull(dataContainerId)) {
throw new IllegalStateException("Container id can't be null.");
}
getDockerCli().inspectContainerCmd(dataContainerId).exec().getId();
LOG.debug("Data containerId: '{}'", dataContainerId);
return dataContainerId;
} }
|
public class class_name {
private static void save(Bitmap src, String fileName, Bitmap.CompressFormat format, int quality) throws ImageSaveException {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileName);
src.compress(format, quality, outputStream);
outputStream.close();
} catch (IOException e) {
throw new ImageSaveException(e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} }
|
public class class_name {
private static void save(Bitmap src, String fileName, Bitmap.CompressFormat format, int quality) throws ImageSaveException {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileName);
src.compress(format, quality, outputStream);
outputStream.close();
} catch (IOException e) {
throw new ImageSaveException(e);
} finally {
if (outputStream != null) {
try {
outputStream.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e1) {
e1.printStackTrace();
} // depends on control dependency: [catch], data = [none]
}
}
} }
|
public class class_name {
private void designTrapeziumPipe( double tau, double g, double maxd, double c, StringBuilder strWarnings ) {
/* [cm] Base della sezione effettivamente adottata. */
double base;
/*
* [%] Pendenza naturale, calcolata in funzione dei dati geometrici
* della rete
*/
double naturalSlope;
/* [cm] Altezza del canale trapezoidale. */
double D;
/*
* [%] Pendenza minima da adottare per il tratto che si sta
* dimensionando.
*/
double ms;
/* DUE FORMULE */
/*
* Dimensiona il diametro del tubo da adottare col criterio di
* autopulizia, calcola altre grandezze correlate come la pendenza e il
* grado di riempimento, e restituisce il riempimento effettivo nel
* tratto progettato
*/
base = getHeight2(tau, g, maxd, c);
/* [%] pendenza minima per il tratto che si sta dimensionando. */
ms = getMinimumPipeSlope();
/* [%] Pendenza del terreno */
naturalSlope = METER2CM * (initialElevation - finalElevation) / lenght;
/*
* Avvisa l'utente che il tratto che si sta progettando e in
* contropendenza
*/
if (naturalSlope < 0) {
strWarnings.append(msg.message("trentoP.warning.slope") + id);
}
/* La pendenza del terreno deve essere superiore a quella minima ms */
if (naturalSlope < ms) {
naturalSlope = ms;
}
/*
* Se la pendenza del terreno e maggiore di quella del tubo, allora la
* pendenza del tubo viene posta uguale a quella del terreno.
*/
if (naturalSlope > pipeSlope) {
pipeSlope = naturalSlope;
/*
* Progetta la condotta assegnado una pendenza pari a quella del
* terreno, calcola altre grandezze correlate come la pendenza e il
* grado di riempimento, e restituisce il riempimento effettivo nel
* tratto progettato
*/
base = getHeight2I(naturalSlope, g, maxd, c);
}
/* Diametro tubo [cm] */
D = diameter;
// Velocita media nella sezione [ m / s ]
meanSpeed = (discharge / CUBICMETER2LITER) / (emptyDegree * D * base / METER2CMSQUARED);
// Quota scavo all 'inizio del tubo [ m s . l . m . ]
depthInitialPipe = getInitialElevation() - diameter / METER2CM;
/*
* Quota dello scavo alla fine del tubo calcolata considerando la
* pendenza effettiva del tratto [ m s . l . m . ]
*/
depthFinalPipe = depthInitialPipe - getLenght() * pipeSlope / METER2CM;
// Quota pelo libero all 'inizio del tubo [ m s . l . m . ]
initialFreesurface = depthInitialPipe + emptyDegree * D / METER2CM;
// Quota pelo libero all 'inizio del tubo [ m s . l . m . ]
finalFreesurface = depthFinalPipe + emptyDegree * D / METER2CM;
} }
|
public class class_name {
private void designTrapeziumPipe( double tau, double g, double maxd, double c, StringBuilder strWarnings ) {
/* [cm] Base della sezione effettivamente adottata. */
double base;
/*
* [%] Pendenza naturale, calcolata in funzione dei dati geometrici
* della rete
*/
double naturalSlope;
/* [cm] Altezza del canale trapezoidale. */
double D;
/*
* [%] Pendenza minima da adottare per il tratto che si sta
* dimensionando.
*/
double ms;
/* DUE FORMULE */
/*
* Dimensiona il diametro del tubo da adottare col criterio di
* autopulizia, calcola altre grandezze correlate come la pendenza e il
* grado di riempimento, e restituisce il riempimento effettivo nel
* tratto progettato
*/
base = getHeight2(tau, g, maxd, c);
/* [%] pendenza minima per il tratto che si sta dimensionando. */
ms = getMinimumPipeSlope();
/* [%] Pendenza del terreno */
naturalSlope = METER2CM * (initialElevation - finalElevation) / lenght;
/*
* Avvisa l'utente che il tratto che si sta progettando e in
* contropendenza
*/
if (naturalSlope < 0) {
strWarnings.append(msg.message("trentoP.warning.slope") + id); // depends on control dependency: [if], data = [none]
}
/* La pendenza del terreno deve essere superiore a quella minima ms */
if (naturalSlope < ms) {
naturalSlope = ms; // depends on control dependency: [if], data = [none]
}
/*
* Se la pendenza del terreno e maggiore di quella del tubo, allora la
* pendenza del tubo viene posta uguale a quella del terreno.
*/
if (naturalSlope > pipeSlope) {
pipeSlope = naturalSlope; // depends on control dependency: [if], data = [none]
/*
* Progetta la condotta assegnado una pendenza pari a quella del
* terreno, calcola altre grandezze correlate come la pendenza e il
* grado di riempimento, e restituisce il riempimento effettivo nel
* tratto progettato
*/
base = getHeight2I(naturalSlope, g, maxd, c); // depends on control dependency: [if], data = [(naturalSlope]
}
/* Diametro tubo [cm] */
D = diameter;
// Velocita media nella sezione [ m / s ]
meanSpeed = (discharge / CUBICMETER2LITER) / (emptyDegree * D * base / METER2CMSQUARED);
// Quota scavo all 'inizio del tubo [ m s . l . m . ]
depthInitialPipe = getInitialElevation() - diameter / METER2CM;
/*
* Quota dello scavo alla fine del tubo calcolata considerando la
* pendenza effettiva del tratto [ m s . l . m . ]
*/
depthFinalPipe = depthInitialPipe - getLenght() * pipeSlope / METER2CM;
// Quota pelo libero all 'inizio del tubo [ m s . l . m . ]
initialFreesurface = depthInitialPipe + emptyDegree * D / METER2CM;
// Quota pelo libero all 'inizio del tubo [ m s . l . m . ]
finalFreesurface = depthFinalPipe + emptyDegree * D / METER2CM;
} }
|
public class class_name {
public void accept(TermVisitor visitor)
{
if (visitor instanceof NumericTypeVisitor)
{
((NumericTypeVisitor) visitor).visit(this);
}
else
{
super.accept(visitor);
}
} }
|
public class class_name {
public void accept(TermVisitor visitor)
{
if (visitor instanceof NumericTypeVisitor)
{
((NumericTypeVisitor) visitor).visit(this); // depends on control dependency: [if], data = [none]
}
else
{
super.accept(visitor); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private Map<HttpMethod, SortedSet<RegisteredCommand>> getCmdEvalMap(String cmdOwner) {
Map<HttpMethod, SortedSet<RegisteredCommand>> evalMap = m_cmdEvalMap.get(cmdOwner);
if (evalMap == null) {
evalMap = new HashMap<>();
m_cmdEvalMap.put(cmdOwner, evalMap);
}
return evalMap;
} }
|
public class class_name {
private Map<HttpMethod, SortedSet<RegisteredCommand>> getCmdEvalMap(String cmdOwner) {
Map<HttpMethod, SortedSet<RegisteredCommand>> evalMap = m_cmdEvalMap.get(cmdOwner);
if (evalMap == null) {
evalMap = new HashMap<>();
// depends on control dependency: [if], data = [none]
m_cmdEvalMap.put(cmdOwner, evalMap);
// depends on control dependency: [if], data = [none]
}
return evalMap;
} }
|
public class class_name {
public List<ProjectRoleSpreadType.Period> getPeriod()
{
if (period == null)
{
period = new ArrayList<ProjectRoleSpreadType.Period>();
}
return this.period;
} }
|
public class class_name {
public List<ProjectRoleSpreadType.Period> getPeriod()
{
if (period == null)
{
period = new ArrayList<ProjectRoleSpreadType.Period>(); // depends on control dependency: [if], data = [none]
}
return this.period;
} }
|
public class class_name {
private void checkForDeadTenantTasks(Tenant tenant) {
m_logger.debug("Checking tenant {} for abandoned tasks", tenant);
try {
for(DRow row: DBService.instance(tenant).getAllRows(TaskManagerService.TASKS_STORE_NAME)) {
TaskRecord taskRecord = buildTaskRecord(row.getKey(), row.getAllColumns(1024).iterator());
if (taskRecord.getStatus() == TaskStatus.IN_PROGRESS) {
checkForDeadTask(tenant, taskRecord);
}
}
} catch (Throwable e) {
m_logger.warn("Unable to check tenant '{}' for dead tasks: {}", tenant.getName(), e.toString());
}
} }
|
public class class_name {
private void checkForDeadTenantTasks(Tenant tenant) {
m_logger.debug("Checking tenant {} for abandoned tasks", tenant);
try {
for(DRow row: DBService.instance(tenant).getAllRows(TaskManagerService.TASKS_STORE_NAME)) {
TaskRecord taskRecord = buildTaskRecord(row.getKey(), row.getAllColumns(1024).iterator());
if (taskRecord.getStatus() == TaskStatus.IN_PROGRESS) {
checkForDeadTask(tenant, taskRecord); // depends on control dependency: [if], data = [none]
}
}
} catch (Throwable e) {
m_logger.warn("Unable to check tenant '{}' for dead tasks: {}", tenant.getName(), e.toString());
}
} }
|
public class class_name {
public void parseProcessDefinitions() {
for (Element processElement : rootElement.elements("process")) {
boolean isExecutable = !deployment.isNew();
String isExecutableStr = processElement.attribute("isExecutable");
if (isExecutableStr != null) {
isExecutable = Boolean.parseBoolean(isExecutableStr);
if (!isExecutable) {
LOG.ignoringNonExecutableProcess(processElement.attribute("id"));
}
} else {
LOG.missingIsExecutableAttribute(processElement.attribute("id"));
}
// Only process executable processes
if (isExecutable) {
processDefinitions.add(parseProcess(processElement));
}
}
} }
|
public class class_name {
public void parseProcessDefinitions() {
for (Element processElement : rootElement.elements("process")) {
boolean isExecutable = !deployment.isNew();
String isExecutableStr = processElement.attribute("isExecutable");
if (isExecutableStr != null) {
isExecutable = Boolean.parseBoolean(isExecutableStr); // depends on control dependency: [if], data = [(isExecutableStr]
if (!isExecutable) {
LOG.ignoringNonExecutableProcess(processElement.attribute("id")); // depends on control dependency: [if], data = [none]
}
} else {
LOG.missingIsExecutableAttribute(processElement.attribute("id")); // depends on control dependency: [if], data = [none]
}
// Only process executable processes
if (isExecutable) {
processDefinitions.add(parseProcess(processElement)); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
private String getSubProcessInstanceId(String instanceId) {
int beg = instanceId.indexOf("/");
if (beg > -1 && beg + 1 < instanceId.length()) {
return instanceId.substring(beg + 1);
}
return "";
} }
|
public class class_name {
private String getSubProcessInstanceId(String instanceId) {
int beg = instanceId.indexOf("/");
if (beg > -1 && beg + 1 < instanceId.length()) {
return instanceId.substring(beg + 1); // depends on control dependency: [if], data = [(beg]
}
return "";
} }
|
public class class_name {
protected void process() {
if (targetInputStream == null) {
throw new ProxettaException("Target missing: " + targetClassName);
}
// create class reader
final ClassReader classReader;
try {
classReader = new ClassReader(targetInputStream);
} catch (IOException ioex) {
throw new ProxettaException("Error reading class input stream", ioex);
}
// reads information
final TargetClassInfoReader targetClassInfoReader = new TargetClassInfoReader(proxetta.getClassLoader());
classReader.accept(targetClassInfoReader, 0);
this.destClassWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
// create proxy
if (log.isDebugEnabled()) {
log.debug("processing: " + classReader.getClassName());
}
WorkData wd = process(classReader, targetClassInfoReader);
// store important data
proxyApplied = wd.proxyApplied;
proxyClassName = wd.thisReference.replace('/', '.');
} }
|
public class class_name {
protected void process() {
if (targetInputStream == null) {
throw new ProxettaException("Target missing: " + targetClassName);
}
// create class reader
final ClassReader classReader;
try {
classReader = new ClassReader(targetInputStream); // depends on control dependency: [try], data = [none]
} catch (IOException ioex) {
throw new ProxettaException("Error reading class input stream", ioex);
} // depends on control dependency: [catch], data = [none]
// reads information
final TargetClassInfoReader targetClassInfoReader = new TargetClassInfoReader(proxetta.getClassLoader());
classReader.accept(targetClassInfoReader, 0);
this.destClassWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
// create proxy
if (log.isDebugEnabled()) {
log.debug("processing: " + classReader.getClassName()); // depends on control dependency: [if], data = [none]
}
WorkData wd = process(classReader, targetClassInfoReader);
// store important data
proxyApplied = wd.proxyApplied;
proxyClassName = wd.thisReference.replace('/', '.');
} }
|
public class class_name {
protected static String createDotStoryName(String scenarioName) {
String[] words = scenarioName.trim().split(" ");
String result = "";
for (int i = 0; i < words.length; i++) {
String word1 = words[i];
String word2 = word1.toLowerCase();
if (!word1.equals(word2)) {
String finalWord = "";
for (int j = 0; j < word1.length(); j++) {
if (i != 0) {
char c = word1.charAt(j);
if (Character.isUpperCase(c)) {
if (j==0) {
finalWord += Character.toLowerCase(c);
} else {
finalWord += "_" + Character.toLowerCase(c);
}
} else {
finalWord += c;
}
} else {
finalWord = word2;
break;
}
}
result += finalWord;
} else {
result += word2;
}
// I don't add the '_' to the last word.
if (!(i == words.length - 1))
result += "_";
}
return result;
} }
|
public class class_name {
protected static String createDotStoryName(String scenarioName) {
String[] words = scenarioName.trim().split(" ");
String result = "";
for (int i = 0; i < words.length; i++) {
String word1 = words[i];
String word2 = word1.toLowerCase();
if (!word1.equals(word2)) {
String finalWord = "";
for (int j = 0; j < word1.length(); j++) {
if (i != 0) {
char c = word1.charAt(j);
if (Character.isUpperCase(c)) {
if (j==0) {
finalWord += Character.toLowerCase(c); // depends on control dependency: [if], data = [none]
} else {
finalWord += "_" + Character.toLowerCase(c); // depends on control dependency: [if], data = [none]
}
} else {
finalWord += c; // depends on control dependency: [if], data = [none]
}
} else {
finalWord = word2; // depends on control dependency: [if], data = [none]
break;
}
}
result += finalWord; // depends on control dependency: [if], data = [none]
} else {
result += word2; // depends on control dependency: [if], data = [none]
}
// I don't add the '_' to the last word.
if (!(i == words.length - 1))
result += "_";
}
return result;
} }
|
public class class_name {
public void setHighlightedDegree(final float highlightedDegree) {
this.mHighlightedDegree = highlightedDegree;
mHighlightedMarker = null;
mHighlightedMarkerPosition = -1;
// Loop through all markers to see if any of them are highlighted.
if (mMarkerList != null) {
final int size = mMarkerList.size();
for (int i = 0; i < size; i++) {
final Marker marker = mMarkerList.get(i);
// Only check the marker if the visibility is not "gone"
if (marker.getVisibility() != View.GONE) {
final boolean markerIsHighlighted = mHighlightedDegree != HIGHLIGHT_NONE && marker.hasInSection(mHighlightedDegree % 360);
marker.setHighlighted(markerIsHighlighted);
if (markerIsHighlighted) {
// Marker is highlighted!
mHighlightedMarker = marker;
mHighlightedMarkerPosition = i;
final boolean highlightAnimationAndAnimateMarker = mIsAnimating && mAnimateMarkersOnHighlightAnimation;
final boolean stillAndAnimateMarker = !mIsAnimating && mAnimateMarkersOnStillHighlight;
final boolean wantsToAnimateMarker = highlightAnimationAndAnimateMarker || stillAndAnimateMarker;
// Animate only if necessary
if (wantsToAnimateMarker && !marker.isAnimating()) {
marker.animateBounce();
}
}
}
// Continue looping through the rest to reset other markers.
}
}
postInvalidate();
} }
|
public class class_name {
public void setHighlightedDegree(final float highlightedDegree) {
this.mHighlightedDegree = highlightedDegree;
mHighlightedMarker = null;
mHighlightedMarkerPosition = -1;
// Loop through all markers to see if any of them are highlighted.
if (mMarkerList != null) {
final int size = mMarkerList.size();
for (int i = 0; i < size; i++) {
final Marker marker = mMarkerList.get(i);
// Only check the marker if the visibility is not "gone"
if (marker.getVisibility() != View.GONE) {
final boolean markerIsHighlighted = mHighlightedDegree != HIGHLIGHT_NONE && marker.hasInSection(mHighlightedDegree % 360);
marker.setHighlighted(markerIsHighlighted); // depends on control dependency: [if], data = [none]
if (markerIsHighlighted) {
// Marker is highlighted!
mHighlightedMarker = marker; // depends on control dependency: [if], data = [none]
mHighlightedMarkerPosition = i; // depends on control dependency: [if], data = [none]
final boolean highlightAnimationAndAnimateMarker = mIsAnimating && mAnimateMarkersOnHighlightAnimation;
final boolean stillAndAnimateMarker = !mIsAnimating && mAnimateMarkersOnStillHighlight;
final boolean wantsToAnimateMarker = highlightAnimationAndAnimateMarker || stillAndAnimateMarker;
// Animate only if necessary
if (wantsToAnimateMarker && !marker.isAnimating()) {
marker.animateBounce(); // depends on control dependency: [if], data = [none]
}
}
}
// Continue looping through the rest to reset other markers.
}
}
postInvalidate();
} }
|
public class class_name {
@Override
public final V view() {
if (this.view == null) {
try {
this.view = buildView();
} catch (final CoreException ce) {
LOGGER.log(UIMessages.CREATION_FAILURE, ce, this.getClass().getName());
throw new CoreRuntimeException(ce);
}
}
return this.view;
} }
|
public class class_name {
@Override
public final V view() {
if (this.view == null) {
try {
this.view = buildView(); // depends on control dependency: [try], data = [none]
} catch (final CoreException ce) {
LOGGER.log(UIMessages.CREATION_FAILURE, ce, this.getClass().getName());
throw new CoreRuntimeException(ce);
} // depends on control dependency: [catch], data = [none]
}
return this.view;
} }
|
public class class_name {
public static void prepareForLogging(HttpServletRequest request) {
// Add the fishtag for Log4j2 MDC
MDC.put("timestamp", System.currentTimeMillis() + "");
MDC.put("request_id", UUID.randomUUID().toString()); // generate random request id
MDC.put("request", request.getRequestURI());
MDC.put("ip", RequestUtils.getClientIpAddress(request));
MDC.put("user_agent", RequestUtils.getUserAgent(request));
MDC.put("method", request.getMethod());
MDC.put("host", request.getServerName());
MDC.put("scheme", RequestUtils.getScheme(request));
MDC.put("domain", UrlUtils.resolveDomain(request.getServerName()));
MDC.put("port", request.getServerPort() + "");
MDC.put("path", request.getContextPath() + request.getPathInfo());
if (request.getUserPrincipal() != null) {
MDC.put("user", request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : null);
}
if (!StringUtils.isNullOrEmptyTrimmed(request.getQueryString())) {
MDC.put("query", request.getQueryString());
}
} }
|
public class class_name {
public static void prepareForLogging(HttpServletRequest request) {
// Add the fishtag for Log4j2 MDC
MDC.put("timestamp", System.currentTimeMillis() + "");
MDC.put("request_id", UUID.randomUUID().toString()); // generate random request id
MDC.put("request", request.getRequestURI());
MDC.put("ip", RequestUtils.getClientIpAddress(request));
MDC.put("user_agent", RequestUtils.getUserAgent(request));
MDC.put("method", request.getMethod());
MDC.put("host", request.getServerName());
MDC.put("scheme", RequestUtils.getScheme(request));
MDC.put("domain", UrlUtils.resolveDomain(request.getServerName()));
MDC.put("port", request.getServerPort() + "");
MDC.put("path", request.getContextPath() + request.getPathInfo());
if (request.getUserPrincipal() != null) {
MDC.put("user", request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : null); // depends on control dependency: [if], data = [null)]
}
if (!StringUtils.isNullOrEmptyTrimmed(request.getQueryString())) {
MDC.put("query", request.getQueryString()); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void addColumn(final Object columnName, final Vector columnData) {
this.columnIdentifiers.addElement(columnName);
if (columnData != null) {
final int columnSize = columnData.size();
if (columnSize > getRowCount()) {
this.dataVector.setSize(columnSize);
}
justifyRows(0, getRowCount());
final int newColumn = getColumnCount() - 1;
for (int i = 0; i < columnSize; i++) {
final Vector row = (Vector) this.dataVector.elementAt(i);
row.setElementAt(columnData.elementAt(i), newColumn);
}
} else {
justifyRows(0, getRowCount());
}
fireTableStructureChanged();
} }
|
public class class_name {
public void addColumn(final Object columnName, final Vector columnData) {
this.columnIdentifiers.addElement(columnName);
if (columnData != null) {
final int columnSize = columnData.size();
if (columnSize > getRowCount()) {
this.dataVector.setSize(columnSize);
// depends on control dependency: [if], data = [(columnSize]
}
justifyRows(0, getRowCount());
// depends on control dependency: [if], data = [none]
final int newColumn = getColumnCount() - 1;
for (int i = 0; i < columnSize; i++) {
final Vector row = (Vector) this.dataVector.elementAt(i);
row.setElementAt(columnData.elementAt(i), newColumn);
// depends on control dependency: [for], data = [i]
}
} else {
justifyRows(0, getRowCount());
// depends on control dependency: [if], data = [none]
}
fireTableStructureChanged();
} }
|
public class class_name {
private Pattern compileRegex( String match ) {
Pattern pattern = compiledRegexCache.get( match );
if ( pattern == null ) {
pattern = Pattern.compile( match );
compiledRegexCache.put( match, pattern );
}
return pattern;
} }
|
public class class_name {
private Pattern compileRegex( String match ) {
Pattern pattern = compiledRegexCache.get( match );
if ( pattern == null ) {
pattern = Pattern.compile( match ); // depends on control dependency: [if], data = [none]
compiledRegexCache.put( match, pattern ); // depends on control dependency: [if], data = [none]
}
return pattern;
} }
|
public class class_name {
public String singularize(String noun) {
String singular = noun;
if (singulars.get(noun) != null) {
singular = singulars.get(noun);
} else if (noun.matches(".*is$")) {
// Singular of *is => *es
singular = noun.substring(0, noun.length() - 2) + "es";
} else if (noun.matches(".*ies$")) {
// Singular of *ies => *y
singular = noun.substring(0, noun.length() - 3) + "y";
} else if (noun.matches(".*ves$")) {
// Singular of *ves => *f
singular = noun.substring(0, noun.length() - 3) + "f";
} else if (noun.matches(".*es$")) {
if (noun.matches(".*les$")) {
// Singular of *les =>
singular = noun.substring(0, noun.length() - 1);
} else {
// Singular of *es =>
singular = noun.substring(0, noun.length() - 2);
}
} else if (noun.matches(".*s$")) {
// Singular of *s =>
singular = noun.substring(0, noun.length() - 1);
}
return singular;
} }
|
public class class_name {
public String singularize(String noun) {
String singular = noun;
if (singulars.get(noun) != null) {
singular = singulars.get(noun); // depends on control dependency: [if], data = [none]
} else if (noun.matches(".*is$")) {
// Singular of *is => *es
singular = noun.substring(0, noun.length() - 2) + "es"; // depends on control dependency: [if], data = [none]
} else if (noun.matches(".*ies$")) {
// Singular of *ies => *y
singular = noun.substring(0, noun.length() - 3) + "y"; // depends on control dependency: [if], data = [none]
} else if (noun.matches(".*ves$")) {
// Singular of *ves => *f
singular = noun.substring(0, noun.length() - 3) + "f"; // depends on control dependency: [if], data = [none]
} else if (noun.matches(".*es$")) {
if (noun.matches(".*les$")) {
// Singular of *les =>
singular = noun.substring(0, noun.length() - 1); // depends on control dependency: [if], data = [none]
} else {
// Singular of *es =>
singular = noun.substring(0, noun.length() - 2); // depends on control dependency: [if], data = [none]
}
} else if (noun.matches(".*s$")) {
// Singular of *s =>
singular = noun.substring(0, noun.length() - 1); // depends on control dependency: [if], data = [none]
}
return singular;
} }
|
public class class_name {
private void resetCorrectOffsets(ConsumerWorker worker) {
KafkaConsumer<String, Serializable> consumer = worker.consumer;
Map<String, List<PartitionInfo>> topicInfos = consumer.listTopics();
Set<String> topics = topicInfos.keySet();
List<String> expectTopics = new ArrayList<>(topicHandlers.keySet());
List<PartitionInfo> patitions = null;
consumer.poll(200);
for (String topic : topics) {
if(!expectTopics.contains(topic))continue;
patitions = topicInfos.get(topic);
for (PartitionInfo partition : patitions) {
try {
//期望的偏移
long expectOffsets = consumerContext.getLatestProcessedOffsets(topic, partition.partition());
//
TopicPartition topicPartition = new TopicPartition(partition.topic(), partition.partition());
OffsetAndMetadata metadata = consumer.committed(topicPartition);
Set<TopicPartition> assignment = consumer.assignment();
if(assignment.contains(topicPartition)){
if(expectOffsets > 0 && expectOffsets < metadata.offset()){
consumer.seek(topicPartition, expectOffsets);
//consumer.seekToBeginning(assignment);
logger.info(">>>>>>> seek Topic[{}] partition[{}] from {} to {}",topic, partition.partition(),metadata.offset(),expectOffsets);
}
}
} catch (Exception e) {
logger.warn("try seek topic["+topic+"] partition["+partition.partition()+"] offsets error");
}
}
}
consumer.resume(consumer.assignment());
} }
|
public class class_name {
private void resetCorrectOffsets(ConsumerWorker worker) {
KafkaConsumer<String, Serializable> consumer = worker.consumer;
Map<String, List<PartitionInfo>> topicInfos = consumer.listTopics();
Set<String> topics = topicInfos.keySet();
List<String> expectTopics = new ArrayList<>(topicHandlers.keySet());
List<PartitionInfo> patitions = null;
consumer.poll(200);
for (String topic : topics) {
if(!expectTopics.contains(topic))continue;
patitions = topicInfos.get(topic); // depends on control dependency: [for], data = [topic]
for (PartitionInfo partition : patitions) {
try {
//期望的偏移
long expectOffsets = consumerContext.getLatestProcessedOffsets(topic, partition.partition());
//
TopicPartition topicPartition = new TopicPartition(partition.topic(), partition.partition());
OffsetAndMetadata metadata = consumer.committed(topicPartition);
Set<TopicPartition> assignment = consumer.assignment();
if(assignment.contains(topicPartition)){
if(expectOffsets > 0 && expectOffsets < metadata.offset()){
consumer.seek(topicPartition, expectOffsets); // depends on control dependency: [if], data = [none]
//consumer.seekToBeginning(assignment);
logger.info(">>>>>>> seek Topic[{}] partition[{}] from {} to {}",topic, partition.partition(),metadata.offset(),expectOffsets); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none]
}
}
} catch (Exception e) {
logger.warn("try seek topic["+topic+"] partition["+partition.partition()+"] offsets error");
} // depends on control dependency: [catch], data = [none]
}
}
consumer.resume(consumer.assignment());
} }
|
public class class_name {
public PermissionsBuilder setUnset(PermissionType... types) {
for (PermissionType type : types) {
setState(type, PermissionState.UNSET);
}
return this;
} }
|
public class class_name {
public PermissionsBuilder setUnset(PermissionType... types) {
for (PermissionType type : types) {
setState(type, PermissionState.UNSET); // depends on control dependency: [for], data = [type]
}
return this;
} }
|
public class class_name {
public void marshall(BatchListIndex batchListIndex, ProtocolMarshaller protocolMarshaller) {
if (batchListIndex == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchListIndex.getRangesOnIndexedValues(), RANGESONINDEXEDVALUES_BINDING);
protocolMarshaller.marshall(batchListIndex.getIndexReference(), INDEXREFERENCE_BINDING);
protocolMarshaller.marshall(batchListIndex.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(batchListIndex.getNextToken(), NEXTTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(BatchListIndex batchListIndex, ProtocolMarshaller protocolMarshaller) {
if (batchListIndex == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchListIndex.getRangesOnIndexedValues(), RANGESONINDEXEDVALUES_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchListIndex.getIndexReference(), INDEXREFERENCE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchListIndex.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(batchListIndex.getNextToken(), NEXTTOKEN_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 {
long parseParam(final String param) {
if (param == null || param.isEmpty()) {
throw new IllegalArgumentException(
"Window parameter may not be null or empty");
}
final char[] chars = param.toCharArray();
int idx = 0;
for (int c = 1; c < chars.length; c++) {
if (Character.isDigit(chars[c])) {
idx++;
} else {
break;
}
}
if (idx < 1) {
throw new IllegalArgumentException("Invalid moving window parameter: "
+ param);
}
try {
final int time = Integer.parseInt(param.substring(1, idx + 1));
final String unit = param.substring(idx + 1, param.length() - 1);
// TODO(CL) - add a Graphite unit parser to DateTime for this kind of conversion
if ("day".equals(unit) || "d".equals(unit)) {
return TimeUnit.MILLISECONDS.convert(time, TimeUnit.DAYS);
} else if ("hr".equals(unit) || "hour".equals(unit) || "h".equals(unit)) {
return TimeUnit.MILLISECONDS.convert(time, TimeUnit.HOURS);
} else if ("min".equals(unit) || "m".equals(unit)) {
return TimeUnit.MILLISECONDS.convert(time, TimeUnit.MINUTES);
} else if ("sec".equals(unit) || "s".equals(unit)) {
return TimeUnit.MILLISECONDS.convert(time, TimeUnit.SECONDS);
} else {
throw new IllegalArgumentException("Unknown time unit=" + unit
+ " in window=" + param);
}
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Unable to parse moving window "
+ "parameter: " + param, nfe);
}
} }
|
public class class_name {
long parseParam(final String param) {
if (param == null || param.isEmpty()) {
throw new IllegalArgumentException(
"Window parameter may not be null or empty");
}
final char[] chars = param.toCharArray();
int idx = 0;
for (int c = 1; c < chars.length; c++) {
if (Character.isDigit(chars[c])) {
idx++; // depends on control dependency: [if], data = [none]
} else {
break;
}
}
if (idx < 1) {
throw new IllegalArgumentException("Invalid moving window parameter: "
+ param);
}
try {
final int time = Integer.parseInt(param.substring(1, idx + 1));
final String unit = param.substring(idx + 1, param.length() - 1);
// TODO(CL) - add a Graphite unit parser to DateTime for this kind of conversion
if ("day".equals(unit) || "d".equals(unit)) {
return TimeUnit.MILLISECONDS.convert(time, TimeUnit.DAYS); // depends on control dependency: [if], data = [none]
} else if ("hr".equals(unit) || "hour".equals(unit) || "h".equals(unit)) {
return TimeUnit.MILLISECONDS.convert(time, TimeUnit.HOURS); // depends on control dependency: [if], data = [none]
} else if ("min".equals(unit) || "m".equals(unit)) {
return TimeUnit.MILLISECONDS.convert(time, TimeUnit.MINUTES); // depends on control dependency: [if], data = [none]
} else if ("sec".equals(unit) || "s".equals(unit)) {
return TimeUnit.MILLISECONDS.convert(time, TimeUnit.SECONDS); // depends on control dependency: [if], data = [none]
} else {
throw new IllegalArgumentException("Unknown time unit=" + unit
+ " in window=" + param);
}
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Unable to parse moving window "
+ "parameter: " + param, nfe);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public static URL getSystemResource(String name) {
ClassLoader system = getSystemClassLoader();
if (system == null) {
return getBootstrapResource(name);
}
return system.getResource(name);
} }
|
public class class_name {
public static URL getSystemResource(String name) {
ClassLoader system = getSystemClassLoader();
if (system == null) {
return getBootstrapResource(name); // depends on control dependency: [if], data = [none]
}
return system.getResource(name);
} }
|
public class class_name {
public String getDivisionName(ProposalDevelopmentDocumentContract pdDoc) {
String divisionName = null;
if (pdDoc != null && pdDoc.getDevelopmentProposal().getOwnedByUnit() != null) {
UnitContract ownedByUnit = pdDoc.getDevelopmentProposal().getOwnedByUnit();
// traverse through the parent units till the top level unit
while (ownedByUnit.getParentUnit() != null) {
ownedByUnit = ownedByUnit.getParentUnit();
}
divisionName = ownedByUnit.getUnitName();
if (divisionName.length() > DIVISION_NAME_MAX_LENGTH) {
divisionName = divisionName.substring(0, DIVISION_NAME_MAX_LENGTH);
}
}
return divisionName;
} }
|
public class class_name {
public String getDivisionName(ProposalDevelopmentDocumentContract pdDoc) {
String divisionName = null;
if (pdDoc != null && pdDoc.getDevelopmentProposal().getOwnedByUnit() != null) {
UnitContract ownedByUnit = pdDoc.getDevelopmentProposal().getOwnedByUnit();
// traverse through the parent units till the top level unit
while (ownedByUnit.getParentUnit() != null) {
ownedByUnit = ownedByUnit.getParentUnit(); // depends on control dependency: [while], data = [none]
}
divisionName = ownedByUnit.getUnitName(); // depends on control dependency: [if], data = [none]
if (divisionName.length() > DIVISION_NAME_MAX_LENGTH) {
divisionName = divisionName.substring(0, DIVISION_NAME_MAX_LENGTH); // depends on control dependency: [if], data = [DIVISION_NAME_MAX_LENGTH)]
}
}
return divisionName;
} }
|
public class class_name {
protected Integer invokeSection()
{
try
{
// run object is a JavaProcessRunner
S runner = getRunner(getRunObject());
if (run_method_str == null)
return null;
createRunMethod(param_types, runner);
Object[] local_params = (Object[])params.clone();
Integer result_code = (Integer) run_method.invoke(runner, local_params);
return result_code;
}
// Allow ProcessImpl exceptions to be rethrown
catch (ForceProcessComplete fpc)
{
throw fpc;
}
catch (ForceRescheduleException fre)
{
throw fre;
}
catch (InvocationTargetException ite)
{
Throwable cause = ite.getCause();
if (cause instanceof ForceProcessComplete|| cause instanceof ForceRescheduleException)
throw (RuntimeException)cause;
new QueujException(ite);
return BatchProcessServer.FAILURE;
}
catch (Exception e)
{
new QueujException(e);
return BatchProcessServer.FAILURE;
}
} }
|
public class class_name {
protected Integer invokeSection()
{
try
{
// run object is a JavaProcessRunner
S runner = getRunner(getRunObject());
if (run_method_str == null)
return null;
createRunMethod(param_types, runner); // depends on control dependency: [try], data = [none]
Object[] local_params = (Object[])params.clone();
Integer result_code = (Integer) run_method.invoke(runner, local_params);
return result_code; // depends on control dependency: [try], data = [none]
}
// Allow ProcessImpl exceptions to be rethrown
catch (ForceProcessComplete fpc)
{
throw fpc;
} // depends on control dependency: [catch], data = [none]
catch (ForceRescheduleException fre)
{
throw fre;
} // depends on control dependency: [catch], data = [none]
catch (InvocationTargetException ite)
{
Throwable cause = ite.getCause();
if (cause instanceof ForceProcessComplete|| cause instanceof ForceRescheduleException)
throw (RuntimeException)cause;
new QueujException(ite);
return BatchProcessServer.FAILURE;
} // depends on control dependency: [catch], data = [none]
catch (Exception e)
{
new QueujException(e);
return BatchProcessServer.FAILURE;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
protected Collector<OT> createSolutionSetUpdateOutputCollector(Collector<OT> delegate) {
Broker<Object> solutionSetBroker = SolutionSetBroker.instance();
Object ss = solutionSetBroker.get(brokerKey());
if (ss instanceof CompactingHashTable) {
@SuppressWarnings("unchecked")
CompactingHashTable<OT> solutionSet = (CompactingHashTable<OT>) ss;
return new SolutionSetUpdateOutputCollector<OT>(solutionSet, delegate);
}
else if (ss instanceof JoinHashMap) {
@SuppressWarnings("unchecked")
JoinHashMap<OT> map = (JoinHashMap<OT>) ss;
return new SolutionSetObjectsUpdateOutputCollector<OT>(map, delegate);
} else {
throw new RuntimeException("Unrecognized solution set handle: " + ss);
}
} }
|
public class class_name {
protected Collector<OT> createSolutionSetUpdateOutputCollector(Collector<OT> delegate) {
Broker<Object> solutionSetBroker = SolutionSetBroker.instance();
Object ss = solutionSetBroker.get(brokerKey());
if (ss instanceof CompactingHashTable) {
@SuppressWarnings("unchecked")
CompactingHashTable<OT> solutionSet = (CompactingHashTable<OT>) ss;
return new SolutionSetUpdateOutputCollector<OT>(solutionSet, delegate); // depends on control dependency: [if], data = [none]
}
else if (ss instanceof JoinHashMap) {
@SuppressWarnings("unchecked")
JoinHashMap<OT> map = (JoinHashMap<OT>) ss;
return new SolutionSetObjectsUpdateOutputCollector<OT>(map, delegate); // depends on control dependency: [if], data = [none]
} else {
throw new RuntimeException("Unrecognized solution set handle: " + ss);
}
} }
|
public class class_name {
private void doReverseKNNQuery(int k, DBIDRef q, ModifiableDoubleDBIDList result, ModifiableDBIDs candidates) {
final ComparableMinHeap<MTreeSearchCandidate> pq = new ComparableMinHeap<>();
// push root
pq.add(new MTreeSearchCandidate(0., getRootID(), null, Double.NaN));
// search in tree
while(!pq.isEmpty()) {
MTreeSearchCandidate pqNode = pq.poll();
// FIXME: cache the distance to the routing object in the queue node!
MkCoPTreeNode<O> node = getNode(pqNode.nodeID);
// directory node
if(!node.isLeaf()) {
for(int i = 0; i < node.getNumEntries(); i++) {
MkCoPEntry entry = node.getEntry(i);
double distance = distance(entry.getRoutingObjectID(), q);
double minDist = entry.getCoveringRadius() > distance ? 0. : distance - entry.getCoveringRadius();
double approximatedKnnDist_cons = entry.approximateConservativeKnnDistance(k);
if(minDist <= approximatedKnnDist_cons) {
pq.add(new MTreeSearchCandidate(minDist, getPageID(entry), entry.getRoutingObjectID(), Double.NaN));
}
}
}
// data node
else {
for(int i = 0; i < node.getNumEntries(); i++) {
MkCoPLeafEntry entry = (MkCoPLeafEntry) node.getEntry(i);
double distance = distance(entry.getRoutingObjectID(), q);
double approximatedKnnDist_prog = entry.approximateProgressiveKnnDistance(k);
if(distance <= approximatedKnnDist_prog) {
result.add(distance, entry.getRoutingObjectID());
}
else {
double approximatedKnnDist_cons = entry.approximateConservativeKnnDistance(k);
double diff = distance - approximatedKnnDist_cons;
if(diff <= 1E-10) {
candidates.add(entry.getRoutingObjectID());
}
}
}
}
}
} }
|
public class class_name {
private void doReverseKNNQuery(int k, DBIDRef q, ModifiableDoubleDBIDList result, ModifiableDBIDs candidates) {
final ComparableMinHeap<MTreeSearchCandidate> pq = new ComparableMinHeap<>();
// push root
pq.add(new MTreeSearchCandidate(0., getRootID(), null, Double.NaN));
// search in tree
while(!pq.isEmpty()) {
MTreeSearchCandidate pqNode = pq.poll();
// FIXME: cache the distance to the routing object in the queue node!
MkCoPTreeNode<O> node = getNode(pqNode.nodeID);
// directory node
if(!node.isLeaf()) {
for(int i = 0; i < node.getNumEntries(); i++) {
MkCoPEntry entry = node.getEntry(i);
double distance = distance(entry.getRoutingObjectID(), q);
double minDist = entry.getCoveringRadius() > distance ? 0. : distance - entry.getCoveringRadius();
double approximatedKnnDist_cons = entry.approximateConservativeKnnDistance(k);
if(minDist <= approximatedKnnDist_cons) {
pq.add(new MTreeSearchCandidate(minDist, getPageID(entry), entry.getRoutingObjectID(), Double.NaN)); // depends on control dependency: [if], data = [(minDist]
}
}
}
// data node
else {
for(int i = 0; i < node.getNumEntries(); i++) {
MkCoPLeafEntry entry = (MkCoPLeafEntry) node.getEntry(i);
double distance = distance(entry.getRoutingObjectID(), q);
double approximatedKnnDist_prog = entry.approximateProgressiveKnnDistance(k);
if(distance <= approximatedKnnDist_prog) {
result.add(distance, entry.getRoutingObjectID()); // depends on control dependency: [if], data = [(distance]
}
else {
double approximatedKnnDist_cons = entry.approximateConservativeKnnDistance(k);
double diff = distance - approximatedKnnDist_cons;
if(diff <= 1E-10) {
candidates.add(entry.getRoutingObjectID()); // depends on control dependency: [if], data = [none]
}
}
}
}
}
} }
|
public class class_name {
private List<CmsDecorationMap> getDecorationMaps(CmsObject cms, List<CmsResource> decorationListFiles) {
List<CmsDecorationMap> decorationMaps = new ArrayList<CmsDecorationMap>();
Iterator<CmsResource> i = decorationListFiles.iterator();
while (i.hasNext()) {
CmsResource res = i.next();
try {
CmsDecorationMap decMap = (CmsDecorationMap)CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().getCachedObject(
cms,
res.getRootPath());
if (decMap == null) {
decMap = new CmsDecorationMap(cms, res, this);
CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().putCachedObject(cms, res.getRootPath(), decMap);
}
decorationMaps.add(decMap);
} catch (CmsException e) {
if (LOG.isErrorEnabled()) {
LOG.error(
Messages.get().getBundle().key(
Messages.LOG_DECORATION_DEFINITION_CREATE_MAP_2,
res.getName(),
e));
}
}
}
return decorationMaps;
} }
|
public class class_name {
private List<CmsDecorationMap> getDecorationMaps(CmsObject cms, List<CmsResource> decorationListFiles) {
List<CmsDecorationMap> decorationMaps = new ArrayList<CmsDecorationMap>();
Iterator<CmsResource> i = decorationListFiles.iterator();
while (i.hasNext()) {
CmsResource res = i.next();
try {
CmsDecorationMap decMap = (CmsDecorationMap)CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().getCachedObject(
cms,
res.getRootPath());
if (decMap == null) {
decMap = new CmsDecorationMap(cms, res, this); // depends on control dependency: [if], data = [none]
CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().putCachedObject(cms, res.getRootPath(), decMap); // depends on control dependency: [if], data = [none]
}
decorationMaps.add(decMap); // depends on control dependency: [try], data = [none]
} catch (CmsException e) {
if (LOG.isErrorEnabled()) {
LOG.error(
Messages.get().getBundle().key(
Messages.LOG_DECORATION_DEFINITION_CREATE_MAP_2,
res.getName(),
e)); // depends on control dependency: [if], data = [none]
}
} // depends on control dependency: [catch], data = [none]
}
return decorationMaps;
} }
|
public class class_name {
public LinkedPredict<T> mergeDuplicate(boolean useScore) {
LinkedPredict<T> pred = new LinkedPredict<T>();
for(int i = 0; i < labels.size(); i++){
T l = labels.get(i);
float score;
if(useScore)
score = scores.get(i);
else
score=1;
pred.addoradjust(l, score);
}
return pred;
} }
|
public class class_name {
public LinkedPredict<T> mergeDuplicate(boolean useScore) {
LinkedPredict<T> pred = new LinkedPredict<T>();
for(int i = 0; i < labels.size(); i++){
T l = labels.get(i);
float score;
if(useScore)
score = scores.get(i);
else
score=1;
pred.addoradjust(l, score);
// depends on control dependency: [for], data = [none]
}
return pred;
} }
|
public class class_name {
public static EnhancedMimeType mimeType(@NotNull final SerializerRegistry registry, @NotNull final List<CommonEvent> commonEvents) {
Contract.requireArgNotNull("registry", registry);
Contract.requireArgNotNull("commonEvents", commonEvents);
EnhancedMimeType mimeType = null;
for (final CommonEvent commonEvent : commonEvents) {
final Serializer serializer = registry.getSerializer(new SerializedDataType(commonEvent.getDataType().asBaseType()));
if (mimeType == null) {
mimeType = serializer.getMimeType();
} else {
if (!mimeType.equals(serializer.getMimeType())) {
return null;
}
}
}
return mimeType;
} }
|
public class class_name {
public static EnhancedMimeType mimeType(@NotNull final SerializerRegistry registry, @NotNull final List<CommonEvent> commonEvents) {
Contract.requireArgNotNull("registry", registry);
Contract.requireArgNotNull("commonEvents", commonEvents);
EnhancedMimeType mimeType = null;
for (final CommonEvent commonEvent : commonEvents) {
final Serializer serializer = registry.getSerializer(new SerializedDataType(commonEvent.getDataType().asBaseType()));
if (mimeType == null) {
mimeType = serializer.getMimeType(); // depends on control dependency: [if], data = [none]
} else {
if (!mimeType.equals(serializer.getMimeType())) {
return null; // depends on control dependency: [if], data = [none]
}
}
}
return mimeType;
} }
|
public class class_name {
public static ClusterSetInfo classifyPoints(final ClusterSet clusterSet, List<Point> points,
ExecutorService executorService) {
final ClusterSetInfo clusterSetInfo = ClusterSetInfo.initialize(clusterSet, true);
List<Runnable> tasks = new ArrayList<>();
for (final Point point : points) {
//tasks.add(new Runnable() {
// public void run() {
try {
PointClassification result = classifyPoint(clusterSet, point);
if (result.isNewLocation())
clusterSetInfo.getPointLocationChange().incrementAndGet();
clusterSetInfo.getClusterInfo(result.getCluster().getId()).getPointDistancesFromCenter()
.put(point.getId(), result.getDistanceFromCenter());
} catch (Throwable t) {
log.warn("Error classifying point", t);
}
// }
}
//MultiThreadUtils.parallelTasks(tasks, executorService);
return clusterSetInfo;
} }
|
public class class_name {
public static ClusterSetInfo classifyPoints(final ClusterSet clusterSet, List<Point> points,
ExecutorService executorService) {
final ClusterSetInfo clusterSetInfo = ClusterSetInfo.initialize(clusterSet, true);
List<Runnable> tasks = new ArrayList<>();
for (final Point point : points) {
//tasks.add(new Runnable() {
// public void run() {
try {
PointClassification result = classifyPoint(clusterSet, point);
if (result.isNewLocation())
clusterSetInfo.getPointLocationChange().incrementAndGet();
clusterSetInfo.getClusterInfo(result.getCluster().getId()).getPointDistancesFromCenter()
.put(point.getId(), result.getDistanceFromCenter()); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
log.warn("Error classifying point", t);
} // depends on control dependency: [catch], data = [none]
// }
}
//MultiThreadUtils.parallelTasks(tasks, executorService);
return clusterSetInfo;
} }
|
public class class_name {
public void marshall(DeleteWebhookRequest deleteWebhookRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteWebhookRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteWebhookRequest.getName(), NAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(DeleteWebhookRequest deleteWebhookRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteWebhookRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteWebhookRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private String getTimeText() {
String timeAsString = m_time.getText().trim();
if (CmsDateConverter.is12HourPresentation()) {
if (!(timeAsString.contains(CmsDateConverter.AM) || timeAsString.contains(CmsDateConverter.PM))) {
if (m_am.isChecked()) {
timeAsString = timeAsString + " " + CmsDateConverter.AM;
} else {
timeAsString = timeAsString + " " + CmsDateConverter.PM;
}
}
}
return timeAsString;
} }
|
public class class_name {
private String getTimeText() {
String timeAsString = m_time.getText().trim();
if (CmsDateConverter.is12HourPresentation()) {
if (!(timeAsString.contains(CmsDateConverter.AM) || timeAsString.contains(CmsDateConverter.PM))) {
if (m_am.isChecked()) {
timeAsString = timeAsString + " " + CmsDateConverter.AM; // depends on control dependency: [if], data = [none]
} else {
timeAsString = timeAsString + " " + CmsDateConverter.PM; // depends on control dependency: [if], data = [none]
}
}
}
return timeAsString;
} }
|
public class class_name {
static CachedScheduler cache(AtomicReference<CachedScheduler> reference, String key, Supplier<Scheduler> supplier) {
CachedScheduler s = reference.get();
if (s != null) {
return s;
}
s = new CachedScheduler(key, supplier.get());
if (reference.compareAndSet(null, s)) {
return s;
}
//the reference was updated in the meantime with a cached scheduler
//fallback to it and dispose the extraneous one
s._dispose();
return reference.get();
} }
|
public class class_name {
static CachedScheduler cache(AtomicReference<CachedScheduler> reference, String key, Supplier<Scheduler> supplier) {
CachedScheduler s = reference.get();
if (s != null) {
return s; // depends on control dependency: [if], data = [none]
}
s = new CachedScheduler(key, supplier.get());
if (reference.compareAndSet(null, s)) {
return s; // depends on control dependency: [if], data = [none]
}
//the reference was updated in the meantime with a cached scheduler
//fallback to it and dispose the extraneous one
s._dispose();
return reference.get();
} }
|
public class class_name {
public RolloverDescription rollover(final String currentActiveFile) {
long n = System.currentTimeMillis();
nextCheck = ((n / 1000) + 1) * 1000;
StringBuffer buf = new StringBuffer();
formatFileName(new Date(n), buf);
String newFileName = buf.toString();
//
// if file names haven't changed, no rollover
//
if (newFileName.equals(lastFileName)) {
return null;
}
Action renameAction = null;
Action compressAction = null;
String lastBaseName =
lastFileName.substring(0, lastFileName.length() - suffixLength);
String nextActiveFile =
newFileName.substring(0, newFileName.length() - suffixLength);
//
// if currentActiveFile is not lastBaseName then
// active file name is not following file pattern
// and requires a rename plus maintaining the same name
if (!currentActiveFile.equals(lastBaseName)) {
renameAction =
new FileRenameAction(
new File(currentActiveFile), new File(lastBaseName), true);
nextActiveFile = currentActiveFile;
}
if (suffixLength == 3) {
compressAction =
new GZCompressAction(
new File(lastBaseName), new File(lastFileName), true);
}
if (suffixLength == 4) {
compressAction =
new ZipCompressAction(
new File(lastBaseName), new File(lastFileName), true);
}
lastFileName = newFileName;
return new RolloverDescriptionImpl(
nextActiveFile, false, renameAction, compressAction);
} }
|
public class class_name {
public RolloverDescription rollover(final String currentActiveFile) {
long n = System.currentTimeMillis();
nextCheck = ((n / 1000) + 1) * 1000;
StringBuffer buf = new StringBuffer();
formatFileName(new Date(n), buf);
String newFileName = buf.toString();
//
// if file names haven't changed, no rollover
//
if (newFileName.equals(lastFileName)) {
return null; // depends on control dependency: [if], data = [none]
}
Action renameAction = null;
Action compressAction = null;
String lastBaseName =
lastFileName.substring(0, lastFileName.length() - suffixLength);
String nextActiveFile =
newFileName.substring(0, newFileName.length() - suffixLength);
//
// if currentActiveFile is not lastBaseName then
// active file name is not following file pattern
// and requires a rename plus maintaining the same name
if (!currentActiveFile.equals(lastBaseName)) {
renameAction =
new FileRenameAction(
new File(currentActiveFile), new File(lastBaseName), true); // depends on control dependency: [if], data = [none]
nextActiveFile = currentActiveFile; // depends on control dependency: [if], data = [none]
}
if (suffixLength == 3) {
compressAction =
new GZCompressAction(
new File(lastBaseName), new File(lastFileName), true); // depends on control dependency: [if], data = [none]
}
if (suffixLength == 4) {
compressAction =
new ZipCompressAction(
new File(lastBaseName), new File(lastFileName), true); // depends on control dependency: [if], data = [none]
}
lastFileName = newFileName;
return new RolloverDescriptionImpl(
nextActiveFile, false, renameAction, compressAction);
} }
|
public class class_name {
public HttpResponseMessageImpl getResponse() {
HttpResponseMessageImpl resp = (HttpResponseMessageImpl) this.respPool.get();
if (null == resp) {
resp = new HttpResponseMessageImpl();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "getResponse(): " + resp);
}
return resp;
} }
|
public class class_name {
public HttpResponseMessageImpl getResponse() {
HttpResponseMessageImpl resp = (HttpResponseMessageImpl) this.respPool.get();
if (null == resp) {
resp = new HttpResponseMessageImpl(); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "getResponse(): " + resp); // depends on control dependency: [if], data = [none]
}
return resp;
} }
|
public class class_name {
public static boolean setIfPossible(final Ruby ruby, final Object target, final String name, final Object value) {
boolean success = false;
if (defined( ruby, target, name + "=" )) {
JavaEmbedUtils.invokeMethod( ruby, target, name + "=", new Object[] { value }, void.class );
success = true;
}
return success;
} }
|
public class class_name {
public static boolean setIfPossible(final Ruby ruby, final Object target, final String name, final Object value) {
boolean success = false;
if (defined( ruby, target, name + "=" )) {
JavaEmbedUtils.invokeMethod( ruby, target, name + "=", new Object[] { value }, void.class ); // depends on control dependency: [if], data = [none]
success = true; // depends on control dependency: [if], data = [none]
}
return success;
} }
|
public class class_name {
private String getFinalPath(String uploadPath) {
if (uploadPath == null) {
throw new IllegalArgumentException("uploadPath can not be null.");
}
uploadPath = uploadPath.trim();
if (uploadPath.startsWith("/") || uploadPath.startsWith("\\")) {
if (baseUploadPath.equals("/")) {
return uploadPath;
} else {
return baseUploadPath + uploadPath;
}
} else {
return baseUploadPath + File.separator + uploadPath;
}
} }
|
public class class_name {
private String getFinalPath(String uploadPath) {
if (uploadPath == null) {
throw new IllegalArgumentException("uploadPath can not be null.");
}
uploadPath = uploadPath.trim();
if (uploadPath.startsWith("/") || uploadPath.startsWith("\\")) {
if (baseUploadPath.equals("/")) {
return uploadPath;
// depends on control dependency: [if], data = [none]
} else {
return baseUploadPath + uploadPath;
// depends on control dependency: [if], data = [none]
}
} else {
return baseUploadPath + File.separator + uploadPath;
// depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void setEnvironmentLinks(java.util.Collection<EnvironmentLink> environmentLinks) {
if (environmentLinks == null) {
this.environmentLinks = null;
return;
}
this.environmentLinks = new com.amazonaws.internal.SdkInternalList<EnvironmentLink>(environmentLinks);
} }
|
public class class_name {
public void setEnvironmentLinks(java.util.Collection<EnvironmentLink> environmentLinks) {
if (environmentLinks == null) {
this.environmentLinks = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.environmentLinks = new com.amazonaws.internal.SdkInternalList<EnvironmentLink>(environmentLinks);
} }
|
public class class_name {
private final DiceNotationExpression
getBinaryOperation(final Collection<String> operators) {
final Stack<DiceNotationExpression> operands;
BinaryOperation operation;
DiceNotationExpression left;
DiceNotationExpression right;
// There are as many operands as operators plus one
operands = new Stack<>();
for (Integer i = 0; i <= operators.size(); i++) {
operands.push(nodes.pop());
}
// The operands and operators are combined into the model expressions
for (final String operator : operators) {
left = operands.pop();
right = operands.pop();
// Checks which kind of operation this is and builds it
if (ADDITION_OPERATOR.equals(operator)) {
LOGGER.trace("Addition operation");
operation = new AdditionOperation(left, right);
} else if (SUBTRACTION_OPERATOR.equals(operator)) {
LOGGER.trace("Subtraction operation");
operation = new SubtractionOperation(left, right);
} else if (MULTIPLICATION_OPERATOR.equals(operator)) {
operation = new MultiplicationOperation(left, right);
} else if (DIVISION_OPERATOR.equals(operator)) {
operation = new DivisionOperation(left, right);
} else {
LOGGER.error("Unknown operator {}", operator);
throw new IllegalArgumentException(
String.format("The %s operator is invalid", operator));
}
// Each new expression is stored back for the next iteration
operands.push(operation);
}
return operands.pop();
} }
|
public class class_name {
private final DiceNotationExpression
getBinaryOperation(final Collection<String> operators) {
final Stack<DiceNotationExpression> operands;
BinaryOperation operation;
DiceNotationExpression left;
DiceNotationExpression right;
// There are as many operands as operators plus one
operands = new Stack<>();
for (Integer i = 0; i <= operators.size(); i++) {
operands.push(nodes.pop()); // depends on control dependency: [for], data = [none]
}
// The operands and operators are combined into the model expressions
for (final String operator : operators) {
left = operands.pop(); // depends on control dependency: [for], data = [none]
right = operands.pop(); // depends on control dependency: [for], data = [none]
// Checks which kind of operation this is and builds it
if (ADDITION_OPERATOR.equals(operator)) {
LOGGER.trace("Addition operation"); // depends on control dependency: [if], data = [none]
operation = new AdditionOperation(left, right); // depends on control dependency: [if], data = [none]
} else if (SUBTRACTION_OPERATOR.equals(operator)) {
LOGGER.trace("Subtraction operation"); // depends on control dependency: [if], data = [none]
operation = new SubtractionOperation(left, right); // depends on control dependency: [if], data = [none]
} else if (MULTIPLICATION_OPERATOR.equals(operator)) {
operation = new MultiplicationOperation(left, right); // depends on control dependency: [if], data = [none]
} else if (DIVISION_OPERATOR.equals(operator)) {
operation = new DivisionOperation(left, right); // depends on control dependency: [if], data = [none]
} else {
LOGGER.error("Unknown operator {}", operator); // depends on control dependency: [if], data = [none]
throw new IllegalArgumentException(
String.format("The %s operator is invalid", operator));
}
// Each new expression is stored back for the next iteration
operands.push(operation); // depends on control dependency: [for], data = [none]
}
return operands.pop();
} }
|
public class class_name {
public static Layout forFile(File file) {
if (file == null) {
throw new IllegalArgumentException("File must not be null");
}
String lowerCaseFileName = file.getName().toLowerCase(Locale.ENGLISH);
if (lowerCaseFileName.endsWith(".jar")) {
return new Jar();
}
if (lowerCaseFileName.endsWith(".war")) {
return new War();
}
if (file.isDirectory() || lowerCaseFileName.endsWith(".zip")) {
return new Expanded();
}
throw new IllegalStateException("Unable to deduce layout for '" + file + "'");
} }
|
public class class_name {
public static Layout forFile(File file) {
if (file == null) {
throw new IllegalArgumentException("File must not be null");
}
String lowerCaseFileName = file.getName().toLowerCase(Locale.ENGLISH);
if (lowerCaseFileName.endsWith(".jar")) {
return new Jar(); // depends on control dependency: [if], data = [none]
}
if (lowerCaseFileName.endsWith(".war")) {
return new War(); // depends on control dependency: [if], data = [none]
}
if (file.isDirectory() || lowerCaseFileName.endsWith(".zip")) {
return new Expanded(); // depends on control dependency: [if], data = [none]
}
throw new IllegalStateException("Unable to deduce layout for '" + file + "'");
} }
|
public class class_name {
public static PipelineOptions tweakOptions(PipelineOptions opts) {
if (!DataflowRunner.class.isAssignableFrom(opts.getRunner())) {
return opts;
}
DataflowPipelineOptions dataflowOpts = opts.as(DataflowPipelineOptions.class);
// By default, dataflow allocates 250 GB local disks, thats not necessary. Lower it unless the
// user requested an explicit size
if (dataflowOpts.getDiskSizeGb() == 0) {
dataflowOpts.setDiskSizeGb(25);
}
return dataflowOpts;
} }
|
public class class_name {
public static PipelineOptions tweakOptions(PipelineOptions opts) {
if (!DataflowRunner.class.isAssignableFrom(opts.getRunner())) {
return opts; // depends on control dependency: [if], data = [none]
}
DataflowPipelineOptions dataflowOpts = opts.as(DataflowPipelineOptions.class);
// By default, dataflow allocates 250 GB local disks, thats not necessary. Lower it unless the
// user requested an explicit size
if (dataflowOpts.getDiskSizeGb() == 0) {
dataflowOpts.setDiskSizeGb(25); // depends on control dependency: [if], data = [none]
}
return dataflowOpts;
} }
|
public class class_name {
public String getStartSourceCode(String packagePath, String strFileName, String strDescription, boolean bResourceListBundle)
{
String string;
if (bResourceListBundle)
{
string =
"package " + packagePath + ";\n"
+ "/**\n"
+ " * @(#)" + strFileName + ".java 0.00 1-Jan-10 Don Corley\n"
+ " *\n"
+ " * Copyright © 2010 tourgeek.com. All Rights Reserved.\n"
+ " * don@donandann.com\n"
+ " */\n"
+ "import java.util.*;\n"
+ "\n"
+ "/**\n"
+ " * " + strFileName + " - Resources.\n"
+ strDescription + "\n"
+ " */\n"
+ "public class " + strFileName + " extends ListResourceBundle\n"
+ "{\n"
+ "\tpublic Object[][] getContents() {\n"
+ "\t\treturn contents;\n"
+ "\t}\n";
}
else
string = "# " + strFileName + " property file" + "\n" + "# " + strDescription + "\n";
return string;
} }
|
public class class_name {
public String getStartSourceCode(String packagePath, String strFileName, String strDescription, boolean bResourceListBundle)
{
String string;
if (bResourceListBundle)
{
string =
"package " + packagePath + ";\n"
+ "/**\n"
+ " * @(#)" + strFileName + ".java 0.00 1-Jan-10 Don Corley\n"
+ " *\n"
+ " * Copyright © 2010 tourgeek.com. All Rights Reserved.\n"
+ " * don@donandann.com\n"
+ " */\n"
+ "import java.util.*;\n" // depends on control dependency: [if], data = [none]
+ "\n"
+ "/**\n"
+ " * " + strFileName + " - Resources.\n"
+ strDescription + "\n"
+ " */\n"
+ "public class " + strFileName + " extends ListResourceBundle\n"
+ "{\n"
+ "\tpublic Object[][] getContents() {\n"
+ "\t\treturn contents;\n"
+ "\t}\n";
}
else
string = "# " + strFileName + " property file" + "\n" + "# " + strDescription + "\n";
return string; // depends on control dependency: [if], data = [none]
} }
|
public class class_name {
@Override
public int getHeight() {
int height = super.getHeight();
if (height <= 0) {
ImageView imageView = (ImageView) viewRef.get();
if (imageView != null) {
height = getImageViewFieldValue(imageView, "mMaxHeight"); // Check maxHeight parameter
}
}
return height;
} }
|
public class class_name {
@Override
public int getHeight() {
int height = super.getHeight();
if (height <= 0) {
ImageView imageView = (ImageView) viewRef.get();
if (imageView != null) {
height = getImageViewFieldValue(imageView, "mMaxHeight"); // Check maxHeight parameter // depends on control dependency: [if], data = [(imageView]
}
}
return height;
} }
|
public class class_name {
private void removeBuffers() {
IntBuffer buffer = BufferUtils.createIntBuffer(1);
int queued = AL10.alGetSourcei(source, AL10.AL_BUFFERS_QUEUED);
while (queued > 0)
{
AL10.alSourceUnqueueBuffers(source, buffer);
queued--;
}
} }
|
public class class_name {
private void removeBuffers() {
IntBuffer buffer = BufferUtils.createIntBuffer(1);
int queued = AL10.alGetSourcei(source, AL10.AL_BUFFERS_QUEUED);
while (queued > 0)
{
AL10.alSourceUnqueueBuffers(source, buffer);
// depends on control dependency: [while], data = [none]
queued--;
// depends on control dependency: [while], data = [none]
}
} }
|
public class class_name {
static InetAddress inet4FromInt(int address) {
byte[] addr = new byte[4];
addr[0] = (byte) ((address >>> 24) & 0xFF);
addr[1] = (byte) ((address >>> 16) & 0xFF);
addr[2] = (byte) ((address >>> 8) & 0xFF);
addr[3] = (byte) (address & 0xFF);
try {
return InetAddress.getByAddress(addr);
} catch (UnknownHostException uhe) {
throw new AssertionError("Should not reach here");
}
} }
|
public class class_name {
static InetAddress inet4FromInt(int address) {
byte[] addr = new byte[4];
addr[0] = (byte) ((address >>> 24) & 0xFF);
addr[1] = (byte) ((address >>> 16) & 0xFF);
addr[2] = (byte) ((address >>> 8) & 0xFF);
addr[3] = (byte) (address & 0xFF);
try {
return InetAddress.getByAddress(addr); // depends on control dependency: [try], data = [none]
} catch (UnknownHostException uhe) {
throw new AssertionError("Should not reach here");
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public ConcurrentMap<String, Object> getAttributesFiltered() {
if ( this.manager == null ) {
throw new IllegalStateException( "There's no manager set." );
}
final Pattern pattern = ((SessionManager)manager).getMemcachedSessionService().getSessionAttributePattern();
final ConcurrentMap<String, Object> attributes = getAttributesInternal();
if ( pattern == null ) {
return attributes;
}
final ConcurrentMap<String, Object> result = new ConcurrentHashMap<String, Object>( attributes.size() );
for ( final Map.Entry<String, Object> entry: attributes.entrySet() ) {
if ( pattern.matcher(entry.getKey()).matches() ) {
result.put( entry.getKey(), entry.getValue() );
}
}
return result;
} }
|
public class class_name {
public ConcurrentMap<String, Object> getAttributesFiltered() {
if ( this.manager == null ) {
throw new IllegalStateException( "There's no manager set." );
}
final Pattern pattern = ((SessionManager)manager).getMemcachedSessionService().getSessionAttributePattern();
final ConcurrentMap<String, Object> attributes = getAttributesInternal();
if ( pattern == null ) {
return attributes; // depends on control dependency: [if], data = [none]
}
final ConcurrentMap<String, Object> result = new ConcurrentHashMap<String, Object>( attributes.size() );
for ( final Map.Entry<String, Object> entry: attributes.entrySet() ) {
if ( pattern.matcher(entry.getKey()).matches() ) {
result.put( entry.getKey(), entry.getValue() ); // depends on control dependency: [if], data = [none]
}
}
return result;
} }
|
public class class_name {
public static List<ExtensionConfig> parseEnum(Enumeration<String> valuesEnum) {
List<ExtensionConfig> configs = new ArrayList<>();
if (valuesEnum != null) {
while (valuesEnum.hasMoreElements()) {
Iterator<String> extTokenIter = QuoteUtil.splitAt(valuesEnum.nextElement(), ",");
while (extTokenIter.hasNext()) {
String extToken = extTokenIter.next();
configs.add(ExtensionConfig.parse(extToken));
}
}
}
return configs;
} }
|
public class class_name {
public static List<ExtensionConfig> parseEnum(Enumeration<String> valuesEnum) {
List<ExtensionConfig> configs = new ArrayList<>();
if (valuesEnum != null) {
while (valuesEnum.hasMoreElements()) {
Iterator<String> extTokenIter = QuoteUtil.splitAt(valuesEnum.nextElement(), ",");
while (extTokenIter.hasNext()) {
String extToken = extTokenIter.next();
configs.add(ExtensionConfig.parse(extToken)); // depends on control dependency: [while], data = [none]
}
}
}
return configs;
} }
|
public class class_name {
public static String join(List<?> things, String delim) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (Object thing : things) {
if (first) {
first = false;
} else {
builder.append(delim);
}
builder.append(thing.toString());
}
return builder.toString();
} }
|
public class class_name {
public static String join(List<?> things, String delim) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (Object thing : things) {
if (first) {
first = false; // depends on control dependency: [if], data = [none]
} else {
builder.append(delim); // depends on control dependency: [if], data = [none]
}
builder.append(thing.toString()); // depends on control dependency: [for], data = [thing]
}
return builder.toString();
} }
|
public class class_name {
private static Date calculateExpiresAt( JSONObject jsonObj )
{
long expiresAt_s = jsonObj.optLong( OAuth2Credentials.EXPIRES_AT, -1 );
// If nothing specified in json, check if expires_in is present:
// this happens when token is received from oauth server
if ( expiresAt_s < 0 && jsonObj.has( OAuth2Credentials.EXPIRES_IN ) ) {
long expiresIn_s = jsonObj.getLong( OAuth2Credentials.EXPIRES_IN );
// We take a margin to be safe: it appears that some providers do NOT take any margin
// so token will not be early refreshed
if ( expiresIn_s > 6 * 60 ) { // should be always true
expiresIn_s -= 5 * 60; // 5 minutes to be safe
}
expiresAt_s = System.currentTimeMillis() / 1000 + expiresIn_s;
}
if ( expiresAt_s < 0 ) {
return null;
}
return new Date( expiresAt_s * 1000 );
} }
|
public class class_name {
private static Date calculateExpiresAt( JSONObject jsonObj )
{
long expiresAt_s = jsonObj.optLong( OAuth2Credentials.EXPIRES_AT, -1 );
// If nothing specified in json, check if expires_in is present:
// this happens when token is received from oauth server
if ( expiresAt_s < 0 && jsonObj.has( OAuth2Credentials.EXPIRES_IN ) ) {
long expiresIn_s = jsonObj.getLong( OAuth2Credentials.EXPIRES_IN );
// We take a margin to be safe: it appears that some providers do NOT take any margin
// so token will not be early refreshed
if ( expiresIn_s > 6 * 60 ) { // should be always true
expiresIn_s -= 5 * 60; // 5 minutes to be safe // depends on control dependency: [if], data = [none]
}
expiresAt_s = System.currentTimeMillis() / 1000 + expiresIn_s; // depends on control dependency: [if], data = [none]
}
if ( expiresAt_s < 0 ) {
return null; // depends on control dependency: [if], data = [none]
}
return new Date( expiresAt_s * 1000 );
} }
|
public class class_name {
private static boolean isKnownClassLoaderAccessibleFrom(final ClassLoader accessibleCL, final ClassLoader fromCL) {
if (fromCL == null) {
return false;
}
ClassLoader parent = fromCL;
try {
while (parent != null && parent != accessibleCL) {
parent = parent.getParent();
}
return (parent != null && parent == accessibleCL);
} catch (final SecurityException se) {
// The SecurityManager prevents us from accessing, so just ignore it
return false;
}
} }
|
public class class_name {
private static boolean isKnownClassLoaderAccessibleFrom(final ClassLoader accessibleCL, final ClassLoader fromCL) {
if (fromCL == null) {
return false; // depends on control dependency: [if], data = [none]
}
ClassLoader parent = fromCL;
try {
while (parent != null && parent != accessibleCL) {
parent = parent.getParent(); // depends on control dependency: [while], data = [none]
}
return (parent != null && parent == accessibleCL); // depends on control dependency: [try], data = [none]
} catch (final SecurityException se) {
// The SecurityManager prevents us from accessing, so just ignore it
return false;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private List<Match> getBestCombination(final Configuration configuration, final String password)
{
this.best_matches.clear();
this.best_matches_length = 0;
final List<Match> all_matches = getAllMatches(configuration, password);
final Map<Integer, Match> brute_force_matches = new HashMap<>();
for (int i = 0; i < password.length(); i++)
{
brute_force_matches.put(i, createBruteForceMatch(password, configuration, i));
}
final List<Match> good_enough_matches = findGoodEnoughCombination(password, all_matches, brute_force_matches);
if (all_matches == null || all_matches.size() == 0 || isRandom(password, good_enough_matches))
{
List<Match> matches = new ArrayList<>();
backfillBruteForce(password, brute_force_matches, matches);
Collections.sort(matches, comparator);
return matches;
}
Collections.sort(all_matches, comparator);
try
{
return findBestCombination(password, all_matches, brute_force_matches);
}
catch (TimeoutException e)
{
return good_enough_matches;
}
} }
|
public class class_name {
private List<Match> getBestCombination(final Configuration configuration, final String password)
{
this.best_matches.clear();
this.best_matches_length = 0;
final List<Match> all_matches = getAllMatches(configuration, password);
final Map<Integer, Match> brute_force_matches = new HashMap<>();
for (int i = 0; i < password.length(); i++)
{
brute_force_matches.put(i, createBruteForceMatch(password, configuration, i)); // depends on control dependency: [for], data = [i]
}
final List<Match> good_enough_matches = findGoodEnoughCombination(password, all_matches, brute_force_matches);
if (all_matches == null || all_matches.size() == 0 || isRandom(password, good_enough_matches))
{
List<Match> matches = new ArrayList<>();
backfillBruteForce(password, brute_force_matches, matches); // depends on control dependency: [if], data = [none]
Collections.sort(matches, comparator); // depends on control dependency: [if], data = [none]
return matches; // depends on control dependency: [if], data = [none]
}
Collections.sort(all_matches, comparator);
try
{
return findBestCombination(password, all_matches, brute_force_matches); // depends on control dependency: [try], data = [none]
}
catch (TimeoutException e)
{
return good_enough_matches;
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static synchronized void enable() {
if (enabled) {
return;
}
oldOnObservableAssembly = RxJavaPlugins.getOnObservableAssembly();
RxJavaPlugins.setOnObservableAssembly(compose(
oldOnObservableAssembly,
new ConditionalOnCurrentRequestContextFunction<Observable>() {
@Override
Observable applyActual(Observable o, RequestContext ctx) {
if (!(o instanceof Callable)) {
return new RequestContextObservable(o, ctx);
}
if (o instanceof ScalarCallable) {
return new RequestContextScalarCallableObservable(o, ctx);
}
return new RequestContextCallableObservable(o, ctx);
}
}));
oldOnConnectableObservableAssembly = RxJavaPlugins.getOnConnectableObservableAssembly();
RxJavaPlugins.setOnConnectableObservableAssembly(compose(
oldOnConnectableObservableAssembly,
new ConditionalOnCurrentRequestContextFunction<ConnectableObservable>() {
@Override
ConnectableObservable applyActual(ConnectableObservable co, RequestContext ctx) {
return new RequestContextConnectableObservable(co, ctx);
}
}));
oldOnCompletableAssembly = RxJavaPlugins.getOnCompletableAssembly();
RxJavaPlugins.setOnCompletableAssembly(
compose(oldOnCompletableAssembly,
new ConditionalOnCurrentRequestContextFunction<Completable>() {
@Override
Completable applyActual(Completable c,
RequestContext ctx) {
if (!(c instanceof Callable)) {
return new RequestContextCompletable(c, ctx);
}
if (c instanceof ScalarCallable) {
return new RequestContextScalarCallableCompletable(
c, ctx);
}
return new RequestContextCallableCompletable(c, ctx);
}
}));
oldOnSingleAssembly = RxJavaPlugins.getOnSingleAssembly();
RxJavaPlugins.setOnSingleAssembly(
compose(oldOnSingleAssembly, new ConditionalOnCurrentRequestContextFunction<Single>() {
@Override
Single applyActual(Single s, RequestContext ctx) {
if (!(s instanceof Callable)) {
return new RequestContextSingle(s, ctx);
}
if (s instanceof ScalarCallable) {
return new RequestContextScalarCallableSingle(s, ctx);
}
return new RequestContextCallableSingle(s, ctx);
}
}));
oldOnMaybeAssembly = RxJavaPlugins.getOnMaybeAssembly();
RxJavaPlugins.setOnMaybeAssembly(
compose(oldOnMaybeAssembly, new ConditionalOnCurrentRequestContextFunction<Maybe>() {
@Override
Maybe applyActual(Maybe m, RequestContext ctx) {
if (!(m instanceof Callable)) {
return new RequestContextMaybe(m, ctx);
}
if (m instanceof ScalarCallable) {
return new RequestContextScalarCallableMaybe(m, ctx);
}
return new RequestContextCallableMaybe(m, ctx);
}
}));
oldOnFlowableAssembly = RxJavaPlugins.getOnFlowableAssembly();
RxJavaPlugins.setOnFlowableAssembly(
compose(oldOnFlowableAssembly, new ConditionalOnCurrentRequestContextFunction<Flowable>() {
@Override
Flowable applyActual(Flowable f, RequestContext ctx) {
if (!(f instanceof Callable)) {
return new RequestContextFlowable(f, ctx);
}
if (f instanceof ScalarCallable) {
return new RequestContextScalarCallableFlowable(f, ctx);
}
return new RequestContextCallableFlowable(f, ctx);
}
}));
oldOnConnectableFlowableAssembly = RxJavaPlugins.getOnConnectableFlowableAssembly();
RxJavaPlugins.setOnConnectableFlowableAssembly(
compose(oldOnConnectableFlowableAssembly,
new ConditionalOnCurrentRequestContextFunction<ConnectableFlowable>() {
@Override
ConnectableFlowable applyActual(
ConnectableFlowable cf,
RequestContext ctx) {
return new RequestContextConnectableFlowable(
cf, ctx);
}
}
));
oldOnParallelAssembly = RxJavaPlugins.getOnParallelAssembly();
RxJavaPlugins.setOnParallelAssembly(
compose(oldOnParallelAssembly,
new ConditionalOnCurrentRequestContextFunction<ParallelFlowable>() {
@Override
ParallelFlowable applyActual(ParallelFlowable pf, RequestContext ctx) {
return new RequestContextParallelFlowable(pf, ctx);
}
}
));
enabled = true;
} }
|
public class class_name {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static synchronized void enable() {
if (enabled) {
return; // depends on control dependency: [if], data = [none]
}
oldOnObservableAssembly = RxJavaPlugins.getOnObservableAssembly();
RxJavaPlugins.setOnObservableAssembly(compose(
oldOnObservableAssembly,
new ConditionalOnCurrentRequestContextFunction<Observable>() {
@Override
Observable applyActual(Observable o, RequestContext ctx) {
if (!(o instanceof Callable)) {
return new RequestContextObservable(o, ctx); // depends on control dependency: [if], data = [none]
}
if (o instanceof ScalarCallable) {
return new RequestContextScalarCallableObservable(o, ctx); // depends on control dependency: [if], data = [none]
}
return new RequestContextCallableObservable(o, ctx);
}
}));
oldOnConnectableObservableAssembly = RxJavaPlugins.getOnConnectableObservableAssembly();
RxJavaPlugins.setOnConnectableObservableAssembly(compose(
oldOnConnectableObservableAssembly,
new ConditionalOnCurrentRequestContextFunction<ConnectableObservable>() {
@Override
ConnectableObservable applyActual(ConnectableObservable co, RequestContext ctx) {
return new RequestContextConnectableObservable(co, ctx);
}
}));
oldOnCompletableAssembly = RxJavaPlugins.getOnCompletableAssembly();
RxJavaPlugins.setOnCompletableAssembly(
compose(oldOnCompletableAssembly,
new ConditionalOnCurrentRequestContextFunction<Completable>() {
@Override
Completable applyActual(Completable c,
RequestContext ctx) {
if (!(c instanceof Callable)) {
return new RequestContextCompletable(c, ctx); // depends on control dependency: [if], data = [none]
}
if (c instanceof ScalarCallable) {
return new RequestContextScalarCallableCompletable(
c, ctx); // depends on control dependency: [if], data = [none]
}
return new RequestContextCallableCompletable(c, ctx);
}
}));
oldOnSingleAssembly = RxJavaPlugins.getOnSingleAssembly();
RxJavaPlugins.setOnSingleAssembly(
compose(oldOnSingleAssembly, new ConditionalOnCurrentRequestContextFunction<Single>() {
@Override
Single applyActual(Single s, RequestContext ctx) {
if (!(s instanceof Callable)) {
return new RequestContextSingle(s, ctx); // depends on control dependency: [if], data = [none]
}
if (s instanceof ScalarCallable) {
return new RequestContextScalarCallableSingle(s, ctx); // depends on control dependency: [if], data = [none]
}
return new RequestContextCallableSingle(s, ctx);
}
}));
oldOnMaybeAssembly = RxJavaPlugins.getOnMaybeAssembly();
RxJavaPlugins.setOnMaybeAssembly(
compose(oldOnMaybeAssembly, new ConditionalOnCurrentRequestContextFunction<Maybe>() {
@Override
Maybe applyActual(Maybe m, RequestContext ctx) {
if (!(m instanceof Callable)) {
return new RequestContextMaybe(m, ctx); // depends on control dependency: [if], data = [none]
}
if (m instanceof ScalarCallable) {
return new RequestContextScalarCallableMaybe(m, ctx); // depends on control dependency: [if], data = [none]
}
return new RequestContextCallableMaybe(m, ctx);
}
}));
oldOnFlowableAssembly = RxJavaPlugins.getOnFlowableAssembly();
RxJavaPlugins.setOnFlowableAssembly(
compose(oldOnFlowableAssembly, new ConditionalOnCurrentRequestContextFunction<Flowable>() {
@Override
Flowable applyActual(Flowable f, RequestContext ctx) {
if (!(f instanceof Callable)) {
return new RequestContextFlowable(f, ctx); // depends on control dependency: [if], data = [none]
}
if (f instanceof ScalarCallable) {
return new RequestContextScalarCallableFlowable(f, ctx); // depends on control dependency: [if], data = [none]
}
return new RequestContextCallableFlowable(f, ctx);
}
}));
oldOnConnectableFlowableAssembly = RxJavaPlugins.getOnConnectableFlowableAssembly();
RxJavaPlugins.setOnConnectableFlowableAssembly(
compose(oldOnConnectableFlowableAssembly,
new ConditionalOnCurrentRequestContextFunction<ConnectableFlowable>() {
@Override
ConnectableFlowable applyActual(
ConnectableFlowable cf,
RequestContext ctx) {
return new RequestContextConnectableFlowable(
cf, ctx);
}
}
));
oldOnParallelAssembly = RxJavaPlugins.getOnParallelAssembly();
RxJavaPlugins.setOnParallelAssembly(
compose(oldOnParallelAssembly,
new ConditionalOnCurrentRequestContextFunction<ParallelFlowable>() {
@Override
ParallelFlowable applyActual(ParallelFlowable pf, RequestContext ctx) {
return new RequestContextParallelFlowable(pf, ctx);
}
}
));
enabled = true;
} }
|
public class class_name {
public static double[] plusTimes(final double[] v1, final double[] v2, final double s2) {
assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
final double[] result = new double[v1.length];
for(int i = 0; i < result.length; i++) {
result[i] = v1[i] + v2[i] * s2;
}
return result;
} }
|
public class class_name {
public static double[] plusTimes(final double[] v1, final double[] v2, final double s2) {
assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
final double[] result = new double[v1.length];
for(int i = 0; i < result.length; i++) {
result[i] = v1[i] + v2[i] * s2; // depends on control dependency: [for], data = [i]
}
return result;
} }
|
public class class_name {
public MethodMetaArgs createDeleteMethod(HandlerMetaDef handlerMetaDef, EventModel em) {
String p_methodName = handlerMetaDef.getDeleteMethod();
if (p_methodName == null) {
Debug.logError("[JdonFramework] not configure the deleteMethod parameter: <deleteMethod name=XXXXX /> ", module);
}
return createCRUDMethodMetaArgs(p_methodName, em);
} }
|
public class class_name {
public MethodMetaArgs createDeleteMethod(HandlerMetaDef handlerMetaDef, EventModel em) {
String p_methodName = handlerMetaDef.getDeleteMethod();
if (p_methodName == null) {
Debug.logError("[JdonFramework] not configure the deleteMethod parameter: <deleteMethod name=XXXXX /> ", module);
// depends on control dependency: [if], data = [none]
}
return createCRUDMethodMetaArgs(p_methodName, em);
} }
|
public class class_name {
public DataOut streamParse( final InputStream is, final StreamDataOut dout, ParseProgressMonitor pmon) throws IOException {
// All output into a fresh pile of NewChunks, one per column
if(_setup._pType.parallelParseSupported){
StreamData din = new StreamData(is);
int cidx=0;
StreamDataOut nextChunk = dout;
long lastProgress = pmon.progress();
while( is.available() > 0 ){
if (pmon.progress() > lastProgress) {
lastProgress = pmon.progress();
nextChunk.close();
if(dout != nextChunk) dout.reduce(nextChunk);
nextChunk = nextChunk.nextChunk();
}
parallelParse(cidx++,din,nextChunk);
}
parallelParse(cidx++,din,nextChunk); // Parse the remaining partial 32K buffer
nextChunk.close();
if(dout != nextChunk)dout.reduce(nextChunk);
} else {
throw H2O.unimpl();
}
return dout;
} }
|
public class class_name {
public DataOut streamParse( final InputStream is, final StreamDataOut dout, ParseProgressMonitor pmon) throws IOException {
// All output into a fresh pile of NewChunks, one per column
if(_setup._pType.parallelParseSupported){
StreamData din = new StreamData(is);
int cidx=0;
StreamDataOut nextChunk = dout;
long lastProgress = pmon.progress();
while( is.available() > 0 ){
if (pmon.progress() > lastProgress) {
lastProgress = pmon.progress(); // depends on control dependency: [if], data = [none]
nextChunk.close(); // depends on control dependency: [if], data = [none]
if(dout != nextChunk) dout.reduce(nextChunk);
nextChunk = nextChunk.nextChunk(); // depends on control dependency: [if], data = [none]
}
parallelParse(cidx++,din,nextChunk); // depends on control dependency: [while], data = [none]
}
parallelParse(cidx++,din,nextChunk); // Parse the remaining partial 32K buffer
nextChunk.close();
if(dout != nextChunk)dout.reduce(nextChunk);
} else {
throw H2O.unimpl();
}
return dout;
} }
|
public class class_name {
private void filterTopics(final Element topicref, final List<FilterUtils> filters) {
final List<FilterUtils> fs = combineFilterUtils(topicref, filters);
final String href = topicref.getAttribute(ATTRIBUTE_NAME_HREF);
final Attr skipFilter = topicref.getAttributeNode(SKIP_FILTER);
final URI srcAbsUri = job.tempDirURI.resolve(map.resolve(href));
if (!fs.isEmpty() && skipFilter == null
&& !filtered.contains(srcAbsUri)
&& !href.isEmpty()
&& !ATTR_SCOPE_VALUE_EXTERNAL.equals(topicref.getAttribute(ATTRIBUTE_NAME_SCOPE))
&& !ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(topicref.getAttribute(ATTRIBUTE_NAME_PROCESSING_ROLE))
&& isDitaFormat(topicref.getAttributeNode(ATTRIBUTE_NAME_FORMAT))) {
final ProfilingFilter writer = new ProfilingFilter();
writer.setLogger(logger);
writer.setJob(job);
writer.setFilterUtils(fs);
writer.setCurrentFile(srcAbsUri);
final List<XMLFilter> pipe = singletonList(writer);
logger.info("Filtering " + srcAbsUri);
try {
xmlUtils.transform(srcAbsUri, pipe);
} catch (final DITAOTException e) {
logger.error("Failed to filter " + srcAbsUri + ": " + e.getMessage(), e);
}
filtered.add(srcAbsUri);
}
if (skipFilter != null) {
topicref.removeAttributeNode(skipFilter);
}
for (final Element child: getChildElements(topicref, MAP_TOPICREF)) {
if (DITAVAREF_D_DITAVALREF.matches(child)) {
continue;
}
filterTopics(child, fs);
}
} }
|
public class class_name {
private void filterTopics(final Element topicref, final List<FilterUtils> filters) {
final List<FilterUtils> fs = combineFilterUtils(topicref, filters);
final String href = topicref.getAttribute(ATTRIBUTE_NAME_HREF);
final Attr skipFilter = topicref.getAttributeNode(SKIP_FILTER);
final URI srcAbsUri = job.tempDirURI.resolve(map.resolve(href));
if (!fs.isEmpty() && skipFilter == null
&& !filtered.contains(srcAbsUri)
&& !href.isEmpty()
&& !ATTR_SCOPE_VALUE_EXTERNAL.equals(topicref.getAttribute(ATTRIBUTE_NAME_SCOPE))
&& !ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(topicref.getAttribute(ATTRIBUTE_NAME_PROCESSING_ROLE))
&& isDitaFormat(topicref.getAttributeNode(ATTRIBUTE_NAME_FORMAT))) {
final ProfilingFilter writer = new ProfilingFilter();
writer.setLogger(logger); // depends on control dependency: [if], data = [none]
writer.setJob(job); // depends on control dependency: [if], data = [none]
writer.setFilterUtils(fs); // depends on control dependency: [if], data = [none]
writer.setCurrentFile(srcAbsUri); // depends on control dependency: [if], data = [none]
final List<XMLFilter> pipe = singletonList(writer);
logger.info("Filtering " + srcAbsUri); // depends on control dependency: [if], data = [none]
try {
xmlUtils.transform(srcAbsUri, pipe); // depends on control dependency: [try], data = [none]
} catch (final DITAOTException e) {
logger.error("Failed to filter " + srcAbsUri + ": " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
filtered.add(srcAbsUri); // depends on control dependency: [if], data = [none]
}
if (skipFilter != null) {
topicref.removeAttributeNode(skipFilter); // depends on control dependency: [if], data = [(skipFilter]
}
for (final Element child: getChildElements(topicref, MAP_TOPICREF)) {
if (DITAVAREF_D_DITAVALREF.matches(child)) {
continue;
}
filterTopics(child, fs); // depends on control dependency: [for], data = [child]
}
} }
|
public class class_name {
private static char[] encode(final byte[] data, final char[] toDigits) {
final int l = data.length;
final char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
} }
|
public class class_name {
private static char[] encode(final byte[] data, final char[] toDigits) {
final int l = data.length;
final char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4]; // depends on control dependency: [for], data = [i]
out[j++] = toDigits[0x0F & data[i]]; // depends on control dependency: [for], data = [i]
}
return out;
} }
|
public class class_name {
public <T extends Throwable> T throwing(T throwable) {
if (instanceofLAL) {
((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "throwing", null, throwable);
}
return throwable;
} }
|
public class class_name {
public <T extends Throwable> T throwing(T throwable) {
if (instanceofLAL) {
((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "throwing", null, throwable); // depends on control dependency: [if], data = [none]
}
return throwable;
} }
|
public class class_name {
@Override
public int read(byte []buf, int offset, int len) throws IOException
{
int available = _available;
// The chunk still has more data left
if (available > 0) {
len = Math.min(len, available);
len = _next.read(buf, offset, len);
if (len > 0) {
_available -= len;
}
}
// The chunk is done, so read the next chunk
else if (available == 0) {
_available = readChunkLength();
// the new chunk has data
if (_available > 0) {
len = Math.min(len, _available);
len = _next.read(buf, offset, len);
if (len > 0)
_available -= len;
}
// the new chunk is the last
else {
_available = -1;
len = -1;
}
}
else {
len = -1;
}
return len;
} }
|
public class class_name {
@Override
public int read(byte []buf, int offset, int len) throws IOException
{
int available = _available;
// The chunk still has more data left
if (available > 0) {
len = Math.min(len, available);
len = _next.read(buf, offset, len);
if (len > 0) {
_available -= len; // depends on control dependency: [if], data = [none]
}
}
// The chunk is done, so read the next chunk
else if (available == 0) {
_available = readChunkLength();
// the new chunk has data
if (_available > 0) {
len = Math.min(len, _available);
len = _next.read(buf, offset, len);
if (len > 0)
_available -= len;
}
// the new chunk is the last
else {
_available = -1;
len = -1;
}
}
else {
len = -1;
}
return len;
} }
|
public class class_name {
public Node getNode(String host, int port, String transport, String version) {
for (Node node : balancerRunner.balancerContext.aliveNodes) {
if(logger.isDebugEnabled()) {
logger.debug("node to check against " + node);
}
// https://telestax.atlassian.net/browse/LB-9 Prevent Routing of Requests to Nodes that exposed null IP address
if(node != null && node.getIp() != null && node.getIp().equals(host)&&node.getProperties().get(transport.toLowerCase() + "Port")!=null){
Integer nodePort = Integer.parseInt(node.getProperties().get(transport.toLowerCase() + "Port"));
if(nodePort != null) {
if(nodePort == port) {
if(version == null) {
return node;
} else {
String nodeVersion = node.getProperties().get("version");
if(nodeVersion == null) nodeVersion = "0";
if(version.equals(nodeVersion)) {
return node;
}
}
}
}
}
}
if(logger.isDebugEnabled()) {
logger.debug("checking if the node is still alive for " + host + ":" + port + "/" + transport + " : false");
}
return null;
} }
|
public class class_name {
public Node getNode(String host, int port, String transport, String version) {
for (Node node : balancerRunner.balancerContext.aliveNodes) {
if(logger.isDebugEnabled()) {
logger.debug("node to check against " + node); // depends on control dependency: [if], data = [none]
}
// https://telestax.atlassian.net/browse/LB-9 Prevent Routing of Requests to Nodes that exposed null IP address
if(node != null && node.getIp() != null && node.getIp().equals(host)&&node.getProperties().get(transport.toLowerCase() + "Port")!=null){
Integer nodePort = Integer.parseInt(node.getProperties().get(transport.toLowerCase() + "Port"));
if(nodePort != null) {
if(nodePort == port) {
if(version == null) {
return node; // depends on control dependency: [if], data = [none]
} else {
String nodeVersion = node.getProperties().get("version");
if(nodeVersion == null) nodeVersion = "0";
if(version.equals(nodeVersion)) {
return node; // depends on control dependency: [if], data = [none]
}
}
}
}
}
}
if(logger.isDebugEnabled()) {
logger.debug("checking if the node is still alive for " + host + ":" + port + "/" + transport + " : false"); // depends on control dependency: [if], data = [none]
}
return null;
} }
|
public class class_name {
public static AuditDto transformToDto(Audit audit) {
if (audit == null) {
throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR);
}
AuditDto auditDto = new AuditDto();
try {
auditDto.setId(audit.getId());
auditDto.setHostName(audit.getHostName());
auditDto.setMessage(audit.getMessage());
auditDto.setCreatedDate(audit.getCreatedDate());
auditDto.setEntityId(audit.getEntityId());
} catch (Exception ex) {
throw new WebApplicationException("DTO transformation failed.", Status.INTERNAL_SERVER_ERROR);
}
return auditDto;
} }
|
public class class_name {
public static AuditDto transformToDto(Audit audit) {
if (audit == null) {
throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR);
}
AuditDto auditDto = new AuditDto();
try {
auditDto.setId(audit.getId()); // depends on control dependency: [try], data = [none]
auditDto.setHostName(audit.getHostName()); // depends on control dependency: [try], data = [none]
auditDto.setMessage(audit.getMessage()); // depends on control dependency: [try], data = [none]
auditDto.setCreatedDate(audit.getCreatedDate()); // depends on control dependency: [try], data = [none]
auditDto.setEntityId(audit.getEntityId()); // depends on control dependency: [try], data = [none]
} catch (Exception ex) {
throw new WebApplicationException("DTO transformation failed.", Status.INTERNAL_SERVER_ERROR);
} // depends on control dependency: [catch], data = [none]
return auditDto;
} }
|
public class class_name {
public void swapRows(int r1, int r2)
{
int n = columns();
ItemSupplier s = supplier;
ItemConsumer c = consumer;
for (int j = 0; j < n; j++)
{
double v = s.get(r1, j);
c.set(r1, j, s.get(r2, j));
c.set(r2, j, v);
}
} }
|
public class class_name {
public void swapRows(int r1, int r2)
{
int n = columns();
ItemSupplier s = supplier;
ItemConsumer c = consumer;
for (int j = 0; j < n; j++)
{
double v = s.get(r1, j);
c.set(r1, j, s.get(r2, j));
// depends on control dependency: [for], data = [j]
c.set(r2, j, v);
// depends on control dependency: [for], data = [j]
}
} }
|
public class class_name {
public static void setMdcFields(String spec, GelfMessageAssembler gelfMessageAssembler) {
if (null != spec) {
String[] fields = spec.split(MULTI_VALUE_DELIMITTER);
for (String field : fields) {
gelfMessageAssembler.addField(new MdcMessageField(field.trim(), field.trim()));
}
}
} }
|
public class class_name {
public static void setMdcFields(String spec, GelfMessageAssembler gelfMessageAssembler) {
if (null != spec) {
String[] fields = spec.split(MULTI_VALUE_DELIMITTER);
for (String field : fields) {
gelfMessageAssembler.addField(new MdcMessageField(field.trim(), field.trim())); // depends on control dependency: [for], data = [field]
}
}
} }
|
public class class_name {
public static Object evaluate(final String strValue,
final Map<String, Object> context,
final ExpressionEngine engine) {
StringBuffer sb = new StringBuffer();
int beginExpressionLength = TieConstants.METHOD_PREFIX.length();
int endExpressionLength = TieConstants.METHOD_END.length();
Matcher exprMatcher = TieConstants.EXPRESSION_NOTATION_PATTERN
.matcher(strValue);
String matchedString;
String expression;
Object lastMatchEvalResult = null;
int matchCount = 0;
int endOffset = 0;
while (exprMatcher.find()) {
endOffset = exprMatcher.end();
matchCount++;
matchedString = exprMatcher.group();
expression = matchedString.substring(beginExpressionLength,
matchedString.length() - endExpressionLength);
lastMatchEvalResult = engine.evaluate(expression, context);
exprMatcher.appendReplacement(sb,
Matcher.quoteReplacement(lastMatchEvalResult != null
? lastMatchEvalResult.toString() : ""));
}
String lastStringResult = lastMatchEvalResult != null
? lastMatchEvalResult.toString() : "";
boolean isAppendTail = matchCount == 1
&& endOffset < strValue.length();
Object evaluationResult = null;
if (matchCount > 1 || isAppendTail) {
exprMatcher.appendTail(sb);
evaluationResult = sb.toString();
} else if (matchCount == 1) {
if (sb.length() > lastStringResult.length()) {
evaluationResult = sb.toString();
} else {
evaluationResult = lastMatchEvalResult;
}
} else if (matchCount == 0) {
evaluationResult = strValue;
}
return evaluationResult;
} }
|
public class class_name {
public static Object evaluate(final String strValue,
final Map<String, Object> context,
final ExpressionEngine engine) {
StringBuffer sb = new StringBuffer();
int beginExpressionLength = TieConstants.METHOD_PREFIX.length();
int endExpressionLength = TieConstants.METHOD_END.length();
Matcher exprMatcher = TieConstants.EXPRESSION_NOTATION_PATTERN
.matcher(strValue);
String matchedString;
String expression;
Object lastMatchEvalResult = null;
int matchCount = 0;
int endOffset = 0;
while (exprMatcher.find()) {
endOffset = exprMatcher.end();
// depends on control dependency: [while], data = [none]
matchCount++;
// depends on control dependency: [while], data = [none]
matchedString = exprMatcher.group();
// depends on control dependency: [while], data = [none]
expression = matchedString.substring(beginExpressionLength,
matchedString.length() - endExpressionLength);
// depends on control dependency: [while], data = [none]
lastMatchEvalResult = engine.evaluate(expression, context);
// depends on control dependency: [while], data = [none]
exprMatcher.appendReplacement(sb,
Matcher.quoteReplacement(lastMatchEvalResult != null
? lastMatchEvalResult.toString() : ""));
// depends on control dependency: [while], data = [none]
}
String lastStringResult = lastMatchEvalResult != null
? lastMatchEvalResult.toString() : "";
boolean isAppendTail = matchCount == 1
&& endOffset < strValue.length();
Object evaluationResult = null;
if (matchCount > 1 || isAppendTail) {
exprMatcher.appendTail(sb);
// depends on control dependency: [if], data = [none]
evaluationResult = sb.toString();
// depends on control dependency: [if], data = [none]
} else if (matchCount == 1) {
if (sb.length() > lastStringResult.length()) {
evaluationResult = sb.toString();
// depends on control dependency: [if], data = [none]
} else {
evaluationResult = lastMatchEvalResult;
// depends on control dependency: [if], data = [none]
}
} else if (matchCount == 0) {
evaluationResult = strValue;
// depends on control dependency: [if], data = [none]
}
return evaluationResult;
} }
|
public class class_name {
public final boolean isValid(Class < T > javaClass,
CobolContext cobolContext, byte[] hostData, int start) {
int hostBytesLen = getBytesLen();
// Is buffer large enough to contain this type?
if (hostData.length < start + hostBytesLen) {
return false;
}
// Let specialized classes perform their validation
if (!isValidInternal(javaClass, cobolContext, hostData, start)) {
return false;
}
// If required to check within range, need to convert
FromHostPrimitiveResult < T > result = fromHostInternal(javaClass,
cobolContext, hostData, start);
return result.isSuccess() && isWithinRange(result.getValue());
} }
|
public class class_name {
public final boolean isValid(Class < T > javaClass,
CobolContext cobolContext, byte[] hostData, int start) {
int hostBytesLen = getBytesLen();
// Is buffer large enough to contain this type?
if (hostData.length < start + hostBytesLen) {
return false; // depends on control dependency: [if], data = [none]
}
// Let specialized classes perform their validation
if (!isValidInternal(javaClass, cobolContext, hostData, start)) {
return false; // depends on control dependency: [if], data = [none]
}
// If required to check within range, need to convert
FromHostPrimitiveResult < T > result = fromHostInternal(javaClass,
cobolContext, hostData, start);
return result.isSuccess() && isWithinRange(result.getValue());
} }
|
public class class_name {
public <N extends Node> ParseResult<N> parse(ParseStart<N> start, Provider provider) {
assertNotNull(start);
assertNotNull(provider);
final GeneratedDrlConstraintParser parser = getParserForProvider(provider);
try {
N resultNode = start.parse(parser);
ParseResult<N> result = new ParseResult<>(resultNode, parser.problems, parser.getTokens(),
parser.getCommentsCollection());
configuration.getPostProcessors().forEach(postProcessor ->
postProcessor.process(result, configuration));
result.getProblems().sort(PROBLEM_BY_BEGIN_POSITION);
return result;
} catch (Exception e) {
final String message = e.getMessage() == null ? "Unknown error" : e.getMessage();
parser.problems.add(new Problem(message, null, e));
return new ParseResult<>(null, parser.problems, parser.getTokens(), parser.getCommentsCollection());
} finally {
try {
provider.close();
} catch (IOException e) {
// Since we're done parsing and have our result, we don't care about any errors.
}
}
} }
|
public class class_name {
public <N extends Node> ParseResult<N> parse(ParseStart<N> start, Provider provider) {
assertNotNull(start);
assertNotNull(provider);
final GeneratedDrlConstraintParser parser = getParserForProvider(provider);
try {
N resultNode = start.parse(parser);
ParseResult<N> result = new ParseResult<>(resultNode, parser.problems, parser.getTokens(),
parser.getCommentsCollection());
configuration.getPostProcessors().forEach(postProcessor ->
postProcessor.process(result, configuration)); // depends on control dependency: [try], data = [none]
result.getProblems().sort(PROBLEM_BY_BEGIN_POSITION); // depends on control dependency: [try], data = [none]
return result; // depends on control dependency: [try], data = [none]
} catch (Exception e) {
final String message = e.getMessage() == null ? "Unknown error" : e.getMessage();
parser.problems.add(new Problem(message, null, e));
return new ParseResult<>(null, parser.problems, parser.getTokens(), parser.getCommentsCollection());
} finally { // depends on control dependency: [catch], data = [none]
try {
provider.close(); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
// Since we're done parsing and have our result, we don't care about any errors.
} // depends on control dependency: [catch], data = [none]
}
} }
|
public class class_name {
public static String format(String msg, Object... args) {
if (args == null || args.length == 0)
return msg;
StringBuilder sb = new StringBuilder();
int argId = 0;
for (int i = 0; i < msg.length(); i++) {
final char c = msg.charAt(i);
if (c == '{' && msg.charAt(i + 1) == '}') {
if (args.length > argId) {
Object val = args[argId++];
if (val == null)
sb.append("null");
else
sb.append(val.toString());
} else {
sb.append("{{MISSING ARG}}");
}
i++;
} else {
sb.append(c);
}
}
return sb.toString();
} }
|
public class class_name {
public static String format(String msg, Object... args) {
if (args == null || args.length == 0)
return msg;
StringBuilder sb = new StringBuilder();
int argId = 0;
for (int i = 0; i < msg.length(); i++) {
final char c = msg.charAt(i);
if (c == '{' && msg.charAt(i + 1) == '}') {
if (args.length > argId) {
Object val = args[argId++];
if (val == null)
sb.append("null");
else
sb.append(val.toString());
} else {
sb.append("{{MISSING ARG}}"); // depends on control dependency: [if], data = [none]
}
i++; // depends on control dependency: [if], data = [none]
} else {
sb.append(c); // depends on control dependency: [if], data = [(c]
}
}
return sb.toString();
} }
|
public class class_name {
@Memoized
public Type type() {
int dotIndex = identifier().indexOf('.');
if (dotIndex == 0) {
checkArgument(BaseUtils.isIdentifierWithLeadingDot(identifier()));
return Type.DOT_IDENT;
} else {
checkArgument(BaseUtils.isDottedIdentifier(identifier()));
return dotIndex == -1 ? Type.SINGLE_IDENT : Type.DOTTED_IDENT;
}
} }
|
public class class_name {
@Memoized
public Type type() {
int dotIndex = identifier().indexOf('.');
if (dotIndex == 0) {
checkArgument(BaseUtils.isIdentifierWithLeadingDot(identifier())); // depends on control dependency: [if], data = [none]
return Type.DOT_IDENT; // depends on control dependency: [if], data = [none]
} else {
checkArgument(BaseUtils.isDottedIdentifier(identifier())); // depends on control dependency: [if], data = [none]
return dotIndex == -1 ? Type.SINGLE_IDENT : Type.DOTTED_IDENT; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public static String getChineseDate(String src) {
String renStr = null;
if (!"".equals(src) && src != null) {
renStr = src.substring(0, 4) + "年" + src.substring(5, 6) + "月"
+ src.substring(6, 8) + "日";
}
return renStr;
} }
|
public class class_name {
public static String getChineseDate(String src) {
String renStr = null;
if (!"".equals(src) && src != null) {
renStr = src.substring(0, 4) + "年" + src.substring(5, 6) + "月"
+ src.substring(6, 8) + "日"; // depends on control dependency: [if], data = [none]
}
return renStr;
} }
|
public class class_name {
private String getLinearGradientElement(String id, GradientPaint paint) {
StringBuilder b = new StringBuilder("<linearGradient id=\"").append(id)
.append("\" ");
Point2D p1 = paint.getPoint1();
Point2D p2 = paint.getPoint2();
b.append("x1=\"").append(geomDP(p1.getX())).append("\" ");
b.append("y1=\"").append(geomDP(p1.getY())).append("\" ");
b.append("x2=\"").append(geomDP(p2.getX())).append("\" ");
b.append("y2=\"").append(geomDP(p2.getY())).append("\" ");
b.append("gradientUnits=\"userSpaceOnUse\">");
Color c1 = paint.getColor1();
b.append("<stop offset=\"0%\" stop-color=\"").append(rgbColorStr(c1))
.append("\"");
if (c1.getAlpha() < 255) {
double alphaPercent = c1.getAlpha() / 255.0;
b.append(" stop-opacity=\"").append(transformDP(alphaPercent))
.append("\"");
}
b.append("/>");
Color c2 = paint.getColor2();
b.append("<stop offset=\"100%\" stop-color=\"").append(rgbColorStr(c2))
.append("\"");
if (c2.getAlpha() < 255) {
double alphaPercent = c2.getAlpha() / 255.0;
b.append(" stop-opacity=\"").append(transformDP(alphaPercent))
.append("\"");
}
b.append("/>");
return b.append("</linearGradient>").toString();
} }
|
public class class_name {
private String getLinearGradientElement(String id, GradientPaint paint) {
StringBuilder b = new StringBuilder("<linearGradient id=\"").append(id)
.append("\" ");
Point2D p1 = paint.getPoint1();
Point2D p2 = paint.getPoint2();
b.append("x1=\"").append(geomDP(p1.getX())).append("\" ");
b.append("y1=\"").append(geomDP(p1.getY())).append("\" ");
b.append("x2=\"").append(geomDP(p2.getX())).append("\" ");
b.append("y2=\"").append(geomDP(p2.getY())).append("\" ");
b.append("gradientUnits=\"userSpaceOnUse\">");
Color c1 = paint.getColor1();
b.append("<stop offset=\"0%\" stop-color=\"").append(rgbColorStr(c1))
.append("\"");
if (c1.getAlpha() < 255) {
double alphaPercent = c1.getAlpha() / 255.0;
b.append(" stop-opacity=\"").append(transformDP(alphaPercent))
.append("\""); // depends on control dependency: [if], data = [none]
}
b.append("/>");
Color c2 = paint.getColor2();
b.append("<stop offset=\"100%\" stop-color=\"").append(rgbColorStr(c2))
.append("\"");
if (c2.getAlpha() < 255) {
double alphaPercent = c2.getAlpha() / 255.0;
b.append(" stop-opacity=\"").append(transformDP(alphaPercent))
.append("\""); // depends on control dependency: [if], data = [none]
}
b.append("/>");
return b.append("</linearGradient>").toString();
} }
|
public class class_name {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
int mode = MeasureSpec.getMode(heightMeasureSpec);
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height) {
height = h;
}
}
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} catch (RuntimeException e) {
Log.e(TAG, "Exception during WrapContentViewPager onMeasure " + e.toString());
}
} }
|
public class class_name {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
int mode = MeasureSpec.getMode(heightMeasureSpec);
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec); // depends on control dependency: [if], data = [none]
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); // depends on control dependency: [if], data = [none]
int h = child.getMeasuredHeight();
if (h > height) {
height = h; // depends on control dependency: [if], data = [none]
}
}
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); // depends on control dependency: [if], data = [none]
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec); // depends on control dependency: [try], data = [none]
} catch (RuntimeException e) {
Log.e(TAG, "Exception during WrapContentViewPager onMeasure " + e.toString());
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private PyExpr escapeCall(String callExpr, ImmutableList<SoyPrintDirective> directives) {
PyExpr escapedExpr = new PyExpr(callExpr, Integer.MAX_VALUE);
if (directives.isEmpty()) {
return escapedExpr;
}
// Successively wrap each escapedExpr in various directives.
for (SoyPrintDirective directive : directives) {
Preconditions.checkState(
directive instanceof SoyPySrcPrintDirective,
"Autoescaping produced a bogus directive: %s",
directive.getName());
escapedExpr =
((SoyPySrcPrintDirective) directive).applyForPySrc(escapedExpr, ImmutableList.of());
}
return escapedExpr;
} }
|
public class class_name {
private PyExpr escapeCall(String callExpr, ImmutableList<SoyPrintDirective> directives) {
PyExpr escapedExpr = new PyExpr(callExpr, Integer.MAX_VALUE);
if (directives.isEmpty()) {
return escapedExpr; // depends on control dependency: [if], data = [none]
}
// Successively wrap each escapedExpr in various directives.
for (SoyPrintDirective directive : directives) {
Preconditions.checkState(
directive instanceof SoyPySrcPrintDirective,
"Autoescaping produced a bogus directive: %s",
directive.getName()); // depends on control dependency: [for], data = [none]
escapedExpr =
((SoyPySrcPrintDirective) directive).applyForPySrc(escapedExpr, ImmutableList.of()); // depends on control dependency: [for], data = [none]
}
return escapedExpr;
} }
|
public class class_name {
private void generateLegalTimesTree() {
// Create a quick cache of numbers to their keycodes.
int k0 = KeyEvent.KEYCODE_0;
int k1 = KeyEvent.KEYCODE_1;
int k2 = KeyEvent.KEYCODE_2;
int k3 = KeyEvent.KEYCODE_3;
int k4 = KeyEvent.KEYCODE_4;
int k5 = KeyEvent.KEYCODE_5;
int k6 = KeyEvent.KEYCODE_6;
int k7 = KeyEvent.KEYCODE_7;
int k8 = KeyEvent.KEYCODE_8;
int k9 = KeyEvent.KEYCODE_9;
// The root of the tree doesn't contain any numbers.
mLegalTimesTree = new Node();
// In case we're only allowing hours
if (!mEnableMinutes && mIs24HourMode) {
// The first digit may be 0-1
Node firstDigit = new Node(k0, k1);
mLegalTimesTree.addChild(firstDigit);
// When the first digit is 0-1, the second digit may be 0-9
Node secondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
firstDigit.addChild(secondDigit);
// The first digit may be 2
firstDigit = new Node(k2);
mLegalTimesTree.addChild(firstDigit);
// When the first digit is 2, the second digit may be 0-3
secondDigit = new Node(k0, k1, k2, k3);
firstDigit.addChild(secondDigit);
return;
}
//noinspection ConstantConditions
if (!mEnableMinutes && !mIs24HourMode) {
// We'll need to use the AM/PM node a lot.
// Set up AM and PM to respond to "a" and "p".
Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));
// The first digit may be 1
Node firstDigit = new Node(k1);
mLegalTimesTree.addChild(firstDigit);
// If the first digit is 1, the second one may be am/pm 1pm
firstDigit.addChild(ampm);
// If the first digit is 1, the second digit may be 0-2
Node secondDigit = new Node(k0, k1, k2);
firstDigit.addChild(secondDigit);
secondDigit.addChild(ampm);
// The first digit may be 2-9
firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9);
mLegalTimesTree.addChild(firstDigit);
firstDigit.addChild(ampm);
return;
}
// In case minutes are allowed
if (mIs24HourMode) {
// We'll be re-using these nodes, so we'll save them.
Node minuteFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
Node minuteSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
// The first digit must be followed by the second digit.
minuteFirstDigit.addChild(minuteSecondDigit);
if (mEnableSeconds) {
Node secondsFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
Node secondsSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondsFirstDigit.addChild(secondsSecondDigit);
// Minutes can be followed by seconds.
minuteSecondDigit.addChild(secondsFirstDigit);
}
// The first digit may be 0-1.
Node firstDigit = new Node(k0, k1);
mLegalTimesTree.addChild(firstDigit);
// When the first digit is 0-1, the second digit may be 0-5.
Node secondDigit = new Node(k0, k1, k2, k3, k4, k5);
firstDigit.addChild(secondDigit);
// We may now be followed by the first minute digit. E.g. 00:09, 15:58.
secondDigit.addChild(minuteFirstDigit);
// When the first digit is 0-1, and the second digit is 0-5, the third digit may be 6-9.
Node thirdDigit = new Node(k6, k7, k8, k9);
// The time must now be finished. E.g. 0:55, 1:08.
secondDigit.addChild(thirdDigit);
// When the first digit is 0-1, the second digit may be 6-9.
secondDigit = new Node(k6, k7, k8, k9);
firstDigit.addChild(secondDigit);
// We must now be followed by the first minute digit. E.g. 06:50, 18:20.
secondDigit.addChild(minuteFirstDigit);
// The first digit may be 2.
firstDigit = new Node(k2);
mLegalTimesTree.addChild(firstDigit);
// When the first digit is 2, the second digit may be 0-3.
secondDigit = new Node(k0, k1, k2, k3);
firstDigit.addChild(secondDigit);
// We must now be followed by the first minute digit. E.g. 20:50, 23:09.
secondDigit.addChild(minuteFirstDigit);
// When the first digit is 2, the second digit may be 4-5.
secondDigit = new Node(k4, k5);
firstDigit.addChild(secondDigit);
// We must now be followd by the last minute digit. E.g. 2:40, 2:53.
secondDigit.addChild(minuteSecondDigit);
// The first digit may be 3-9.
firstDigit = new Node(k3, k4, k5, k6, k7, k8, k9);
mLegalTimesTree.addChild(firstDigit);
// We must now be followed by the first minute digit. E.g. 3:57, 8:12.
firstDigit.addChild(minuteFirstDigit);
} else {
// We'll need to use the AM/PM node a lot.
// Set up AM and PM to respond to "a" and "p".
Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));
// Seconds will be used a few times as well, if enabled.
Node secondsFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
Node secondsSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondsSecondDigit.addChild(ampm);
secondsFirstDigit.addChild(secondsSecondDigit);
// The first hour digit may be 1.
Node firstDigit = new Node(k1);
mLegalTimesTree.addChild(firstDigit);
// We'll allow quick input of on-the-hour times. E.g. 1pm.
firstDigit.addChild(ampm);
// When the first digit is 1, the second digit may be 0-2.
Node secondDigit = new Node(k0, k1, k2);
firstDigit.addChild(secondDigit);
// Also for quick input of on-the-hour times. E.g. 10pm, 12am.
secondDigit.addChild(ampm);
// When the first digit is 1, and the second digit is 0-2, the third digit may be 0-5.
Node thirdDigit = new Node(k0, k1, k2, k3, k4, k5);
secondDigit.addChild(thirdDigit);
// The time may be finished now. E.g. 1:02pm, 1:25am.
thirdDigit.addChild(ampm);
// When the first digit is 1, the second digit is 0-2, and the third digit is 0-5,
// the fourth digit may be 0-9.
Node fourthDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
thirdDigit.addChild(fourthDigit);
// The time must be finished now, when seconds are disabled. E.g. 10:49am, 12:40pm.
fourthDigit.addChild(ampm);
// When the first digit is 1, the second digit is 0-2, and the third digit is 0-5,
// and fourth digit is 0-9, we may add seconds if enabled.
if (mEnableSeconds) {
// The time must be finished now. E.g. 10:49:01am, 12:40:59pm.
fourthDigit.addChild(secondsFirstDigit);
}
// When the first digit is 1, and the second digit is 0-2, the third digit may be 6-9.
thirdDigit = new Node(k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
// The time must be finished now. E.g. 1:08am, 1:26pm.
thirdDigit.addChild(ampm);
// When the first digit is 1, and the second digit is 0-2, and the third digit is 6-9,
// we may add seconds is enabled.
if (mEnableSeconds) {
// The time must be finished now. E.g. 1:08:01am, 1:26:59pm.
thirdDigit.addChild(secondsFirstDigit);
}
// When the first digit is 1, the second digit may be 3-5.
secondDigit = new Node(k3, k4, k5);
firstDigit.addChild(secondDigit);
// When the first digit is 1, and the second digit is 3-5, the third digit may be 0-9.
thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
// The time must be finished now if seconds are disabled. E.g. 1:39am, 1:50pm.
thirdDigit.addChild(ampm);
// When the first digit is 1, and the second digit is 3-5, and the third digit is 0-9,
// we may add seconds if enabled.
if (mEnableSeconds) {
// The time must be finished now. E.g. 1:39:01am, 1:50:59pm.
thirdDigit.addChild(secondsFirstDigit);
}
// The hour digit may be 2-9.
firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9);
mLegalTimesTree.addChild(firstDigit);
// We'll allow quick input of on-the-hour-times. E.g. 2am, 5pm.
firstDigit.addChild(ampm);
// When the first digit is 2-9, the second digit may be 0-5.
secondDigit = new Node(k0, k1, k2, k3, k4, k5);
firstDigit.addChild(secondDigit);
// When the first digit is 2-9, and the second digit is 0-5, the third digit may be 0-9.
thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondDigit.addChild(thirdDigit);
// The time must be finished now. E.g. 2:57am, 9:30pm.
thirdDigit.addChild(ampm);
// When the first digit is 2-9, and the second digit is 0-5, and third digit is 0-9, we
// may add seconds if enabled.
if (mEnableSeconds) {
// The time must be finished now. E.g. 2:57:01am, 9:30:59pm.
thirdDigit.addChild(secondsFirstDigit);
}
}
} }
|
public class class_name {
private void generateLegalTimesTree() {
// Create a quick cache of numbers to their keycodes.
int k0 = KeyEvent.KEYCODE_0;
int k1 = KeyEvent.KEYCODE_1;
int k2 = KeyEvent.KEYCODE_2;
int k3 = KeyEvent.KEYCODE_3;
int k4 = KeyEvent.KEYCODE_4;
int k5 = KeyEvent.KEYCODE_5;
int k6 = KeyEvent.KEYCODE_6;
int k7 = KeyEvent.KEYCODE_7;
int k8 = KeyEvent.KEYCODE_8;
int k9 = KeyEvent.KEYCODE_9;
// The root of the tree doesn't contain any numbers.
mLegalTimesTree = new Node();
// In case we're only allowing hours
if (!mEnableMinutes && mIs24HourMode) {
// The first digit may be 0-1
Node firstDigit = new Node(k0, k1);
mLegalTimesTree.addChild(firstDigit); // depends on control dependency: [if], data = [none]
// When the first digit is 0-1, the second digit may be 0-9
Node secondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
firstDigit.addChild(secondDigit); // depends on control dependency: [if], data = [none]
// The first digit may be 2
firstDigit = new Node(k2); // depends on control dependency: [if], data = [none]
mLegalTimesTree.addChild(firstDigit); // depends on control dependency: [if], data = [none]
// When the first digit is 2, the second digit may be 0-3
secondDigit = new Node(k0, k1, k2, k3); // depends on control dependency: [if], data = [none]
firstDigit.addChild(secondDigit); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
//noinspection ConstantConditions
if (!mEnableMinutes && !mIs24HourMode) {
// We'll need to use the AM/PM node a lot.
// Set up AM and PM to respond to "a" and "p".
Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));
// The first digit may be 1
Node firstDigit = new Node(k1);
mLegalTimesTree.addChild(firstDigit); // depends on control dependency: [if], data = [none]
// If the first digit is 1, the second one may be am/pm 1pm
firstDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
// If the first digit is 1, the second digit may be 0-2
Node secondDigit = new Node(k0, k1, k2);
firstDigit.addChild(secondDigit); // depends on control dependency: [if], data = [none]
secondDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
// The first digit may be 2-9
firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9); // depends on control dependency: [if], data = [none]
mLegalTimesTree.addChild(firstDigit); // depends on control dependency: [if], data = [none]
firstDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
// In case minutes are allowed
if (mIs24HourMode) {
// We'll be re-using these nodes, so we'll save them.
Node minuteFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
Node minuteSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
// The first digit must be followed by the second digit.
minuteFirstDigit.addChild(minuteSecondDigit); // depends on control dependency: [if], data = [none]
if (mEnableSeconds) {
Node secondsFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
Node secondsSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondsFirstDigit.addChild(secondsSecondDigit); // depends on control dependency: [if], data = [none]
// Minutes can be followed by seconds.
minuteSecondDigit.addChild(secondsFirstDigit); // depends on control dependency: [if], data = [none]
}
// The first digit may be 0-1.
Node firstDigit = new Node(k0, k1);
mLegalTimesTree.addChild(firstDigit); // depends on control dependency: [if], data = [none]
// When the first digit is 0-1, the second digit may be 0-5.
Node secondDigit = new Node(k0, k1, k2, k3, k4, k5);
firstDigit.addChild(secondDigit); // depends on control dependency: [if], data = [none]
// We may now be followed by the first minute digit. E.g. 00:09, 15:58.
secondDigit.addChild(minuteFirstDigit); // depends on control dependency: [if], data = [none]
// When the first digit is 0-1, and the second digit is 0-5, the third digit may be 6-9.
Node thirdDigit = new Node(k6, k7, k8, k9);
// The time must now be finished. E.g. 0:55, 1:08.
secondDigit.addChild(thirdDigit); // depends on control dependency: [if], data = [none]
// When the first digit is 0-1, the second digit may be 6-9.
secondDigit = new Node(k6, k7, k8, k9); // depends on control dependency: [if], data = [none]
firstDigit.addChild(secondDigit); // depends on control dependency: [if], data = [none]
// We must now be followed by the first minute digit. E.g. 06:50, 18:20.
secondDigit.addChild(minuteFirstDigit); // depends on control dependency: [if], data = [none]
// The first digit may be 2.
firstDigit = new Node(k2); // depends on control dependency: [if], data = [none]
mLegalTimesTree.addChild(firstDigit); // depends on control dependency: [if], data = [none]
// When the first digit is 2, the second digit may be 0-3.
secondDigit = new Node(k0, k1, k2, k3); // depends on control dependency: [if], data = [none]
firstDigit.addChild(secondDigit); // depends on control dependency: [if], data = [none]
// We must now be followed by the first minute digit. E.g. 20:50, 23:09.
secondDigit.addChild(minuteFirstDigit); // depends on control dependency: [if], data = [none]
// When the first digit is 2, the second digit may be 4-5.
secondDigit = new Node(k4, k5); // depends on control dependency: [if], data = [none]
firstDigit.addChild(secondDigit); // depends on control dependency: [if], data = [none]
// We must now be followd by the last minute digit. E.g. 2:40, 2:53.
secondDigit.addChild(minuteSecondDigit); // depends on control dependency: [if], data = [none]
// The first digit may be 3-9.
firstDigit = new Node(k3, k4, k5, k6, k7, k8, k9); // depends on control dependency: [if], data = [none]
mLegalTimesTree.addChild(firstDigit); // depends on control dependency: [if], data = [none]
// We must now be followed by the first minute digit. E.g. 3:57, 8:12.
firstDigit.addChild(minuteFirstDigit); // depends on control dependency: [if], data = [none]
} else {
// We'll need to use the AM/PM node a lot.
// Set up AM and PM to respond to "a" and "p".
Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));
// Seconds will be used a few times as well, if enabled.
Node secondsFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
Node secondsSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
secondsSecondDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
secondsFirstDigit.addChild(secondsSecondDigit); // depends on control dependency: [if], data = [none]
// The first hour digit may be 1.
Node firstDigit = new Node(k1);
mLegalTimesTree.addChild(firstDigit); // depends on control dependency: [if], data = [none]
// We'll allow quick input of on-the-hour times. E.g. 1pm.
firstDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
// When the first digit is 1, the second digit may be 0-2.
Node secondDigit = new Node(k0, k1, k2);
firstDigit.addChild(secondDigit); // depends on control dependency: [if], data = [none]
// Also for quick input of on-the-hour times. E.g. 10pm, 12am.
secondDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
// When the first digit is 1, and the second digit is 0-2, the third digit may be 0-5.
Node thirdDigit = new Node(k0, k1, k2, k3, k4, k5);
secondDigit.addChild(thirdDigit); // depends on control dependency: [if], data = [none]
// The time may be finished now. E.g. 1:02pm, 1:25am.
thirdDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
// When the first digit is 1, the second digit is 0-2, and the third digit is 0-5,
// the fourth digit may be 0-9.
Node fourthDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
thirdDigit.addChild(fourthDigit); // depends on control dependency: [if], data = [none]
// The time must be finished now, when seconds are disabled. E.g. 10:49am, 12:40pm.
fourthDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
// When the first digit is 1, the second digit is 0-2, and the third digit is 0-5,
// and fourth digit is 0-9, we may add seconds if enabled.
if (mEnableSeconds) {
// The time must be finished now. E.g. 10:49:01am, 12:40:59pm.
fourthDigit.addChild(secondsFirstDigit); // depends on control dependency: [if], data = [none]
}
// When the first digit is 1, and the second digit is 0-2, the third digit may be 6-9.
thirdDigit = new Node(k6, k7, k8, k9); // depends on control dependency: [if], data = [none]
secondDigit.addChild(thirdDigit); // depends on control dependency: [if], data = [none]
// The time must be finished now. E.g. 1:08am, 1:26pm.
thirdDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
// When the first digit is 1, and the second digit is 0-2, and the third digit is 6-9,
// we may add seconds is enabled.
if (mEnableSeconds) {
// The time must be finished now. E.g. 1:08:01am, 1:26:59pm.
thirdDigit.addChild(secondsFirstDigit); // depends on control dependency: [if], data = [none]
}
// When the first digit is 1, the second digit may be 3-5.
secondDigit = new Node(k3, k4, k5); // depends on control dependency: [if], data = [none]
firstDigit.addChild(secondDigit); // depends on control dependency: [if], data = [none]
// When the first digit is 1, and the second digit is 3-5, the third digit may be 0-9.
thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9); // depends on control dependency: [if], data = [none]
secondDigit.addChild(thirdDigit); // depends on control dependency: [if], data = [none]
// The time must be finished now if seconds are disabled. E.g. 1:39am, 1:50pm.
thirdDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
// When the first digit is 1, and the second digit is 3-5, and the third digit is 0-9,
// we may add seconds if enabled.
if (mEnableSeconds) {
// The time must be finished now. E.g. 1:39:01am, 1:50:59pm.
thirdDigit.addChild(secondsFirstDigit); // depends on control dependency: [if], data = [none]
}
// The hour digit may be 2-9.
firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9); // depends on control dependency: [if], data = [none]
mLegalTimesTree.addChild(firstDigit); // depends on control dependency: [if], data = [none]
// We'll allow quick input of on-the-hour-times. E.g. 2am, 5pm.
firstDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
// When the first digit is 2-9, the second digit may be 0-5.
secondDigit = new Node(k0, k1, k2, k3, k4, k5); // depends on control dependency: [if], data = [none]
firstDigit.addChild(secondDigit); // depends on control dependency: [if], data = [none]
// When the first digit is 2-9, and the second digit is 0-5, the third digit may be 0-9.
thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9); // depends on control dependency: [if], data = [none]
secondDigit.addChild(thirdDigit); // depends on control dependency: [if], data = [none]
// The time must be finished now. E.g. 2:57am, 9:30pm.
thirdDigit.addChild(ampm); // depends on control dependency: [if], data = [none]
// When the first digit is 2-9, and the second digit is 0-5, and third digit is 0-9, we
// may add seconds if enabled.
if (mEnableSeconds) {
// The time must be finished now. E.g. 2:57:01am, 9:30:59pm.
thirdDigit.addChild(secondsFirstDigit); // depends on control dependency: [if], data = [none]
}
}
} }
|
public class class_name {
private Optional<PushUpBooleanExpressionProposal> makeNodeCentricProposal(CommutativeJoinOrFilterNode providerNode,
ImmutableExpression propagatedExpression,
Optional<ImmutableExpression> nonPropagatedExpression,
IntermediateQuery query,
boolean propagateThroughNextUnionNodeAncestor) {
Optional<JoinOrFilterNode> recipient;
ImmutableSet.Builder<ExplicitVariableProjectionNode> inbetweenProjectorsBuilder = ImmutableSet.builder();
QueryNode currentChildNode;
QueryNode currentParentNode = providerNode;
do {
currentChildNode = currentParentNode;
currentParentNode = query.getParent(currentParentNode)
.orElseThrow(() -> new InvalidIntermediateQueryException("This node must have a parent node"));
if (currentParentNode == query.getRootNode()) {
break;
}
if (currentParentNode instanceof ConstructionNode) {
/* keep track of Construction nodes on the path between provider and recipient */
inbetweenProjectorsBuilder.add((ConstructionNode) currentParentNode);
continue;
}
if (currentParentNode instanceof UnionNode) {
/* optionally propagate the expression through the first encountered UnionNode */
if (propagateThroughNextUnionNodeAncestor) {
propagateThroughNextUnionNodeAncestor = false;
/* keep track of it as an inbetween projector */
inbetweenProjectorsBuilder.add((ExplicitVariableProjectionNode) currentParentNode);
continue;
}
break;
}
if (currentParentNode instanceof LeftJoinNode &&
(query.getOptionalPosition(currentChildNode)
.orElseThrow(() -> new InvalidIntermediateQueryException("The child of a LeftJoin node must have a position"))
== RIGHT)) {
/*
Stop propagation when reaching a LeftJoinNode from its right branch,
and select the leftJoinNode as recipient
*/
return Optional.of(
new PushUpBooleanExpressionProposalImpl(
propagatedExpression,
ImmutableMap.of(providerNode, nonPropagatedExpression),
currentChildNode,
Optional.of((JoinOrFilterNode) currentParentNode),
inbetweenProjectorsBuilder.build()
));
}
}
while (true);
// If no effective propagation
if (currentChildNode == providerNode) {
return Optional.empty();
}
// if we reach this point, the upward propagation up must have been blocked by a union or by the root
recipient = currentChildNode instanceof CommutativeJoinOrFilterNode ?
Optional.of((CommutativeJoinOrFilterNode) currentChildNode) :
Optional.empty();
PushUpBooleanExpressionProposal proposal = new PushUpBooleanExpressionProposalImpl(
propagatedExpression,
ImmutableMap.of(providerNode, nonPropagatedExpression),
currentChildNode,
recipient,
inbetweenProjectorsBuilder.build()
);
// Possibly adjust the proposal, to enforce that the second exception (see the class comments) holds
return adjustProposal(proposal, query);
} }
|
public class class_name {
private Optional<PushUpBooleanExpressionProposal> makeNodeCentricProposal(CommutativeJoinOrFilterNode providerNode,
ImmutableExpression propagatedExpression,
Optional<ImmutableExpression> nonPropagatedExpression,
IntermediateQuery query,
boolean propagateThroughNextUnionNodeAncestor) {
Optional<JoinOrFilterNode> recipient;
ImmutableSet.Builder<ExplicitVariableProjectionNode> inbetweenProjectorsBuilder = ImmutableSet.builder();
QueryNode currentChildNode;
QueryNode currentParentNode = providerNode;
do {
currentChildNode = currentParentNode;
currentParentNode = query.getParent(currentParentNode)
.orElseThrow(() -> new InvalidIntermediateQueryException("This node must have a parent node"));
if (currentParentNode == query.getRootNode()) {
break;
}
if (currentParentNode instanceof ConstructionNode) {
/* keep track of Construction nodes on the path between provider and recipient */
inbetweenProjectorsBuilder.add((ConstructionNode) currentParentNode); // depends on control dependency: [if], data = [none]
continue;
}
if (currentParentNode instanceof UnionNode) {
/* optionally propagate the expression through the first encountered UnionNode */
if (propagateThroughNextUnionNodeAncestor) {
propagateThroughNextUnionNodeAncestor = false; // depends on control dependency: [if], data = [none]
/* keep track of it as an inbetween projector */
inbetweenProjectorsBuilder.add((ExplicitVariableProjectionNode) currentParentNode); // depends on control dependency: [if], data = [none]
continue;
}
break;
}
if (currentParentNode instanceof LeftJoinNode &&
(query.getOptionalPosition(currentChildNode)
.orElseThrow(() -> new InvalidIntermediateQueryException("The child of a LeftJoin node must have a position"))
== RIGHT)) {
/*
Stop propagation when reaching a LeftJoinNode from its right branch,
and select the leftJoinNode as recipient
*/
return Optional.of(
new PushUpBooleanExpressionProposalImpl(
propagatedExpression,
ImmutableMap.of(providerNode, nonPropagatedExpression),
currentChildNode,
Optional.of((JoinOrFilterNode) currentParentNode),
inbetweenProjectorsBuilder.build()
)); // depends on control dependency: [if], data = [none]
}
}
while (true);
// If no effective propagation
if (currentChildNode == providerNode) {
return Optional.empty(); // depends on control dependency: [if], data = [none]
}
// if we reach this point, the upward propagation up must have been blocked by a union or by the root
recipient = currentChildNode instanceof CommutativeJoinOrFilterNode ?
Optional.of((CommutativeJoinOrFilterNode) currentChildNode) :
Optional.empty();
PushUpBooleanExpressionProposal proposal = new PushUpBooleanExpressionProposalImpl(
propagatedExpression,
ImmutableMap.of(providerNode, nonPropagatedExpression),
currentChildNode,
recipient,
inbetweenProjectorsBuilder.build()
);
// Possibly adjust the proposal, to enforce that the second exception (see the class comments) holds
return adjustProposal(proposal, query);
} }
|
public class class_name {
public static void registerFunction(Statement st,Function function,String packagePrepend,boolean dropAlias) throws SQLException {
String functionClass = function.getClass().getName();
String functionAlias = getAlias(function);
if(function instanceof ScalarFunction) {
ScalarFunction scalarFunction = (ScalarFunction)function;
String functionName = scalarFunction.getJavaStaticMethod();
if(dropAlias) {
try {
st.execute("DROP ALIAS IF EXISTS " + functionAlias);
} catch (SQLException ex) {
// Ignore, some tables constraints may depend on this function
LOGGER.debug(ex.getLocalizedMessage(), ex);
}
}
String deterministic = "";
if(getBooleanProperty(function,ScalarFunction.PROP_DETERMINISTIC,false)) {
deterministic = " DETERMINISTIC";
}
String nobuffer = "";
if(getBooleanProperty(function, ScalarFunction.PROP_NOBUFFER, false)) {
nobuffer = " NOBUFFER";
}
// Create alias, H2 does not support prepare statement on create alias
// "FORCE ALIAS means that the class not existing will not prevent the database from being opened."
st.execute("CREATE FORCE ALIAS IF NOT EXISTS " + functionAlias + deterministic + nobuffer + " FOR \"" + packagePrepend + functionClass + "." + functionName + "\"");
// Set comment
String functionRemarks = getStringProperty(function, Function.PROP_REMARKS);
if(!functionRemarks.isEmpty()) {
PreparedStatement ps = st.getConnection().prepareStatement("COMMENT ON ALIAS "+functionAlias+" IS ?");
ps.setString(1, functionRemarks);
ps.execute();
}
} else if(function instanceof Aggregate) {
if(dropAlias) {
st.execute("DROP AGGREGATE IF EXISTS " + functionAlias);
}
st.execute("CREATE FORCE AGGREGATE IF NOT EXISTS " + functionAlias + " FOR \"" + packagePrepend + functionClass + "\"");
} else {
throw new SQLException("Unsupported function "+functionClass);
}
} }
|
public class class_name {
public static void registerFunction(Statement st,Function function,String packagePrepend,boolean dropAlias) throws SQLException {
String functionClass = function.getClass().getName();
String functionAlias = getAlias(function);
if(function instanceof ScalarFunction) {
ScalarFunction scalarFunction = (ScalarFunction)function;
String functionName = scalarFunction.getJavaStaticMethod();
if(dropAlias) {
try {
st.execute("DROP ALIAS IF EXISTS " + functionAlias); // depends on control dependency: [try], data = [none]
} catch (SQLException ex) {
// Ignore, some tables constraints may depend on this function
LOGGER.debug(ex.getLocalizedMessage(), ex);
} // depends on control dependency: [catch], data = [none]
}
String deterministic = "";
if(getBooleanProperty(function,ScalarFunction.PROP_DETERMINISTIC,false)) {
deterministic = " DETERMINISTIC"; // depends on control dependency: [if], data = [none]
}
String nobuffer = "";
if(getBooleanProperty(function, ScalarFunction.PROP_NOBUFFER, false)) {
nobuffer = " NOBUFFER"; // depends on control dependency: [if], data = [none]
}
// Create alias, H2 does not support prepare statement on create alias
// "FORCE ALIAS means that the class not existing will not prevent the database from being opened."
st.execute("CREATE FORCE ALIAS IF NOT EXISTS " + functionAlias + deterministic + nobuffer + " FOR \"" + packagePrepend + functionClass + "." + functionName + "\"");
// Set comment
String functionRemarks = getStringProperty(function, Function.PROP_REMARKS);
if(!functionRemarks.isEmpty()) {
PreparedStatement ps = st.getConnection().prepareStatement("COMMENT ON ALIAS "+functionAlias+" IS ?");
ps.setString(1, functionRemarks);
ps.execute();
}
} else if(function instanceof Aggregate) {
if(dropAlias) {
st.execute("DROP AGGREGATE IF EXISTS " + functionAlias);
}
st.execute("CREATE FORCE AGGREGATE IF NOT EXISTS " + functionAlias + " FOR \"" + packagePrepend + functionClass + "\"");
} else {
throw new SQLException("Unsupported function "+functionClass);
}
} }
|
public class class_name {
private static void sendSessMsg(CommsServerByteBuffer request,
Conversation conversation,
int requestNumber,
boolean partOfExchange,
boolean allocatedFromBufferPool,
boolean sendReply,
boolean txOptimized)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "sendSessMsg",
new Object[]
{
request,
conversation,
"" + requestNumber,
"" + partOfExchange,
"" + allocatedFromBufferPool,
"" + sendReply,
"" + txOptimized,
});
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
if (sendReply)
SibTr.debug(tc, "The client will be informed of the outcome");
else
SibTr.debug(tc, "The client will NOT be informed of the outcome");
}
ConversationState convState = (ConversationState) conversation.getAttachment();
ServerLinkLevelState linkState = (ServerLinkLevelState) conversation.getLinkLevelAttachment();
short connectionObjectId = request.getShort(); // BIT16 ConnectionObjectId
short producerObjectId = request.getShort(); // BIT16 SyncProducerSessionId
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "connectionObjectId", connectionObjectId);
SibTr.debug(tc, "producerObjectId", producerObjectId);
}
// Get the transaction
int transactionId = request.getSITransactionId(connectionObjectId, linkState, txOptimized);
SITransaction siTran = linkState.getTransactionTable().get(transactionId);
try
{
try
{
// Now get the message
int messageLength = (int) request.peekLong();
SIBusMessage sibMessage = request.getMessage(null);
ProducerSession producer =
((ProducerSession) convState.getObject(producerObjectId));
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "Sending client message - " + sibMessage);
SibTr.debug(tc, "Destination: " + producer.getDestinationAddress());
SibTr.debug(tc, "Discriminator: " + sibMessage.getDiscriminator());
SibTr.debug(tc, "Reliability: " + sibMessage.getReliability());
}
if (siTran != IdToTransactionTable.INVALID_TRANSACTION)
{
producer.send(sibMessage, siTran);
}
if (sendReply)
{
try
{
conversation.send(poolManager.allocate(),
JFapChannelConstants.SEG_SEND_SESS_MSG_R,
requestNumber,
JFapChannelConstants.PRIORITY_MEDIUM,
true,
ThrottlingPolicy.BLOCK_THREAD,
null);
} catch (SIException e)
{
FFDCFilter.processException(e,
CLASS_NAME + ".sendSessMsg",
CommsConstants.STATICCATPRODUCER_SEND_01);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, e.getMessage(), e);
SibTr.error(tc, "COMMUNICATION_ERROR_SICO2024", e);
}
}
} catch (Exception e)
{
// No FFDC code needed
// (actually we FFDC later on - but we need that line to fool the FFDC tool :-)
// If we are sending replies, rethrow the exception so
// that the specific exeption handlers will deal with it
// and send the response to the client
if (sendReply)
throw e;
// Otherwise, mark this transaction as error if we are not sending a reply
if (transactionId != CommsConstants.NO_TRANSACTION)
linkState.getTransactionTable().markAsRollbackOnly(transactionId, e);
//Only FFDC if we haven't received a meTerminated event OR if this Exception isn't a SIException.
if (!(e instanceof SIException) || !convState.hasMETerminated())
{
FFDCFilter.processException(e,
CLASS_NAME + ".sendSessMsg",
CommsConstants.STATICCATPRODUCER_SEND_02);
}
SibTr.error(tc, SibTr.Suppressor.ALL_FOR_A_WHILE_SIMILAR_INSERTS,
"UNABLE_TO_SEND_MESSAGE_SICO2009", e);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "Failed to send a message", e);
}
} catch (SIException e)
{
//No FFDC code needed - processor will have already FFDC'ed any interesting ones....
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, e.getMessage(), e);
StaticCATHelper.sendExceptionToClient(e,
CommsConstants.STATICCATPRODUCER_SEND_03,
conversation, requestNumber);
} catch (Exception e)
{
FFDCFilter.processException(e,
CLASS_NAME + ".sendSessMsg",
CommsConstants.STATICCATPRODUCER_SEND_04);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, e.getMessage(), e);
StaticCATHelper.sendExceptionToClient(e,
CommsConstants.STATICCATPRODUCER_SEND_04,
conversation, requestNumber);
}
request.release(allocatedFromBufferPool);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "sendSessMsg");
} }
|
public class class_name {
private static void sendSessMsg(CommsServerByteBuffer request,
Conversation conversation,
int requestNumber,
boolean partOfExchange,
boolean allocatedFromBufferPool,
boolean sendReply,
boolean txOptimized)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "sendSessMsg",
new Object[]
{
request,
conversation,
"" + requestNumber,
"" + partOfExchange,
"" + allocatedFromBufferPool,
"" + sendReply,
"" + txOptimized,
});
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
if (sendReply)
SibTr.debug(tc, "The client will be informed of the outcome");
else
SibTr.debug(tc, "The client will NOT be informed of the outcome");
}
ConversationState convState = (ConversationState) conversation.getAttachment();
ServerLinkLevelState linkState = (ServerLinkLevelState) conversation.getLinkLevelAttachment();
short connectionObjectId = request.getShort(); // BIT16 ConnectionObjectId
short producerObjectId = request.getShort(); // BIT16 SyncProducerSessionId
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "connectionObjectId", connectionObjectId); // depends on control dependency: [if], data = [none]
SibTr.debug(tc, "producerObjectId", producerObjectId); // depends on control dependency: [if], data = [none]
}
// Get the transaction
int transactionId = request.getSITransactionId(connectionObjectId, linkState, txOptimized);
SITransaction siTran = linkState.getTransactionTable().get(transactionId);
try
{
try
{
// Now get the message
int messageLength = (int) request.peekLong();
SIBusMessage sibMessage = request.getMessage(null);
ProducerSession producer =
((ProducerSession) convState.getObject(producerObjectId));
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
SibTr.debug(tc, "Sending client message - " + sibMessage); // depends on control dependency: [if], data = [none]
SibTr.debug(tc, "Destination: " + producer.getDestinationAddress()); // depends on control dependency: [if], data = [none]
SibTr.debug(tc, "Discriminator: " + sibMessage.getDiscriminator()); // depends on control dependency: [if], data = [none]
SibTr.debug(tc, "Reliability: " + sibMessage.getReliability()); // depends on control dependency: [if], data = [none]
}
if (siTran != IdToTransactionTable.INVALID_TRANSACTION)
{
producer.send(sibMessage, siTran); // depends on control dependency: [if], data = [none]
}
if (sendReply)
{
try
{
conversation.send(poolManager.allocate(),
JFapChannelConstants.SEG_SEND_SESS_MSG_R,
requestNumber,
JFapChannelConstants.PRIORITY_MEDIUM,
true,
ThrottlingPolicy.BLOCK_THREAD,
null); // depends on control dependency: [try], data = [none]
} catch (SIException e)
{
FFDCFilter.processException(e,
CLASS_NAME + ".sendSessMsg",
CommsConstants.STATICCATPRODUCER_SEND_01);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, e.getMessage(), e);
SibTr.error(tc, "COMMUNICATION_ERROR_SICO2024", e);
} // depends on control dependency: [catch], data = [none]
}
} catch (Exception e)
{
// No FFDC code needed
// (actually we FFDC later on - but we need that line to fool the FFDC tool :-)
// If we are sending replies, rethrow the exception so
// that the specific exeption handlers will deal with it
// and send the response to the client
if (sendReply)
throw e;
// Otherwise, mark this transaction as error if we are not sending a reply
if (transactionId != CommsConstants.NO_TRANSACTION)
linkState.getTransactionTable().markAsRollbackOnly(transactionId, e);
//Only FFDC if we haven't received a meTerminated event OR if this Exception isn't a SIException.
if (!(e instanceof SIException) || !convState.hasMETerminated())
{
FFDCFilter.processException(e,
CLASS_NAME + ".sendSessMsg",
CommsConstants.STATICCATPRODUCER_SEND_02); // depends on control dependency: [if], data = [none]
}
SibTr.error(tc, SibTr.Suppressor.ALL_FOR_A_WHILE_SIMILAR_INSERTS,
"UNABLE_TO_SEND_MESSAGE_SICO2009", e);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "Failed to send a message", e);
} // depends on control dependency: [catch], data = [none]
} catch (SIException e)
{
//No FFDC code needed - processor will have already FFDC'ed any interesting ones....
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, e.getMessage(), e);
StaticCATHelper.sendExceptionToClient(e,
CommsConstants.STATICCATPRODUCER_SEND_03,
conversation, requestNumber);
} catch (Exception e) // depends on control dependency: [catch], data = [none]
{
FFDCFilter.processException(e,
CLASS_NAME + ".sendSessMsg",
CommsConstants.STATICCATPRODUCER_SEND_04);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, e.getMessage(), e);
StaticCATHelper.sendExceptionToClient(e,
CommsConstants.STATICCATPRODUCER_SEND_04,
conversation, requestNumber);
} // depends on control dependency: [catch], data = [none]
request.release(allocatedFromBufferPool);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "sendSessMsg");
} }
|
public class class_name {
public List<Resource<?>> resolve()
{
Resource<?> r = res;
String tk;
char slashChar = File.separatorChar;
String slashString = File.separator;
if (".".equals(path))
{
return singleResult(r);
}
else if (path.startsWith("~"))
{
File homeDir = OperatingSystemUtils.getUserHomeDir();
if (path.length() == 1)
{
return singleResult(factory.create(DirectoryResource.class, homeDir));
}
else
{
cursor++;
r = factory.create(DirectoryResource.class, homeDir);
}
}
// for windows, support drive letter prefixes here.
else if (isWindows && WINDOWS_DRIVE_PATTERN.matcher(path).matches())
{
int idx = path.lastIndexOf(slashChar) + 1;
r = factory.create(DirectoryResource.class, new File(path.substring(0, idx)).getAbsoluteFile());
cursor = idx;
}
// Is an URL ?
else if (path.matches(".*://.*"))
{
int idx = path.indexOf(" ");
if (idx == -1)
{
idx = length;
}
try
{
r = factory.create(URLResource.class, new URL(path.substring(0, idx)));
}
catch (MalformedURLException e)
{
throw new RuntimeException(e);
}
cursor = idx + 1;
}
while (cursor < length)
{
SW: switch (path.charAt(cursor++))
{
case '\\':
case '/':
if (cursor - 1 == 0)
{
r = factory.create(new File(slashString).getAbsoluteFile());
}
continue;
case '.':
switch (read())
{
case '.':
cursor++;
Resource<?> parent = r.getParent();
if (parent != null)
{
r = parent;
}
break SW;
default:
if (cursor < length && path.charAt(cursor) == slashChar)
{
cursor++;
break SW;
}
}
default:
boolean first = --cursor == 0;
tk = capture();
if (WILDCARDS_PATTERN.matcher(tk).matches())
{
boolean startDot = tk.startsWith(".");
String regex = pathspecToRegEx(tk.startsWith(slashString) ? tk.substring(1) : tk);
Pattern p;
try
{
p = Pattern.compile(regex);
}
catch (PatternSyntaxException pe)
{
// Regex might be incomplete, trying again quoted
p = Pattern.compile(Pattern.quote(regex));
}
List<Resource<?>> res = new ArrayList<>();
for (Resource<?> child : r.listResources())
{
if (p.matcher(child.getName()).matches())
{
// child.setFlag(ResourceFlag.AmbiguouslyQualified);
if (child.getName().startsWith("."))
{
if (startDot)
{
res.add(child);
}
}
else
{
res.add(child);
}
}
}
if (cursor != length)
{
for (Resource<?> child : res)
{
results.addAll(new ResourcePathResolver(factory, child, path, cursor).resolve());
}
}
else
{
results.addAll(res);
}
return results;
}
if (tk.startsWith(slashString))
{
if (first)
{
r = factory.create(new File(tk));
cursor++;
continue;
}
else
{
tk = tk.substring(1);
}
}
Resource<?> child = r.getChild(tk);
if (child == null)
{
throw new RuntimeException("no such child: " + tk);
}
r = child;
break;
}
}
return singleResult(r);
} }
|
public class class_name {
public List<Resource<?>> resolve()
{
Resource<?> r = res;
String tk;
char slashChar = File.separatorChar;
String slashString = File.separator;
if (".".equals(path))
{
return singleResult(r); // depends on control dependency: [if], data = [none]
}
else if (path.startsWith("~"))
{
File homeDir = OperatingSystemUtils.getUserHomeDir();
if (path.length() == 1)
{
return singleResult(factory.create(DirectoryResource.class, homeDir)); // depends on control dependency: [if], data = [none]
}
else
{
cursor++; // depends on control dependency: [if], data = [none]
r = factory.create(DirectoryResource.class, homeDir); // depends on control dependency: [if], data = [none]
}
}
// for windows, support drive letter prefixes here.
else if (isWindows && WINDOWS_DRIVE_PATTERN.matcher(path).matches())
{
int idx = path.lastIndexOf(slashChar) + 1;
r = factory.create(DirectoryResource.class, new File(path.substring(0, idx)).getAbsoluteFile()); // depends on control dependency: [if], data = [none]
cursor = idx; // depends on control dependency: [if], data = [none]
}
// Is an URL ?
else if (path.matches(".*://.*"))
{
int idx = path.indexOf(" ");
if (idx == -1)
{
idx = length;
}
try
{
r = factory.create(URLResource.class, new URL(path.substring(0, idx)));
}
catch (MalformedURLException e)
{
throw new RuntimeException(e);
}
cursor = idx + 1;
}
while (cursor < length)
{
SW: switch (path.charAt(cursor++))
{
case '\\':
case '/':
if (cursor - 1 == 0)
{
r = factory.create(new File(slashString).getAbsoluteFile());
}
continue;
case '.':
switch (read())
{
case '.':
cursor++;
Resource<?> parent = r.getParent();
if (parent != null)
{
r = parent; // depends on control dependency: [if], data = [none]
}
break SW;
default:
if (cursor < length && path.charAt(cursor) == slashChar)
{
cursor++; // depends on control dependency: [if], data = [none]
break SW;
}
}
default:
boolean first = --cursor == 0;
tk = capture();
if (WILDCARDS_PATTERN.matcher(tk).matches())
{
boolean startDot = tk.startsWith(".");
String regex = pathspecToRegEx(tk.startsWith(slashString) ? tk.substring(1) : tk);
Pattern p;
try
{
p = Pattern.compile(regex); // depends on control dependency: [try], data = [none]
}
catch (PatternSyntaxException pe)
{
// Regex might be incomplete, trying again quoted
p = Pattern.compile(Pattern.quote(regex));
} // depends on control dependency: [catch], data = [none]
List<Resource<?>> res = new ArrayList<>(); // depends on control dependency: [if], data = [none]
for (Resource<?> child : r.listResources())
{
if (p.matcher(child.getName()).matches())
{
// child.setFlag(ResourceFlag.AmbiguouslyQualified);
if (child.getName().startsWith("."))
{
if (startDot)
{
res.add(child); // depends on control dependency: [if], data = [none]
}
}
else
{
res.add(child); // depends on control dependency: [if], data = [none]
}
}
}
if (cursor != length)
{
for (Resource<?> child : res)
{
results.addAll(new ResourcePathResolver(factory, child, path, cursor).resolve()); // depends on control dependency: [for], data = [child]
}
}
else
{
results.addAll(res); // depends on control dependency: [if], data = [none]
}
return results; // depends on control dependency: [if], data = [none]
}
if (tk.startsWith(slashString))
{
if (first)
{
r = factory.create(new File(tk)); // depends on control dependency: [if], data = [none]
cursor++; // depends on control dependency: [if], data = [none]
continue;
}
else
{
tk = tk.substring(1); // depends on control dependency: [if], data = [none]
}
}
Resource<?> child = r.getChild(tk);
if (child == null)
{
throw new RuntimeException("no such child: " + tk);
}
r = child;
break;
}
}
return singleResult(r);
} }
|
public class class_name {
public final void setServerNames(List<SNIServerName> serverNames) {
if (serverNames != null) {
if (!serverNames.isEmpty()) {
sniNames = new LinkedHashMap<>(serverNames.size());
for (SNIServerName serverName : serverNames) {
if (sniNames.put(serverName.getType(),
serverName) != null) {
throw new IllegalArgumentException(
"Duplicated server name of type " +
serverName.getType());
}
}
} else {
sniNames = Collections.<Integer, SNIServerName>emptyMap();
}
} else {
sniNames = null;
}
} }
|
public class class_name {
public final void setServerNames(List<SNIServerName> serverNames) {
if (serverNames != null) {
if (!serverNames.isEmpty()) {
sniNames = new LinkedHashMap<>(serverNames.size()); // depends on control dependency: [if], data = [none]
for (SNIServerName serverName : serverNames) {
if (sniNames.put(serverName.getType(),
serverName) != null) {
throw new IllegalArgumentException(
"Duplicated server name of type " +
serverName.getType());
}
}
} else {
sniNames = Collections.<Integer, SNIServerName>emptyMap(); // depends on control dependency: [if], data = [none]
}
} else {
sniNames = null; // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public java.util.List<Dimension> getDimensions() {
if (dimensions == null) {
dimensions = new com.amazonaws.internal.SdkInternalList<Dimension>();
}
return dimensions;
} }
|
public class class_name {
public java.util.List<Dimension> getDimensions() {
if (dimensions == null) {
dimensions = new com.amazonaws.internal.SdkInternalList<Dimension>(); // depends on control dependency: [if], data = [none]
}
return dimensions;
} }
|
public class class_name {
public boolean export(Context context, Class<?> spaceClass, String accessToken) {
successful = false;
final SpaceHelper helper = crateSpaceHelper(spaceClass);
final String outputPath = createOutputPath(helper);
final CountDownLatch countDownLatch = new CountDownLatch(1);
final Vault vault = Vault.with(context, spaceClass);
vault.requestSync(
SyncConfig
.builder()
.setSpaceId(helper.getSpaceId())
.setAccessToken(accessToken)
.build(),
new SyncCallback() {
@Override public void onResult(SyncResult result) {
try {
successful = saveResultInDatabaseFile(result, vault, outputPath);
} catch (Throwable t) {
t.printStackTrace(System.err);
} finally {
countDownLatch.countDown();
}
}
}, new Executor() {
@Override public void execute(Runnable runnable) {
runnable.run();
}
});
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
return successful;
} }
|
public class class_name {
public boolean export(Context context, Class<?> spaceClass, String accessToken) {
successful = false;
final SpaceHelper helper = crateSpaceHelper(spaceClass);
final String outputPath = createOutputPath(helper);
final CountDownLatch countDownLatch = new CountDownLatch(1);
final Vault vault = Vault.with(context, spaceClass);
vault.requestSync(
SyncConfig
.builder()
.setSpaceId(helper.getSpaceId())
.setAccessToken(accessToken)
.build(),
new SyncCallback() {
@Override public void onResult(SyncResult result) {
try {
successful = saveResultInDatabaseFile(result, vault, outputPath); // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
t.printStackTrace(System.err);
} finally { // depends on control dependency: [catch], data = [none]
countDownLatch.countDown();
}
}
}, new Executor() {
@Override public void execute(Runnable runnable) {
runnable.run();
}
});
try {
countDownLatch.await(); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
e.printStackTrace(System.err);
} // depends on control dependency: [catch], data = [none]
return successful;
} }
|
public class class_name {
public double[][] toMatrix(List<K1> firstKeys, List<K2> secondKeys) {
double[][] counts = new double[firstKeys.size()][secondKeys.size()];
for (int i = 0; i < firstKeys.size(); i++) {
for (int j = 0; j < secondKeys.size(); j++) {
counts[i][j] = getCount(firstKeys.get(i), secondKeys.get(j));
}
}
return counts;
} }
|
public class class_name {
public double[][] toMatrix(List<K1> firstKeys, List<K2> secondKeys) {
double[][] counts = new double[firstKeys.size()][secondKeys.size()];
for (int i = 0; i < firstKeys.size(); i++) {
for (int j = 0; j < secondKeys.size(); j++) {
counts[i][j] = getCount(firstKeys.get(i), secondKeys.get(j));
// depends on control dependency: [for], data = [j]
}
}
return counts;
} }
|
public class class_name {
public void recycle() {
try {
recycleSoundMap();
if (soundPool != null) {
soundPool.release();
soundPool = null;
}
} catch (Exception ex) {
Log.e(TAG, "", ex);
}
} }
|
public class class_name {
public void recycle() {
try {
recycleSoundMap(); // depends on control dependency: [try], data = [none]
if (soundPool != null) {
soundPool.release(); // depends on control dependency: [if], data = [none]
soundPool = null; // depends on control dependency: [if], data = [none]
}
} catch (Exception ex) {
Log.e(TAG, "", ex);
} // depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
private boolean escape(final Map<String, Object> _map)
{
boolean ret = true;
if (_map.containsKey(EFapsKey.PICKER_DEACTIVATEESCAPE.getKey())) {
final Object value = _map.get(EFapsKey.PICKER_DEACTIVATEESCAPE.getKey());
if (value == null) {
ret = false;
} else {
ret = BooleanUtils.toBoolean(EFapsKey.PICKER_DEACTIVATEESCAPE.getKey());
}
}
return ret;
} }
|
public class class_name {
private boolean escape(final Map<String, Object> _map)
{
boolean ret = true;
if (_map.containsKey(EFapsKey.PICKER_DEACTIVATEESCAPE.getKey())) {
final Object value = _map.get(EFapsKey.PICKER_DEACTIVATEESCAPE.getKey());
if (value == null) {
ret = false; // depends on control dependency: [if], data = [none]
} else {
ret = BooleanUtils.toBoolean(EFapsKey.PICKER_DEACTIVATEESCAPE.getKey()); // depends on control dependency: [if], data = [none]
}
}
return ret;
} }
|
public class class_name {
protected void startReclaimConnectionThread() {
if (tc.isEntryEnabled()) {
Tr.entry(this, tc, "startReclaimConnectionThread");
}
//long reapTime;
synchronized (taskTimerLockObject) {
if (!reaperThreadStarted) {
if (reapTime > 0) {
if ((this.unusedTimeout > 0)
|| (this.agedTimeout > 0)) {
final PoolManager tempPM = this;
reaperThreadStarted = true;
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
new TaskTimer(tempPM);
return null;
}
});
if (tc.isDebugEnabled()) {
Tr.debug(this, tc, "Started reclaim connection thread for pool " + gConfigProps.getXpathId());
}
}
}
}
}
if (tc.isEntryEnabled()) {
Tr.exit(this, tc, "startReclaimConnectionThread");
}
} }
|
public class class_name {
protected void startReclaimConnectionThread() {
if (tc.isEntryEnabled()) {
Tr.entry(this, tc, "startReclaimConnectionThread"); // depends on control dependency: [if], data = [none]
}
//long reapTime;
synchronized (taskTimerLockObject) {
if (!reaperThreadStarted) {
if (reapTime > 0) {
if ((this.unusedTimeout > 0)
|| (this.agedTimeout > 0)) {
final PoolManager tempPM = this;
reaperThreadStarted = true; // depends on control dependency: [if], data = [none]
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
new TaskTimer(tempPM);
return null;
}
}); // depends on control dependency: [if], data = [none]
if (tc.isDebugEnabled()) {
Tr.debug(this, tc, "Started reclaim connection thread for pool " + gConfigProps.getXpathId()); // depends on control dependency: [if], data = [none]
}
}
}
}
}
if (tc.isEntryEnabled()) {
Tr.exit(this, tc, "startReclaimConnectionThread"); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
private void checkAccess(List<Operation> operations, QueryContext queryContext) {
for (Operation operation : operations) {
checkAccess(operation, queryContext);
}
} }
|
public class class_name {
private void checkAccess(List<Operation> operations, QueryContext queryContext) {
for (Operation operation : operations) {
checkAccess(operation, queryContext); // depends on control dependency: [for], data = [operation]
}
} }
|
public class class_name {
protected List<CmsUser> getNotificationMailRecipients() {
String group = getWorkflowProjectManagerGroup();
CmsObject cms = m_adminCms;
try {
List<CmsUser> users = cms.getUsersOfGroup(group);
return users;
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
return new ArrayList<CmsUser>();
}
} }
|
public class class_name {
protected List<CmsUser> getNotificationMailRecipients() {
String group = getWorkflowProjectManagerGroup();
CmsObject cms = m_adminCms;
try {
List<CmsUser> users = cms.getUsersOfGroup(group);
return users;
// depends on control dependency: [try], data = [none]
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
return new ArrayList<CmsUser>();
}
// depends on control dependency: [catch], data = [none]
} }
|
public class class_name {
public GitlabHTTPRequestor with(String key, Object value) {
if (value != null && key != null) {
data.put(key, value);
}
return this;
} }
|
public class class_name {
public GitlabHTTPRequestor with(String key, Object value) {
if (value != null && key != null) {
data.put(key, value); // depends on control dependency: [if], data = [none]
}
return this;
} }
|
public class class_name {
public static <T, A, R extends Collection<A>> R collect(
Iterable<T> iterable,
Function<? super T, ? extends A> function,
R targetCollection)
{
if (iterable instanceof RichIterable)
{
return ((RichIterable<T>) iterable).collect(function, targetCollection);
}
if (iterable instanceof ArrayList)
{
return ArrayListIterate.collect((ArrayList<T>) iterable, function, targetCollection);
}
if (iterable instanceof RandomAccess)
{
return RandomAccessListIterate.collect((List<T>) iterable, function, targetCollection);
}
if (iterable != null)
{
return IterableIterate.collect(iterable, function, targetCollection);
}
throw new IllegalArgumentException("Cannot perform a collect on null");
} }
|
public class class_name {
public static <T, A, R extends Collection<A>> R collect(
Iterable<T> iterable,
Function<? super T, ? extends A> function,
R targetCollection)
{
if (iterable instanceof RichIterable)
{
return ((RichIterable<T>) iterable).collect(function, targetCollection); // depends on control dependency: [if], data = [none]
}
if (iterable instanceof ArrayList)
{
return ArrayListIterate.collect((ArrayList<T>) iterable, function, targetCollection); // depends on control dependency: [if], data = [none]
}
if (iterable instanceof RandomAccess)
{
return RandomAccessListIterate.collect((List<T>) iterable, function, targetCollection); // depends on control dependency: [if], data = [none]
}
if (iterable != null)
{
return IterableIterate.collect(iterable, function, targetCollection); // depends on control dependency: [if], data = [(iterable]
}
throw new IllegalArgumentException("Cannot perform a collect on null");
} }
|
public class class_name {
public void close() throws SQLException {
lock.lock();
try {
closed = true;
if (results != null) {
if (results.getFetchSize() != 0) {
skipMoreResults();
}
results.close();
}
protocol = null;
if (connection == null || connection.pooledConnection == null
|| connection.pooledConnection.noStmtEventListeners()) {
return;
}
connection.pooledConnection.fireStatementClosed(this);
} finally {
lock.unlock();
}
} }
|
public class class_name {
public void close() throws SQLException {
lock.lock();
try {
closed = true;
if (results != null) {
if (results.getFetchSize() != 0) {
skipMoreResults(); // depends on control dependency: [if], data = [none]
}
results.close(); // depends on control dependency: [if], data = [none]
}
protocol = null;
if (connection == null || connection.pooledConnection == null
|| connection.pooledConnection.noStmtEventListeners()) {
return; // depends on control dependency: [if], data = [none]
}
connection.pooledConnection.fireStatementClosed(this);
} finally {
lock.unlock();
}
} }
|
public class class_name {
@Deprecated
public static void writeFullModel(@NonNull Word2Vec vec, @NonNull String path) {
/*
Basically we need to save:
1. WeightLookupTable, especially syn0 and syn1 matrices
2. VocabCache, including only WordCounts
3. Settings from Word2Vect model: workers, layers, etc.
*/
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8"));
} catch (Exception e) {
throw new RuntimeException(e);
}
WeightLookupTable<VocabWord> lookupTable = vec.getLookupTable();
VocabCache<VocabWord> vocabCache = vec.getVocab(); // ((InMemoryLookupTable) lookupTable).getVocab(); //vec.getVocab();
if (!(lookupTable instanceof InMemoryLookupTable))
throw new IllegalStateException("At this moment only InMemoryLookupTable is supported.");
VectorsConfiguration conf = vec.getConfiguration();
conf.setVocabSize(vocabCache.numWords());
printWriter.println(conf.toJson());
//log.info("Word2Vec conf. JSON: " + conf.toJson());
/*
We have the following map:
Line 0 - VectorsConfiguration JSON string
Line 1 - expTable
Line 2 - table
All following lines are vocab/weight lookup table saved line by line as VocabularyWord JSON representation
*/
// actually we don't need expTable, since it produces exact results on subsequent runs untill you dont modify expTable size :)
// saving ExpTable just for "special case in future"
StringBuilder builder = new StringBuilder();
for (int x = 0; x < ((InMemoryLookupTable) lookupTable).getExpTable().length; x++) {
builder.append(((InMemoryLookupTable) lookupTable).getExpTable()[x]).append(" ");
}
printWriter.println(builder.toString().trim());
// saving table, available only if negative sampling is used
if (conf.getNegative() > 0 && ((InMemoryLookupTable) lookupTable).getTable() != null) {
builder = new StringBuilder();
for (int x = 0; x < ((InMemoryLookupTable) lookupTable).getTable().columns(); x++) {
builder.append(((InMemoryLookupTable) lookupTable).getTable().getDouble(x)).append(" ");
}
printWriter.println(builder.toString().trim());
} else
printWriter.println("");
List<VocabWord> words = new ArrayList<>(vocabCache.vocabWords());
for (SequenceElement word : words) {
VocabularyWord vw = new VocabularyWord(word.getLabel());
vw.setCount(vocabCache.wordFrequency(word.getLabel()));
vw.setHuffmanNode(VocabularyHolder.buildNode(word.getCodes(), word.getPoints(), word.getCodeLength(),
word.getIndex()));
// writing down syn0
INDArray syn0 = ((InMemoryLookupTable) lookupTable).getSyn0().getRow(vocabCache.indexOf(word.getLabel()));
double[] dsyn0 = new double[syn0.columns()];
for (int x = 0; x < conf.getLayersSize(); x++) {
dsyn0[x] = syn0.getDouble(x);
}
vw.setSyn0(dsyn0);
// writing down syn1
INDArray syn1 = ((InMemoryLookupTable) lookupTable).getSyn1().getRow(vocabCache.indexOf(word.getLabel()));
double[] dsyn1 = new double[syn1.columns()];
for (int x = 0; x < syn1.columns(); x++) {
dsyn1[x] = syn1.getDouble(x);
}
vw.setSyn1(dsyn1);
// writing down syn1Neg, if negative sampling is used
if (conf.getNegative() > 0 && ((InMemoryLookupTable) lookupTable).getSyn1Neg() != null) {
INDArray syn1Neg = ((InMemoryLookupTable) lookupTable).getSyn1Neg()
.getRow(vocabCache.indexOf(word.getLabel()));
double[] dsyn1Neg = new double[syn1Neg.columns()];
for (int x = 0; x < syn1Neg.columns(); x++) {
dsyn1Neg[x] = syn1Neg.getDouble(x);
}
vw.setSyn1Neg(dsyn1Neg);
}
// in case of UseAdaGrad == true - we should save gradients for each word in vocab
if (conf.isUseAdaGrad() && ((InMemoryLookupTable) lookupTable).isUseAdaGrad()) {
INDArray gradient = word.getHistoricalGradient();
if (gradient == null)
gradient = Nd4j.zeros(word.getCodes().size());
double ada[] = new double[gradient.columns()];
for (int x = 0; x < gradient.columns(); x++) {
ada[x] = gradient.getDouble(x);
}
vw.setHistoricalGradient(ada);
}
printWriter.println(vw.toJson());
}
// at this moment we have whole vocab serialized
printWriter.flush();
printWriter.close();
} }
|
public class class_name {
@Deprecated
public static void writeFullModel(@NonNull Word2Vec vec, @NonNull String path) {
/*
Basically we need to save:
1. WeightLookupTable, especially syn0 and syn1 matrices
2. VocabCache, including only WordCounts
3. Settings from Word2Vect model: workers, layers, etc.
*/
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8")); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new RuntimeException(e);
} // depends on control dependency: [catch], data = [none]
WeightLookupTable<VocabWord> lookupTable = vec.getLookupTable();
VocabCache<VocabWord> vocabCache = vec.getVocab(); // ((InMemoryLookupTable) lookupTable).getVocab(); //vec.getVocab();
if (!(lookupTable instanceof InMemoryLookupTable))
throw new IllegalStateException("At this moment only InMemoryLookupTable is supported.");
VectorsConfiguration conf = vec.getConfiguration();
conf.setVocabSize(vocabCache.numWords());
printWriter.println(conf.toJson());
//log.info("Word2Vec conf. JSON: " + conf.toJson());
/*
We have the following map:
Line 0 - VectorsConfiguration JSON string
Line 1 - expTable
Line 2 - table
All following lines are vocab/weight lookup table saved line by line as VocabularyWord JSON representation
*/
// actually we don't need expTable, since it produces exact results on subsequent runs untill you dont modify expTable size :)
// saving ExpTable just for "special case in future"
StringBuilder builder = new StringBuilder();
for (int x = 0; x < ((InMemoryLookupTable) lookupTable).getExpTable().length; x++) {
builder.append(((InMemoryLookupTable) lookupTable).getExpTable()[x]).append(" "); // depends on control dependency: [for], data = [x]
}
printWriter.println(builder.toString().trim());
// saving table, available only if negative sampling is used
if (conf.getNegative() > 0 && ((InMemoryLookupTable) lookupTable).getTable() != null) {
builder = new StringBuilder(); // depends on control dependency: [if], data = [none]
for (int x = 0; x < ((InMemoryLookupTable) lookupTable).getTable().columns(); x++) {
builder.append(((InMemoryLookupTable) lookupTable).getTable().getDouble(x)).append(" "); // depends on control dependency: [for], data = [x]
}
printWriter.println(builder.toString().trim()); // depends on control dependency: [if], data = [none]
} else
printWriter.println("");
List<VocabWord> words = new ArrayList<>(vocabCache.vocabWords());
for (SequenceElement word : words) {
VocabularyWord vw = new VocabularyWord(word.getLabel());
vw.setCount(vocabCache.wordFrequency(word.getLabel())); // depends on control dependency: [for], data = [word]
vw.setHuffmanNode(VocabularyHolder.buildNode(word.getCodes(), word.getPoints(), word.getCodeLength(),
word.getIndex())); // depends on control dependency: [for], data = [none]
// writing down syn0
INDArray syn0 = ((InMemoryLookupTable) lookupTable).getSyn0().getRow(vocabCache.indexOf(word.getLabel()));
double[] dsyn0 = new double[syn0.columns()];
for (int x = 0; x < conf.getLayersSize(); x++) {
dsyn0[x] = syn0.getDouble(x); // depends on control dependency: [for], data = [x]
}
vw.setSyn0(dsyn0); // depends on control dependency: [for], data = [none]
// writing down syn1
INDArray syn1 = ((InMemoryLookupTable) lookupTable).getSyn1().getRow(vocabCache.indexOf(word.getLabel()));
double[] dsyn1 = new double[syn1.columns()];
for (int x = 0; x < syn1.columns(); x++) {
dsyn1[x] = syn1.getDouble(x); // depends on control dependency: [for], data = [x]
}
vw.setSyn1(dsyn1); // depends on control dependency: [for], data = [none]
// writing down syn1Neg, if negative sampling is used
if (conf.getNegative() > 0 && ((InMemoryLookupTable) lookupTable).getSyn1Neg() != null) {
INDArray syn1Neg = ((InMemoryLookupTable) lookupTable).getSyn1Neg()
.getRow(vocabCache.indexOf(word.getLabel()));
double[] dsyn1Neg = new double[syn1Neg.columns()];
for (int x = 0; x < syn1Neg.columns(); x++) {
dsyn1Neg[x] = syn1Neg.getDouble(x); // depends on control dependency: [for], data = [x]
}
vw.setSyn1Neg(dsyn1Neg); // depends on control dependency: [if], data = [none]
}
// in case of UseAdaGrad == true - we should save gradients for each word in vocab
if (conf.isUseAdaGrad() && ((InMemoryLookupTable) lookupTable).isUseAdaGrad()) {
INDArray gradient = word.getHistoricalGradient();
if (gradient == null)
gradient = Nd4j.zeros(word.getCodes().size());
double ada[] = new double[gradient.columns()];
for (int x = 0; x < gradient.columns(); x++) {
ada[x] = gradient.getDouble(x); // depends on control dependency: [for], data = [x]
}
vw.setHistoricalGradient(ada); // depends on control dependency: [if], data = [none]
}
printWriter.println(vw.toJson()); // depends on control dependency: [for], data = [none]
}
// at this moment we have whole vocab serialized
printWriter.flush();
printWriter.close();
} }
|
public class class_name {
public double linearInterpolateY( double xValue ) {
double first = xList[0];
double last = xList[xList.length - 1];
// check out of range
if (first <= last) {
if (xValue < xList[0] || xValue > xList[xList.length - 1]) {
return Double.NaN;
}
isInverse = false;
} else {
// inverse proportional
if (xValue > xList[0] || xValue < xList[xList.length - 1]) {
return Double.NaN;
}
isInverse = true;
}
for( int i = 0; i < xList.length; i++ ) {
double x2 = xList[i];
// if equal to a number in the array
if (NumericsUtilities.dEq(x2, xValue)) {
return yList[i];
}// else interpolate
else if ((!isInverse && x2 > xValue) || (isInverse && x2 < xValue)) {
double x1 = xList[i - 1];
double y1 = yList[i - 1];
double y2 = yList[i];
double y = (y2 - y1) * (xValue - x1) / (x2 - x1) + y1;
return y;
}
}
return Double.NaN;
} }
|
public class class_name {
public double linearInterpolateY( double xValue ) {
double first = xList[0];
double last = xList[xList.length - 1];
// check out of range
if (first <= last) {
if (xValue < xList[0] || xValue > xList[xList.length - 1]) {
return Double.NaN; // depends on control dependency: [if], data = [none]
}
isInverse = false; // depends on control dependency: [if], data = [none]
} else {
// inverse proportional
if (xValue > xList[0] || xValue < xList[xList.length - 1]) {
return Double.NaN; // depends on control dependency: [if], data = [none]
}
isInverse = true; // depends on control dependency: [if], data = [none]
}
for( int i = 0; i < xList.length; i++ ) {
double x2 = xList[i];
// if equal to a number in the array
if (NumericsUtilities.dEq(x2, xValue)) {
return yList[i]; // depends on control dependency: [if], data = [none]
}// else interpolate
else if ((!isInverse && x2 > xValue) || (isInverse && x2 < xValue)) {
double x1 = xList[i - 1];
double y1 = yList[i - 1];
double y2 = yList[i];
double y = (y2 - y1) * (xValue - x1) / (x2 - x1) + y1;
return y; // depends on control dependency: [if], data = [none]
}
}
return Double.NaN;
} }
|
public class class_name {
public void marshall(DirectoryVpcSettingsDescription directoryVpcSettingsDescription, ProtocolMarshaller protocolMarshaller) {
if (directoryVpcSettingsDescription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(directoryVpcSettingsDescription.getVpcId(), VPCID_BINDING);
protocolMarshaller.marshall(directoryVpcSettingsDescription.getSubnetIds(), SUBNETIDS_BINDING);
protocolMarshaller.marshall(directoryVpcSettingsDescription.getSecurityGroupId(), SECURITYGROUPID_BINDING);
protocolMarshaller.marshall(directoryVpcSettingsDescription.getAvailabilityZones(), AVAILABILITYZONES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} }
|
public class class_name {
public void marshall(DirectoryVpcSettingsDescription directoryVpcSettingsDescription, ProtocolMarshaller protocolMarshaller) {
if (directoryVpcSettingsDescription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(directoryVpcSettingsDescription.getVpcId(), VPCID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(directoryVpcSettingsDescription.getSubnetIds(), SUBNETIDS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(directoryVpcSettingsDescription.getSecurityGroupId(), SECURITYGROUPID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(directoryVpcSettingsDescription.getAvailabilityZones(), AVAILABILITYZONES_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 {
protected String getTitle() {
if (!StringUtils.hasText(this.title)) {
if (StringUtils.hasText(getCallingCommandText()))
return getCallingCommandText();
return DEFAULT_DIALOG_TITLE;
}
return this.title;
} }
|
public class class_name {
protected String getTitle() {
if (!StringUtils.hasText(this.title)) {
if (StringUtils.hasText(getCallingCommandText()))
return getCallingCommandText();
return DEFAULT_DIALOG_TITLE; // depends on control dependency: [if], data = [none]
}
return this.title;
} }
|
public class class_name {
private long heartbeatTime() {
int quorumIndex = quorumIndex();
if (quorumIndex >= 0) {
return context.getClusterState().getActiveMemberStates((m1, m2)-> Long.compare(m2.getHeartbeatTime(), m1.getHeartbeatTime())).get(quorumIndex).getHeartbeatTime();
}
return System.currentTimeMillis();
} }
|
public class class_name {
private long heartbeatTime() {
int quorumIndex = quorumIndex();
if (quorumIndex >= 0) {
return context.getClusterState().getActiveMemberStates((m1, m2)-> Long.compare(m2.getHeartbeatTime(), m1.getHeartbeatTime())).get(quorumIndex).getHeartbeatTime(); // depends on control dependency: [if], data = [(quorumIndex]
}
return System.currentTimeMillis();
} }
|
public class class_name {
public static StepIntersection findCurrentIntersection(@NonNull List<StepIntersection> intersections,
@NonNull List<Pair<StepIntersection, Double>> measuredIntersections,
double stepDistanceTraveled) {
for (Pair<StepIntersection, Double> measuredIntersection : measuredIntersections) {
double intersectionDistance = measuredIntersection.second;
int intersectionIndex = measuredIntersections.indexOf(measuredIntersection);
int nextIntersectionIndex = intersectionIndex + ONE_INDEX;
int measuredIntersectionSize = measuredIntersections.size();
boolean hasValidNextIntersection = nextIntersectionIndex < measuredIntersectionSize;
if (hasValidNextIntersection) {
double nextIntersectionDistance = measuredIntersections.get(nextIntersectionIndex).second;
if (stepDistanceTraveled > intersectionDistance && stepDistanceTraveled < nextIntersectionDistance) {
return measuredIntersection.first;
}
} else if (stepDistanceTraveled > measuredIntersection.second) {
return measuredIntersection.first;
} else {
return measuredIntersections.get(FIRST_INTERSECTION).first;
}
}
return intersections.get(FIRST_INTERSECTION);
} }
|
public class class_name {
public static StepIntersection findCurrentIntersection(@NonNull List<StepIntersection> intersections,
@NonNull List<Pair<StepIntersection, Double>> measuredIntersections,
double stepDistanceTraveled) {
for (Pair<StepIntersection, Double> measuredIntersection : measuredIntersections) {
double intersectionDistance = measuredIntersection.second;
int intersectionIndex = measuredIntersections.indexOf(measuredIntersection);
int nextIntersectionIndex = intersectionIndex + ONE_INDEX;
int measuredIntersectionSize = measuredIntersections.size();
boolean hasValidNextIntersection = nextIntersectionIndex < measuredIntersectionSize;
if (hasValidNextIntersection) {
double nextIntersectionDistance = measuredIntersections.get(nextIntersectionIndex).second;
if (stepDistanceTraveled > intersectionDistance && stepDistanceTraveled < nextIntersectionDistance) {
return measuredIntersection.first; // depends on control dependency: [if], data = [none]
}
} else if (stepDistanceTraveled > measuredIntersection.second) {
return measuredIntersection.first; // depends on control dependency: [if], data = [none]
} else {
return measuredIntersections.get(FIRST_INTERSECTION).first; // depends on control dependency: [if], data = [none]
}
}
return intersections.get(FIRST_INTERSECTION);
} }
|
public class class_name {
@Override
public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
if (anyRequestMatcher.matches(request) && !ajaxRequestMatcher.matches(request)) {
DefaultSavedRequest savedRequest = new DefaultSavedRequest(request, portResolver);
HttpUtils.setStateParam(Config.RETURNTO_COOKIE,
Utils.base64enc(savedRequest.getRedirectUrl().getBytes()), request, response);
}
} }
|
public class class_name {
@Override
public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
if (anyRequestMatcher.matches(request) && !ajaxRequestMatcher.matches(request)) {
DefaultSavedRequest savedRequest = new DefaultSavedRequest(request, portResolver);
HttpUtils.setStateParam(Config.RETURNTO_COOKIE,
Utils.base64enc(savedRequest.getRedirectUrl().getBytes()), request, response); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public DoConcat CREATE(IElement... X) {
for (int i = 0; i < X.length;i++) {
PatternExpression clause = XFactory.getExpression(X[i]);
clause.setClauseType(ClauseType.CREATE);
addClause(clause);
}
return createConcat();
} }
|
public class class_name {
public DoConcat CREATE(IElement... X) {
for (int i = 0; i < X.length;i++) {
PatternExpression clause = XFactory.getExpression(X[i]);
clause.setClauseType(ClauseType.CREATE); // depends on control dependency: [for], data = [none]
addClause(clause); // depends on control dependency: [for], data = [none]
}
return createConcat();
} }
|
public class class_name {
@Trivial
private boolean isStringValueUndefined(Object str) {
if (str instanceof SerializableProtectedString) {
// Avoid constructing a String from a ProtectedString
char[] contents = ((SerializableProtectedString) str).getChars();
for (char ch : contents)
if (ch > '\u0020')
return false; // See the description of String.trim()
return true;
} else {
return (str == null || ((String) str).trim().isEmpty());
}
} }
|
public class class_name {
@Trivial
private boolean isStringValueUndefined(Object str) {
if (str instanceof SerializableProtectedString) {
// Avoid constructing a String from a ProtectedString
char[] contents = ((SerializableProtectedString) str).getChars();
for (char ch : contents)
if (ch > '\u0020')
return false; // See the description of String.trim()
return true; // depends on control dependency: [if], data = [none]
} else {
return (str == null || ((String) str).trim().isEmpty()); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public Object read() {
preRead();
String curData = null;
try {
curData = reader.readLine();
} catch (IOException e1) {
logger.error(curData, e1);
}
indexInCsv++;
if (null == curData) {
return null;
} else {
return Strings.split(curData, ",");
}
} }
|
public class class_name {
public Object read() {
preRead();
String curData = null;
try {
curData = reader.readLine(); // depends on control dependency: [try], data = [none]
} catch (IOException e1) {
logger.error(curData, e1);
} // depends on control dependency: [catch], data = [none]
indexInCsv++;
if (null == curData) {
return null; // depends on control dependency: [if], data = [none]
} else {
return Strings.split(curData, ","); // depends on control dependency: [if], data = [none]
}
} }
|
public class class_name {
public void pushDataToView() {
getView().dataClear();
getView().dataRowCount(dataSet.getRowCount());
List<DataColumn> columns = dataSet.getColumns();
for (int i = 0; i < columns.size(); i++) {
DataColumn dataColumn = columns.get(i);
String columnId = dataColumn.getId();
ColumnType columnType = dataColumn.getColumnType();
ColumnSettings columnSettings = displayerSettings.getColumnSettings(dataColumn);
getView().dataAddColumn(dataColumn.getColumnType(), columnId, columnSettings.getColumnName());
List columnValues = dataColumn.getValues();
for (int j = 0; j < columnValues.size(); j++) {
Object value = columnValues.get(j);
if (ColumnType.DATE.equals(columnType)) {
getView().dataSetValue(j, i, value == null ? new Date() : (Date) value);
}
else if (ColumnType.NUMBER.equals(columnType)) {
if (value == null) {
getView().dataSetValue(j, i, 0d);
} else {
String valueStr = getEvaluator().evalExpression(value.toString(), columnSettings.getValueExpression());
getView().dataSetValue(j, i, Double.parseDouble(valueStr));
}
}
else {
String valueStr = super.formatValue(j, i);
getView().dataSetValue(j, i, valueStr);
}
}
}
// Format the table values
for (int i = 0; i < dataSet.getColumns().size(); i++) {
DataColumn dataColumn = columns.get(i);
ColumnSettings columnSettings = displayerSettings.getColumnSettings(dataColumn);
String pattern = columnSettings.getValuePattern();
if (ColumnType.DATE.equals(dataColumn.getColumnType())) {
getView().dataFormatDateColumn(pattern, i);
}
else if (ColumnType.NUMBER.equals(dataColumn.getColumnType())) {
getView().dataFormatNumberColumn(pattern, i);
}
}
} }
|
public class class_name {
public void pushDataToView() {
getView().dataClear();
getView().dataRowCount(dataSet.getRowCount());
List<DataColumn> columns = dataSet.getColumns();
for (int i = 0; i < columns.size(); i++) {
DataColumn dataColumn = columns.get(i);
String columnId = dataColumn.getId();
ColumnType columnType = dataColumn.getColumnType();
ColumnSettings columnSettings = displayerSettings.getColumnSettings(dataColumn);
getView().dataAddColumn(dataColumn.getColumnType(), columnId, columnSettings.getColumnName()); // depends on control dependency: [for], data = [none]
List columnValues = dataColumn.getValues();
for (int j = 0; j < columnValues.size(); j++) {
Object value = columnValues.get(j);
if (ColumnType.DATE.equals(columnType)) {
getView().dataSetValue(j, i, value == null ? new Date() : (Date) value); // depends on control dependency: [if], data = [none]
}
else if (ColumnType.NUMBER.equals(columnType)) {
if (value == null) {
getView().dataSetValue(j, i, 0d); // depends on control dependency: [if], data = [none]
} else {
String valueStr = getEvaluator().evalExpression(value.toString(), columnSettings.getValueExpression());
getView().dataSetValue(j, i, Double.parseDouble(valueStr)); // depends on control dependency: [if], data = [(value]
}
}
else {
String valueStr = super.formatValue(j, i);
getView().dataSetValue(j, i, valueStr); // depends on control dependency: [if], data = [none]
}
}
}
// Format the table values
for (int i = 0; i < dataSet.getColumns().size(); i++) {
DataColumn dataColumn = columns.get(i);
ColumnSettings columnSettings = displayerSettings.getColumnSettings(dataColumn);
String pattern = columnSettings.getValuePattern();
if (ColumnType.DATE.equals(dataColumn.getColumnType())) {
getView().dataFormatDateColumn(pattern, i); // depends on control dependency: [if], data = [none]
}
else if (ColumnType.NUMBER.equals(dataColumn.getColumnType())) {
getView().dataFormatNumberColumn(pattern, i); // depends on control dependency: [if], data = [none]
}
}
} }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.