code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { @Nonnull public final LinkedList<A> toLinkedList() { LinkedList<A> list = new LinkedList<>(); ImmutableList<A> l = this; for (int i = 0; i < length; i++) { list.add(((NonEmptyImmutableList<A>) l).head); l = ((NonEmptyImmutableList<A>) l).tail; } return list; } }
public class class_name { @Nonnull public final LinkedList<A> toLinkedList() { LinkedList<A> list = new LinkedList<>(); ImmutableList<A> l = this; for (int i = 0; i < length; i++) { list.add(((NonEmptyImmutableList<A>) l).head); // depends on control dependency: [for], data = [none] l = ((NonEmptyImmutableList<A>) l).tail; // depends on control dependency: [for], data = [none] } return list; } }
public class class_name { private static LblTree createTree(TreeWalker walker) { Node parent = walker.getCurrentNode(); LblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1 for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) { node.add(createTree(walker)); } walker.setCurrentNode(parent); return node; } }
public class class_name { private static LblTree createTree(TreeWalker walker) { Node parent = walker.getCurrentNode(); LblTree node = new LblTree(parent.getNodeName(), -1); // treeID = -1 for (Node n = walker.firstChild(); n != null; n = walker.nextSibling()) { node.add(createTree(walker)); // depends on control dependency: [for], data = [none] } walker.setCurrentNode(parent); return node; } }
public class class_name { public static Type getReturnTypeOfInvocation(AbstractInsnNode invokeNode) { Validate.notNull(invokeNode); if (invokeNode instanceof MethodInsnNode) { MethodInsnNode methodInsnNode = (MethodInsnNode) invokeNode; Type methodType = Type.getType(methodInsnNode.desc); return methodType.getReturnType(); } else if (invokeNode instanceof InvokeDynamicInsnNode) { InvokeDynamicInsnNode invokeDynamicInsnNode = (InvokeDynamicInsnNode) invokeNode; Type methodType = Type.getType(invokeDynamicInsnNode.desc); return methodType.getReturnType(); } else { throw new IllegalArgumentException(); } } }
public class class_name { public static Type getReturnTypeOfInvocation(AbstractInsnNode invokeNode) { Validate.notNull(invokeNode); if (invokeNode instanceof MethodInsnNode) { MethodInsnNode methodInsnNode = (MethodInsnNode) invokeNode; Type methodType = Type.getType(methodInsnNode.desc); return methodType.getReturnType(); // depends on control dependency: [if], data = [none] } else if (invokeNode instanceof InvokeDynamicInsnNode) { InvokeDynamicInsnNode invokeDynamicInsnNode = (InvokeDynamicInsnNode) invokeNode; Type methodType = Type.getType(invokeDynamicInsnNode.desc); return methodType.getReturnType(); // depends on control dependency: [if], data = [none] } else { throw new IllegalArgumentException(); } } }
public class class_name { @Override public void updateBeanValue() { List<?> beanList = this.getBeanList(); WComponent renderer = getRepeatedComponent(); for (int i = 0; i < beanList.size(); i++) { Object rowData = beanList.get(i); UIContext rowContext = getRowContext(rowData, i); UIContextHolder.pushContext(rowContext); try { WebUtilities.updateBeanValue(renderer); } finally { UIContextHolder.popContext(); } } } }
public class class_name { @Override public void updateBeanValue() { List<?> beanList = this.getBeanList(); WComponent renderer = getRepeatedComponent(); for (int i = 0; i < beanList.size(); i++) { Object rowData = beanList.get(i); UIContext rowContext = getRowContext(rowData, i); UIContextHolder.pushContext(rowContext); // depends on control dependency: [for], data = [none] try { WebUtilities.updateBeanValue(renderer); // depends on control dependency: [try], data = [none] } finally { UIContextHolder.popContext(); } } } }
public class class_name { public static String replaceProperties(final String string, final Properties props) { if (string == null || string.isEmpty()) { return string; } final char[] chars = string.toCharArray(); StringBuffer buffer = new StringBuffer(); boolean properties = false; int state = NORMAL; int start = 0; for (int i = 0; i < chars.length; ++i) { char c = chars[i]; // Dollar sign outside brackets if (c == '$' && state != IN_BRACKET) { state = SEEN_DOLLAR; } // Open bracket immediatley after dollar else if (c == '{' && state == SEEN_DOLLAR) { buffer.append(string.substring(start, i - 1)); state = IN_BRACKET; start = i - 1; } // No open bracket after dollar else if (state == SEEN_DOLLAR) { state = NORMAL; } // Closed bracket after open bracket else if (c == '}' && state == IN_BRACKET) { // No content if (start + 2 == i) { buffer.append("${}"); // REVIEW: Correct? } else // Collect the system property { String value = null; String key = string.substring(start + 2, i); // check for alias if (FILE_SEPARATOR_ALIAS.equals(key)) { value = FILE_SEPARATOR; } else if (PATH_SEPARATOR_ALIAS.equals(key)) { value = PATH_SEPARATOR; } else { // check from the properties value = getReplacementString(key, props); if (value == null) { // Check for a default value ${key:default} int colon = key.indexOf(':'); if (colon > 0) { String realKey = key.substring(0, colon); value = getReplacementString(realKey, props); if (value == null) { // Check for a composite key, "key1,key2" value = resolveCompositeKey(realKey, props); // Not a composite key either, use the specified default if (value == null) { value = key.substring(colon + 1); } } } else { // No default, check for a composite key, "key1,key2" value = resolveCompositeKey(key, props); } } } if (value != null) { properties = true; buffer.append(value); } else { buffer.append("${"); buffer.append(key); buffer.append('}'); } } start = i + 1; state = NORMAL; } } // No properties if (properties == false) { return string; } // Collect the trailing characters if (start != chars.length) { buffer.append(string.substring(start, chars.length)); } // Done return buffer.toString(); } }
public class class_name { public static String replaceProperties(final String string, final Properties props) { if (string == null || string.isEmpty()) { return string; // depends on control dependency: [if], data = [none] } final char[] chars = string.toCharArray(); StringBuffer buffer = new StringBuffer(); boolean properties = false; int state = NORMAL; int start = 0; for (int i = 0; i < chars.length; ++i) { char c = chars[i]; // Dollar sign outside brackets if (c == '$' && state != IN_BRACKET) { state = SEEN_DOLLAR; // depends on control dependency: [if], data = [none] } // Open bracket immediatley after dollar else if (c == '{' && state == SEEN_DOLLAR) { buffer.append(string.substring(start, i - 1)); // depends on control dependency: [if], data = [none] state = IN_BRACKET; // depends on control dependency: [if], data = [none] start = i - 1; // depends on control dependency: [if], data = [none] } // No open bracket after dollar else if (state == SEEN_DOLLAR) { state = NORMAL; // depends on control dependency: [if], data = [none] } // Closed bracket after open bracket else if (c == '}' && state == IN_BRACKET) { // No content if (start + 2 == i) { buffer.append("${}"); // REVIEW: Correct? // depends on control dependency: [if], data = [none] } else // Collect the system property { String value = null; String key = string.substring(start + 2, i); // check for alias if (FILE_SEPARATOR_ALIAS.equals(key)) { value = FILE_SEPARATOR; // depends on control dependency: [if], data = [none] } else if (PATH_SEPARATOR_ALIAS.equals(key)) { value = PATH_SEPARATOR; // depends on control dependency: [if], data = [none] } else { // check from the properties value = getReplacementString(key, props); // depends on control dependency: [if], data = [none] if (value == null) { // Check for a default value ${key:default} int colon = key.indexOf(':'); if (colon > 0) { String realKey = key.substring(0, colon); value = getReplacementString(realKey, props); // depends on control dependency: [if], data = [none] if (value == null) { // Check for a composite key, "key1,key2" value = resolveCompositeKey(realKey, props); // depends on control dependency: [if], data = [none] // Not a composite key either, use the specified default if (value == null) { value = key.substring(colon + 1); // depends on control dependency: [if], data = [none] } } } else { // No default, check for a composite key, "key1,key2" value = resolveCompositeKey(key, props); // depends on control dependency: [if], data = [none] } } } if (value != null) { properties = true; // depends on control dependency: [if], data = [none] buffer.append(value); // depends on control dependency: [if], data = [(value] } else { buffer.append("${"); // depends on control dependency: [if], data = [none] buffer.append(key); // depends on control dependency: [if], data = [none] buffer.append('}'); // depends on control dependency: [if], data = [none] } } start = i + 1; // depends on control dependency: [if], data = [none] state = NORMAL; // depends on control dependency: [if], data = [none] } } // No properties if (properties == false) { return string; // depends on control dependency: [if], data = [none] } // Collect the trailing characters if (start != chars.length) { buffer.append(string.substring(start, chars.length)); // depends on control dependency: [if], data = [(start] } // Done return buffer.toString(); } }
public class class_name { @Override public void init(ServletConfig config) throws ServletException { super.init(config); try { if (!validateConfiguration()) { LOG.error("Rpc configuration has some problems, so interrupt initialization process, please figure out."); return; } ApplicationContext factory = WebApplicationContextUtils.getWebApplicationContext(config .getServletContext()); if (factory == null) { LOG.error("That is fatal! No spring factory found in container, which prevent servlet initialization from executing!"); return; } // 注册XML方式暴露的bean Map<String, NaviRpcExporter> xmlBeans = factory.getBeansOfType(NaviRpcExporter.class); if (xmlBeans == null || xmlBeans.isEmpty()) { LOG.warn("No navi rpc service found with XML configured."); } else { for (NaviRpcExporter bean : xmlBeans.values()) { serviceLocator.regiserService(bean); } } // 注册注解方式暴露的bean Map<String, Object> annoBeans = factory.getBeansWithAnnotation(NaviRpcService.class); if (annoBeans == null || annoBeans.isEmpty()) { LOG.warn("No navi rpc service found with annotation configured."); } else { for (Object bean : annoBeans.values()) { NaviRpcService anno = bean.getClass().getAnnotation(NaviRpcService.class); Class<?> targetClass = bean.getClass(); if (anno == null) { targetClass = AopUtils.getTargetClass(bean); anno = targetClass.getAnnotation(NaviRpcService.class); if (anno == null) { continue; } if (anno.serviceInterface() == null) { LOG.error("Rpc service interface not configured for " + targetClass.getName()); continue; } } serviceLocator.regiserService(new NaviRpcExporter(anno.serviceInterface() .getName(), bean)); } } // 发布服务 serviceLocator.publishService(publishHandler); LOG.info("Please visit http://" + IPUtils.getLocalHostAddress() + ":${port}" + NaviCommonConstant.TRANSPORT_URL_BASE_PATH + " for details"); } catch (Exception e) { LOG.error("Initialize rpc bean failed, " + e.toString(), e); } } }
public class class_name { @Override public void init(ServletConfig config) throws ServletException { super.init(config); try { if (!validateConfiguration()) { LOG.error("Rpc configuration has some problems, so interrupt initialization process, please figure out."); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } ApplicationContext factory = WebApplicationContextUtils.getWebApplicationContext(config .getServletContext()); if (factory == null) { LOG.error("That is fatal! No spring factory found in container, which prevent servlet initialization from executing!"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // 注册XML方式暴露的bean Map<String, NaviRpcExporter> xmlBeans = factory.getBeansOfType(NaviRpcExporter.class); if (xmlBeans == null || xmlBeans.isEmpty()) { LOG.warn("No navi rpc service found with XML configured."); // depends on control dependency: [if], data = [none] } else { for (NaviRpcExporter bean : xmlBeans.values()) { serviceLocator.regiserService(bean); // depends on control dependency: [for], data = [bean] } } // 注册注解方式暴露的bean Map<String, Object> annoBeans = factory.getBeansWithAnnotation(NaviRpcService.class); if (annoBeans == null || annoBeans.isEmpty()) { LOG.warn("No navi rpc service found with annotation configured."); // depends on control dependency: [if], data = [none] } else { for (Object bean : annoBeans.values()) { NaviRpcService anno = bean.getClass().getAnnotation(NaviRpcService.class); Class<?> targetClass = bean.getClass(); if (anno == null) { targetClass = AopUtils.getTargetClass(bean); // depends on control dependency: [if], data = [none] anno = targetClass.getAnnotation(NaviRpcService.class); // depends on control dependency: [if], data = [none] if (anno == null) { continue; } if (anno.serviceInterface() == null) { LOG.error("Rpc service interface not configured for " + targetClass.getName()); // depends on control dependency: [if], data = [none] continue; } } serviceLocator.regiserService(new NaviRpcExporter(anno.serviceInterface() .getName(), bean)); // depends on control dependency: [for], data = [none] } } // 发布服务 serviceLocator.publishService(publishHandler); LOG.info("Please visit http://" + IPUtils.getLocalHostAddress() + ":${port}" + NaviCommonConstant.TRANSPORT_URL_BASE_PATH + " for details"); } catch (Exception e) { LOG.error("Initialize rpc bean failed, " + e.toString(), e); } } }
public class class_name { public <T> T shallowClone(final T o) { if (o == null) { return null; } if (!this.cloningEnabled) { return o; } try { return cloneInternal(o, null); } catch (final IllegalAccessException e) { throw new RuntimeException("error during cloning of " + o, e); } } }
public class class_name { public <T> T shallowClone(final T o) { if (o == null) { return null; // depends on control dependency: [if], data = [none] } if (!this.cloningEnabled) { return o; // depends on control dependency: [if], data = [none] } try { return cloneInternal(o, null); // depends on control dependency: [try], data = [none] } catch (final IllegalAccessException e) { throw new RuntimeException("error during cloning of " + o, e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void marshall(DescribeEnvironmentMembershipsRequest describeEnvironmentMembershipsRequest, ProtocolMarshaller protocolMarshaller) { if (describeEnvironmentMembershipsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getUserArn(), USERARN_BINDING); protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getEnvironmentId(), ENVIRONMENTID_BINDING); protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getPermissions(), PERMISSIONS_BINDING); protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getNextToken(), NEXTTOKEN_BINDING); protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getMaxResults(), MAXRESULTS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DescribeEnvironmentMembershipsRequest describeEnvironmentMembershipsRequest, ProtocolMarshaller protocolMarshaller) { if (describeEnvironmentMembershipsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getUserArn(), USERARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getEnvironmentId(), ENVIRONMENTID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getPermissions(), PERMISSIONS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getMaxResults(), MAXRESULTS_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 { void removeEdgeRole(EdgeRole er, boolean preserveData) { if (er.getVertexLabel() != this) { throw new IllegalStateException("Trying to remove a EdgeRole from a non owner VertexLabel"); } Collection<VertexLabel> ers; switch (er.getDirection()) { // we don't support both case BOTH: throw new IllegalStateException("BOTH is not a supported direction"); case IN: ers = er.getEdgeLabel().getInVertexLabels(); break; case OUT: ers = er.getEdgeLabel().getOutVertexLabels(); break; default: throw new IllegalStateException("Unknown direction!"); } if (!ers.contains(this)) { throw new IllegalStateException("Trying to remove a EdgeRole from a non owner VertexLabel"); } // the edge had only this vertex on that direction, remove the edge if (ers.size() == 1) { er.getEdgeLabel().remove(preserveData); } else { getSchema().getTopology().lock(); switch (er.getDirection()) { // we don't support both case BOTH: throw new IllegalStateException("BOTH is not a supported direction"); case IN: uncommittedRemovedInEdgeLabels.put(er.getEdgeLabel().getFullName(), EdgeRemoveType.ROLE); er.getEdgeLabel().removeInVertexLabel(this, preserveData); break; case OUT: uncommittedRemovedOutEdgeLabels.put(er.getEdgeLabel().getFullName(), EdgeRemoveType.ROLE); er.getEdgeLabel().removeOutVertexLabel(this, preserveData); break; } this.getSchema().getTopology().fire(er, "", TopologyChangeAction.DELETE); } } }
public class class_name { void removeEdgeRole(EdgeRole er, boolean preserveData) { if (er.getVertexLabel() != this) { throw new IllegalStateException("Trying to remove a EdgeRole from a non owner VertexLabel"); } Collection<VertexLabel> ers; switch (er.getDirection()) { // we don't support both case BOTH: throw new IllegalStateException("BOTH is not a supported direction"); case IN: ers = er.getEdgeLabel().getInVertexLabels(); break; case OUT: ers = er.getEdgeLabel().getOutVertexLabels(); break; default: throw new IllegalStateException("Unknown direction!"); } if (!ers.contains(this)) { throw new IllegalStateException("Trying to remove a EdgeRole from a non owner VertexLabel"); } // the edge had only this vertex on that direction, remove the edge if (ers.size() == 1) { er.getEdgeLabel().remove(preserveData); // depends on control dependency: [if], data = [none] } else { getSchema().getTopology().lock(); // depends on control dependency: [if], data = [none] switch (er.getDirection()) { // depends on control dependency: [if], data = [none] // we don't support both case BOTH: throw new IllegalStateException("BOTH is not a supported direction"); case IN: uncommittedRemovedInEdgeLabels.put(er.getEdgeLabel().getFullName(), EdgeRemoveType.ROLE); er.getEdgeLabel().removeInVertexLabel(this, preserveData); break; case OUT: uncommittedRemovedOutEdgeLabels.put(er.getEdgeLabel().getFullName(), EdgeRemoveType.ROLE); er.getEdgeLabel().removeOutVertexLabel(this, preserveData); break; } this.getSchema().getTopology().fire(er, "", TopologyChangeAction.DELETE); // depends on control dependency: [if], data = [none] } } }
public class class_name { public String toDistributionString(int treshold) { Counter<Double> weightCounts = new ClassicCounter<Double>(); StringBuilder s = new StringBuilder(); s.append("Total number of weights: ").append(totalSize()); for (int f = 0; f < weights.length; f++) { for (int l = 0; l < weights[f].length; l++) { weightCounts.incrementCount(weights[f][l]); } } s.append("Counts of weights\n"); Set<Double> keys = Counters.keysAbove(weightCounts, treshold); s.append(keys.size()).append(" keys occur more than ").append(treshold).append(" times "); return s.toString(); } }
public class class_name { public String toDistributionString(int treshold) { Counter<Double> weightCounts = new ClassicCounter<Double>(); StringBuilder s = new StringBuilder(); s.append("Total number of weights: ").append(totalSize()); for (int f = 0; f < weights.length; f++) { for (int l = 0; l < weights[f].length; l++) { weightCounts.incrementCount(weights[f][l]); // depends on control dependency: [for], data = [l] } } s.append("Counts of weights\n"); Set<Double> keys = Counters.keysAbove(weightCounts, treshold); s.append(keys.size()).append(" keys occur more than ").append(treshold).append(" times "); return s.toString(); } }
public class class_name { public void setMessage(String message) { this.message = message; if (errorMessage == null) { logger.debug("Setting status bar message to \"" + message + "\""); messageLabel.setText(this.message); } } }
public class class_name { public void setMessage(String message) { this.message = message; if (errorMessage == null) { logger.debug("Setting status bar message to \"" + message + "\""); // depends on control dependency: [if], data = [none] messageLabel.setText(this.message); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public T addAsResources(Package resourcePackage, String... resourceNames) throws IllegalArgumentException { Validate.notNull(resourcePackage, "ResourcePackage must be specified"); Validate.notNullAndNoNullValues(resourceNames, "ResourceNames must be specified and can not container null values"); for (String resourceName : resourceNames) { addAsResource(resourcePackage, resourceName); } return covarientReturn(); } }
public class class_name { @Override public T addAsResources(Package resourcePackage, String... resourceNames) throws IllegalArgumentException { Validate.notNull(resourcePackage, "ResourcePackage must be specified"); Validate.notNullAndNoNullValues(resourceNames, "ResourceNames must be specified and can not container null values"); for (String resourceName : resourceNames) { addAsResource(resourcePackage, resourceName); // depends on control dependency: [for], data = [resourceName] } return covarientReturn(); } }
public class class_name { public boolean remove(Object o) { if (o != null) { Node<E> next, pred = null; for (Node<E> p = first(); p != null; pred = p, p = next) { boolean removed = false; E item = p.item; if (item != null) { if (!o.equals(item)) { next = succ(p); continue; } removed = casItem(p, item, null); } next = succ(p); if (pred != null && next != null) // unlink casNext(pred, p, next); if (removed) return true; } } return false; } }
public class class_name { public boolean remove(Object o) { if (o != null) { Node<E> next, pred = null; for (Node<E> p = first(); p != null; pred = p, p = next) { boolean removed = false; E item = p.item; if (item != null) { if (!o.equals(item)) { next = succ(p); // depends on control dependency: [if], data = [none] continue; } removed = casItem(p, item, null); // depends on control dependency: [if], data = [null)] } next = succ(p); // depends on control dependency: [for], data = [p] if (pred != null && next != null) // unlink casNext(pred, p, next); if (removed) return true; } } return false; } }
public class class_name { private static boolean disableChecks(String springVersion, String springSecurityVersion) { if (springVersion == null || springVersion.equals(springSecurityVersion)) { return true; } return Boolean.getBoolean(DISABLE_CHECKS); } }
public class class_name { private static boolean disableChecks(String springVersion, String springSecurityVersion) { if (springVersion == null || springVersion.equals(springSecurityVersion)) { return true; // depends on control dependency: [if], data = [none] } return Boolean.getBoolean(DISABLE_CHECKS); } }
public class class_name { public void setAll(int index, Collection<? extends Byte> items) { rangeCheck(index, index + items.size()); for (byte e : items) { elements[index++] = e; } } }
public class class_name { public void setAll(int index, Collection<? extends Byte> items) { rangeCheck(index, index + items.size()); for (byte e : items) { elements[index++] = e; // depends on control dependency: [for], data = [e] } } }
public class class_name { @Override protected void load() { //recordId can be null when in batchMode if (this.recordId != null && this.properties.isEmpty()) { this.sqlgGraph.tx().readWrite(); if (this.sqlgGraph.getSqlDialect().supportsBatchMode() && this.sqlgGraph.tx().getBatchManager().isStreaming()) { throw new IllegalStateException("streaming is in progress, first flush or commit before querying."); } //Generate the columns to prevent 'ERROR: cached plan must not change result type" error' //This happens when the schema changes after the statement is prepared. @SuppressWarnings("OptionalGetWithoutIsPresent") EdgeLabel edgeLabel = this.sqlgGraph.getTopology().getSchema(this.schema).orElseThrow(() -> new IllegalStateException(String.format("Schema %s not found", this.schema))).getEdgeLabel(this.table).orElseThrow(() -> new IllegalStateException(String.format("EdgeLabel %s not found", this.table))); StringBuilder sql = new StringBuilder("SELECT\n\t"); sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes("ID")); appendProperties(edgeLabel, sql); List<VertexLabel> outForeignKeys = new ArrayList<>(); for (VertexLabel vertexLabel : edgeLabel.getOutVertexLabels()) { outForeignKeys.add(vertexLabel); sql.append(", "); if (vertexLabel.hasIDPrimaryKey()) { String foreignKey = vertexLabel.getSchema().getName() + "." + vertexLabel.getName() + Topology.OUT_VERTEX_COLUMN_END; sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(foreignKey)); } else { int countIdentifier = 1; for (String identifier : vertexLabel.getIdentifiers()) { PropertyColumn propertyColumn = vertexLabel.getProperty(identifier).orElseThrow( () -> new IllegalStateException(String.format("identifier %s column must be a property", identifier)) ); PropertyType propertyType = propertyColumn.getPropertyType(); String[] propertyTypeToSqlDefinition = this.sqlgGraph.getSqlDialect().propertyTypeToSqlDefinition(propertyType); int count = 1; for (String ignored : propertyTypeToSqlDefinition) { if (count > 1) { sql.append(sqlgGraph.getSqlDialect().maybeWrapInQoutes(vertexLabel.getFullName() + "." + identifier + propertyType.getPostFixes()[count - 2] + Topology.OUT_VERTEX_COLUMN_END)); } else { //The first column existVertexLabel no postfix sql.append(sqlgGraph.getSqlDialect().maybeWrapInQoutes(vertexLabel.getFullName() + "." + identifier + Topology.OUT_VERTEX_COLUMN_END)); } if (count++ < propertyTypeToSqlDefinition.length) { sql.append(", "); } } if (countIdentifier++ < vertexLabel.getIdentifiers().size()) { sql.append(", "); } } } } List<VertexLabel> inForeignKeys = new ArrayList<>(); for (VertexLabel vertexLabel : edgeLabel.getInVertexLabels()) { sql.append(", "); inForeignKeys.add(vertexLabel); if (vertexLabel.hasIDPrimaryKey()) { String foreignKey = vertexLabel.getSchema().getName() + "." + vertexLabel.getName() + Topology.IN_VERTEX_COLUMN_END; sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(foreignKey)); } else { int countIdentifier = 1; for (String identifier : vertexLabel.getIdentifiers()) { PropertyColumn propertyColumn = vertexLabel.getProperty(identifier).orElseThrow( () -> new IllegalStateException(String.format("identifier %s column must be a property", identifier)) ); PropertyType propertyType = propertyColumn.getPropertyType(); String[] propertyTypeToSqlDefinition = this.sqlgGraph.getSqlDialect().propertyTypeToSqlDefinition(propertyType); int count = 1; for (String ignored : propertyTypeToSqlDefinition) { if (count > 1) { sql.append(sqlgGraph.getSqlDialect().maybeWrapInQoutes(vertexLabel.getFullName() + "." + identifier + propertyType.getPostFixes()[count - 2] + Topology.IN_VERTEX_COLUMN_END)); } else { //The first column existVertexLabel no postfix sql.append(sqlgGraph.getSqlDialect().maybeWrapInQoutes(vertexLabel.getFullName() + "." + identifier + Topology.IN_VERTEX_COLUMN_END)); } if (count++ < propertyTypeToSqlDefinition.length) { sql.append(", "); } } if (countIdentifier++ < vertexLabel.getIdentifiers().size()) { sql.append(", "); } } } } sql.append("\nFROM\n\t"); sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(this.schema)); sql.append("."); sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(EDGE_PREFIX + this.table)); sql.append(" WHERE "); //noinspection Duplicates if (edgeLabel.hasIDPrimaryKey()) { sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes("ID")); sql.append(" = ?"); } else { int count = 1; for (String identifier : edgeLabel.getIdentifiers()) { sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(identifier)); sql.append(" = ?"); if (count++ < edgeLabel.getIdentifiers().size()) { sql.append(" AND "); } } } if (this.sqlgGraph.getSqlDialect().needsSemicolon()) { sql.append(";"); } Connection conn = this.sqlgGraph.tx().getConnection(); if (logger.isDebugEnabled()) { logger.debug(sql.toString()); } try (PreparedStatement preparedStatement = conn.prepareStatement(sql.toString())) { if (edgeLabel.hasIDPrimaryKey()) { preparedStatement.setLong(1, this.recordId.sequenceId()); } else { int count = 1; for (Comparable identifierValue : this.recordId.getIdentifiers()) { preparedStatement.setObject(count++, identifierValue); } } ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { loadResultSet(resultSet, inForeignKeys, outForeignKeys); } } catch (SQLException e) { throw new RuntimeException(e); } } } }
public class class_name { @Override protected void load() { //recordId can be null when in batchMode if (this.recordId != null && this.properties.isEmpty()) { this.sqlgGraph.tx().readWrite(); // depends on control dependency: [if], data = [none] if (this.sqlgGraph.getSqlDialect().supportsBatchMode() && this.sqlgGraph.tx().getBatchManager().isStreaming()) { throw new IllegalStateException("streaming is in progress, first flush or commit before querying."); } //Generate the columns to prevent 'ERROR: cached plan must not change result type" error' //This happens when the schema changes after the statement is prepared. @SuppressWarnings("OptionalGetWithoutIsPresent") EdgeLabel edgeLabel = this.sqlgGraph.getTopology().getSchema(this.schema).orElseThrow(() -> new IllegalStateException(String.format("Schema %s not found", this.schema))).getEdgeLabel(this.table).orElseThrow(() -> new IllegalStateException(String.format("EdgeLabel %s not found", this.table))); StringBuilder sql = new StringBuilder("SELECT\n\t"); sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes("ID")); // depends on control dependency: [if], data = [none] appendProperties(edgeLabel, sql); // depends on control dependency: [if], data = [none] List<VertexLabel> outForeignKeys = new ArrayList<>(); for (VertexLabel vertexLabel : edgeLabel.getOutVertexLabels()) { outForeignKeys.add(vertexLabel); // depends on control dependency: [for], data = [vertexLabel] sql.append(", "); // depends on control dependency: [for], data = [none] if (vertexLabel.hasIDPrimaryKey()) { String foreignKey = vertexLabel.getSchema().getName() + "." + vertexLabel.getName() + Topology.OUT_VERTEX_COLUMN_END; sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(foreignKey)); // depends on control dependency: [if], data = [none] } else { int countIdentifier = 1; for (String identifier : vertexLabel.getIdentifiers()) { PropertyColumn propertyColumn = vertexLabel.getProperty(identifier).orElseThrow( () -> new IllegalStateException(String.format("identifier %s column must be a property", identifier)) ); PropertyType propertyType = propertyColumn.getPropertyType(); String[] propertyTypeToSqlDefinition = this.sqlgGraph.getSqlDialect().propertyTypeToSqlDefinition(propertyType); int count = 1; for (String ignored : propertyTypeToSqlDefinition) { if (count > 1) { sql.append(sqlgGraph.getSqlDialect().maybeWrapInQoutes(vertexLabel.getFullName() + "." + identifier + propertyType.getPostFixes()[count - 2] + Topology.OUT_VERTEX_COLUMN_END)); // depends on control dependency: [if], data = [none] } else { //The first column existVertexLabel no postfix sql.append(sqlgGraph.getSqlDialect().maybeWrapInQoutes(vertexLabel.getFullName() + "." + identifier + Topology.OUT_VERTEX_COLUMN_END)); // depends on control dependency: [if], data = [none] } if (count++ < propertyTypeToSqlDefinition.length) { sql.append(", "); // depends on control dependency: [if], data = [none] } } if (countIdentifier++ < vertexLabel.getIdentifiers().size()) { sql.append(", "); // depends on control dependency: [if], data = [none] } } } } List<VertexLabel> inForeignKeys = new ArrayList<>(); for (VertexLabel vertexLabel : edgeLabel.getInVertexLabels()) { sql.append(", "); // depends on control dependency: [for], data = [none] inForeignKeys.add(vertexLabel); // depends on control dependency: [for], data = [vertexLabel] if (vertexLabel.hasIDPrimaryKey()) { String foreignKey = vertexLabel.getSchema().getName() + "." + vertexLabel.getName() + Topology.IN_VERTEX_COLUMN_END; sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(foreignKey)); // depends on control dependency: [if], data = [none] } else { int countIdentifier = 1; for (String identifier : vertexLabel.getIdentifiers()) { PropertyColumn propertyColumn = vertexLabel.getProperty(identifier).orElseThrow( () -> new IllegalStateException(String.format("identifier %s column must be a property", identifier)) ); PropertyType propertyType = propertyColumn.getPropertyType(); String[] propertyTypeToSqlDefinition = this.sqlgGraph.getSqlDialect().propertyTypeToSqlDefinition(propertyType); int count = 1; for (String ignored : propertyTypeToSqlDefinition) { if (count > 1) { sql.append(sqlgGraph.getSqlDialect().maybeWrapInQoutes(vertexLabel.getFullName() + "." + identifier + propertyType.getPostFixes()[count - 2] + Topology.IN_VERTEX_COLUMN_END)); // depends on control dependency: [if], data = [none] } else { //The first column existVertexLabel no postfix sql.append(sqlgGraph.getSqlDialect().maybeWrapInQoutes(vertexLabel.getFullName() + "." + identifier + Topology.IN_VERTEX_COLUMN_END)); // depends on control dependency: [if], data = [none] } if (count++ < propertyTypeToSqlDefinition.length) { sql.append(", "); // depends on control dependency: [if], data = [none] } } if (countIdentifier++ < vertexLabel.getIdentifiers().size()) { sql.append(", "); // depends on control dependency: [if], data = [none] } } } } sql.append("\nFROM\n\t"); // depends on control dependency: [if], data = [none] sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(this.schema)); // depends on control dependency: [if], data = [none] sql.append("."); // depends on control dependency: [if], data = [none] sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(EDGE_PREFIX + this.table)); // depends on control dependency: [if], data = [none] sql.append(" WHERE "); // depends on control dependency: [if], data = [none] //noinspection Duplicates if (edgeLabel.hasIDPrimaryKey()) { sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes("ID")); // depends on control dependency: [if], data = [none] sql.append(" = ?"); // depends on control dependency: [if], data = [none] } else { int count = 1; for (String identifier : edgeLabel.getIdentifiers()) { sql.append(this.sqlgGraph.getSqlDialect().maybeWrapInQoutes(identifier)); // depends on control dependency: [for], data = [identifier] sql.append(" = ?"); // depends on control dependency: [for], data = [none] if (count++ < edgeLabel.getIdentifiers().size()) { sql.append(" AND "); // depends on control dependency: [if], data = [none] } } } if (this.sqlgGraph.getSqlDialect().needsSemicolon()) { sql.append(";"); // depends on control dependency: [if], data = [none] } Connection conn = this.sqlgGraph.tx().getConnection(); if (logger.isDebugEnabled()) { logger.debug(sql.toString()); // depends on control dependency: [if], data = [none] } try (PreparedStatement preparedStatement = conn.prepareStatement(sql.toString())) { if (edgeLabel.hasIDPrimaryKey()) { preparedStatement.setLong(1, this.recordId.sequenceId()); // depends on control dependency: [if], data = [none] } else { int count = 1; for (Comparable identifierValue : this.recordId.getIdentifiers()) { preparedStatement.setObject(count++, identifierValue); // depends on control dependency: [for], data = [identifierValue] } } ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { loadResultSet(resultSet, inForeignKeys, outForeignKeys); // depends on control dependency: [if], data = [none] } } catch (SQLException e) { throw new RuntimeException(e); } } } }
public class class_name { public static Map<String, ?> getMapFromProperties(Properties properties, String prefix) { Map<String, Object> result = new HashMap<String, Object>(); for (String key : properties.stringPropertyNames()) { if (key.startsWith(prefix)) { String name = key.substring(prefix.length()); result.put(name, properties.getProperty(key)); } } return result; } }
public class class_name { public static Map<String, ?> getMapFromProperties(Properties properties, String prefix) { Map<String, Object> result = new HashMap<String, Object>(); for (String key : properties.stringPropertyNames()) { if (key.startsWith(prefix)) { String name = key.substring(prefix.length()); result.put(name, properties.getProperty(key)); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public EClass getIfcResource() { if (ifcResourceEClass == null) { ifcResourceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(492); } return ifcResourceEClass; } }
public class class_name { public EClass getIfcResource() { if (ifcResourceEClass == null) { ifcResourceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(492); // depends on control dependency: [if], data = [none] } return ifcResourceEClass; } }
public class class_name { private int subspaceDimensionality(NumberVector v1, NumberVector v2, long[] pv1, long[] pv2, long[] commonPreferenceVector) { // number of zero values in commonPreferenceVector int subspaceDim = v1.getDimensionality() - BitsUtil.cardinality(commonPreferenceVector); // special case: v1 and v2 are in parallel subspaces if(BitsUtil.equal(commonPreferenceVector, pv1) || BitsUtil.equal(commonPreferenceVector, pv2)) { double d = weightedDistance(v1, v2, commonPreferenceVector); if(d > 2 * epsilon) { subspaceDim++; } } return subspaceDim; } }
public class class_name { private int subspaceDimensionality(NumberVector v1, NumberVector v2, long[] pv1, long[] pv2, long[] commonPreferenceVector) { // number of zero values in commonPreferenceVector int subspaceDim = v1.getDimensionality() - BitsUtil.cardinality(commonPreferenceVector); // special case: v1 and v2 are in parallel subspaces if(BitsUtil.equal(commonPreferenceVector, pv1) || BitsUtil.equal(commonPreferenceVector, pv2)) { double d = weightedDistance(v1, v2, commonPreferenceVector); if(d > 2 * epsilon) { subspaceDim++; // depends on control dependency: [if], data = [none] } } return subspaceDim; } }
public class class_name { @NotNull public static String unescapeChars(@NotNull final String string, final char[] toUnescape) { String toReturn = string; for (char character : toUnescape) { toReturn = unescapeChar(toReturn, character); } return toReturn; } }
public class class_name { @NotNull public static String unescapeChars(@NotNull final String string, final char[] toUnescape) { String toReturn = string; for (char character : toUnescape) { toReturn = unescapeChar(toReturn, character); // depends on control dependency: [for], data = [character] } return toReturn; } }
public class class_name { public void marshall(DisassociateTagOptionFromResourceRequest disassociateTagOptionFromResourceRequest, ProtocolMarshaller protocolMarshaller) { if (disassociateTagOptionFromResourceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(disassociateTagOptionFromResourceRequest.getResourceId(), RESOURCEID_BINDING); protocolMarshaller.marshall(disassociateTagOptionFromResourceRequest.getTagOptionId(), TAGOPTIONID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DisassociateTagOptionFromResourceRequest disassociateTagOptionFromResourceRequest, ProtocolMarshaller protocolMarshaller) { if (disassociateTagOptionFromResourceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(disassociateTagOptionFromResourceRequest.getResourceId(), RESOURCEID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(disassociateTagOptionFromResourceRequest.getTagOptionId(), TAGOPTIONID_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public String getStatement() { StringBuffer sb = new StringBuffer(512); int argumentCount = this.procedureDescriptor.getArgumentCount(); if (this.procedureDescriptor.hasReturnValue()) { sb.append("{ ?= call "); } else { sb.append("{ call "); } sb.append(this.procedureDescriptor.getName()); sb.append("("); for (int i = 0; i < argumentCount; i++) { if (i == 0) { sb.append("?"); } else { sb.append(",?"); } } sb.append(") }"); return sb.toString(); } }
public class class_name { public String getStatement() { StringBuffer sb = new StringBuffer(512); int argumentCount = this.procedureDescriptor.getArgumentCount(); if (this.procedureDescriptor.hasReturnValue()) { sb.append("{ ?= call "); // depends on control dependency: [if], data = [none] } else { sb.append("{ call "); // depends on control dependency: [if], data = [none] } sb.append(this.procedureDescriptor.getName()); sb.append("("); for (int i = 0; i < argumentCount; i++) { if (i == 0) { sb.append("?"); // depends on control dependency: [if], data = [none] } else { sb.append(",?"); // depends on control dependency: [if], data = [none] } } sb.append(") }"); return sb.toString(); } }
public class class_name { private long cleanupTime(W window) { if (windowAssigner.isEventTime()) { long cleanupTime = Math.max(0, window.maxTimestamp() + allowedLateness); return cleanupTime >= window.maxTimestamp() ? cleanupTime : Long.MAX_VALUE; } else { return Math.max(0, window.maxTimestamp()); } } }
public class class_name { private long cleanupTime(W window) { if (windowAssigner.isEventTime()) { long cleanupTime = Math.max(0, window.maxTimestamp() + allowedLateness); return cleanupTime >= window.maxTimestamp() ? cleanupTime : Long.MAX_VALUE; // depends on control dependency: [if], data = [none] } else { return Math.max(0, window.maxTimestamp()); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override @NonNull public String[] selectImports(@NonNull AnnotationMetadata importingClassMetadata) { boolean enabledTxc = Boolean.valueOf( Objects.requireNonNull( importingClassMetadata.getAnnotationAttributes(EnableDistributedTransaction.class.getName())) .get("enableTxc").toString()); List<String> importClasses = new ArrayList<>(); importClasses.add("com.codingapi.txlcn.txmsg.MessageConfiguration"); if (enabledTxc) { importClasses.add(TxcConfiguration.class.getName()); } return importClasses.toArray(new String[0]); } }
public class class_name { @Override @NonNull public String[] selectImports(@NonNull AnnotationMetadata importingClassMetadata) { boolean enabledTxc = Boolean.valueOf( Objects.requireNonNull( importingClassMetadata.getAnnotationAttributes(EnableDistributedTransaction.class.getName())) .get("enableTxc").toString()); List<String> importClasses = new ArrayList<>(); importClasses.add("com.codingapi.txlcn.txmsg.MessageConfiguration"); if (enabledTxc) { importClasses.add(TxcConfiguration.class.getName()); // depends on control dependency: [if], data = [none] } return importClasses.toArray(new String[0]); } }
public class class_name { public static void setIdentity( DMatrix1Row mat ) { int width = mat.numRows < mat.numCols ? mat.numRows : mat.numCols; Arrays.fill(mat.data,0,mat.getNumElements(),0); int index = 0; for( int i = 0; i < width; i++ , index += mat.numCols + 1) { mat.data[index] = 1; } } }
public class class_name { public static void setIdentity( DMatrix1Row mat ) { int width = mat.numRows < mat.numCols ? mat.numRows : mat.numCols; Arrays.fill(mat.data,0,mat.getNumElements(),0); int index = 0; for( int i = 0; i < width; i++ , index += mat.numCols + 1) { mat.data[index] = 1; // depends on control dependency: [for], data = [none] } } }
public class class_name { public static <T> List<T> getServices(Class<T> intf) { List<T> ret = new ArrayList<T>(); for (T service : ServiceLoader.load(intf)) { if (!(service instanceof ServiceStatus) || ((ServiceStatus)service).isAvailable()) { if (service instanceof ServiceLifecycle) { ((ServiceLifecycle)service).init(); } ret.add(service); } } return ret; } }
public class class_name { public static <T> List<T> getServices(Class<T> intf) { List<T> ret = new ArrayList<T>(); for (T service : ServiceLoader.load(intf)) { if (!(service instanceof ServiceStatus) || ((ServiceStatus)service).isAvailable()) { if (service instanceof ServiceLifecycle) { ((ServiceLifecycle)service).init(); // depends on control dependency: [if], data = [none] } ret.add(service); // depends on control dependency: [if], data = [none] } } return ret; } }
public class class_name { @Override @XmlTransient public JSONObject toJsonForElasticSearch() throws JSONException { JSONObject returnVal = super.toJsonObject(); //Form Type... if(this.getFormType() != null) { returnVal.put(JSONMapping.FORM_TYPE, this.getFormType()); } //Form Type Id... if(this.getFormTypeId() != null) { returnVal.put(JSONMapping.FORM_TYPE_ID, this.getFormTypeId()); } //Title... if(this.getTitle() != null) { returnVal.put(JSONMapping.TITLE, this.getTitle()); } //Form Description... if(this.getFormDescription() != null) { returnVal.put(JSONMapping.FORM_DESCRIPTION, this.getFormDescription()); } //State... if(this.getState() != null) { returnVal.put(JSONMapping.STATE, this.getState()); } //Flow State... if(this.getFlowState() != null) { returnVal.put(JSONMapping.FLOW_STATE, this.getFlowState()); } //Current User... JSONObject currentUserJsonObj = new JSONObject(); if(this.getCurrentUser() == null) { currentUserJsonObj.put( User.JSONMapping.Elastic.USER_ID, JSONObject.NULL); currentUserJsonObj.put(User.JSONMapping.USERNAME, JSONObject.NULL); } else{ //Id... if(this.getCurrentUser().getId() == null || this.getCurrentUser().getId().longValue() < 1) { currentUserJsonObj.put( User.JSONMapping.Elastic.USER_ID, JSONObject.NULL); } else{ currentUserJsonObj.put( User.JSONMapping.Elastic.USER_ID, this.getCurrentUser().getId()); } //Username... if(this.getCurrentUser().getUsername() == null || this.getCurrentUser().getUsername().trim().isEmpty()) { currentUserJsonObj.put(User.JSONMapping.USERNAME, JSONObject.NULL); } else { currentUserJsonObj.put(User.JSONMapping.USERNAME, this.getCurrentUser().getUsername()); } } returnVal.put(JSONMapping.CURRENT_USER, currentUserJsonObj); //Date Created... if(this.getDateCreated() != null) { returnVal.put(JSONMapping.DATE_CREATED, this.getDateAsLongFromJson(this.getDateCreated())); } //Date Last Updated... if(this.getDateLastUpdated() != null) { returnVal.put(JSONMapping.DATE_LAST_UPDATED, this.getDateAsLongFromJson(this.getDateLastUpdated())); } //Form Fields... if(this.getFormFields() != null && !this.getFormFields().isEmpty()) { for(Field toAdd : this.getFormFields()) { JSONObject convertedFieldObj = toAdd.toJsonForElasticSearch(); if(convertedFieldObj == null) { continue; } Iterator<String> iterKeys = convertedFieldObj.keys(); while(iterKeys.hasNext()) { String key = iterKeys.next(); returnVal.put(key, convertedFieldObj.get(key)); } } } //Ancestor... Long ancestorIdLcl = this.getAncestorId(); if(ancestorIdLcl != null) { returnVal.put(JSONMapping.ANCESTOR_ID, ancestorIdLcl); } //Table Field Parent Id... if(this.getTableFieldParentId() != null) { returnVal.put(JSONMapping.TABLE_FIELD_PARENT_ID, this.getTableFieldParentId()); } //Descendant Ids... if(this.getDescendantIds() != null && !this.getDescendantIds().isEmpty()) { JSONArray array = new JSONArray(); for(Long formId : this.getDescendantIds()) { array.put(formId); } returnVal.put(JSONMapping.DESCENDANT_IDS, array); } return returnVal; } }
public class class_name { @Override @XmlTransient public JSONObject toJsonForElasticSearch() throws JSONException { JSONObject returnVal = super.toJsonObject(); //Form Type... if(this.getFormType() != null) { returnVal.put(JSONMapping.FORM_TYPE, this.getFormType()); } //Form Type Id... if(this.getFormTypeId() != null) { returnVal.put(JSONMapping.FORM_TYPE_ID, this.getFormTypeId()); } //Title... if(this.getTitle() != null) { returnVal.put(JSONMapping.TITLE, this.getTitle()); } //Form Description... if(this.getFormDescription() != null) { returnVal.put(JSONMapping.FORM_DESCRIPTION, this.getFormDescription()); } //State... if(this.getState() != null) { returnVal.put(JSONMapping.STATE, this.getState()); } //Flow State... if(this.getFlowState() != null) { returnVal.put(JSONMapping.FLOW_STATE, this.getFlowState()); } //Current User... JSONObject currentUserJsonObj = new JSONObject(); if(this.getCurrentUser() == null) { currentUserJsonObj.put( User.JSONMapping.Elastic.USER_ID, JSONObject.NULL); currentUserJsonObj.put(User.JSONMapping.USERNAME, JSONObject.NULL); } else{ //Id... if(this.getCurrentUser().getId() == null || this.getCurrentUser().getId().longValue() < 1) { currentUserJsonObj.put( User.JSONMapping.Elastic.USER_ID, JSONObject.NULL); // depends on control dependency: [if], data = [none] } else{ currentUserJsonObj.put( User.JSONMapping.Elastic.USER_ID, this.getCurrentUser().getId()); // depends on control dependency: [if], data = [none] } //Username... if(this.getCurrentUser().getUsername() == null || this.getCurrentUser().getUsername().trim().isEmpty()) { currentUserJsonObj.put(User.JSONMapping.USERNAME, JSONObject.NULL); // depends on control dependency: [if], data = [none] } else { currentUserJsonObj.put(User.JSONMapping.USERNAME, this.getCurrentUser().getUsername()); // depends on control dependency: [if], data = [none] } } returnVal.put(JSONMapping.CURRENT_USER, currentUserJsonObj); //Date Created... if(this.getDateCreated() != null) { returnVal.put(JSONMapping.DATE_CREATED, this.getDateAsLongFromJson(this.getDateCreated())); } //Date Last Updated... if(this.getDateLastUpdated() != null) { returnVal.put(JSONMapping.DATE_LAST_UPDATED, this.getDateAsLongFromJson(this.getDateLastUpdated())); } //Form Fields... if(this.getFormFields() != null && !this.getFormFields().isEmpty()) { for(Field toAdd : this.getFormFields()) { JSONObject convertedFieldObj = toAdd.toJsonForElasticSearch(); if(convertedFieldObj == null) { continue; } Iterator<String> iterKeys = convertedFieldObj.keys(); while(iterKeys.hasNext()) { String key = iterKeys.next(); returnVal.put(key, convertedFieldObj.get(key)); // depends on control dependency: [while], data = [none] } } } //Ancestor... Long ancestorIdLcl = this.getAncestorId(); if(ancestorIdLcl != null) { returnVal.put(JSONMapping.ANCESTOR_ID, ancestorIdLcl); } //Table Field Parent Id... if(this.getTableFieldParentId() != null) { returnVal.put(JSONMapping.TABLE_FIELD_PARENT_ID, this.getTableFieldParentId()); } //Descendant Ids... if(this.getDescendantIds() != null && !this.getDescendantIds().isEmpty()) { JSONArray array = new JSONArray(); for(Long formId : this.getDescendantIds()) { array.put(formId); } returnVal.put(JSONMapping.DESCENDANT_IDS, array); } return returnVal; } }
public class class_name { public static int writeLongAsVarIntBytes(long v, byte[] bytes, int offest) { int pos = offest; while (true) { if ((v & ~0x7FL) == 0) { bytes[pos++] = ((byte)v); return pos; } else { bytes[pos++] = (byte)((v & 0x7F) | 0x80); v >>>= 7; } } } }
public class class_name { public static int writeLongAsVarIntBytes(long v, byte[] bytes, int offest) { int pos = offest; while (true) { if ((v & ~0x7FL) == 0) { bytes[pos++] = ((byte)v); // depends on control dependency: [if], data = [none] return pos; // depends on control dependency: [if], data = [none] } else { bytes[pos++] = (byte)((v & 0x7F) | 0x80); // depends on control dependency: [if], data = [0)] v >>>= 7; // depends on control dependency: [if], data = [none] } } } }
public class class_name { public DomainCommandBuilder setMasterPortHint(final String port) { if (port != null) { setMasterPortHint(Integer.parseInt(port)); } return this; } }
public class class_name { public DomainCommandBuilder setMasterPortHint(final String port) { if (port != null) { setMasterPortHint(Integer.parseInt(port)); // depends on control dependency: [if], data = [(port] } return this; } }
public class class_name { @Override public synchronized void start() { if (!running && !used) { this.running = true; this.used = true; this.setDaemon(true); super.start(); } } }
public class class_name { @Override public synchronized void start() { if (!running && !used) { this.running = true; // depends on control dependency: [if], data = [none] this.used = true; // depends on control dependency: [if], data = [none] this.setDaemon(true); // depends on control dependency: [if], data = [none] super.start(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Integer[] nullToEmpty(Integer[] array) { if (array == null || array.length == 0) { return EMPTY_INTEGER_OBJECT_ARRAY; } return array; } }
public class class_name { public static Integer[] nullToEmpty(Integer[] array) { if (array == null || array.length == 0) { return EMPTY_INTEGER_OBJECT_ARRAY; // depends on control dependency: [if], data = [none] } return array; } }
public class class_name { protected Object lookupVar(JsonNode node, String var) { List<? extends JsonNode> children = node.getChildren(var); if (children.size()>1) { // multiple with name, treat as list of values List<String> result = new ArrayList<String>(); for (JsonNode child : children) { result.add(child.getValue()); } return result; } else if (children.size()==1) { JsonNode child = children.get(0); List<String> attributeNames = child.getAttributeNames(); Collections.sort(attributeNames); if (attributeNames.size()==0) { // treat child as the attribute value return child.getValue(); } else { // treat child as object with map values Map<String, String> result = new LinkedHashMap<String, String>(); for (String attrName : attributeNames) { result.put(attrName, child.getAttribute(attrName)); } return result; } } else { // return null return null; } } }
public class class_name { protected Object lookupVar(JsonNode node, String var) { List<? extends JsonNode> children = node.getChildren(var); if (children.size()>1) { // multiple with name, treat as list of values List<String> result = new ArrayList<String>(); for (JsonNode child : children) { result.add(child.getValue()); // depends on control dependency: [for], data = [child] } return result; // depends on control dependency: [if], data = [none] } else if (children.size()==1) { JsonNode child = children.get(0); List<String> attributeNames = child.getAttributeNames(); Collections.sort(attributeNames); // depends on control dependency: [if], data = [none] if (attributeNames.size()==0) { // treat child as the attribute value return child.getValue(); // depends on control dependency: [if], data = [none] } else { // treat child as object with map values Map<String, String> result = new LinkedHashMap<String, String>(); for (String attrName : attributeNames) { result.put(attrName, child.getAttribute(attrName)); // depends on control dependency: [for], data = [attrName] } return result; // depends on control dependency: [if], data = [none] } } else { // return null return null; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static int intersectQuadAndCubic (float qx1, float qy1, float qx2, float qy2, float qx3, float qy3, float cx1, float cy1, float cx2, float cy2, float cx3, float cy3, float cx4, float cy4, float[] params) { int quantity = 0; float[] initParams = new float[3]; float[] xCoefs1 = new float[3]; float[] yCoefs1 = new float[3]; float[] xCoefs2 = new float[4]; float[] yCoefs2 = new float[4]; xCoefs1[0] = qx1 - 2 * qx2 + qx3; xCoefs1[1] = 2 * qx2 - 2 * qx1; xCoefs1[2] = qx1; yCoefs1[0] = qy1 - 2 * qy2 + qy3; yCoefs1[1] = 2 * qy2 - 2 * qy1; yCoefs1[2] = qy1; xCoefs2[0] = -cx1 + 3 * cx2 - 3 * cx3 + cx4; xCoefs2[1] = 3 * cx1 - 6 * cx2 + 3 * cx3; xCoefs2[2] = -3 * cx1 + 3 * cx2; xCoefs2[3] = cx1; yCoefs2[0] = -cy1 + 3 * cy2 - 3 * cy3 + cy4; yCoefs2[1] = 3 * cy1 - 6 * cy2 + 3 * cy3; yCoefs2[2] = -3 * cy1 + 3 * cy2; yCoefs2[3] = cy1; // initialize params[0] and params[1] params[0] = params[1] = 0.25f; quadAndCubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, initParams); if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) { params[2 * quantity] = initParams[0]; params[2 * quantity + 1] = initParams[1]; ++quantity; } // initialize params params[0] = params[1] = 0.5f; quadAndCubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, params); if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) { params[2 * quantity] = initParams[0]; params[2 * quantity + 1] = initParams[1]; ++quantity; } params[0] = params[1] = 0.75f; quadAndCubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, params); if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) { params[2 * quantity] = initParams[0]; params[2 * quantity + 1] = initParams[1]; ++quantity; } return quantity; } }
public class class_name { public static int intersectQuadAndCubic (float qx1, float qy1, float qx2, float qy2, float qx3, float qy3, float cx1, float cy1, float cx2, float cy2, float cx3, float cy3, float cx4, float cy4, float[] params) { int quantity = 0; float[] initParams = new float[3]; float[] xCoefs1 = new float[3]; float[] yCoefs1 = new float[3]; float[] xCoefs2 = new float[4]; float[] yCoefs2 = new float[4]; xCoefs1[0] = qx1 - 2 * qx2 + qx3; xCoefs1[1] = 2 * qx2 - 2 * qx1; xCoefs1[2] = qx1; yCoefs1[0] = qy1 - 2 * qy2 + qy3; yCoefs1[1] = 2 * qy2 - 2 * qy1; yCoefs1[2] = qy1; xCoefs2[0] = -cx1 + 3 * cx2 - 3 * cx3 + cx4; xCoefs2[1] = 3 * cx1 - 6 * cx2 + 3 * cx3; xCoefs2[2] = -3 * cx1 + 3 * cx2; xCoefs2[3] = cx1; yCoefs2[0] = -cy1 + 3 * cy2 - 3 * cy3 + cy4; yCoefs2[1] = 3 * cy1 - 6 * cy2 + 3 * cy3; yCoefs2[2] = -3 * cy1 + 3 * cy2; yCoefs2[3] = cy1; // initialize params[0] and params[1] params[0] = params[1] = 0.25f; quadAndCubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, initParams); if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) { params[2 * quantity] = initParams[0]; // depends on control dependency: [if], data = [none] params[2 * quantity + 1] = initParams[1]; // depends on control dependency: [if], data = [none] ++quantity; // depends on control dependency: [if], data = [none] } // initialize params params[0] = params[1] = 0.5f; quadAndCubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, params); if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) { params[2 * quantity] = initParams[0]; // depends on control dependency: [if], data = [none] params[2 * quantity + 1] = initParams[1]; // depends on control dependency: [if], data = [none] ++quantity; // depends on control dependency: [if], data = [none] } params[0] = params[1] = 0.75f; quadAndCubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, params); if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) { params[2 * quantity] = initParams[0]; // depends on control dependency: [if], data = [none] params[2 * quantity + 1] = initParams[1]; // depends on control dependency: [if], data = [none] ++quantity; // depends on control dependency: [if], data = [none] } return quantity; } }
public class class_name { public static Double[] toObject(double... a) { if (a != null) { Double[] w = new Double[a.length]; for (int i = 0; i < a.length; i++) { w[i] = a[i]; } return w; } return null; } }
public class class_name { public static Double[] toObject(double... a) { if (a != null) { Double[] w = new Double[a.length]; for (int i = 0; i < a.length; i++) { w[i] = a[i]; // depends on control dependency: [for], data = [i] } return w; // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public Observable<ServiceResponse<Page<SasTokenInformationInner>>> listSasTokensNextWithServiceResponseAsync(final String nextPageLink) { return listSasTokensNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<SasTokenInformationInner>>, Observable<ServiceResponse<Page<SasTokenInformationInner>>>>() { @Override public Observable<ServiceResponse<Page<SasTokenInformationInner>>> call(ServiceResponse<Page<SasTokenInformationInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listSasTokensNextWithServiceResponseAsync(nextPageLink)); } }); } }
public class class_name { public Observable<ServiceResponse<Page<SasTokenInformationInner>>> listSasTokensNextWithServiceResponseAsync(final String nextPageLink) { return listSasTokensNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<SasTokenInformationInner>>, Observable<ServiceResponse<Page<SasTokenInformationInner>>>>() { @Override public Observable<ServiceResponse<Page<SasTokenInformationInner>>> call(ServiceResponse<Page<SasTokenInformationInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); // depends on control dependency: [if], data = [none] } return Observable.just(page).concatWith(listSasTokensNextWithServiceResponseAsync(nextPageLink)); } }); } }
public class class_name { private static MultiLineString convertMultiCurve(JGeometry geometry) { JGeometry[] elements = geometry.getElements(); if (elements == null || elements.length == 0) { return MultiLineString.createEmpty(); } CrsId crs = CrsId.valueOf(geometry.getSRID()); LineString[] lineStrings = new LineString[elements.length]; for (int i = 0; i < elements.length; i++) { PointSequence points = getPoints(elements[i]); lineStrings[i] = new LineString(points); } return new MultiLineString(lineStrings); } }
public class class_name { private static MultiLineString convertMultiCurve(JGeometry geometry) { JGeometry[] elements = geometry.getElements(); if (elements == null || elements.length == 0) { return MultiLineString.createEmpty(); // depends on control dependency: [if], data = [none] } CrsId crs = CrsId.valueOf(geometry.getSRID()); LineString[] lineStrings = new LineString[elements.length]; for (int i = 0; i < elements.length; i++) { PointSequence points = getPoints(elements[i]); lineStrings[i] = new LineString(points); // depends on control dependency: [for], data = [i] } return new MultiLineString(lineStrings); } }
public class class_name { public static boolean isServiceRunning(Context context, Class<? extends Service> service, int maxCheckCount) { if (context == null || service == null) { return false; } ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningServiceInfo> list = manager.getRunningServices(maxCheckCount); for (RunningServiceInfo info : list) { if (service.getCanonicalName().equals(info.service.getClassName())) { return true; } } return false; } }
public class class_name { public static boolean isServiceRunning(Context context, Class<? extends Service> service, int maxCheckCount) { if (context == null || service == null) { return false; // depends on control dependency: [if], data = [none] } ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningServiceInfo> list = manager.getRunningServices(maxCheckCount); for (RunningServiceInfo info : list) { if (service.getCanonicalName().equals(info.service.getClassName())) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { protected void addName() { if (Strings.isNotEmpty(builder)) { int endOffset = 0; if (Strings.endsWith(builder, tagSeparator)) { // Ends with ','. endOffset = 1; } if (Strings.startsWith(builder, inheritanceMarker)) { // Starts with '.'. inherits.add(builder.substring(1, builder.length() - endOffset)); } else { tags.add(builder.substring(0, builder.length() - endOffset)); } Strings.clearBuilder(builder); } } }
public class class_name { protected void addName() { if (Strings.isNotEmpty(builder)) { int endOffset = 0; if (Strings.endsWith(builder, tagSeparator)) { // Ends with ','. endOffset = 1; // depends on control dependency: [if], data = [none] } if (Strings.startsWith(builder, inheritanceMarker)) { // Starts with '.'. inherits.add(builder.substring(1, builder.length() - endOffset)); // depends on control dependency: [if], data = [none] } else { tags.add(builder.substring(0, builder.length() - endOffset)); // depends on control dependency: [if], data = [none] } Strings.clearBuilder(builder); // depends on control dependency: [if], data = [none] } } }
public class class_name { public final EObject ruleJvmUpperBoundAnded() throws RecognitionException { EObject current = null; Token otherlv_0=null; EObject lv_typeReference_1_0 = null; enterRule(); try { // InternalPureXbase.g:6484:2: ( (otherlv_0= '&' ( (lv_typeReference_1_0= ruleJvmTypeReference ) ) ) ) // InternalPureXbase.g:6485:2: (otherlv_0= '&' ( (lv_typeReference_1_0= ruleJvmTypeReference ) ) ) { // InternalPureXbase.g:6485:2: (otherlv_0= '&' ( (lv_typeReference_1_0= ruleJvmTypeReference ) ) ) // InternalPureXbase.g:6486:3: otherlv_0= '&' ( (lv_typeReference_1_0= ruleJvmTypeReference ) ) { otherlv_0=(Token)match(input,83,FOLLOW_11); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_0, grammarAccess.getJvmUpperBoundAndedAccess().getAmpersandKeyword_0()); } // InternalPureXbase.g:6490:3: ( (lv_typeReference_1_0= ruleJvmTypeReference ) ) // InternalPureXbase.g:6491:4: (lv_typeReference_1_0= ruleJvmTypeReference ) { // InternalPureXbase.g:6491:4: (lv_typeReference_1_0= ruleJvmTypeReference ) // InternalPureXbase.g:6492:5: lv_typeReference_1_0= ruleJvmTypeReference { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getJvmUpperBoundAndedAccess().getTypeReferenceJvmTypeReferenceParserRuleCall_1_0()); } pushFollow(FOLLOW_2); lv_typeReference_1_0=ruleJvmTypeReference(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getJvmUpperBoundAndedRule()); } set( current, "typeReference", lv_typeReference_1_0, "org.eclipse.xtext.xbase.Xtype.JvmTypeReference"); afterParserOrEnumRuleCall(); } } } } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { public final EObject ruleJvmUpperBoundAnded() throws RecognitionException { EObject current = null; Token otherlv_0=null; EObject lv_typeReference_1_0 = null; enterRule(); try { // InternalPureXbase.g:6484:2: ( (otherlv_0= '&' ( (lv_typeReference_1_0= ruleJvmTypeReference ) ) ) ) // InternalPureXbase.g:6485:2: (otherlv_0= '&' ( (lv_typeReference_1_0= ruleJvmTypeReference ) ) ) { // InternalPureXbase.g:6485:2: (otherlv_0= '&' ( (lv_typeReference_1_0= ruleJvmTypeReference ) ) ) // InternalPureXbase.g:6486:3: otherlv_0= '&' ( (lv_typeReference_1_0= ruleJvmTypeReference ) ) { otherlv_0=(Token)match(input,83,FOLLOW_11); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_0, grammarAccess.getJvmUpperBoundAndedAccess().getAmpersandKeyword_0()); // depends on control dependency: [if], data = [none] } // InternalPureXbase.g:6490:3: ( (lv_typeReference_1_0= ruleJvmTypeReference ) ) // InternalPureXbase.g:6491:4: (lv_typeReference_1_0= ruleJvmTypeReference ) { // InternalPureXbase.g:6491:4: (lv_typeReference_1_0= ruleJvmTypeReference ) // InternalPureXbase.g:6492:5: lv_typeReference_1_0= ruleJvmTypeReference { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getJvmUpperBoundAndedAccess().getTypeReferenceJvmTypeReferenceParserRuleCall_1_0()); // depends on control dependency: [if], data = [none] } pushFollow(FOLLOW_2); lv_typeReference_1_0=ruleJvmTypeReference(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { if (current==null) { current = createModelElementForParent(grammarAccess.getJvmUpperBoundAndedRule()); // depends on control dependency: [if], data = [none] } set( current, "typeReference", lv_typeReference_1_0, "org.eclipse.xtext.xbase.Xtype.JvmTypeReference"); afterParserOrEnumRuleCall(); // depends on control dependency: [if], data = [none] } } } } } if ( state.backtracking==0 ) { leaveRule(); // depends on control dependency: [if], data = [none] } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { protected I_CmsContextMenuEntry createViewOnlineEntry() { final String onlineLink = m_controller.getData().getOnlineLink(); CmsContextMenuEntry entry = null; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(onlineLink)) { I_CmsContextMenuCommand command = new I_CmsContextMenuCommand() { public void execute( CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { Window.open(onlineLink, "opencms-online", null); } public A_CmsContextMenuItem getItemWidget( CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { return null; } public boolean hasItemWidget() { return false; } }; entry = new CmsContextMenuEntry(this, null, command); CmsContextMenuEntryBean entryBean = new CmsContextMenuEntryBean(); entryBean.setLabel(Messages.get().key(Messages.GUI_VIEW_ONLINE_0)); entryBean.setActive(true); entryBean.setVisible(true); entry.setBean(entryBean); } return entry; } }
public class class_name { protected I_CmsContextMenuEntry createViewOnlineEntry() { final String onlineLink = m_controller.getData().getOnlineLink(); CmsContextMenuEntry entry = null; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(onlineLink)) { I_CmsContextMenuCommand command = new I_CmsContextMenuCommand() { public void execute( CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { Window.open(onlineLink, "opencms-online", null); } public A_CmsContextMenuItem getItemWidget( CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { return null; } public boolean hasItemWidget() { return false; } }; entry = new CmsContextMenuEntry(this, null, command); // depends on control dependency: [if], data = [none] CmsContextMenuEntryBean entryBean = new CmsContextMenuEntryBean(); entryBean.setLabel(Messages.get().key(Messages.GUI_VIEW_ONLINE_0)); // depends on control dependency: [if], data = [none] entryBean.setActive(true); // depends on control dependency: [if], data = [none] entryBean.setVisible(true); // depends on control dependency: [if], data = [none] entry.setBean(entryBean); // depends on control dependency: [if], data = [none] } return entry; } }
public class class_name { @CheckForNull public NodeProperty getNodeProperty(String className) { for (NodeProperty p: getNodeProperties()) { if (p.getClass().getName().equals(className)) { return p; } } return null; } }
public class class_name { @CheckForNull public NodeProperty getNodeProperty(String className) { for (NodeProperty p: getNodeProperties()) { if (p.getClass().getName().equals(className)) { return p; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public Matcher getMatcher(String str) { Matcher m; if (matchers.containsKey(str)) { m = matchers.get(str); } else { m = p.matcher(str); matchers.put(str, m); } return m; } }
public class class_name { public Matcher getMatcher(String str) { Matcher m; if (matchers.containsKey(str)) { m = matchers.get(str); // depends on control dependency: [if], data = [none] } else { m = p.matcher(str); // depends on control dependency: [if], data = [none] matchers.put(str, m); // depends on control dependency: [if], data = [none] } return m; } }
public class class_name { public List<T> getPermutation(List<T> storage) { if( storage == null ) storage = new ArrayList<T>(); else storage.clear(); for( int i = 0; i < list.size(); i++ ) { storage.add(get(i)); } return storage; } }
public class class_name { public List<T> getPermutation(List<T> storage) { if( storage == null ) storage = new ArrayList<T>(); else storage.clear(); for( int i = 0; i < list.size(); i++ ) { storage.add(get(i)); // depends on control dependency: [for], data = [i] } return storage; } }
public class class_name { @Nonnull @ReturnsMutableCopy public Matrix getQ () { final Matrix aNewMatrix = new Matrix (m_nRows, m_nCols); final double [] [] aNewArray = aNewMatrix.internalGetArray (); for (int k = m_nCols - 1; k >= 0; k--) { final double [] aQRk = m_aQR[k]; for (int nRow = 0; nRow < m_nRows; nRow++) aNewArray[nRow][k] = 0.0; aNewArray[k][k] = 1.0; for (int j = k; j < m_nCols; j++) { if (aQRk[k] != 0) { double s = 0.0; for (int i = k; i < m_nRows; i++) s += m_aQR[i][k] * aNewArray[i][j]; s = -s / aQRk[k]; for (int i = k; i < m_nRows; i++) { aNewArray[i][j] += s * m_aQR[i][k]; } } } } return aNewMatrix; } }
public class class_name { @Nonnull @ReturnsMutableCopy public Matrix getQ () { final Matrix aNewMatrix = new Matrix (m_nRows, m_nCols); final double [] [] aNewArray = aNewMatrix.internalGetArray (); for (int k = m_nCols - 1; k >= 0; k--) { final double [] aQRk = m_aQR[k]; for (int nRow = 0; nRow < m_nRows; nRow++) aNewArray[nRow][k] = 0.0; aNewArray[k][k] = 1.0; // depends on control dependency: [for], data = [k] for (int j = k; j < m_nCols; j++) { if (aQRk[k] != 0) { double s = 0.0; for (int i = k; i < m_nRows; i++) s += m_aQR[i][k] * aNewArray[i][j]; s = -s / aQRk[k]; // depends on control dependency: [if], data = [none] for (int i = k; i < m_nRows; i++) { aNewArray[i][j] += s * m_aQR[i][k]; // depends on control dependency: [for], data = [i] } } } } return aNewMatrix; } }
public class class_name { public static alluxio.grpc.FileInfo toProto(FileInfo fileInfo) { List<alluxio.grpc.FileBlockInfo> fileBlockInfos = new ArrayList<>(); for (FileBlockInfo fileBlockInfo : fileInfo.getFileBlockInfos()) { fileBlockInfos.add(toProto(fileBlockInfo)); } alluxio.grpc.FileInfo.Builder builder = alluxio.grpc.FileInfo.newBuilder() .setFileId(fileInfo.getFileId()).setName(fileInfo.getName()).setPath(fileInfo.getPath()) .setUfsPath(fileInfo.getUfsPath()).setLength(fileInfo.getLength()) .setBlockSizeBytes(fileInfo.getBlockSizeBytes()) .setCreationTimeMs(fileInfo.getCreationTimeMs()).setCompleted(fileInfo.isCompleted()) .setFolder(fileInfo.isFolder()).setPinned(fileInfo.isPinned()) .setCacheable(fileInfo.isCacheable()).setPersisted(fileInfo.isPersisted()) .addAllBlockIds(fileInfo.getBlockIds()) .setLastModificationTimeMs(fileInfo.getLastModificationTimeMs()).setTtl(fileInfo.getTtl()) .setOwner(fileInfo.getOwner()).setGroup(fileInfo.getGroup()).setMode(fileInfo.getMode()) .setPersistenceState(fileInfo.getPersistenceState()).setMountPoint(fileInfo.isMountPoint()) .addAllFileBlockInfos(fileBlockInfos) .setTtlAction(fileInfo.getTtlAction()).setMountId(fileInfo.getMountId()) .setInAlluxioPercentage(fileInfo.getInAlluxioPercentage()) .setInMemoryPercentage(fileInfo.getInMemoryPercentage()) .setUfsFingerprint(fileInfo.getUfsFingerprint()) .setReplicationMax(fileInfo.getReplicationMax()) .setReplicationMin(fileInfo.getReplicationMin()); if (!fileInfo.getAcl().equals(AccessControlList.EMPTY_ACL)) { builder.setAcl(toProto(fileInfo.getAcl())); } if (!fileInfo.getDefaultAcl().equals(DefaultAccessControlList.EMPTY_DEFAULT_ACL)) { builder.setDefaultAcl(toProto(fileInfo.getDefaultAcl())); } return builder.build(); } }
public class class_name { public static alluxio.grpc.FileInfo toProto(FileInfo fileInfo) { List<alluxio.grpc.FileBlockInfo> fileBlockInfos = new ArrayList<>(); for (FileBlockInfo fileBlockInfo : fileInfo.getFileBlockInfos()) { fileBlockInfos.add(toProto(fileBlockInfo)); // depends on control dependency: [for], data = [fileBlockInfo] } alluxio.grpc.FileInfo.Builder builder = alluxio.grpc.FileInfo.newBuilder() .setFileId(fileInfo.getFileId()).setName(fileInfo.getName()).setPath(fileInfo.getPath()) .setUfsPath(fileInfo.getUfsPath()).setLength(fileInfo.getLength()) .setBlockSizeBytes(fileInfo.getBlockSizeBytes()) .setCreationTimeMs(fileInfo.getCreationTimeMs()).setCompleted(fileInfo.isCompleted()) .setFolder(fileInfo.isFolder()).setPinned(fileInfo.isPinned()) .setCacheable(fileInfo.isCacheable()).setPersisted(fileInfo.isPersisted()) .addAllBlockIds(fileInfo.getBlockIds()) .setLastModificationTimeMs(fileInfo.getLastModificationTimeMs()).setTtl(fileInfo.getTtl()) .setOwner(fileInfo.getOwner()).setGroup(fileInfo.getGroup()).setMode(fileInfo.getMode()) .setPersistenceState(fileInfo.getPersistenceState()).setMountPoint(fileInfo.isMountPoint()) .addAllFileBlockInfos(fileBlockInfos) .setTtlAction(fileInfo.getTtlAction()).setMountId(fileInfo.getMountId()) .setInAlluxioPercentage(fileInfo.getInAlluxioPercentage()) .setInMemoryPercentage(fileInfo.getInMemoryPercentage()) .setUfsFingerprint(fileInfo.getUfsFingerprint()) .setReplicationMax(fileInfo.getReplicationMax()) .setReplicationMin(fileInfo.getReplicationMin()); if (!fileInfo.getAcl().equals(AccessControlList.EMPTY_ACL)) { builder.setAcl(toProto(fileInfo.getAcl())); // depends on control dependency: [if], data = [none] } if (!fileInfo.getDefaultAcl().equals(DefaultAccessControlList.EMPTY_DEFAULT_ACL)) { builder.setDefaultAcl(toProto(fileInfo.getDefaultAcl())); // depends on control dependency: [if], data = [none] } return builder.build(); } }
public class class_name { private List<String> computePath( AbstractPath specifiedClasspath ) { List<Artifact> artifacts = new ArrayList<>(); List<Path> theClasspathFiles = new ArrayList<>(); List<String> resultList = new ArrayList<>(); collectProjectArtifactsAndClasspath( artifacts, theClasspathFiles ); if ( ( specifiedClasspath != null ) && ( specifiedClasspath.getDependencies() != null ) ) { artifacts = filterArtifacts( artifacts, specifiedClasspath.getDependencies() ); } for ( Path f : theClasspathFiles ) { resultList.add( f.toAbsolutePath().toString() ); } for ( Artifact artifact : artifacts ) { getLog().debug( "dealing with " + artifact ); resultList.add( artifact.getFile().getAbsolutePath() ); } return resultList; } }
public class class_name { private List<String> computePath( AbstractPath specifiedClasspath ) { List<Artifact> artifacts = new ArrayList<>(); List<Path> theClasspathFiles = new ArrayList<>(); List<String> resultList = new ArrayList<>(); collectProjectArtifactsAndClasspath( artifacts, theClasspathFiles ); if ( ( specifiedClasspath != null ) && ( specifiedClasspath.getDependencies() != null ) ) { artifacts = filterArtifacts( artifacts, specifiedClasspath.getDependencies() ); // depends on control dependency: [if], data = [none] } for ( Path f : theClasspathFiles ) { resultList.add( f.toAbsolutePath().toString() ); // depends on control dependency: [for], data = [f] } for ( Artifact artifact : artifacts ) { getLog().debug( "dealing with " + artifact ); // depends on control dependency: [for], data = [artifact] resultList.add( artifact.getFile().getAbsolutePath() ); // depends on control dependency: [for], data = [artifact] } return resultList; } }
public class class_name { public int deleteIds(String type) { int deleted = 0; try { if (contentsIdDao.isTableExists()) { List<ContentsId> contentsIds = getIds(type); deleted = contentsIdDao.delete(contentsIds); } } catch (SQLException e) { throw new GeoPackageException( "Failed to delete contents ids by type. GeoPackage: " + geoPackage.getName() + ", Type: " + type, e); } return deleted; } }
public class class_name { public int deleteIds(String type) { int deleted = 0; try { if (contentsIdDao.isTableExists()) { List<ContentsId> contentsIds = getIds(type); deleted = contentsIdDao.delete(contentsIds); // depends on control dependency: [if], data = [none] } } catch (SQLException e) { throw new GeoPackageException( "Failed to delete contents ids by type. GeoPackage: " + geoPackage.getName() + ", Type: " + type, e); } // depends on control dependency: [catch], data = [none] return deleted; } }
public class class_name { public List<BeanSpec> fields($.Predicate<Field> filter) { List<BeanSpec> retVal = new ArrayList<>(); BeanSpec current = this; Class<?> rawType = rawType(); if ($.isSimpleType(rawType)) { return C.list(); } Type[] typeDeclarations = rawType.getTypeParameters(); Map<String, Class> typeImplLookup = null; while (null != current && current.isNotObject()) { Type[] fieldTypeParams = null; Type[] classTypeParams; Map<String, Type> typeParamsMapping = new HashMap<>(); for (Field field : current.rawType().getDeclaredFields()) { if (!filter.test(field)) { continue; } Type fieldGenericType = field.getGenericType(); if (fieldGenericType instanceof ParameterizedType) { if (null == fieldTypeParams) { fieldTypeParams = ((ParameterizedType) fieldGenericType).getActualTypeArguments(); if (fieldTypeParams != null && fieldTypeParams.length > 0) { classTypeParams = current.rawType().getTypeParameters(); if (classTypeParams != null && classTypeParams.length > 0) { List<Type> classTypeImpls = current.typeParams(); for (int i = 0; i < classTypeParams.length; ++i) { if (i >= classTypeImpls.size()) { break; } Type classTypeParam = classTypeParams[i]; if (classTypeParam instanceof TypeVariable) { typeParamsMapping.put(((TypeVariable) classTypeParam).getName(), classTypeImpls.get(i)); } } } } } boolean updated = false; if (!typeParamsMapping.isEmpty()) { for (int i = 0; i < fieldTypeParams.length; ++i) { Type typeArg = fieldTypeParams[i]; if (typeArg instanceof TypeVariable) { String name = ((TypeVariable) typeArg).getName(); Type typeImpl = typeParamsMapping.get(name); if (null != typeImpl && $.ne(typeImpl, typeArg)) { updated = true; fieldTypeParams[i] = typeImpl; } } } } if (updated) { fieldGenericType = new ParameterizedTypeImpl(fieldTypeParams, ((ParameterizedType) fieldGenericType).getOwnerType(), ((ParameterizedType) fieldGenericType).getRawType()); } retVal.add(beanSpecOf(field, fieldGenericType)); } else if (fieldGenericType instanceof TypeVariable) { if (null == typeImplLookup) { typeImplLookup = Generics.buildTypeParamImplLookup(this.rawType); if (null != fieldTypeImplLookup) { typeImplLookup.putAll(fieldTypeImplLookup); } } TypeVariable fieldType = (TypeVariable) fieldGenericType; Class clazz = typeImplLookup.get(fieldType.getName()); if (null != clazz) { retVal.add(of(field, fieldGenericType, injector, typeImplLookup)); } else { boolean added = false; for (int i = typeDeclarations.length - 1; i >= 0; --i) { if (typeDeclarations[i].equals(fieldGenericType)) { fieldGenericType = current.typeParams().get(i); retVal.add(of(field, fieldGenericType, injector, typeImplLookup)); added = true; break; } } if (!added) { throw new InjectException("Cannot infer field type: " + field); } } } else if (fieldGenericType instanceof GenericArrayType) { if (null == typeImplLookup) { typeImplLookup = Generics.buildTypeParamImplLookup(this.rawType); } retVal.add(of(field, injector(), typeImplLookup)); } else { retVal.add(of(field, injector())); } } current = current.parent(); if (null != current) { typeDeclarations = current.rawType.getTypeParameters(); } } return retVal; } }
public class class_name { public List<BeanSpec> fields($.Predicate<Field> filter) { List<BeanSpec> retVal = new ArrayList<>(); BeanSpec current = this; Class<?> rawType = rawType(); if ($.isSimpleType(rawType)) { return C.list(); // depends on control dependency: [if], data = [none] } Type[] typeDeclarations = rawType.getTypeParameters(); Map<String, Class> typeImplLookup = null; while (null != current && current.isNotObject()) { Type[] fieldTypeParams = null; Type[] classTypeParams; Map<String, Type> typeParamsMapping = new HashMap<>(); for (Field field : current.rawType().getDeclaredFields()) { if (!filter.test(field)) { continue; } Type fieldGenericType = field.getGenericType(); if (fieldGenericType instanceof ParameterizedType) { if (null == fieldTypeParams) { fieldTypeParams = ((ParameterizedType) fieldGenericType).getActualTypeArguments(); // depends on control dependency: [if], data = [none] if (fieldTypeParams != null && fieldTypeParams.length > 0) { classTypeParams = current.rawType().getTypeParameters(); // depends on control dependency: [if], data = [none] if (classTypeParams != null && classTypeParams.length > 0) { List<Type> classTypeImpls = current.typeParams(); for (int i = 0; i < classTypeParams.length; ++i) { if (i >= classTypeImpls.size()) { break; } Type classTypeParam = classTypeParams[i]; if (classTypeParam instanceof TypeVariable) { typeParamsMapping.put(((TypeVariable) classTypeParam).getName(), classTypeImpls.get(i)); // depends on control dependency: [if], data = [none] } } } } } boolean updated = false; if (!typeParamsMapping.isEmpty()) { for (int i = 0; i < fieldTypeParams.length; ++i) { Type typeArg = fieldTypeParams[i]; if (typeArg instanceof TypeVariable) { String name = ((TypeVariable) typeArg).getName(); Type typeImpl = typeParamsMapping.get(name); if (null != typeImpl && $.ne(typeImpl, typeArg)) { updated = true; // depends on control dependency: [if], data = [none] fieldTypeParams[i] = typeImpl; // depends on control dependency: [if], data = [none] } } } } if (updated) { fieldGenericType = new ParameterizedTypeImpl(fieldTypeParams, ((ParameterizedType) fieldGenericType).getOwnerType(), ((ParameterizedType) fieldGenericType).getRawType()); // depends on control dependency: [if], data = [none] } retVal.add(beanSpecOf(field, fieldGenericType)); // depends on control dependency: [if], data = [none] } else if (fieldGenericType instanceof TypeVariable) { if (null == typeImplLookup) { typeImplLookup = Generics.buildTypeParamImplLookup(this.rawType); // depends on control dependency: [if], data = [none] if (null != fieldTypeImplLookup) { typeImplLookup.putAll(fieldTypeImplLookup); // depends on control dependency: [if], data = [fieldTypeImplLookup)] } } TypeVariable fieldType = (TypeVariable) fieldGenericType; Class clazz = typeImplLookup.get(fieldType.getName()); if (null != clazz) { retVal.add(of(field, fieldGenericType, injector, typeImplLookup)); // depends on control dependency: [if], data = [none] } else { boolean added = false; for (int i = typeDeclarations.length - 1; i >= 0; --i) { if (typeDeclarations[i].equals(fieldGenericType)) { fieldGenericType = current.typeParams().get(i); // depends on control dependency: [if], data = [none] retVal.add(of(field, fieldGenericType, injector, typeImplLookup)); // depends on control dependency: [if], data = [none] added = true; // depends on control dependency: [if], data = [none] break; } } if (!added) { throw new InjectException("Cannot infer field type: " + field); } } } else if (fieldGenericType instanceof GenericArrayType) { if (null == typeImplLookup) { typeImplLookup = Generics.buildTypeParamImplLookup(this.rawType); // depends on control dependency: [if], data = [none] } retVal.add(of(field, injector(), typeImplLookup)); // depends on control dependency: [if], data = [none] } else { retVal.add(of(field, injector())); // depends on control dependency: [if], data = [none] } } current = current.parent(); // depends on control dependency: [while], data = [none] if (null != current) { typeDeclarations = current.rawType.getTypeParameters(); // depends on control dependency: [if], data = [none] } } return retVal; } }
public class class_name { protected void storeExtension(Extension e, XMLStreamWriter writer, String elementName) throws XMLStreamException { writer.writeStartElement(elementName); writer.writeAttribute(CommonXML.ATTRIBUTE_CLASS_NAME, e.getValue(CommonXML.ATTRIBUTE_CLASS_NAME, e.getClassName())); if (e.getModuleName() != null) writer.writeAttribute(CommonXML.ATTRIBUTE_MODULE_NAME, e.getValue(CommonXML.ATTRIBUTE_MODULE_NAME, e.getModuleName())); if (e.getModuleSlot() != null) writer.writeAttribute(CommonXML.ATTRIBUTE_MODULE_SLOT, e.getValue(CommonXML.ATTRIBUTE_MODULE_SLOT, e.getModuleSlot())); if (!e.getConfigPropertiesMap().isEmpty()) { Iterator<Map.Entry<String, String>> it = e.getConfigPropertiesMap().entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); writer.writeStartElement(CommonXML.ELEMENT_CONFIG_PROPERTY); writer.writeAttribute(CommonXML.ATTRIBUTE_NAME, entry.getKey()); writer.writeCharacters(e.getValue(CommonXML.ELEMENT_CONFIG_PROPERTY, entry.getKey(), entry.getValue())); writer.writeEndElement(); } } writer.writeEndElement(); } }
public class class_name { protected void storeExtension(Extension e, XMLStreamWriter writer, String elementName) throws XMLStreamException { writer.writeStartElement(elementName); writer.writeAttribute(CommonXML.ATTRIBUTE_CLASS_NAME, e.getValue(CommonXML.ATTRIBUTE_CLASS_NAME, e.getClassName())); if (e.getModuleName() != null) writer.writeAttribute(CommonXML.ATTRIBUTE_MODULE_NAME, e.getValue(CommonXML.ATTRIBUTE_MODULE_NAME, e.getModuleName())); if (e.getModuleSlot() != null) writer.writeAttribute(CommonXML.ATTRIBUTE_MODULE_SLOT, e.getValue(CommonXML.ATTRIBUTE_MODULE_SLOT, e.getModuleSlot())); if (!e.getConfigPropertiesMap().isEmpty()) { Iterator<Map.Entry<String, String>> it = e.getConfigPropertiesMap().entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); writer.writeStartElement(CommonXML.ELEMENT_CONFIG_PROPERTY); // depends on control dependency: [while], data = [none] writer.writeAttribute(CommonXML.ATTRIBUTE_NAME, entry.getKey()); // depends on control dependency: [while], data = [none] writer.writeCharacters(e.getValue(CommonXML.ELEMENT_CONFIG_PROPERTY, entry.getKey(), entry.getValue())); // depends on control dependency: [while], data = [none] writer.writeEndElement(); // depends on control dependency: [while], data = [none] } } writer.writeEndElement(); } }
public class class_name { public ListElasticsearchInstanceTypesResult withElasticsearchInstanceTypes(ESPartitionInstanceType... elasticsearchInstanceTypes) { java.util.ArrayList<String> elasticsearchInstanceTypesCopy = new java.util.ArrayList<String>(elasticsearchInstanceTypes.length); for (ESPartitionInstanceType value : elasticsearchInstanceTypes) { elasticsearchInstanceTypesCopy.add(value.toString()); } if (getElasticsearchInstanceTypes() == null) { setElasticsearchInstanceTypes(elasticsearchInstanceTypesCopy); } else { getElasticsearchInstanceTypes().addAll(elasticsearchInstanceTypesCopy); } return this; } }
public class class_name { public ListElasticsearchInstanceTypesResult withElasticsearchInstanceTypes(ESPartitionInstanceType... elasticsearchInstanceTypes) { java.util.ArrayList<String> elasticsearchInstanceTypesCopy = new java.util.ArrayList<String>(elasticsearchInstanceTypes.length); for (ESPartitionInstanceType value : elasticsearchInstanceTypes) { elasticsearchInstanceTypesCopy.add(value.toString()); // depends on control dependency: [for], data = [value] } if (getElasticsearchInstanceTypes() == null) { setElasticsearchInstanceTypes(elasticsearchInstanceTypesCopy); // depends on control dependency: [if], data = [none] } else { getElasticsearchInstanceTypes().addAll(elasticsearchInstanceTypesCopy); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { @Override public void updateProgress(float value) { final int size = mTransitionList.size(); for (int i = 0; i < size; i++) { mTransitionList.get(i).updateProgress(value); } } }
public class class_name { @Override public void updateProgress(float value) { final int size = mTransitionList.size(); for (int i = 0; i < size; i++) { mTransitionList.get(i).updateProgress(value); // depends on control dependency: [for], data = [i] } } }
public class class_name { private static void internalCopyBitmap(Bitmap destBitmap, Bitmap sourceBitmap) { if (destBitmap.getConfig() == sourceBitmap.getConfig()) { Bitmaps.copyBitmap(destBitmap, sourceBitmap); } else { // The bitmap configurations might be different when the source bitmap's configuration is // null, because it uses an internal configuration and the destination bitmap's configuration // is the FALLBACK_BITMAP_CONFIGURATION. This is the case for static images for animated GIFs. Canvas canvas = new Canvas(destBitmap); canvas.drawBitmap(sourceBitmap, 0, 0, null); } } }
public class class_name { private static void internalCopyBitmap(Bitmap destBitmap, Bitmap sourceBitmap) { if (destBitmap.getConfig() == sourceBitmap.getConfig()) { Bitmaps.copyBitmap(destBitmap, sourceBitmap); // depends on control dependency: [if], data = [none] } else { // The bitmap configurations might be different when the source bitmap's configuration is // null, because it uses an internal configuration and the destination bitmap's configuration // is the FALLBACK_BITMAP_CONFIGURATION. This is the case for static images for animated GIFs. Canvas canvas = new Canvas(destBitmap); canvas.drawBitmap(sourceBitmap, 0, 0, null); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static final char[] append(char[] array, char suffix) { if (array == null) { return new char[] { suffix }; } int length = array.length; System.arraycopy(array, 0, array = new char[length + 1], 0, length); array[length] = suffix; return array; } }
public class class_name { public static final char[] append(char[] array, char suffix) { if (array == null) { return new char[] { suffix }; // depends on control dependency: [if], data = [none] } int length = array.length; System.arraycopy(array, 0, array = new char[length + 1], 0, length); array[length] = suffix; return array; } }
public class class_name { public void setUsername (Name username, final UserChangeListener ucl) { ClientResolutionListener clr = new ClientResolutionListener() { public void clientResolved (final Name username, final ClientObject clobj) { // if they old client object is gone by now, they ended their session while we were // switching, so freak out if (_clobj == null) { log.warning("Client disappeared before we could complete the switch to a " + "new client object", "ousername", clobj.username, "nusername", username); _clmgr.releaseClientObject(username); Exception error = new Exception("Early withdrawal"); resolutionFailed(username, error); return; } // call down to any derived classes clientObjectWillChange(_clobj, clobj); // let the caller know that we've got some new business if (ucl != null) { ucl.changeReported(clobj, new ResultListener<Void>() { public void requestCompleted (Void result) { finishResolved(username, clobj); } public void requestFailed (Exception cause) { finishResolved(username, clobj); } }); } else { finishResolved(username, clobj); } } /** * Finish the final phase of the switch. */ protected void finishResolved (Name username, ClientObject clobj) { // let the client know that the rug has been yanked out from under their ass Object[] args = new Object[] { clobj.getOid() }; _clobj.postMessage(ClientObject.CLOBJ_CHANGED, args); // release our old client object; this will destroy it _clmgr.releaseClientObject(_clobj.username); // update our internal fields _clobj = clobj; // call down to any derived classes clientObjectDidChange(_clobj); // let our listener know we're groovy if (ucl != null) { ucl.changeCompleted(_clobj); } } public void resolutionFailed (Name username, Exception reason) { Name oldName = (_clobj == null) ? null : _clobj.username; log.warning("Unable to resolve new client object", "oldname", oldName, "newname", username, "reason", reason, reason); // let our listener know we're hosed if (ucl != null) { ucl.changeFailed(reason); } } }; // resolve the new client object _clmgr.resolveClientObject(username, clr); } }
public class class_name { public void setUsername (Name username, final UserChangeListener ucl) { ClientResolutionListener clr = new ClientResolutionListener() { public void clientResolved (final Name username, final ClientObject clobj) { // if they old client object is gone by now, they ended their session while we were // switching, so freak out if (_clobj == null) { log.warning("Client disappeared before we could complete the switch to a " + "new client object", "ousername", clobj.username, "nusername", username); // depends on control dependency: [if], data = [none] _clmgr.releaseClientObject(username); // depends on control dependency: [if], data = [none] Exception error = new Exception("Early withdrawal"); resolutionFailed(username, error); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // call down to any derived classes clientObjectWillChange(_clobj, clobj); // let the caller know that we've got some new business if (ucl != null) { ucl.changeReported(clobj, new ResultListener<Void>() { public void requestCompleted (Void result) { finishResolved(username, clobj); } public void requestFailed (Exception cause) { finishResolved(username, clobj); } }); // depends on control dependency: [if], data = [none] } else { finishResolved(username, clobj); // depends on control dependency: [if], data = [none] } } /** * Finish the final phase of the switch. */ protected void finishResolved (Name username, ClientObject clobj) { // let the client know that the rug has been yanked out from under their ass Object[] args = new Object[] { clobj.getOid() }; _clobj.postMessage(ClientObject.CLOBJ_CHANGED, args); // release our old client object; this will destroy it _clmgr.releaseClientObject(_clobj.username); // update our internal fields _clobj = clobj; // call down to any derived classes clientObjectDidChange(_clobj); // let our listener know we're groovy if (ucl != null) { ucl.changeCompleted(_clobj); // depends on control dependency: [if], data = [none] } } public void resolutionFailed (Name username, Exception reason) { Name oldName = (_clobj == null) ? null : _clobj.username; log.warning("Unable to resolve new client object", "oldname", oldName, "newname", username, "reason", reason, reason); // let our listener know we're hosed if (ucl != null) { ucl.changeFailed(reason); // depends on control dependency: [if], data = [none] } } }; // resolve the new client object _clmgr.resolveClientObject(username, clr); } }
public class class_name { private Object addSettingParameter(Setting setting, String key, String value) { if ("startOnBoot".equals(key)) { setting.setStartOnBoot(Boolean.parseBoolean(value)); } else if ("enableVerbose".equals(key)) { setting.setEnableVerbose(Boolean.parseBoolean(value)); } else if ("maxLogFileSize".equals(key)) { setting.setMaxLogFileSize(BigInteger.valueOf(Long.parseLong(value))); } else if ("maxLogFileCount".equals(key)) { setting.setMaxLogFileCount(BigInteger.valueOf(Long.parseLong(value))); } else if ("threadCount".equals(key)) { setting.setThreadCount(BigInteger.valueOf(Long.parseLong(value))); } else if ("NTService".equals(key)) { if (setting.getNTService() == null) { setting.setNTService(new NTService()); } return setting.getNTService(); } else if ("java".equals(key)) { if (setting.getJava() == null) { setting.setJava(new Java()); } return setting.getJava(); } return setting; } }
public class class_name { private Object addSettingParameter(Setting setting, String key, String value) { if ("startOnBoot".equals(key)) { setting.setStartOnBoot(Boolean.parseBoolean(value)); // depends on control dependency: [if], data = [none] } else if ("enableVerbose".equals(key)) { setting.setEnableVerbose(Boolean.parseBoolean(value)); // depends on control dependency: [if], data = [none] } else if ("maxLogFileSize".equals(key)) { setting.setMaxLogFileSize(BigInteger.valueOf(Long.parseLong(value))); // depends on control dependency: [if], data = [none] } else if ("maxLogFileCount".equals(key)) { setting.setMaxLogFileCount(BigInteger.valueOf(Long.parseLong(value))); // depends on control dependency: [if], data = [none] } else if ("threadCount".equals(key)) { setting.setThreadCount(BigInteger.valueOf(Long.parseLong(value))); // depends on control dependency: [if], data = [none] } else if ("NTService".equals(key)) { if (setting.getNTService() == null) { setting.setNTService(new NTService()); // depends on control dependency: [if], data = [none] } return setting.getNTService(); // depends on control dependency: [if], data = [none] } else if ("java".equals(key)) { if (setting.getJava() == null) { setting.setJava(new Java()); // depends on control dependency: [if], data = [none] } return setting.getJava(); // depends on control dependency: [if], data = [none] } return setting; } }
public class class_name { public String appendFileSeparator(String path) { if (null == path) { return File.separator; } // add "/" prefix if (!path.startsWith(StringPool.SLASH) && !path.startsWith(StringPool.BACK_SLASH)) { path = File.separator + path; } // add "/" postfix if (!path.endsWith(StringPool.SLASH) && !path.endsWith(StringPool.BACK_SLASH)) { path = path + File.separator; } return path; } }
public class class_name { public String appendFileSeparator(String path) { if (null == path) { return File.separator; // depends on control dependency: [if], data = [none] } // add "/" prefix if (!path.startsWith(StringPool.SLASH) && !path.startsWith(StringPool.BACK_SLASH)) { path = File.separator + path; // depends on control dependency: [if], data = [none] } // add "/" postfix if (!path.endsWith(StringPool.SLASH) && !path.endsWith(StringPool.BACK_SLASH)) { path = path + File.separator; // depends on control dependency: [if], data = [none] } return path; } }
public class class_name { public BoundingBox overlap(BoundingBox projectedCoverage) { BoundingBox overlap = null; if (point) { overlap = projectedBoundingBox; } else { overlap = projectedBoundingBox.overlap(projectedCoverage); } return overlap; } }
public class class_name { public BoundingBox overlap(BoundingBox projectedCoverage) { BoundingBox overlap = null; if (point) { overlap = projectedBoundingBox; // depends on control dependency: [if], data = [none] } else { overlap = projectedBoundingBox.overlap(projectedCoverage); // depends on control dependency: [if], data = [none] } return overlap; } }
public class class_name { public static final void setActiveSession(Session session) { synchronized (Session.STATIC_LOCK) { if (session != Session.activeSession) { Session oldSession = Session.activeSession; if (oldSession != null) { oldSession.close(); } Session.activeSession = session; if (oldSession != null) { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_UNSET); } if (session != null) { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_SET); if (session.isOpened()) { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_OPENED); } } } } } }
public class class_name { public static final void setActiveSession(Session session) { synchronized (Session.STATIC_LOCK) { if (session != Session.activeSession) { Session oldSession = Session.activeSession; if (oldSession != null) { oldSession.close(); // depends on control dependency: [if], data = [none] } Session.activeSession = session; // depends on control dependency: [if], data = [none] if (oldSession != null) { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_UNSET); // depends on control dependency: [if], data = [none] } if (session != null) { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_SET); // depends on control dependency: [if], data = [none] if (session.isOpened()) { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_OPENED); // depends on control dependency: [if], data = [none] } } } } } }
public class class_name { private boolean attemptToBind(final int port) throws Throwable { log.debug("Attempting to start {} on port {}.", serverName, port); this.queryExecutor = createQueryExecutor(); this.handler = initializeHandler(); final NettyBufferPool bufferPool = new NettyBufferPool(numEventLoopThreads); final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("Flink " + serverName + " EventLoop Thread %d") .build(); final NioEventLoopGroup nioGroup = new NioEventLoopGroup(numEventLoopThreads, threadFactory); this.bootstrap = new ServerBootstrap() .localAddress(bindAddress, port) .group(nioGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.ALLOCATOR, bufferPool) .childOption(ChannelOption.ALLOCATOR, bufferPool) .childHandler(new ServerChannelInitializer<>(handler)); final int defaultHighWaterMark = 64 * 1024; // from DefaultChannelConfig (not exposed) //noinspection ConstantConditions // (ignore warning here to make this flexible in case the configuration values change) if (LOW_WATER_MARK > defaultHighWaterMark) { bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK); bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK); } else { // including (newHighWaterMark < defaultLowWaterMark) bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK); bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK); } try { final ChannelFuture future = bootstrap.bind().sync(); if (future.isSuccess()) { final InetSocketAddress localAddress = (InetSocketAddress) future.channel().localAddress(); serverAddress = new InetSocketAddress(localAddress.getAddress(), localAddress.getPort()); return true; } // the following throw is to bypass Netty's "optimization magic" // and catch the bind exception. // the exception is thrown by the sync() call above. throw future.cause(); } catch (BindException e) { log.debug("Failed to start {} on port {}: {}.", serverName, port, e.getMessage()); try { // we shutdown the server but we reset the future every time because in // case of failure to bind, we will call attemptToBind() here, and not resetting // the flag will interfere with future shutdown attempts. shutdownServer() .whenComplete((ignoredV, ignoredT) -> serverShutdownFuture.getAndSet(null)) .get(); } catch (Exception r) { // Here we were seeing this problem: // https://github.com/netty/netty/issues/4357 if we do a get(). // this is why we now simply wait a bit so that everything is shut down. log.warn("Problem while shutting down {}: {}", serverName, r.getMessage()); } } // any other type of exception we let it bubble up. return false; } }
public class class_name { private boolean attemptToBind(final int port) throws Throwable { log.debug("Attempting to start {} on port {}.", serverName, port); this.queryExecutor = createQueryExecutor(); this.handler = initializeHandler(); final NettyBufferPool bufferPool = new NettyBufferPool(numEventLoopThreads); final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("Flink " + serverName + " EventLoop Thread %d") .build(); final NioEventLoopGroup nioGroup = new NioEventLoopGroup(numEventLoopThreads, threadFactory); this.bootstrap = new ServerBootstrap() .localAddress(bindAddress, port) .group(nioGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.ALLOCATOR, bufferPool) .childOption(ChannelOption.ALLOCATOR, bufferPool) .childHandler(new ServerChannelInitializer<>(handler)); final int defaultHighWaterMark = 64 * 1024; // from DefaultChannelConfig (not exposed) //noinspection ConstantConditions // (ignore warning here to make this flexible in case the configuration values change) if (LOW_WATER_MARK > defaultHighWaterMark) { bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK); bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK); } else { // including (newHighWaterMark < defaultLowWaterMark) bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK); bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK); } try { final ChannelFuture future = bootstrap.bind().sync(); if (future.isSuccess()) { final InetSocketAddress localAddress = (InetSocketAddress) future.channel().localAddress(); serverAddress = new InetSocketAddress(localAddress.getAddress(), localAddress.getPort()); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } // the following throw is to bypass Netty's "optimization magic" // and catch the bind exception. // the exception is thrown by the sync() call above. throw future.cause(); } catch (BindException e) { log.debug("Failed to start {} on port {}: {}.", serverName, port, e.getMessage()); try { // we shutdown the server but we reset the future every time because in // case of failure to bind, we will call attemptToBind() here, and not resetting // the flag will interfere with future shutdown attempts. shutdownServer() .whenComplete((ignoredV, ignoredT) -> serverShutdownFuture.getAndSet(null)) .get(); } catch (Exception r) { // Here we were seeing this problem: // https://github.com/netty/netty/issues/4357 if we do a get(). // this is why we now simply wait a bit so that everything is shut down. log.warn("Problem while shutting down {}: {}", serverName, r.getMessage()); } } // any other type of exception we let it bubble up. return false; } }
public class class_name { public static boolean isValidJson(String s) { try { new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s, FakeMapper.DEFAULT); return true; } catch (ParseException e) { return false; } } }
public class class_name { public static boolean isValidJson(String s) { try { new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(s, FakeMapper.DEFAULT); // depends on control dependency: [try], data = [none] return true; // depends on control dependency: [try], data = [none] } catch (ParseException e) { return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static <T extends Object> boolean arraryContains(T[] array, T value) { // Si le tableau est vide if(array == null || array.length == 0) { // On retourne false return false; } // Si le mode est vide if(value == null) { // On retourne false return false; } // Mode dedans boolean modeIn = false; // Index du Tableau int index = 0; // Parcours while(index < array.length && !modeIn) { // Valeur du Tableau T tValue = array[index++]; modeIn = tValue.equals(value); } // On retourne false return modeIn; } }
public class class_name { public static <T extends Object> boolean arraryContains(T[] array, T value) { // Si le tableau est vide if(array == null || array.length == 0) { // On retourne false return false; // depends on control dependency: [if], data = [none] } // Si le mode est vide if(value == null) { // On retourne false return false; // depends on control dependency: [if], data = [none] } // Mode dedans boolean modeIn = false; // Index du Tableau int index = 0; // Parcours while(index < array.length && !modeIn) { // Valeur du Tableau T tValue = array[index++]; modeIn = tValue.equals(value); // depends on control dependency: [while], data = [none] } // On retourne false return modeIn; } }
public class class_name { public static void execute( int parallelism, ExecutorService executorService, int globalMin, int globalMax, final RangeExecutor rangeExecutor) { if (parallelism <= 0) { throw new IllegalArgumentException( "Parallelism must be positive, but is " + parallelism); } if (globalMin > globalMax) { throw new IllegalArgumentException( "The global minimum may not be larger than the global " + "maximum. Global minimum is "+globalMin+", " + "global maximum is "+globalMax); } int range = globalMax - globalMin; if (range == 0) { return; } int numTasks = Math.min(range, parallelism); int localRange = (range - 1) / numTasks + 1; int spare = localRange * numTasks - range; int currentIndex = globalMin; List<Callable<Object>> tasks = new ArrayList<Callable<Object>>(numTasks); for (int i = 0; i < numTasks; i++) { final int taskIndex = i; final int min = currentIndex; final int max = min + localRange - (i < spare ? 1 : 0); Runnable runnable = new Runnable() { @Override public void run() { rangeExecutor.execute(taskIndex, min, max); } }; tasks.add(Executors.callable(runnable)); currentIndex = max; } try { executorService.invokeAll(tasks); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
public class class_name { public static void execute( int parallelism, ExecutorService executorService, int globalMin, int globalMax, final RangeExecutor rangeExecutor) { if (parallelism <= 0) { throw new IllegalArgumentException( "Parallelism must be positive, but is " + parallelism); } if (globalMin > globalMax) { throw new IllegalArgumentException( "The global minimum may not be larger than the global " + "maximum. Global minimum is "+globalMin+", " + "global maximum is "+globalMax); } int range = globalMax - globalMin; if (range == 0) { return; // depends on control dependency: [if], data = [none] } int numTasks = Math.min(range, parallelism); int localRange = (range - 1) / numTasks + 1; int spare = localRange * numTasks - range; int currentIndex = globalMin; List<Callable<Object>> tasks = new ArrayList<Callable<Object>>(numTasks); for (int i = 0; i < numTasks; i++) { final int taskIndex = i; final int min = currentIndex; final int max = min + localRange - (i < spare ? 1 : 0); Runnable runnable = new Runnable() { @Override public void run() { rangeExecutor.execute(taskIndex, min, max); } }; tasks.add(Executors.callable(runnable)); // depends on control dependency: [for], data = [none] currentIndex = max; // depends on control dependency: [for], data = [none] } try { executorService.invokeAll(tasks); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { Thread.currentThread().interrupt(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public ValidationResult validate () { long validationStartTime = System.currentTimeMillis(); // Create an empty validation result that will have its fields populated by certain validators. ValidationResult validationResult = new ValidationResult(); // Error tables should already be present from the initial load. // Reconnect to the existing error tables. SQLErrorStorage errorStorage = null; try { errorStorage = new SQLErrorStorage(dataSource.getConnection(), tablePrefix, false); } catch (SQLException | InvalidNamespaceException ex) { throw new StorageException(ex); } int errorCountBeforeValidation = errorStorage.getErrorCount(); List<FeedValidator> feedValidators = Arrays.asList( new MisplacedStopValidator(this, errorStorage, validationResult), new DuplicateStopsValidator(this, errorStorage), new TimeZoneValidator(this, errorStorage), new NewTripTimesValidator(this, errorStorage), new NamesValidator(this, errorStorage)); for (FeedValidator feedValidator : feedValidators) { String validatorName = feedValidator.getClass().getSimpleName(); try { LOG.info("Running {}.", validatorName); int errorCountBefore = errorStorage.getErrorCount(); // todo why not just pass the feed and errorstorage in here? feedValidator.validate(); LOG.info("{} found {} errors.", validatorName, errorStorage.getErrorCount() - errorCountBefore); } catch (Exception e) { // store an error if the validator fails // FIXME: should the exception be stored? String badValue = String.join(":", validatorName, e.toString()); errorStorage.storeError(NewGTFSError.forFeed(VALIDATOR_FAILED, badValue)); LOG.error("{} failed.", validatorName); LOG.error(e.toString()); e.printStackTrace(); } } // Signal to all validators that validation is complete and allow them to report on results / status. for (FeedValidator feedValidator : feedValidators) { try { feedValidator.complete(validationResult); } catch (Exception e) { String badValue = String.join(":", feedValidator.getClass().getSimpleName(), e.toString()); errorStorage.storeError(NewGTFSError.forFeed(VALIDATOR_FAILED, badValue)); LOG.error("Validator failed completion stage.", e); } } // Total validation errors accounts for errors found during both loading and validation. Otherwise, this value // may be confusing if it reads zero but there were a number of data type or referential integrity errors found // during feed loading stage. int totalValidationErrors = errorStorage.getErrorCount(); LOG.info("Errors found during load stage: {}", errorCountBeforeValidation); LOG.info("Errors found by validators: {}", totalValidationErrors - errorCountBeforeValidation); errorStorage.commitAndClose(); long validationEndTime = System.currentTimeMillis(); long totalValidationTime = validationEndTime - validationStartTime; LOG.info("{} validators completed in {} milliseconds.", feedValidators.size(), totalValidationTime); // update validation result fields validationResult.errorCount = totalValidationErrors; validationResult.validationTime = totalValidationTime; // FIXME: Validation result date and int[] fields need to be set somewhere. return validationResult; } }
public class class_name { public ValidationResult validate () { long validationStartTime = System.currentTimeMillis(); // Create an empty validation result that will have its fields populated by certain validators. ValidationResult validationResult = new ValidationResult(); // Error tables should already be present from the initial load. // Reconnect to the existing error tables. SQLErrorStorage errorStorage = null; try { errorStorage = new SQLErrorStorage(dataSource.getConnection(), tablePrefix, false); // depends on control dependency: [try], data = [none] } catch (SQLException | InvalidNamespaceException ex) { throw new StorageException(ex); } // depends on control dependency: [catch], data = [none] int errorCountBeforeValidation = errorStorage.getErrorCount(); List<FeedValidator> feedValidators = Arrays.asList( new MisplacedStopValidator(this, errorStorage, validationResult), new DuplicateStopsValidator(this, errorStorage), new TimeZoneValidator(this, errorStorage), new NewTripTimesValidator(this, errorStorage), new NamesValidator(this, errorStorage)); for (FeedValidator feedValidator : feedValidators) { String validatorName = feedValidator.getClass().getSimpleName(); try { LOG.info("Running {}.", validatorName); // depends on control dependency: [try], data = [none] int errorCountBefore = errorStorage.getErrorCount(); // todo why not just pass the feed and errorstorage in here? feedValidator.validate(); // depends on control dependency: [try], data = [none] LOG.info("{} found {} errors.", validatorName, errorStorage.getErrorCount() - errorCountBefore); // depends on control dependency: [try], data = [none] } catch (Exception e) { // store an error if the validator fails // FIXME: should the exception be stored? String badValue = String.join(":", validatorName, e.toString()); errorStorage.storeError(NewGTFSError.forFeed(VALIDATOR_FAILED, badValue)); LOG.error("{} failed.", validatorName); LOG.error(e.toString()); e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } // Signal to all validators that validation is complete and allow them to report on results / status. for (FeedValidator feedValidator : feedValidators) { try { feedValidator.complete(validationResult); // depends on control dependency: [try], data = [none] } catch (Exception e) { String badValue = String.join(":", feedValidator.getClass().getSimpleName(), e.toString()); errorStorage.storeError(NewGTFSError.forFeed(VALIDATOR_FAILED, badValue)); LOG.error("Validator failed completion stage.", e); } // depends on control dependency: [catch], data = [none] } // Total validation errors accounts for errors found during both loading and validation. Otherwise, this value // may be confusing if it reads zero but there were a number of data type or referential integrity errors found // during feed loading stage. int totalValidationErrors = errorStorage.getErrorCount(); LOG.info("Errors found during load stage: {}", errorCountBeforeValidation); LOG.info("Errors found by validators: {}", totalValidationErrors - errorCountBeforeValidation); errorStorage.commitAndClose(); long validationEndTime = System.currentTimeMillis(); long totalValidationTime = validationEndTime - validationStartTime; LOG.info("{} validators completed in {} milliseconds.", feedValidators.size(), totalValidationTime); // update validation result fields validationResult.errorCount = totalValidationErrors; validationResult.validationTime = totalValidationTime; // FIXME: Validation result date and int[] fields need to be set somewhere. return validationResult; } }
public class class_name { public java.util.List<String> getNotificationEvents() { if (notificationEvents == null) { notificationEvents = new com.amazonaws.internal.SdkInternalList<String>(); } return notificationEvents; } }
public class class_name { public java.util.List<String> getNotificationEvents() { if (notificationEvents == null) { notificationEvents = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none] } return notificationEvents; } }
public class class_name { private void adaptMessageContainerVisibility() { if (titleContainer != null) { boolean visible = isCustomMessageUsed() || !TextUtils.isEmpty(message); if (visible) { messageContainer.setVisibility(View.VISIBLE); notifyOnAreaShown(Area.MESSAGE); } else { messageContainer.setVisibility(View.GONE); notifyOnAreaHidden(Area.MESSAGE); } } } }
public class class_name { private void adaptMessageContainerVisibility() { if (titleContainer != null) { boolean visible = isCustomMessageUsed() || !TextUtils.isEmpty(message); if (visible) { messageContainer.setVisibility(View.VISIBLE); // depends on control dependency: [if], data = [none] notifyOnAreaShown(Area.MESSAGE); // depends on control dependency: [if], data = [none] } else { messageContainer.setVisibility(View.GONE); // depends on control dependency: [if], data = [none] notifyOnAreaHidden(Area.MESSAGE); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static <T extends GeoTuple3D_F64> T multTran( DMatrixRMaj M, T pt, T mod ) { if( M.numRows != 3 || M.numCols != 3 ) throw new IllegalArgumentException( "Rotation matrices are 3 by 3." ); if( mod == null ) { mod = (T) pt.createNewInstance(); } double x = pt.x; double y = pt.y; double z = pt.z; mod.x = (double) ( M.unsafe_get( 0, 0 ) * x + M.unsafe_get( 1, 0 ) * y + M.unsafe_get( 2, 0 ) * z ); mod.y = (double) ( M.unsafe_get( 0, 1 ) * x + M.unsafe_get( 1, 1 ) * y + M.unsafe_get( 2, 1 ) * z ); mod.z = (double) ( M.unsafe_get( 0, 2 ) * x + M.unsafe_get( 1, 2 ) * y + M.unsafe_get( 2, 2 ) * z ); return (T) mod; } }
public class class_name { public static <T extends GeoTuple3D_F64> T multTran( DMatrixRMaj M, T pt, T mod ) { if( M.numRows != 3 || M.numCols != 3 ) throw new IllegalArgumentException( "Rotation matrices are 3 by 3." ); if( mod == null ) { mod = (T) pt.createNewInstance(); // depends on control dependency: [if], data = [none] } double x = pt.x; double y = pt.y; double z = pt.z; mod.x = (double) ( M.unsafe_get( 0, 0 ) * x + M.unsafe_get( 1, 0 ) * y + M.unsafe_get( 2, 0 ) * z ); mod.y = (double) ( M.unsafe_get( 0, 1 ) * x + M.unsafe_get( 1, 1 ) * y + M.unsafe_get( 2, 1 ) * z ); mod.z = (double) ( M.unsafe_get( 0, 2 ) * x + M.unsafe_get( 1, 2 ) * y + M.unsafe_get( 2, 2 ) * z ); return (T) mod; } }
public class class_name { public double getLongitudeFromElasticSearchText(String textToCheckParam) { if(textToCheckParam == null || textToCheckParam.trim().isEmpty()) { return 0.0; } String[] latitudeAndLongitude = textToCheckParam.split(REG_EX_COMMA); if(latitudeAndLongitude == null || latitudeAndLongitude.length < 2) { latitudeAndLongitude = textToCheckParam.split(REG_EX_PIPE); } if(latitudeAndLongitude == null || latitudeAndLongitude.length == 0) { return 0.0; } if(latitudeAndLongitude.length > 1) { return this.toDoubleSafe(latitudeAndLongitude[1]); } return 0.0; } }
public class class_name { public double getLongitudeFromElasticSearchText(String textToCheckParam) { if(textToCheckParam == null || textToCheckParam.trim().isEmpty()) { return 0.0; // depends on control dependency: [if], data = [none] } String[] latitudeAndLongitude = textToCheckParam.split(REG_EX_COMMA); if(latitudeAndLongitude == null || latitudeAndLongitude.length < 2) { latitudeAndLongitude = textToCheckParam.split(REG_EX_PIPE); // depends on control dependency: [if], data = [none] } if(latitudeAndLongitude == null || latitudeAndLongitude.length == 0) { return 0.0; // depends on control dependency: [if], data = [none] } if(latitudeAndLongitude.length > 1) { return this.toDoubleSafe(latitudeAndLongitude[1]); // depends on control dependency: [if], data = [none] } return 0.0; } }
public class class_name { protected int checkWrite(int offset, int length) { checkOffset(offset); if (limit == -1) { if (offset + length > capacity) { if (capacity < maxCapacity) { capacity(calculateCapacity(offset + length)); } else { throw new BufferOverflowException(); } } } else { if (offset + length > limit) { throw new BufferOverflowException(); } } return offset(offset); } }
public class class_name { protected int checkWrite(int offset, int length) { checkOffset(offset); if (limit == -1) { if (offset + length > capacity) { if (capacity < maxCapacity) { capacity(calculateCapacity(offset + length)); // depends on control dependency: [if], data = [none] } else { throw new BufferOverflowException(); } } } else { if (offset + length > limit) { throw new BufferOverflowException(); } } return offset(offset); } }
public class class_name { public EClass getIfcConic() { if (ifcConicEClass == null) { ifcConicEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers() .get(99); } return ifcConicEClass; } }
public class class_name { public EClass getIfcConic() { if (ifcConicEClass == null) { ifcConicEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers() .get(99); // depends on control dependency: [if], data = [none] } return ifcConicEClass; } }
public class class_name { public static Config build(final BaseHazelcastProperties hz) { val cluster = hz.getCluster(); val config = new Config(); config.setLicenseKey(hz.getLicenseKey()); val networkConfig = new NetworkConfig() .setPort(cluster.getPort()) .setPortAutoIncrement(cluster.isPortAutoIncrement()); if (StringUtils.hasText(hz.getCluster().getLocalAddress())) { config.setProperty(BaseHazelcastProperties.HAZELCAST_LOCAL_ADDRESS_PROP, hz.getCluster().getLocalAddress()); } if (StringUtils.hasText(hz.getCluster().getPublicAddress())) { config.setProperty(BaseHazelcastProperties.HAZELCAST_PUBLIC_ADDRESS_PROP, hz.getCluster().getPublicAddress()); networkConfig.setPublicAddress(hz.getCluster().getPublicAddress()); } if (cluster.getWanReplication().isEnabled()) { if (!StringUtils.hasText(hz.getLicenseKey())) { throw new IllegalArgumentException("Cannot activate WAN replication, a Hazelcast enterprise feature, without a license key"); } LOGGER.warn("Using Hazelcast WAN Replication requires a Hazelcast Enterprise subscription. Make sure you " + "have acquired the proper license, SDK and tooling from Hazelcast before activating this feature."); buildWanReplicationSettingsForConfig(hz, config); } val joinConfig = cluster.getDiscovery().isEnabled() ? createDiscoveryJoinConfig(config, hz.getCluster(), networkConfig) : createDefaultJoinConfig(config, hz.getCluster()); LOGGER.trace("Created Hazelcast join configuration [{}]", joinConfig); networkConfig.setJoin(joinConfig); LOGGER.trace("Created Hazelcast network configuration [{}]", networkConfig); config.setNetworkConfig(networkConfig); return config.setInstanceName(cluster.getInstanceName()) .setProperty(BaseHazelcastProperties.HAZELCAST_DISCOVERY_ENABLED_PROP, BooleanUtils.toStringTrueFalse(cluster.getDiscovery().isEnabled())) .setProperty(BaseHazelcastProperties.IPV4_STACK_PROP, String.valueOf(cluster.isIpv4Enabled())) .setProperty(BaseHazelcastProperties.LOGGING_TYPE_PROP, cluster.getLoggingType()) .setProperty(BaseHazelcastProperties.MAX_HEARTBEAT_SECONDS_PROP, String.valueOf(cluster.getMaxNoHeartbeatSeconds())); } }
public class class_name { public static Config build(final BaseHazelcastProperties hz) { val cluster = hz.getCluster(); val config = new Config(); config.setLicenseKey(hz.getLicenseKey()); val networkConfig = new NetworkConfig() .setPort(cluster.getPort()) .setPortAutoIncrement(cluster.isPortAutoIncrement()); if (StringUtils.hasText(hz.getCluster().getLocalAddress())) { config.setProperty(BaseHazelcastProperties.HAZELCAST_LOCAL_ADDRESS_PROP, hz.getCluster().getLocalAddress()); // depends on control dependency: [if], data = [none] } if (StringUtils.hasText(hz.getCluster().getPublicAddress())) { config.setProperty(BaseHazelcastProperties.HAZELCAST_PUBLIC_ADDRESS_PROP, hz.getCluster().getPublicAddress()); // depends on control dependency: [if], data = [none] networkConfig.setPublicAddress(hz.getCluster().getPublicAddress()); // depends on control dependency: [if], data = [none] } if (cluster.getWanReplication().isEnabled()) { if (!StringUtils.hasText(hz.getLicenseKey())) { throw new IllegalArgumentException("Cannot activate WAN replication, a Hazelcast enterprise feature, without a license key"); } LOGGER.warn("Using Hazelcast WAN Replication requires a Hazelcast Enterprise subscription. Make sure you " + "have acquired the proper license, SDK and tooling from Hazelcast before activating this feature."); // depends on control dependency: [if], data = [none] buildWanReplicationSettingsForConfig(hz, config); // depends on control dependency: [if], data = [none] } val joinConfig = cluster.getDiscovery().isEnabled() ? createDiscoveryJoinConfig(config, hz.getCluster(), networkConfig) : createDefaultJoinConfig(config, hz.getCluster()); LOGGER.trace("Created Hazelcast join configuration [{}]", joinConfig); networkConfig.setJoin(joinConfig); LOGGER.trace("Created Hazelcast network configuration [{}]", networkConfig); config.setNetworkConfig(networkConfig); return config.setInstanceName(cluster.getInstanceName()) .setProperty(BaseHazelcastProperties.HAZELCAST_DISCOVERY_ENABLED_PROP, BooleanUtils.toStringTrueFalse(cluster.getDiscovery().isEnabled())) .setProperty(BaseHazelcastProperties.IPV4_STACK_PROP, String.valueOf(cluster.isIpv4Enabled())) .setProperty(BaseHazelcastProperties.LOGGING_TYPE_PROP, cluster.getLoggingType()) .setProperty(BaseHazelcastProperties.MAX_HEARTBEAT_SECONDS_PROP, String.valueOf(cluster.getMaxNoHeartbeatSeconds())); } }
public class class_name { public java.util.List<InstanceStateChange> getStoppingInstances() { if (stoppingInstances == null) { stoppingInstances = new com.amazonaws.internal.SdkInternalList<InstanceStateChange>(); } return stoppingInstances; } }
public class class_name { public java.util.List<InstanceStateChange> getStoppingInstances() { if (stoppingInstances == null) { stoppingInstances = new com.amazonaws.internal.SdkInternalList<InstanceStateChange>(); // depends on control dependency: [if], data = [none] } return stoppingInstances; } }
public class class_name { private void handleAtRule(CssToken start, CssTokenIterator iter, CssContentHandler doc, CssErrorHandler err) throws CssException { if (debug) { checkArgument(start.type == CssToken.Type.ATKEYWORD); checkArgument(iter.index() == iter.list.indexOf(start)); checkArgument(iter.filter() == FILTER_S_CMNT); } CssAtRule atRule = new CssAtRule(start.getChars(), start.location); CssToken tk; try { while (true) { tk = iter.next(); if (MATCH_SEMI_OPENBRACE.apply(tk)) { // ';' or '{', expected end atRule.hasBlock = tk.getChar() == '{'; break; } else { CssConstruct param = handleAtRuleParam(tk, iter, doc, err); if (param == null) { // issue error, forward, then return err.error(new CssGrammarException(GRAMMAR_UNEXPECTED_TOKEN, iter.last.location, messages.getLocale(), iter.last.chars)); //skip to atrule closebrace, ignoring any inner blocks int stack = 0; while (true) { CssToken tok = iter.next(); if (MATCH_SEMI.apply(tok) && stack == 0) { return; //a non-block at rule } else if (MATCH_OPENBRACE.apply(tok)) { stack++; } else if (MATCH_CLOSEBRACE.apply(tok)) { if (stack == 1) { break; } stack--; } } return; } else { atRule.components.add(param); } } } } catch (NoSuchElementException nse) { // UAs required to close any open constructs on premature EOF doc.startAtRule(atRule); err.error(new CssGrammarException(GRAMMAR_PREMATURE_EOF, iter.last.location, messages.getLocale(), "';' " + messages.get("or") + " '{'")); doc.endAtRule(atRule.getName().get()); throw new PrematureEOFException(); } if (debug) { checkArgument(MATCH_SEMI_OPENBRACE.apply(iter.last)); checkArgument(iter.filter() == FILTER_S_CMNT); } // ending up here only on expected end doc.startAtRule(atRule); if (atRule.hasBlock) { try { if (hasRuleSet(atRule, iter)) { while (!MATCH_CLOSEBRACE.apply(iter.next())) { if (iter.last.type == CssToken.Type.ATKEYWORD) { handleAtRule(iter.last, iter, doc, err); } else { handleRuleSet(iter.last, iter, doc, err); } } } else { handleDeclarationBlock(iter.next(), iter, doc, err); } } catch (NoSuchElementException nse) { err.error(new CssGrammarException(GRAMMAR_PREMATURE_EOF, iter.last.location, messages.getLocale(), "'}'")); doc.endAtRule(atRule.name.get()); throw new PrematureEOFException(); } } doc.endAtRule(atRule.name.get()); } }
public class class_name { private void handleAtRule(CssToken start, CssTokenIterator iter, CssContentHandler doc, CssErrorHandler err) throws CssException { if (debug) { checkArgument(start.type == CssToken.Type.ATKEYWORD); checkArgument(iter.index() == iter.list.indexOf(start)); checkArgument(iter.filter() == FILTER_S_CMNT); } CssAtRule atRule = new CssAtRule(start.getChars(), start.location); CssToken tk; try { while (true) { tk = iter.next(); // depends on control dependency: [while], data = [none] if (MATCH_SEMI_OPENBRACE.apply(tk)) { // ';' or '{', expected end atRule.hasBlock = tk.getChar() == '{'; // depends on control dependency: [if], data = [none] break; } else { CssConstruct param = handleAtRuleParam(tk, iter, doc, err); if (param == null) { // issue error, forward, then return err.error(new CssGrammarException(GRAMMAR_UNEXPECTED_TOKEN, iter.last.location, messages.getLocale(), iter.last.chars)); // depends on control dependency: [if], data = [none] //skip to atrule closebrace, ignoring any inner blocks int stack = 0; while (true) { CssToken tok = iter.next(); if (MATCH_SEMI.apply(tok) && stack == 0) { return; //a non-block at rule // depends on control dependency: [if], data = [none] } else if (MATCH_OPENBRACE.apply(tok)) { stack++; // depends on control dependency: [if], data = [none] } else if (MATCH_CLOSEBRACE.apply(tok)) { if (stack == 1) { break; } stack--; // depends on control dependency: [if], data = [none] } } return; // depends on control dependency: [if], data = [none] } else { atRule.components.add(param); // depends on control dependency: [if], data = [(param] } } } } catch (NoSuchElementException nse) { // UAs required to close any open constructs on premature EOF doc.startAtRule(atRule); err.error(new CssGrammarException(GRAMMAR_PREMATURE_EOF, iter.last.location, messages.getLocale(), "';' " + messages.get("or") + " '{'")); doc.endAtRule(atRule.getName().get()); throw new PrematureEOFException(); } if (debug) { checkArgument(MATCH_SEMI_OPENBRACE.apply(iter.last)); checkArgument(iter.filter() == FILTER_S_CMNT); } // ending up here only on expected end doc.startAtRule(atRule); if (atRule.hasBlock) { try { if (hasRuleSet(atRule, iter)) { while (!MATCH_CLOSEBRACE.apply(iter.next())) { if (iter.last.type == CssToken.Type.ATKEYWORD) { handleAtRule(iter.last, iter, doc, err); } else { handleRuleSet(iter.last, iter, doc, err); } } } else { handleDeclarationBlock(iter.next(), iter, doc, err); } } catch (NoSuchElementException nse) { err.error(new CssGrammarException(GRAMMAR_PREMATURE_EOF, iter.last.location, messages.getLocale(), "'}'")); doc.endAtRule(atRule.name.get()); throw new PrematureEOFException(); } } doc.endAtRule(atRule.name.get()); } }
public class class_name { public QueueItem poll() { QueueItem item = peek(); if (item == null) { return null; } if (store.isEnabled()) { try { store.delete(item.getItemId()); } catch (Exception e) { throw new HazelcastException(e); } } getItemQueue().poll(); age(item, Clock.currentTimeMillis()); scheduleEvictionIfEmpty(); return item; } }
public class class_name { public QueueItem poll() { QueueItem item = peek(); if (item == null) { return null; // depends on control dependency: [if], data = [none] } if (store.isEnabled()) { try { store.delete(item.getItemId()); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new HazelcastException(e); } // depends on control dependency: [catch], data = [none] } getItemQueue().poll(); age(item, Clock.currentTimeMillis()); scheduleEvictionIfEmpty(); return item; } }
public class class_name { public Object[] setEnableNonFilter(Object[] rgobjEnable, boolean bHasNext, boolean bBreak, boolean bAfterRequery, boolean bSelectEOF, boolean bFieldListeners) { boolean bEnable = (rgobjEnable == null) ? false : true; if (bFieldListeners) { if (rgobjEnable == null) rgobjEnable = this.setEnableFieldListeners(bEnable); else this.setEnableFieldListeners(rgobjEnable); } else { if (rgobjEnable == null) rgobjEnable = new Object[0]; } FileListener listener = this.getListener(); int iCount = this.getFieldCount(); while (listener != null) { if (!(listener instanceof org.jbundle.base.db.filter.FileFilter)) { if (!bEnable) { rgobjEnable = Utility.growArray(rgobjEnable, iCount + 1, 8); if (listener.isEnabledListener()) rgobjEnable[iCount] = Boolean.TRUE; else rgobjEnable[iCount] = Boolean.FALSE; listener.setEnabledListener(bEnable); } else { // Enable boolean bEnableThis = true; if (iCount < rgobjEnable.length) if (rgobjEnable[iCount] != null) bEnableThis = ((Boolean)rgobjEnable[iCount]).booleanValue(); listener.setEnabledListener(bEnableThis); } iCount++; } listener = (FileListener)listener.getNextListener(); } if (bEnable) { if (bAfterRequery) this.handleRecordChange(null, DBConstants.AFTER_REQUERY_TYPE, true); if (bBreak) this.handleRecordChange(null, DBConstants.CONTROL_BREAK_TYPE, true); if (bHasNext) { this.handleValidRecord(true); this.handleRecordChange(null, DBConstants.MOVE_NEXT_TYPE, true); } if (bSelectEOF) this.handleRecordChange(null, DBConstants.SELECT_EOF_TYPE, true); if (this.getTable().getCurrentTable().getRecord() != this) { // Special logic - match listeners on current record (if shared) boolean bCloneListeners = false; boolean bMatchEnabledState = true; boolean bSyncReferenceFields = false; boolean bMatchSelectedState = true; this.matchListeners(this.getTable().getCurrentTable().getRecord(), bCloneListeners, bMatchEnabledState, bSyncReferenceFields, bMatchSelectedState, true); } } return rgobjEnable; } }
public class class_name { public Object[] setEnableNonFilter(Object[] rgobjEnable, boolean bHasNext, boolean bBreak, boolean bAfterRequery, boolean bSelectEOF, boolean bFieldListeners) { boolean bEnable = (rgobjEnable == null) ? false : true; if (bFieldListeners) { if (rgobjEnable == null) rgobjEnable = this.setEnableFieldListeners(bEnable); else this.setEnableFieldListeners(rgobjEnable); } else { if (rgobjEnable == null) rgobjEnable = new Object[0]; } FileListener listener = this.getListener(); int iCount = this.getFieldCount(); while (listener != null) { if (!(listener instanceof org.jbundle.base.db.filter.FileFilter)) { if (!bEnable) { rgobjEnable = Utility.growArray(rgobjEnable, iCount + 1, 8); // depends on control dependency: [if], data = [none] if (listener.isEnabledListener()) rgobjEnable[iCount] = Boolean.TRUE; else rgobjEnable[iCount] = Boolean.FALSE; listener.setEnabledListener(bEnable); // depends on control dependency: [if], data = [none] } else { // Enable boolean bEnableThis = true; if (iCount < rgobjEnable.length) if (rgobjEnable[iCount] != null) bEnableThis = ((Boolean)rgobjEnable[iCount]).booleanValue(); listener.setEnabledListener(bEnableThis); // depends on control dependency: [if], data = [none] } iCount++; // depends on control dependency: [if], data = [none] } listener = (FileListener)listener.getNextListener(); // depends on control dependency: [while], data = [none] } if (bEnable) { if (bAfterRequery) this.handleRecordChange(null, DBConstants.AFTER_REQUERY_TYPE, true); if (bBreak) this.handleRecordChange(null, DBConstants.CONTROL_BREAK_TYPE, true); if (bHasNext) { this.handleValidRecord(true); // depends on control dependency: [if], data = [none] this.handleRecordChange(null, DBConstants.MOVE_NEXT_TYPE, true); // depends on control dependency: [if], data = [none] } if (bSelectEOF) this.handleRecordChange(null, DBConstants.SELECT_EOF_TYPE, true); if (this.getTable().getCurrentTable().getRecord() != this) { // Special logic - match listeners on current record (if shared) boolean bCloneListeners = false; boolean bMatchEnabledState = true; boolean bSyncReferenceFields = false; boolean bMatchSelectedState = true; this.matchListeners(this.getTable().getCurrentTable().getRecord(), bCloneListeners, bMatchEnabledState, bSyncReferenceFields, bMatchSelectedState, true); // depends on control dependency: [if], data = [(this.getTable().getCurrentTable().getRecord()] } } return rgobjEnable; } }
public class class_name { @Override @PortalTransactional public IPortalCookie addOrUpdatePortletCookie(IPortalCookie portalCookie, Cookie cookie) { final Set<IPortletCookie> portletCookies = portalCookie.getPortletCookies(); boolean found = false; final String name = cookie.getName(); final EntityManager entityManager = this.getEntityManager(); for (final Iterator<IPortletCookie> portletCookieItr = portletCookies.iterator(); portletCookieItr.hasNext(); ) { final IPortletCookie portletCookie = portletCookieItr.next(); if (name.equals(portletCookie.getName())) { // Delete cookies with a maxAge of 0 if (cookie.getMaxAge() == 0) { portletCookieItr.remove(); entityManager.remove(portletCookie); } else { portletCookie.updateFromCookie(cookie); } found = true; break; } } if (!found) { IPortletCookie newPortletCookie = new PortletCookieImpl(portalCookie, cookie); portletCookies.add(newPortletCookie); } entityManager.persist(portalCookie); return portalCookie; } }
public class class_name { @Override @PortalTransactional public IPortalCookie addOrUpdatePortletCookie(IPortalCookie portalCookie, Cookie cookie) { final Set<IPortletCookie> portletCookies = portalCookie.getPortletCookies(); boolean found = false; final String name = cookie.getName(); final EntityManager entityManager = this.getEntityManager(); for (final Iterator<IPortletCookie> portletCookieItr = portletCookies.iterator(); portletCookieItr.hasNext(); ) { final IPortletCookie portletCookie = portletCookieItr.next(); if (name.equals(portletCookie.getName())) { // Delete cookies with a maxAge of 0 if (cookie.getMaxAge() == 0) { portletCookieItr.remove(); // depends on control dependency: [if], data = [none] entityManager.remove(portletCookie); // depends on control dependency: [if], data = [none] } else { portletCookie.updateFromCookie(cookie); // depends on control dependency: [if], data = [none] } found = true; // depends on control dependency: [if], data = [none] break; } } if (!found) { IPortletCookie newPortletCookie = new PortletCookieImpl(portalCookie, cookie); portletCookies.add(newPortletCookie); // depends on control dependency: [if], data = [none] } entityManager.persist(portalCookie); return portalCookie; } }
public class class_name { public long addAll(T[] items) { long firstSequence = ringbuffer.peekNextTailSequence(); long lastSequence = ringbuffer.peekNextTailSequence(); if (store.isEnabled() && items.length != 0) { try { store.storeAll(firstSequence, convertToData(items)); } catch (Exception e) { throw new HazelcastException(e); } } for (int i = 0; i < items.length; i++) { lastSequence = addInternal(items[i]); } return lastSequence; } }
public class class_name { public long addAll(T[] items) { long firstSequence = ringbuffer.peekNextTailSequence(); long lastSequence = ringbuffer.peekNextTailSequence(); if (store.isEnabled() && items.length != 0) { try { store.storeAll(firstSequence, convertToData(items)); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new HazelcastException(e); } // depends on control dependency: [catch], data = [none] } for (int i = 0; i < items.length; i++) { lastSequence = addInternal(items[i]); // depends on control dependency: [for], data = [i] } return lastSequence; } }
public class class_name { @PublicAPI(usage = ACCESS) public Slices namingSlices(String pattern) { List<Slice> newSlices = new ArrayList<>(); for (Slice slice : slices) { newSlices.add(slice.as(pattern)); } return new Slices(newSlices, description); } }
public class class_name { @PublicAPI(usage = ACCESS) public Slices namingSlices(String pattern) { List<Slice> newSlices = new ArrayList<>(); for (Slice slice : slices) { newSlices.add(slice.as(pattern)); // depends on control dependency: [for], data = [slice] } return new Slices(newSlices, description); } }
public class class_name { @Override public void onStatusChange(JobExecutionState state, RunningState previousStatus, RunningState newStatus) { if (this.filter.apply(state.getJobSpec())) { this.delegate.onStatusChange(state, previousStatus, newStatus); } } }
public class class_name { @Override public void onStatusChange(JobExecutionState state, RunningState previousStatus, RunningState newStatus) { if (this.filter.apply(state.getJobSpec())) { this.delegate.onStatusChange(state, previousStatus, newStatus); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String getOtherName(String source, String target){ String other; if (target.contains(source) && !target.equals(source)) { int start = target.indexOf(source); other = start == 0 ? target.substring(source.length()) : target.substring(0, start); } else{ return null; } if(other.startsWith("_")){ other = other.replaceFirst("_", " "); } if(other.endsWith("_")){ byte[] otherb = other.getBytes(); otherb[otherb.length - 1] = ' '; other = new String(otherb); } return other.trim(); } }
public class class_name { public static String getOtherName(String source, String target){ String other; if (target.contains(source) && !target.equals(source)) { int start = target.indexOf(source); other = start == 0 ? target.substring(source.length()) : target.substring(0, start); // depends on control dependency: [if], data = [none] } else{ return null; // depends on control dependency: [if], data = [none] } if(other.startsWith("_")){ other = other.replaceFirst("_", " "); // depends on control dependency: [if], data = [none] } if(other.endsWith("_")){ byte[] otherb = other.getBytes(); otherb[otherb.length - 1] = ' '; // depends on control dependency: [if], data = [none] other = new String(otherb); // depends on control dependency: [if], data = [none] } return other.trim(); } }
public class class_name { public List<MetaProperty> getProperties() { checkInitalised(); SingleKeyHashMap propertyMap = classPropertyIndex.getNullable(theCachedClass); if (propertyMap==null) { // GROOVY-6903: May happen in some special environment, like under Android, due // to classloading issues propertyMap = new SingleKeyHashMap(); } // simply return the values of the metaproperty map as a List List ret = new ArrayList(propertyMap.size()); for (ComplexKeyHashMap.EntryIterator iter = propertyMap.getEntrySetIterator(); iter.hasNext();) { MetaProperty element = (MetaProperty) ((SingleKeyHashMap.Entry) iter.next()).value; if (element instanceof CachedField) continue; // filter out DGM beans if (element instanceof MetaBeanProperty) { MetaBeanProperty mp = (MetaBeanProperty) element; boolean setter = true; boolean getter = true; if (mp.getGetter() == null || mp.getGetter() instanceof GeneratedMetaMethod || mp.getGetter() instanceof NewInstanceMetaMethod) { getter = false; } if (mp.getSetter() == null || mp.getSetter() instanceof GeneratedMetaMethod || mp.getSetter() instanceof NewInstanceMetaMethod) { setter = false; } if (!setter && !getter) continue; // TODO: I (ait) don't know why these strange tricks needed and comment following as it effects some Grails tests // if (!setter && mp.getSetter() != null) { // element = new MetaBeanProperty(mp.getName(), mp.getType(), mp.getGetter(), null); // } // if (!getter && mp.getGetter() != null) { // element = new MetaBeanProperty(mp.getName(), mp.getType(), null, mp.getSetter()); // } } ret.add(element); } return ret; } }
public class class_name { public List<MetaProperty> getProperties() { checkInitalised(); SingleKeyHashMap propertyMap = classPropertyIndex.getNullable(theCachedClass); if (propertyMap==null) { // GROOVY-6903: May happen in some special environment, like under Android, due // to classloading issues propertyMap = new SingleKeyHashMap(); // depends on control dependency: [if], data = [none] } // simply return the values of the metaproperty map as a List List ret = new ArrayList(propertyMap.size()); for (ComplexKeyHashMap.EntryIterator iter = propertyMap.getEntrySetIterator(); iter.hasNext();) { MetaProperty element = (MetaProperty) ((SingleKeyHashMap.Entry) iter.next()).value; if (element instanceof CachedField) continue; // filter out DGM beans if (element instanceof MetaBeanProperty) { MetaBeanProperty mp = (MetaBeanProperty) element; boolean setter = true; boolean getter = true; if (mp.getGetter() == null || mp.getGetter() instanceof GeneratedMetaMethod || mp.getGetter() instanceof NewInstanceMetaMethod) { getter = false; // depends on control dependency: [if], data = [none] } if (mp.getSetter() == null || mp.getSetter() instanceof GeneratedMetaMethod || mp.getSetter() instanceof NewInstanceMetaMethod) { setter = false; // depends on control dependency: [if], data = [none] } if (!setter && !getter) continue; // TODO: I (ait) don't know why these strange tricks needed and comment following as it effects some Grails tests // if (!setter && mp.getSetter() != null) { // element = new MetaBeanProperty(mp.getName(), mp.getType(), mp.getGetter(), null); // } // if (!getter && mp.getGetter() != null) { // element = new MetaBeanProperty(mp.getName(), mp.getType(), null, mp.getSetter()); // } } ret.add(element); // depends on control dependency: [for], data = [none] } return ret; } }
public class class_name { private void exportModules() { // avoid to export modules if unnecessary if (((null != m_copyAndUnzip) && !m_copyAndUnzip.booleanValue()) || ((null == m_copyAndUnzip) && !m_currentConfiguration.getDefaultCopyAndUnzip())) { m_logStream.println(); m_logStream.println("NOT EXPORTING MODULES - you disabled copy and unzip."); m_logStream.println(); return; } CmsModuleManager moduleManager = OpenCms.getModuleManager(); Collection<String> modulesToExport = ((m_modulesToExport == null) || m_modulesToExport.isEmpty()) ? m_currentConfiguration.getConfiguredModules() : m_modulesToExport; for (String moduleName : modulesToExport) { CmsModule module = moduleManager.getModule(moduleName); if (module != null) { CmsModuleImportExportHandler handler = CmsModuleImportExportHandler.getExportHandler( getCmsObject(), module, "Git export handler"); try { handler.exportData( getCmsObject(), new CmsPrintStreamReport( m_logStream, OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()), false)); } catch (CmsRoleViolationException | CmsConfigurationException | CmsImportExportException e) { e.printStackTrace(m_logStream); } } } } }
public class class_name { private void exportModules() { // avoid to export modules if unnecessary if (((null != m_copyAndUnzip) && !m_copyAndUnzip.booleanValue()) || ((null == m_copyAndUnzip) && !m_currentConfiguration.getDefaultCopyAndUnzip())) { m_logStream.println(); // depends on control dependency: [if], data = [none] m_logStream.println("NOT EXPORTING MODULES - you disabled copy and unzip."); // depends on control dependency: [if], data = [none] m_logStream.println(); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } CmsModuleManager moduleManager = OpenCms.getModuleManager(); Collection<String> modulesToExport = ((m_modulesToExport == null) || m_modulesToExport.isEmpty()) ? m_currentConfiguration.getConfiguredModules() : m_modulesToExport; for (String moduleName : modulesToExport) { CmsModule module = moduleManager.getModule(moduleName); if (module != null) { CmsModuleImportExportHandler handler = CmsModuleImportExportHandler.getExportHandler( getCmsObject(), module, "Git export handler"); try { handler.exportData( getCmsObject(), new CmsPrintStreamReport( m_logStream, OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()), false)); // depends on control dependency: [try], data = [none] } catch (CmsRoleViolationException | CmsConfigurationException | CmsImportExportException e) { e.printStackTrace(m_logStream); } // depends on control dependency: [catch], data = [none] } } } }
public class class_name { public CodeBuilder addInterface(Class<?> interfaceClass) { if (!interfaceClass.isInterface()) { System.out.println(interfaceClass + "不是接口类型!取消设为实现。"); return this; } String simpleName = interfaceClass.getSimpleName(); Package pkg = interfaceClass.getPackage(); imports.add(pkg.getName() + "." + simpleName);// 导入包 this.interfaces.add(simpleName);// 添加实现的接口 return this; } }
public class class_name { public CodeBuilder addInterface(Class<?> interfaceClass) { if (!interfaceClass.isInterface()) { System.out.println(interfaceClass + "不是接口类型!取消设为实现。"); // depends on control dependency: [if], data = [none] return this; // depends on control dependency: [if], data = [none] } String simpleName = interfaceClass.getSimpleName(); Package pkg = interfaceClass.getPackage(); imports.add(pkg.getName() + "." + simpleName);// 导入包 this.interfaces.add(simpleName);// 添加实现的接口 return this; } }
public class class_name { static int getAnimationResource(int gravity, boolean isInAnimation) { if ((gravity & Gravity.TOP) == Gravity.TOP) { return isInAnimation ? R.anim.slide_in_top : R.anim.slide_out_top; } if ((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) { return isInAnimation ? R.anim.slide_in_bottom : R.anim.slide_out_bottom; } if ((gravity & Gravity.CENTER) == Gravity.CENTER) { return isInAnimation ? R.anim.fade_in_center : R.anim.fade_out_center; } return INVALID; } }
public class class_name { static int getAnimationResource(int gravity, boolean isInAnimation) { if ((gravity & Gravity.TOP) == Gravity.TOP) { return isInAnimation ? R.anim.slide_in_top : R.anim.slide_out_top; // depends on control dependency: [if], data = [none] } if ((gravity & Gravity.BOTTOM) == Gravity.BOTTOM) { return isInAnimation ? R.anim.slide_in_bottom : R.anim.slide_out_bottom; // depends on control dependency: [if], data = [none] } if ((gravity & Gravity.CENTER) == Gravity.CENTER) { return isInAnimation ? R.anim.fade_in_center : R.anim.fade_out_center; // depends on control dependency: [if], data = [none] } return INVALID; } }
public class class_name { protected synchronized void evictStaleEntries() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { int size = primaryTable.size(); Tr.debug(tc, "The current cache size is " + size); } Map<String, Object> secondaryTable = new HashMap<String, Object>(); secondaryTable.putAll(primaryTable); //create 2nd map to avoid concurrent during entry manipulation Set<String> keysToRemove = findExpiredTokens(secondaryTable); removeExpiredTokens(keysToRemove); secondaryTable.clear(); } }
public class class_name { protected synchronized void evictStaleEntries() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { int size = primaryTable.size(); Tr.debug(tc, "The current cache size is " + size); // depends on control dependency: [if], data = [none] } Map<String, Object> secondaryTable = new HashMap<String, Object>(); secondaryTable.putAll(primaryTable); //create 2nd map to avoid concurrent during entry manipulation Set<String> keysToRemove = findExpiredTokens(secondaryTable); removeExpiredTokens(keysToRemove); secondaryTable.clear(); } }
public class class_name { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext sc = sce.getServletContext(); WunderBoss.putOption("servlet-context-path", sc.getContextPath()); /* We don't want to initialize the application on this thread, because if that hangs, we have no way to detect that or fail the deployment, so we run the init in a separate thread. But due to locks in jbossweb, we can't register servlets on a different thread. So we set up a queue that we pass along to ServletWeb, and it feeds servlet registration actions back to this thread. We also wrap the init with a Future, so we can know when it completes or time it out. We use the timeout as we poll the queue and wait for init to complete, and we also pass it to ServletWeb to use when it waits for the servlet actions to complete. It's a shared pool of time that both threads work down to prevent overrunning the timeout in toto. */ final ActionConduit addServletActions = new ActionConduit(); final CompletableFuture<Void> initDone = new CompletableFuture<>(); long totalTimeout = DEFAULT_TIMEOUT_SECONDS; final String timeoutProp = System.getProperty(TIMEOUT_PROPERTY); if (timeoutProp != null) { totalTimeout = Long.parseLong(timeoutProp); } final AtomicLong sharedTimeout = new AtomicLong(totalTimeout * 1000); try { WunderBoss.registerComponentProvider(Web.class, new ServletWebProvider(sc, addServletActions, sharedTimeout)); } catch (LinkageError ignored) { // Ignore - perhaps the user isn't using our web } this.applicationRunner = new ApplicationRunner(getName(sc)) { @Override protected void updateClassPath() throws Exception { super.updateClassPath(); // TODO: Is this still needed? Things seem to work with it commented out ModuleUtils.addToModuleClasspath(Module.forClass(WunderBossService.class), classPathAdditions); } @Override protected URL jarURL() { String mainPath = ApplicationRunner.class.getName().replace(".", "/") + ".class"; String mainUrl = ApplicationRunner.class.getClassLoader().getResource(mainPath).toString(); String marker = ".jar"; int to = mainUrl.lastIndexOf(marker); try { return new URL(mainUrl.substring(0, to + marker.length())); } catch (MalformedURLException e) { throw new RuntimeException("Error determining jar url", e); } } @Override public void start(String[] args) { try { super.start(args); initDone.complete(null); } catch (Exception e) { initDone.completeExceptionally(e); } } }; WunderBoss.workerPool().submit(new Runnable() { @Override public void run() { try { applicationRunner.start(null); } catch (Exception ignored) { // start() catches all exceptions, so won't really throw } } }); while (sharedTimeout.get() > 0 && !initDone.isDone()) { final Runnable action = addServletActions.poll(); if (action != null) { action.run(); } else { try { Thread.sleep(10); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while waiting for application initialization to complete", e); } sharedTimeout.addAndGet(-10); } } if (sharedTimeout.get() <= 0) { throw new RuntimeException(String.format("Timed out waiting for initialization to complete after %d " + "seconds. If you need more time, use the %s sysprop.", totalTimeout, TIMEOUT_PROPERTY)); } // there is a potential race here, where ServletWeb can put an action on the queue after // we've exited the while() loop but before we've called close(), but we don't care, because // we'll only leave the while() if 1) the timeout has occurred (which will throw above), // or b) the init has signaled it is done (and therefore can't add an action) addServletActions.close(); try { initDone.get(); } catch (ExecutionException e) { throw new RuntimeException("Application initialization failed", e.getCause()); } catch (CancellationException | InterruptedException e) { // shouldn't happen, but... throw new RuntimeException("Application initialization was cancelled", e); } } }
public class class_name { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext sc = sce.getServletContext(); WunderBoss.putOption("servlet-context-path", sc.getContextPath()); /* We don't want to initialize the application on this thread, because if that hangs, we have no way to detect that or fail the deployment, so we run the init in a separate thread. But due to locks in jbossweb, we can't register servlets on a different thread. So we set up a queue that we pass along to ServletWeb, and it feeds servlet registration actions back to this thread. We also wrap the init with a Future, so we can know when it completes or time it out. We use the timeout as we poll the queue and wait for init to complete, and we also pass it to ServletWeb to use when it waits for the servlet actions to complete. It's a shared pool of time that both threads work down to prevent overrunning the timeout in toto. */ final ActionConduit addServletActions = new ActionConduit(); final CompletableFuture<Void> initDone = new CompletableFuture<>(); long totalTimeout = DEFAULT_TIMEOUT_SECONDS; final String timeoutProp = System.getProperty(TIMEOUT_PROPERTY); if (timeoutProp != null) { totalTimeout = Long.parseLong(timeoutProp); // depends on control dependency: [if], data = [(timeoutProp] } final AtomicLong sharedTimeout = new AtomicLong(totalTimeout * 1000); try { WunderBoss.registerComponentProvider(Web.class, new ServletWebProvider(sc, addServletActions, sharedTimeout)); // depends on control dependency: [try], data = [none] } catch (LinkageError ignored) { // Ignore - perhaps the user isn't using our web } // depends on control dependency: [catch], data = [none] this.applicationRunner = new ApplicationRunner(getName(sc)) { @Override protected void updateClassPath() throws Exception { super.updateClassPath(); // TODO: Is this still needed? Things seem to work with it commented out ModuleUtils.addToModuleClasspath(Module.forClass(WunderBossService.class), classPathAdditions); } @Override protected URL jarURL() { String mainPath = ApplicationRunner.class.getName().replace(".", "/") + ".class"; String mainUrl = ApplicationRunner.class.getClassLoader().getResource(mainPath).toString(); String marker = ".jar"; int to = mainUrl.lastIndexOf(marker); try { return new URL(mainUrl.substring(0, to + marker.length())); // depends on control dependency: [try], data = [none] } catch (MalformedURLException e) { throw new RuntimeException("Error determining jar url", e); } // depends on control dependency: [catch], data = [none] } @Override public void start(String[] args) { try { super.start(args); // depends on control dependency: [try], data = [none] initDone.complete(null); // depends on control dependency: [try], data = [none] } catch (Exception e) { initDone.completeExceptionally(e); } // depends on control dependency: [catch], data = [none] } }; WunderBoss.workerPool().submit(new Runnable() { @Override public void run() { try { applicationRunner.start(null); } catch (Exception ignored) { // start() catches all exceptions, so won't really throw } } }); while (sharedTimeout.get() > 0 && !initDone.isDone()) { final Runnable action = addServletActions.poll(); if (action != null) { action.run(); } else { try { Thread.sleep(10); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while waiting for application initialization to complete", e); } sharedTimeout.addAndGet(-10); } } if (sharedTimeout.get() <= 0) { throw new RuntimeException(String.format("Timed out waiting for initialization to complete after %d " + "seconds. If you need more time, use the %s sysprop.", totalTimeout, TIMEOUT_PROPERTY)); } // there is a potential race here, where ServletWeb can put an action on the queue after // we've exited the while() loop but before we've called close(), but we don't care, because // we'll only leave the while() if 1) the timeout has occurred (which will throw above), // or b) the init has signaled it is done (and therefore can't add an action) addServletActions.close(); try { initDone.get(); } catch (ExecutionException e) { throw new RuntimeException("Application initialization failed", e.getCause()); } catch (CancellationException | InterruptedException e) { // shouldn't happen, but... throw new RuntimeException("Application initialization was cancelled", e); } } }
public class class_name { public void displayDialog() throws Exception { Map<String, String[]> params = initAdminTool(); // explorer view dialogs if (CmsExplorerDialog.EXPLORER_TOOLS.contains(getCurrentToolPath())) { if (getAction() == CmsDialog.ACTION_CANCEL) { actionCloseDialog(); return; } getToolManager().jspForwardPage(this, CmsToolManager.ADMINVIEW_ROOT_LOCATION + "/tool-fs.jsp", params); return; } // real tool if (!getAdminTool().getHandler().getLink().equals(getCms().getRequestContext().getUri())) { getToolManager().jspForwardPage(this, getAdminTool().getHandler().getLink(), params); return; } // just grouping if (getAction() == CmsDialog.ACTION_CANCEL) { actionCloseDialog(); return; } JspWriter out = getJsp().getJspContext().getOut(); out.print(htmlStart()); out.print(bodyStart(null)); out.print(dialogStart()); out.print(dialogContentStart(getParamTitle())); out.print(dialogContentEnd()); out.print(dialogEnd()); out.print(bodyEnd()); out.print(htmlEnd()); } }
public class class_name { public void displayDialog() throws Exception { Map<String, String[]> params = initAdminTool(); // explorer view dialogs if (CmsExplorerDialog.EXPLORER_TOOLS.contains(getCurrentToolPath())) { if (getAction() == CmsDialog.ACTION_CANCEL) { actionCloseDialog(); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } getToolManager().jspForwardPage(this, CmsToolManager.ADMINVIEW_ROOT_LOCATION + "/tool-fs.jsp", params); return; } // real tool if (!getAdminTool().getHandler().getLink().equals(getCms().getRequestContext().getUri())) { getToolManager().jspForwardPage(this, getAdminTool().getHandler().getLink(), params); return; } // just grouping if (getAction() == CmsDialog.ACTION_CANCEL) { actionCloseDialog(); return; } JspWriter out = getJsp().getJspContext().getOut(); out.print(htmlStart()); out.print(bodyStart(null)); out.print(dialogStart()); out.print(dialogContentStart(getParamTitle())); out.print(dialogContentEnd()); out.print(dialogEnd()); out.print(bodyEnd()); out.print(htmlEnd()); } }
public class class_name { public void replaceStringInFile(File folder, File file, String template, String[] replacement) throws IOException { System.out.println("Patching file: "+file.getCanonicalPath()); String name = file.getName(); File origFile = new File(folder, name+".orig"); file.renameTo(origFile); File temporaryFile = new File(folder, name+".tmp"); if (temporaryFile.exists()) { temporaryFile.delete(); } temporaryFile.createNewFile(); String line; FileInputStream fis = new FileInputStream(origFile); PrintWriter pw = new PrintWriter(temporaryFile); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); while ((line = br.readLine()) != null) { if (line.trim().equals(template)) { for (String s : replacement) { pw.println(s); } } else { pw.println(line); } } pw.flush(); pw.close(); if (!temporaryFile.renameTo(new File(folder, name))) { throw new IOException("Unable to rename file in folder "+folder.getName()+ " from \""+temporaryFile.getName()+"\" into \""+name + "\n Original file saved as "+origFile.getName()); } origFile.delete(); } }
public class class_name { public void replaceStringInFile(File folder, File file, String template, String[] replacement) throws IOException { System.out.println("Patching file: "+file.getCanonicalPath()); String name = file.getName(); File origFile = new File(folder, name+".orig"); file.renameTo(origFile); File temporaryFile = new File(folder, name+".tmp"); if (temporaryFile.exists()) { temporaryFile.delete(); } temporaryFile.createNewFile(); String line; FileInputStream fis = new FileInputStream(origFile); PrintWriter pw = new PrintWriter(temporaryFile); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); while ((line = br.readLine()) != null) { if (line.trim().equals(template)) { for (String s : replacement) { pw.println(s); // depends on control dependency: [for], data = [s] } } else { pw.println(line); // depends on control dependency: [if], data = [none] } } pw.flush(); pw.close(); if (!temporaryFile.renameTo(new File(folder, name))) { throw new IOException("Unable to rename file in folder "+folder.getName()+ " from \""+temporaryFile.getName()+"\" into \""+name + "\n Original file saved as "+origFile.getName()); } origFile.delete(); } }
public class class_name { private void readResourceAssignment(Allocation gpAllocation) { Integer taskID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getTaskId()) + 1); Integer resourceID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getResourceId()) + 1); Task task = m_projectFile.getTaskByUniqueID(taskID); Resource resource = m_projectFile.getResourceByUniqueID(resourceID); if (task != null && resource != null) { ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource); mpxjAssignment.setUnits(gpAllocation.getLoad()); m_eventManager.fireAssignmentReadEvent(mpxjAssignment); } } }
public class class_name { private void readResourceAssignment(Allocation gpAllocation) { Integer taskID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getTaskId()) + 1); Integer resourceID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getResourceId()) + 1); Task task = m_projectFile.getTaskByUniqueID(taskID); Resource resource = m_projectFile.getResourceByUniqueID(resourceID); if (task != null && resource != null) { ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource); mpxjAssignment.setUnits(gpAllocation.getLoad()); // depends on control dependency: [if], data = [none] m_eventManager.fireAssignmentReadEvent(mpxjAssignment); // depends on control dependency: [if], data = [none] } } }
public class class_name { private List<Row> getRows(String tableName, String columnName, Integer id) { List<Row> result; List<Row> table = m_tables.get(tableName); if (table == null) { result = Collections.<Row> emptyList(); } else { if (columnName == null) { result = table; } else { result = new LinkedList<Row>(); for (Row row : table) { if (NumberHelper.equals(id, row.getInteger(columnName))) { result.add(row); } } } } return result; } }
public class class_name { private List<Row> getRows(String tableName, String columnName, Integer id) { List<Row> result; List<Row> table = m_tables.get(tableName); if (table == null) { result = Collections.<Row> emptyList(); // depends on control dependency: [if], data = [none] } else { if (columnName == null) { result = table; // depends on control dependency: [if], data = [none] } else { result = new LinkedList<Row>(); // depends on control dependency: [if], data = [none] for (Row row : table) { if (NumberHelper.equals(id, row.getInteger(columnName))) { result.add(row); // depends on control dependency: [if], data = [none] } } } } return result; } }
public class class_name { private static List<AtomNode> atomSegment(String sSentence, int start, int end) { if (end < start) { throw new RuntimeException("start=" + start + " < end=" + end); } List<AtomNode> atomSegment = new ArrayList<AtomNode>(); int pCur = 0, nCurType, nNextType; StringBuilder sb = new StringBuilder(); char c; //============================================================================================== // by zhenyulu: // // TODO: 使用一系列正则表达式将句子中的完整成分(百分比、日期、电子邮件、URL等)预先提取出来 //============================================================================================== char[] charArray = sSentence.substring(start, end).toCharArray(); int[] charTypeArray = new int[charArray.length]; // 生成对应单个汉字的字符类型数组 for (int i = 0; i < charArray.length; ++i) { c = charArray[i]; charTypeArray[i] = CharType.get(c); if (c == '.' && i < (charArray.length - 1) && CharType.get(charArray[i + 1]) == CharType.CT_NUM) charTypeArray[i] = CharType.CT_NUM; else if (c == '.' && i < (charArray.length - 1) && charArray[i + 1] >= '0' && charArray[i + 1] <= '9') charTypeArray[i] = CharType.CT_SINGLE; else if (charTypeArray[i] == CharType.CT_LETTER) charTypeArray[i] = CharType.CT_SINGLE; } // 根据字符类型数组中的内容完成原子切割 while (pCur < charArray.length) { nCurType = charTypeArray[pCur]; if (nCurType == CharType.CT_CHINESE || nCurType == CharType.CT_INDEX || nCurType == CharType.CT_DELIMITER || nCurType == CharType.CT_OTHER) { String single = String.valueOf(charArray[pCur]); if (single.length() != 0) atomSegment.add(new AtomNode(single, nCurType)); pCur++; } //如果是字符、数字或者后面跟随了数字的小数点“.”则一直取下去。 else if (pCur < charArray.length - 1 && ((nCurType == CharType.CT_SINGLE) || nCurType == CharType.CT_NUM)) { sb.delete(0, sb.length()); sb.append(charArray[pCur]); boolean reachEnd = true; while (pCur < charArray.length - 1) { nNextType = charTypeArray[++pCur]; if (nNextType == nCurType) sb.append(charArray[pCur]); else { reachEnd = false; break; } } atomSegment.add(new AtomNode(sb.toString(), nCurType)); if (reachEnd) pCur++; } // 对于所有其它情况 else { atomSegment.add(new AtomNode(charArray[pCur], nCurType)); pCur++; } } // logger.trace("原子分词:" + atomSegment); return atomSegment; } }
public class class_name { private static List<AtomNode> atomSegment(String sSentence, int start, int end) { if (end < start) { throw new RuntimeException("start=" + start + " < end=" + end); } List<AtomNode> atomSegment = new ArrayList<AtomNode>(); int pCur = 0, nCurType, nNextType; StringBuilder sb = new StringBuilder(); char c; //============================================================================================== // by zhenyulu: // // TODO: 使用一系列正则表达式将句子中的完整成分(百分比、日期、电子邮件、URL等)预先提取出来 //============================================================================================== char[] charArray = sSentence.substring(start, end).toCharArray(); int[] charTypeArray = new int[charArray.length]; // 生成对应单个汉字的字符类型数组 for (int i = 0; i < charArray.length; ++i) { c = charArray[i]; // depends on control dependency: [for], data = [i] charTypeArray[i] = CharType.get(c); // depends on control dependency: [for], data = [i] if (c == '.' && i < (charArray.length - 1) && CharType.get(charArray[i + 1]) == CharType.CT_NUM) charTypeArray[i] = CharType.CT_NUM; else if (c == '.' && i < (charArray.length - 1) && charArray[i + 1] >= '0' && charArray[i + 1] <= '9') charTypeArray[i] = CharType.CT_SINGLE; else if (charTypeArray[i] == CharType.CT_LETTER) charTypeArray[i] = CharType.CT_SINGLE; } // 根据字符类型数组中的内容完成原子切割 while (pCur < charArray.length) { nCurType = charTypeArray[pCur]; // depends on control dependency: [while], data = [none] if (nCurType == CharType.CT_CHINESE || nCurType == CharType.CT_INDEX || nCurType == CharType.CT_DELIMITER || nCurType == CharType.CT_OTHER) { String single = String.valueOf(charArray[pCur]); if (single.length() != 0) atomSegment.add(new AtomNode(single, nCurType)); pCur++; // depends on control dependency: [if], data = [none] } //如果是字符、数字或者后面跟随了数字的小数点“.”则一直取下去。 else if (pCur < charArray.length - 1 && ((nCurType == CharType.CT_SINGLE) || nCurType == CharType.CT_NUM)) { sb.delete(0, sb.length()); // depends on control dependency: [if], data = [none] sb.append(charArray[pCur]); // depends on control dependency: [if], data = [none] boolean reachEnd = true; while (pCur < charArray.length - 1) { nNextType = charTypeArray[++pCur]; // depends on control dependency: [while], data = [none] if (nNextType == nCurType) sb.append(charArray[pCur]); else { reachEnd = false; // depends on control dependency: [if], data = [none] break; } } atomSegment.add(new AtomNode(sb.toString(), nCurType)); // depends on control dependency: [if], data = [none] if (reachEnd) pCur++; } // 对于所有其它情况 else { atomSegment.add(new AtomNode(charArray[pCur], nCurType)); // depends on control dependency: [if], data = [none] pCur++; // depends on control dependency: [if], data = [none] } } // logger.trace("原子分词:" + atomSegment); return atomSegment; } }
public class class_name { public void marshall(GetImportJobRequest getImportJobRequest, ProtocolMarshaller protocolMarshaller) { if (getImportJobRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getImportJobRequest.getApplicationId(), APPLICATIONID_BINDING); protocolMarshaller.marshall(getImportJobRequest.getJobId(), JOBID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(GetImportJobRequest getImportJobRequest, ProtocolMarshaller protocolMarshaller) { if (getImportJobRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getImportJobRequest.getApplicationId(), APPLICATIONID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(getImportJobRequest.getJobId(), JOBID_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 List<String> getRotatedList(List<String> strings) { int index = RANDOM.nextInt(strings.size()); List<String> rotated = new ArrayList<String>(); for (int i = 0; i < strings.size(); i++) { rotated.add(strings.get(index)); index = (index + 1) % strings.size(); } return rotated; } }
public class class_name { private List<String> getRotatedList(List<String> strings) { int index = RANDOM.nextInt(strings.size()); List<String> rotated = new ArrayList<String>(); for (int i = 0; i < strings.size(); i++) { rotated.add(strings.get(index)); // depends on control dependency: [for], data = [none] index = (index + 1) % strings.size(); // depends on control dependency: [for], data = [none] } return rotated; } }
public class class_name { List<Key> subrecordKeys(long lowTime, long highTime) { List<Key> keys = new ArrayList<Key>(); long lowBucketNumber = bucketNumber(lowTime); long highBucketNumber = bucketNumber(highTime); for (long index = lowBucketNumber; index <= highBucketNumber; index += this.bucketSize) { keys.add(formSubrecordKey(index)); } return keys; } }
public class class_name { List<Key> subrecordKeys(long lowTime, long highTime) { List<Key> keys = new ArrayList<Key>(); long lowBucketNumber = bucketNumber(lowTime); long highBucketNumber = bucketNumber(highTime); for (long index = lowBucketNumber; index <= highBucketNumber; index += this.bucketSize) { keys.add(formSubrecordKey(index)); // depends on control dependency: [for], data = [index] } return keys; } }
public class class_name { public File getFirstExistingDirectory(String param) { final List<String> directoryStrings = getStringList(param); for (final String dirName : directoryStrings) { final File dir = new File(dirName.trim()); if (dir.isDirectory()) { return dir; } } throw new ParameterConversionException(fullString(param), directoryStrings.toString(), "No provided path is an existing directory"); } }
public class class_name { public File getFirstExistingDirectory(String param) { final List<String> directoryStrings = getStringList(param); for (final String dirName : directoryStrings) { final File dir = new File(dirName.trim()); if (dir.isDirectory()) { return dir; // depends on control dependency: [if], data = [none] } } throw new ParameterConversionException(fullString(param), directoryStrings.toString(), "No provided path is an existing directory"); } }
public class class_name { public void marshall(EntitiesDetectionJobFilter entitiesDetectionJobFilter, ProtocolMarshaller protocolMarshaller) { if (entitiesDetectionJobFilter == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(entitiesDetectionJobFilter.getJobName(), JOBNAME_BINDING); protocolMarshaller.marshall(entitiesDetectionJobFilter.getJobStatus(), JOBSTATUS_BINDING); protocolMarshaller.marshall(entitiesDetectionJobFilter.getSubmitTimeBefore(), SUBMITTIMEBEFORE_BINDING); protocolMarshaller.marshall(entitiesDetectionJobFilter.getSubmitTimeAfter(), SUBMITTIMEAFTER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(EntitiesDetectionJobFilter entitiesDetectionJobFilter, ProtocolMarshaller protocolMarshaller) { if (entitiesDetectionJobFilter == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(entitiesDetectionJobFilter.getJobName(), JOBNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(entitiesDetectionJobFilter.getJobStatus(), JOBSTATUS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(entitiesDetectionJobFilter.getSubmitTimeBefore(), SUBMITTIMEBEFORE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(entitiesDetectionJobFilter.getSubmitTimeAfter(), SUBMITTIMEAFTER_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void visit(final WebApp webApp) { bundleClassLoader = new BundleClassLoader(webApp.getBundle()); httpContext = webApp.getHttpContext(); // Make sure we stop the context first, so that listeners // can be called correctly before removing ann objects webContainer.begin(httpContext); // unregister war content resources //CHECKSTYLE:OFF try { webContainer.unregister("/"); } catch (IllegalArgumentException badarg) { // Ignore, we haven't registered anything } catch (Exception ignore) { LOG.warn("Unregistration exception. Skipping.", ignore); } // unregister welcome files try { webContainer.unregisterWelcomeFiles(webApp.getWelcomeFiles(), httpContext); } catch (IllegalArgumentException badarg) { // Ignore, we haven't registered anything } catch (Exception ignore) { LOG.warn("Unregistration exception. Skipping.", ignore); } // unregister JSP support try { webContainer.unregisterJsps(httpContext); } catch (IllegalArgumentException | UnsupportedOperationException badarg) { // Ignore, we haven't registered anything } catch (Exception ignore) { LOG.warn("Unregistration exception. Skipping.", ignore); } //CHECKSTYLE:ON } }
public class class_name { public void visit(final WebApp webApp) { bundleClassLoader = new BundleClassLoader(webApp.getBundle()); httpContext = webApp.getHttpContext(); // Make sure we stop the context first, so that listeners // can be called correctly before removing ann objects webContainer.begin(httpContext); // unregister war content resources //CHECKSTYLE:OFF try { webContainer.unregister("/"); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException badarg) { // Ignore, we haven't registered anything } catch (Exception ignore) { // depends on control dependency: [catch], data = [none] LOG.warn("Unregistration exception. Skipping.", ignore); } // depends on control dependency: [catch], data = [none] // unregister welcome files try { webContainer.unregisterWelcomeFiles(webApp.getWelcomeFiles(), httpContext); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException badarg) { // Ignore, we haven't registered anything } catch (Exception ignore) { // depends on control dependency: [catch], data = [none] LOG.warn("Unregistration exception. Skipping.", ignore); } // depends on control dependency: [catch], data = [none] // unregister JSP support try { webContainer.unregisterJsps(httpContext); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException | UnsupportedOperationException badarg) { // Ignore, we haven't registered anything } catch (Exception ignore) { // depends on control dependency: [catch], data = [none] LOG.warn("Unregistration exception. Skipping.", ignore); } // depends on control dependency: [catch], data = [none] //CHECKSTYLE:ON } }
public class class_name { public <T extends Entity<ID>, ID extends Serializable> T newInstance(final Class<T> clazz, final ID id) { EntityType type = getEntityType(clazz); @SuppressWarnings("unchecked") T entity = (T) type.newInstance(); try { PropertyUtils.setProperty(entity, type.getIdName(), id); } catch (Exception e) { logger.error("initialize {} with id {} error", clazz, id); } return entity; } }
public class class_name { public <T extends Entity<ID>, ID extends Serializable> T newInstance(final Class<T> clazz, final ID id) { EntityType type = getEntityType(clazz); @SuppressWarnings("unchecked") T entity = (T) type.newInstance(); try { PropertyUtils.setProperty(entity, type.getIdName(), id); // depends on control dependency: [try], data = [none] } catch (Exception e) { logger.error("initialize {} with id {} error", clazz, id); } // depends on control dependency: [catch], data = [none] return entity; } }
public class class_name { private static List<AbstractWarningsParser> getAllParsers() { List<AbstractWarningsParser> parsers = Lists.newArrayList(); parsers.add(new MsBuildParser(Messages._Warnings_PCLint_ParserName(), Messages._Warnings_PCLint_LinkName(), Messages._Warnings_PCLint_TrendName())); if (PluginDescriptor.isPluginInstalled("violations")) { ViolationsRegistry.addParsers(parsers); } Iterable<GroovyParser> parserDescriptions = getDynamicParserDescriptions(); parsers.addAll(getDynamicParsers(parserDescriptions)); parsers.addAll(all()); return ImmutableList.copyOf(parsers); } }
public class class_name { private static List<AbstractWarningsParser> getAllParsers() { List<AbstractWarningsParser> parsers = Lists.newArrayList(); parsers.add(new MsBuildParser(Messages._Warnings_PCLint_ParserName(), Messages._Warnings_PCLint_LinkName(), Messages._Warnings_PCLint_TrendName())); if (PluginDescriptor.isPluginInstalled("violations")) { ViolationsRegistry.addParsers(parsers); // depends on control dependency: [if], data = [none] } Iterable<GroovyParser> parserDescriptions = getDynamicParserDescriptions(); parsers.addAll(getDynamicParsers(parserDescriptions)); parsers.addAll(all()); return ImmutableList.copyOf(parsers); } }
public class class_name { public boolean publish(String channel, Message message, String className, Recipient... recipients) { try { IMessageProducer producer = findRegisteredProducer(Class.forName(className, false, null)); return publish(channel, message, producer, recipients); } catch (Exception e) { return false; } } }
public class class_name { public boolean publish(String channel, Message message, String className, Recipient... recipients) { try { IMessageProducer producer = findRegisteredProducer(Class.forName(className, false, null)); return publish(channel, message, producer, recipients); // depends on control dependency: [try], data = [none] } catch (Exception e) { return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public String doLayout(ILoggingEvent event) { // Reset working buffer. If the buffer is too large, then we need a new // one in order to avoid the penalty of creating a large array. if (buf.capacity() > UPPER_LIMIT) { buf = new StringBuilder(DEFAULT_SIZE); } else { buf.setLength(0); } // We yield to the \r\n heresy. buf.append("<log4j:event logger=\""); buf.append(Transform.escapeTags(event.getLoggerName())); buf.append("\"\r\n"); buf.append(" timestamp=\""); buf.append(event.getTimeStamp()); buf.append("\" level=\""); buf.append(event.getLevel()); buf.append("\" thread=\""); buf.append(Transform.escapeTags(event.getThreadName())); buf.append("\">\r\n"); buf.append(" <log4j:message>"); buf.append(Transform.escapeTags(event.getFormattedMessage())); buf.append("</log4j:message>\r\n"); // logback does not support NDC // String ndc = event.getNDC(); IThrowableProxy tp = event.getThrowableProxy(); if (tp != null) { StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); buf.append(" <log4j:throwable><![CDATA["); for (StackTraceElementProxy step : stepArray) { buf.append(CoreConstants.TAB); buf.append(step.toString()); buf.append("\r\n"); } buf.append("]]></log4j:throwable>\r\n"); } if (locationInfo) { StackTraceElement[] callerDataArray = event.getCallerData(); if (callerDataArray != null && callerDataArray.length > 0) { StackTraceElement immediateCallerData = callerDataArray[0]; buf.append(" <log4j:locationInfo class=\""); buf.append(immediateCallerData.getClassName()); buf.append("\"\r\n"); buf.append(" method=\""); buf.append(Transform.escapeTags(immediateCallerData.getMethodName())); buf.append("\" file=\""); buf.append(Transform.escapeTags(immediateCallerData.getFileName())); buf.append("\" line=\""); buf.append(immediateCallerData.getLineNumber()); buf.append("\"/>\r\n"); } } /* * <log4j:properties> <log4j:data name="name" value="value"/> * </log4j:properties> */ if (this.getProperties()) { Map<String, String> propertyMap = event.getMDCPropertyMap(); if ((propertyMap != null) && (propertyMap.size() != 0)) { Set<Entry<String, String>> entrySet = propertyMap.entrySet(); buf.append(" <log4j:properties>"); for (Entry<String, String> entry : entrySet) { buf.append("\r\n <log4j:data"); buf.append(" name=\"" + Transform.escapeTags(entry.getKey()) + "\""); buf.append(" value=\"" + Transform.escapeTags(entry.getValue()) + "\""); buf.append(" />"); } buf.append("\r\n </log4j:properties>"); } } buf.append("\r\n</log4j:event>\r\n\r\n"); return buf.toString(); } }
public class class_name { public String doLayout(ILoggingEvent event) { // Reset working buffer. If the buffer is too large, then we need a new // one in order to avoid the penalty of creating a large array. if (buf.capacity() > UPPER_LIMIT) { buf = new StringBuilder(DEFAULT_SIZE); // depends on control dependency: [if], data = [none] } else { buf.setLength(0); // depends on control dependency: [if], data = [none] } // We yield to the \r\n heresy. buf.append("<log4j:event logger=\""); buf.append(Transform.escapeTags(event.getLoggerName())); buf.append("\"\r\n"); buf.append(" timestamp=\""); buf.append(event.getTimeStamp()); buf.append("\" level=\""); buf.append(event.getLevel()); buf.append("\" thread=\""); buf.append(Transform.escapeTags(event.getThreadName())); buf.append("\">\r\n"); buf.append(" <log4j:message>"); buf.append(Transform.escapeTags(event.getFormattedMessage())); buf.append("</log4j:message>\r\n"); // logback does not support NDC // String ndc = event.getNDC(); IThrowableProxy tp = event.getThrowableProxy(); if (tp != null) { StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); buf.append(" <log4j:throwable><![CDATA["); // depends on control dependency: [if], data = [none] for (StackTraceElementProxy step : stepArray) { buf.append(CoreConstants.TAB); // depends on control dependency: [for], data = [none] buf.append(step.toString()); // depends on control dependency: [for], data = [step] buf.append("\r\n"); // depends on control dependency: [for], data = [none] } buf.append("]]></log4j:throwable>\r\n"); // depends on control dependency: [if], data = [none] } if (locationInfo) { StackTraceElement[] callerDataArray = event.getCallerData(); if (callerDataArray != null && callerDataArray.length > 0) { StackTraceElement immediateCallerData = callerDataArray[0]; buf.append(" <log4j:locationInfo class=\""); buf.append(immediateCallerData.getClassName()); // depends on control dependency: [if], data = [none] buf.append("\"\r\n"); // depends on control dependency: [if], data = [none] buf.append(" method=\""); // depends on control dependency: [if], data = [none] buf.append(Transform.escapeTags(immediateCallerData.getMethodName())); // depends on control dependency: [if], data = [none] buf.append("\" file=\""); // depends on control dependency: [if], data = [none] buf.append(Transform.escapeTags(immediateCallerData.getFileName())); // depends on control dependency: [if], data = [none] buf.append("\" line=\""); // depends on control dependency: [if], data = [none] buf.append(immediateCallerData.getLineNumber()); // depends on control dependency: [if], data = [none] buf.append("\"/>\r\n"); // depends on control dependency: [if], data = [none] } } /* * <log4j:properties> <log4j:data name="name" value="value"/> * </log4j:properties> */ if (this.getProperties()) { Map<String, String> propertyMap = event.getMDCPropertyMap(); if ((propertyMap != null) && (propertyMap.size() != 0)) { Set<Entry<String, String>> entrySet = propertyMap.entrySet(); buf.append(" <log4j:properties>"); for (Entry<String, String> entry : entrySet) { buf.append("\r\n <log4j:data"); buf.append(" name=\"" + Transform.escapeTags(entry.getKey()) + "\""); buf.append(" value=\"" + Transform.escapeTags(entry.getValue()) + "\""); buf.append(" />"); } buf.append("\r\n </log4j:properties>"); } } buf.append("\r\n</log4j:event>\r\n\r\n"); return buf.toString(); } }