id
stringlengths
25
27
content
stringlengths
190
15.4k
max_stars_repo_path
stringlengths
31
217
robustness-copilot_data_801
/** * Builds functions that map the fields from source CronDefinition to target. * * @param from - source CronDefinition * @param to - target CronDefinition */ private void buildMappings(final CronDefinition from, final CronDefinition to){ final Map<CronFieldName, FieldDefinition> sourceFieldDefinitions = getFieldDefinitions(from); final Map<CronFieldName, FieldDefinition> destFieldDefinitions = getFieldDefinitions(to); boolean startedDestMapping = false; boolean startedSourceMapping = false; for (final CronFieldName name : CronFieldName.values()) { final FieldDefinition destinationFieldDefinition = destFieldDefinitions.get(name); final FieldDefinition sourceFieldDefinition = sourceFieldDefinitions.get(name); if (destinationFieldDefinition != null) { startedDestMapping = true; } if (sourceFieldDefinition != null) { startedSourceMapping = true; } if (startedDestMapping && destinationFieldDefinition == null) { break; } if (!startedSourceMapping && destinationFieldDefinition != null) { mappings.put(name, returnOnZeroExpression(name)); } if (startedSourceMapping && sourceFieldDefinition == null && destinationFieldDefinition != null) { mappings.put(name, returnAlwaysExpression(name)); } if (sourceFieldDefinition == null || destinationFieldDefinition == null) { continue; } if (CronFieldName.DAY_OF_WEEK.equals(name)) { mappings.put(name, dayOfWeekMapping((DayOfWeekFieldDefinition) sourceFieldDefinition, (DayOfWeekFieldDefinition) destinationFieldDefinition)); } else if (CronFieldName.DAY_OF_MONTH.equals(name)) { mappings.put(name, dayOfMonthMapping(sourceFieldDefinition, destinationFieldDefinition)); } else { mappings.put(name, returnSameExpression()); } } }
/src/main/java/com/cronutils/mapper/CronMapper.java
robustness-copilot_data_802
/** * Does the atom at index {@code i} have priority over the atom at index * {@code j} for the tetrahedral atom {@code focus}. * * @param focus tetrahedral centre (or -1 if double bond) * @param i adjacent atom index * @param j adjacent atom index * @return whether atom i has priority */ boolean hasPriority(int focus, int i, int j){ if (tetrahedralElements[i] == null && tetrahedralElements[j] != null) return true; if (tetrahedralElements[i] != null && tetrahedralElements[j] == null) return false; if (doubleBondElements[i] == null && doubleBondElements[j] != null) return true; if (doubleBondElements[i] != null && doubleBondElements[j] == null) return false; IAtom iAtom = container.getAtom(i); IAtom jAtom = container.getAtom(j); boolean iIsSp3 = isSp3Carbon(iAtom, graph[i].length); boolean jIsSp3 = isSp3Carbon(jAtom, graph[j].length); if (iIsSp3 != jIsSp3) return !iIsSp3; if (tetrahedralElements[i] == null && tetrahedralElements[j] != null) return true; if (tetrahedralElements[i] != null && tetrahedralElements[j] == null) return false; boolean iCyclic = focus >= 0 ? ringSearch.cyclic(focus, i) : ringSearch.cyclic(i); boolean jCyclic = focus >= 0 ? ringSearch.cyclic(focus, j) : ringSearch.cyclic(j); if (!iCyclic && jCyclic) return true; if (iCyclic && !jCyclic) return false; if (iAtom.getAtomicNumber() > 0 && jAtom.getAtomicNumber() == 0) return true; if (iAtom.getAtomicNumber() == 0 && jAtom.getAtomicNumber() > 0) return false; final int iDegree = graph[i].length; int iElem = iAtom.getAtomicNumber(); final int jDegree = graph[j].length; int jElem = jAtom.getAtomicNumber(); if (iElem == 6) iElem = 256; if (jElem == 6) jElem = 256; if (iDegree == 1 && jDegree > 1) return true; if (jDegree == 1 && iDegree > 1) return false; if (iElem < jElem) return true; if (iElem > jElem) return false; if (iDegree < jDegree) return true; if (iDegree > jDegree) return false; return false; }
/tool/sdg/src/main/java/org/openscience/cdk/layout/NonplanarBonds.java
robustness-copilot_data_803
/** * Find out if the PortImplementation object is already stored in the repository. It uses the fully qualified name to retrieve the entity * * @param userId the name of the calling user * @param qualifiedName the qualifiedName name of the process to be searched * * @return optional with entity details if found, empty optional if not found * * @throws InvalidParameterException the bean properties are invalid * @throws UserNotAuthorizedException user not authorized to issue this request * @throws PropertyServerException problem accessing the property server */ public Optional<EntityDetail> findPortImplementationEntity(String userId, String qualifiedName) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException{ return dataEngineCommonHandler.findEntity(userId, qualifiedName, PORT_IMPLEMENTATION_TYPE_NAME); }
/open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEnginePortHandler.java
robustness-copilot_data_804
/** * Checks if each next {@link ILigand} is different from the previous * one according to the {@link CIPLigandRule}. It assumes that the input * is sorted based on that rule. * * @param ligands array of {@link ILigand} to check * @return true, if all ligands are different */ public static boolean checkIfAllLigandsAreDifferent(ILigand[] ligands){ for (int i = 0; i < (ligands.length - 1); i++) { if (cipRule.compare(ligands[i], ligands[i + 1]) == 0) return false; } return true; }
/descriptor/cip/src/main/java/org/openscience/cdk/geometry/cip/CIPTool.java
robustness-copilot_data_805
/** * Builder for molecules (rather, for atom containers) from signature * strings. * * @param signatureString the signature string to use * @param coBuilder {@link IChemObjectBuilder} to build the returned atom container from * @return an atom container */ public static IAtomContainer fromSignatureString(String signatureString, IChemObjectBuilder coBuilder){ ColoredTree tree = AtomSignature.parse(signatureString); MoleculeFromSignatureBuilder builder = new MoleculeFromSignatureBuilder(coBuilder); builder.makeFromColoredTree(tree); return builder.getAtomContainer(); }
/descriptor/signature/src/main/java/org/openscience/cdk/signature/MoleculeSignature.java
robustness-copilot_data_806
/** Returns a column of the same type containing the first {@code numRows} of this column. */ Column<T> first(final int numRows){ int newRowCount = Math.min(numRows, size()); return inRange(0, newRowCount); }
/core/src/main/java/tech/tablesaw/columns/Column.java
robustness-copilot_data_807
/** * Returns a StringColumn with the year and month from this column concatenated into a String that * will sort lexicographically in temporal order. * * <p>This simplifies the production of plots and tables that aggregate values into standard * temporal units (e.g., you want monthly data but your source data is more than a year long and * you don't want months from different years aggregated together). */ StringColumn yearMonth(){ StringColumn newColumn = StringColumn.create(this.name() + " year & month"); for (int r = 0; r < this.size(); r++) { long c1 = this.getLongInternal(r); if (DateTimeColumn.valueIsMissing(c1)) { newColumn.append(StringColumnType.missingValueIndicator()); } else { String ym = String.valueOf(getYear(c1)); ym = ym + "-" + Strings.padStart(String.valueOf(getMonthValue(c1)), 2, '0'); newColumn.append(ym); } } return newColumn; }
/core/src/main/java/tech/tablesaw/columns/datetimes/DateTimeMapFunctions.java
robustness-copilot_data_808
/** * Reports on the options that have been inserted into the MATSim {@link Config} * via the command line. */ private void reportOptions(){ logger.info(String.format("Received %d positional command line arguments:", positionalArguments.size())); logger.info(" " + String.join(" , ", positionalArguments)); Map<String, List<String>> prefixedOptions = new HashMap<>(); List<String> nonPrefixedOptions = new LinkedList<>(); for (String option : options.keySet()) { int separatorIndex = option.indexOf(':'); if (separatorIndex > -1) { String prefix = option.substring(0, separatorIndex); option = option.substring(separatorIndex + 1); if (!prefixedOptions.containsKey(prefix)) { prefixedOptions.put(prefix, new LinkedList<>()); } prefixedOptions.get(prefix).add(option); } else { nonPrefixedOptions.add(option); } } logger.info(String.format("Received %d command line options with %d prefixes:", options.size(), prefixedOptions.size())); Collections.sort(nonPrefixedOptions); for (String option : nonPrefixedOptions) { logger.info(String.format(" %s = %s", option, options.get(option))); } List<String> orderedPrefixes = new LinkedList<>(prefixedOptions.keySet()); Collections.sort(orderedPrefixes); for (String prefix : orderedPrefixes) { logger.info(String.format(" Prefix %s:", prefix)); for (String option : prefixedOptions.get(prefix)) { logger.info(String.format(" %s = %s", option, options.get(prefix + ":" + option))); } } }
/matsim/src/main/java/org/matsim/core/config/CommandLine.java
robustness-copilot_data_809
/** * Returns a List for looping over all isotopes in this adduct formula. * * @return A List with the isotopes in this adduct formula */ private List<IIsotope> isotopesList(){ List<IIsotope> isotopes = new ArrayList<IIsotope>(); Iterator<IMolecularFormula> componentIterator = components.iterator(); while (componentIterator.hasNext()) { Iterator<IIsotope> compIsotopes = componentIterator.next().isotopes().iterator(); while (compIsotopes.hasNext()) { IIsotope isotope = compIsotopes.next(); if (!isotopes.contains(isotope)) { isotopes.add(isotope); } } } return isotopes; }
/base/data/src/main/java/org/openscience/cdk/formula/AdductFormula.java
robustness-copilot_data_810
/** * Splits this partition by taking the cell at cellIndex and making two * new cells - the first with the singleton splitElement and the second * with the rest of the elements from that cell. * * @param cellIndex the index of the cell to split on * @param splitElement the element to put in its own cell * @return a new (finer) Partition */ public Partition splitBefore(int cellIndex, int splitElement){ Partition r = new Partition(); for (int j = 0; j < cellIndex; j++) { r.addCell(this.copyBlock(j)); } r.addSingletonCell(splitElement); SortedSet<Integer> splitBlock = this.copyBlock(cellIndex); splitBlock.remove(splitElement); r.addCell(splitBlock); for (int j = cellIndex + 1; j < this.size(); j++) { r.addCell(this.copyBlock(j)); } return r; }
/tool/group/src/main/java/org/openscience/cdk/group/Partition.java
robustness-copilot_data_811
/** * Increases the priority (=decrease the given double value) of the element. * If the element ins not part of the queue, it is added. If the new priority * is lower than the existing one, the method returns <tt>false</tt> * * @return <tt>true</tt> if the elements priority was decreased. */ public boolean decreaseKey(E value, double cost){ int index = indices[this.getIndex(value)]; if (index < 0) { return this.add(value, cost); } double oldCost = costs[index]; if (oldCost < cost) return false; siftUp(index, value, cost); return true; }
/matsim/src/main/java/org/matsim/core/router/priorityqueue/BinaryMinHeap.java
robustness-copilot_data_812
/** * Layout the molecule, starts with ring systems and than aliphatic chains. * *@param ringSetMolecule ringSystems of the molecule */ private void layoutMolecule(List ringSetMolecule, IAtomContainer molecule, AtomPlacer3D ap3d, AtomTetrahedralLigandPlacer3D atlp3d, AtomPlacer atomPlacer) throws CDKException, IOException, CloneNotSupportedException{ IAtomContainer ac = null; int safetyCounter = 0; IAtom atom = null; do { safetyCounter++; atom = ap3d.getNextPlacedHeavyAtomWithUnplacedRingNeighbour(molecule); if (atom != null) { IAtom unplacedAtom = ap3d.getUnplacedRingHeavyAtom(molecule, atom); IRingSet ringSetA = getRingSetOfAtom(ringSetMolecule, unplacedAtom); IAtomContainer ringSetAContainer = RingSetManipulator.getAllInOneContainer(ringSetA); templateHandler.mapTemplates(ringSetAContainer, ringSetAContainer.getAtomCount()); if (checkAllRingAtomsHasCoordinates(ringSetAContainer)) { } else { throw new IOException("RingAtomLayoutError: Not every ring atom is placed! Molecule cannot be layout.Sorry"); } Point3d firstAtomOriginalCoord = unplacedAtom.getPoint3d(); Point3d centerPlacedMolecule = ap3d.geometricCenterAllPlacedAtoms(molecule); setBranchAtom(molecule, unplacedAtom, atom, ap3d.getPlacedHeavyAtoms(molecule, atom), ap3d, atlp3d); layoutRingSystem(firstAtomOriginalCoord, unplacedAtom, ringSetA, centerPlacedMolecule, atom, ap3d); searchAndPlaceBranches(molecule, ringSetAContainer, ap3d, atlp3d, atomPlacer); ringSetA = null; unplacedAtom = null; firstAtomOriginalCoord = null; centerPlacedMolecule = null; } else { setAtomsToUnVisited(molecule); atom = ap3d.getNextPlacedHeavyAtomWithUnplacedAliphaticNeighbour(molecule); if (atom != null) { ac = atom.getBuilder().newInstance(IAtomContainer.class); ac.addAtom(atom); searchAndPlaceBranches(molecule, ac, ap3d, atlp3d, atomPlacer); ac = null; } } } while (!ap3d.allHeavyAtomsPlaced(molecule) || safetyCounter > molecule.getAtomCount()); }
/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/ModelBuilder3D.java
robustness-copilot_data_813
/** * Given a new proposed label or directoryLabel for a file, check against * existing files if a duplicate directoryLabel/label combination would be * created. */ public static boolean conflictsWithExistingFilenames(String pathPlusFilename, List<FileMetadata> fileMetadatas){ List<String> filePathsAndNames = getPathsAndFileNames(fileMetadatas); return filePathsAndNames.contains(pathPlusFilename); }
/src/main/java/edu/harvard/iq/dataverse/ingest/IngestUtil.java
robustness-copilot_data_814
/** * Applies the given function to a list subtag if it is present and its contents are double * tags. * * @param key the key to look up * @param consumer the function to apply * @return true if the tag exists and was passed to the consumer; false otherwise */ public boolean readDoubleList(@NonNls String key, Consumer<? super List<Double>> consumer){ return readList(key, TagType.DOUBLE, consumer); }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_815
/** * Position the mass label relative to the element label. The mass adjunct is position to the * top left of the element label. * * @param massLabel mass label outline * @param elementLabel element label outline * @return positioned mass label */ TextOutline positionMassLabel(TextOutline massLabel, TextOutline elementLabel){ final Rectangle2D elementBounds = elementLabel.getBounds(); final Rectangle2D massBounds = massLabel.getBounds(); return massLabel.translate((elementBounds.getMinX() - padding) - massBounds.getMaxX(), (elementBounds.getMinY() - (massBounds.getHeight() / 2)) - massBounds.getMinY()); }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardAtomGenerator.java
robustness-copilot_data_816
/** * Searches for the current sling:resourceType under /content and replaces any nodes it finds * with the newResourceType. * * @param oldResourceType The current sling:resourceType. * @param newResourceType The new sling:resourceType to be used. */ protected final void searchAndUpdateResourceType(String oldResourceType, String newResourceType) throws RepositoryException{ Map<String, String> map = new HashMap<>(); map.put("p.limit", "-1"); map.put("path", "/content"); map.put("1_property", SLING_RESOURCE_TYPE); map.put("1_property.value", oldResourceType); logger.info("Finding all nodes under /content with resource type: {}", oldResourceType); final QueryBuilder queryBuilder = resourceResolver.adaptTo(QueryBuilder.class); if (queryBuilder != null) { Query query = queryBuilder.createQuery(PredicateGroup.create(map), session); QueryUtil.setResourceResolverOn(resourceResolver, query); SearchResult result = query.getResult(); Iterator<Node> nodeItr = result.getNodes(); if (nodeItr.hasNext()) { while (nodeItr.hasNext()) { Node node = nodeItr.next(); updateResourceType(node, newResourceType); } } else { logger.info("No nodes found with resource type: {}", oldResourceType); } } }
/bundle/src/main/java/com/adobe/acs/commons/ondeploy/scripts/OnDeployScriptBase.java
robustness-copilot_data_817
/** * Returns the "raw" field of a document based on an internal Lucene docid. * The method is named to be consistent with Lucene's {@link IndexReader#document(int)}, contra Java's standard * method naming conventions. * * @param ldocid internal Lucene docid * @return the "raw" field the document */ public String documentRaw(int ldocid){ try { return reader.document(ldocid).get(IndexArgs.RAW); } catch (Exception e) { return null; } }
/src/main/java/io/anserini/search/SimpleImpactSearcher.java
robustness-copilot_data_818
/** * Checks to see if this tag is a strict, deep submap of the given CompoundTag. * * @param other The CompoundTag that should contain our values. */ public boolean matches(CompoundTag other){ for (Entry<String, Tag> entry : value.entrySet()) { if (!other.value.containsKey(entry.getKey())) { return false; } Tag value = entry.getValue(); Tag otherValue = other.value.get(entry.getKey()); if ((value == null && otherValue != null) || (value != null && otherValue == null)) { return false; } if (value != null) { if (value.getClass() != otherValue.getClass()) { return false; } if (value instanceof CompoundTag) { if (!((CompoundTag) value).matches((CompoundTag) otherValue)) { return false; } } else if (value instanceof IntArrayTag) { if (!Arrays.equals(((IntArrayTag) value).getValue(), ((IntArrayTag) otherValue).getValue())) { return false; } } else if (value instanceof ByteArrayTag) { if (!Arrays.equals(((ByteArrayTag) value).getValue(), ((ByteArrayTag) otherValue).getValue())) { return false; } } else if (!value.equals(otherValue)) { return false; } } } return true; }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_819
/** * Mass number for a atom with a given atomic number and exact mass. * * @param atomicNumber atomic number * @param exactMass exact mass * @return the mass number (or null) if no mass number was found * @throws IOException isotope configuration could not be loaded */ private Integer massNumber(int atomicNumber, double exactMass) throws IOException{ String symbol = PeriodicTable.getSymbol(atomicNumber); IIsotope isotope = Isotopes.getInstance().getIsotope(symbol, exactMass, 0.001); return isotope != null ? isotope.getMassNumber() : null; }
/tool/forcefield/src/main/java/org/openscience/cdk/modeling/builder3d/MMFF94BasedParameterSetReader.java
robustness-copilot_data_820
/** * Checks whether this query atom matches a target atom. * * Currently a query pharmacophore atom will match a target pharmacophore group if the * symbols of the two groups match. This is based on the assumption that * pharmacophore groups with the same symbol will have the same SMARTS * pattern. * * @param atom A target pharmacophore group * @return true if the current query group has the same symbol as the target group */ public boolean matches(IAtom atom){ PharmacophoreAtom patom = PharmacophoreAtom.get(atom); return patom.getSymbol().equals(getSymbol()); }
/tool/pcore/src/main/java/org/openscience/cdk/pharmacophore/PharmacophoreQueryAtom.java
robustness-copilot_data_821
/** * For each item in the column, returns the same number with the sign changed. For example: -1.3 * returns 1.3, 2.135 returns -2.135 0 returns 0 */ DoubleColumn neg(){ DoubleColumn newColumn = DoubleColumn.create(name() + "[neg]", size()); for (int i = 0; i < size(); i++) { newColumn.set(i, getDouble(i) * -1); } return newColumn; }
/core/src/main/java/tech/tablesaw/columns/numbers/NumberMapFunctions.java
robustness-copilot_data_822
/** * Copy all shipments from the existing carrier to the new carrier with * shipments. * * @param carrierWS the "new" carrier with Shipments * @param carrier the already existing carrier */ private static void copyShipments(Carrier carrierWS, Carrier carrier){ for (CarrierShipment carrierShipment : carrier.getShipments().values()) { log.debug("Copy CarrierShipment: " + carrierShipment.toString()); CarrierUtils.addShipment(carrierWS, carrierShipment); } }
/contribs/freight/src/main/java/org/matsim/contrib/freight/utils/FreightUtils.java
robustness-copilot_data_823
/** * Convert a Java 2D shape to a list of points. * * @param shape a shape * @return list of point */ static List<Point2D> pointsOf(final Shape shape){ final List<Point2D> points = new ArrayList<Point2D>(); final double[] coordinates = new double[6]; for (PathIterator i = shape.getPathIterator(null); !i.isDone(); i.next()) { switch(i.currentSegment(coordinates)) { case PathIterator.SEG_CLOSE: break; case PathIterator.SEG_MOVETO: case PathIterator.SEG_LINETO: points.add(new Point2D.Double(coordinates[0], coordinates[1])); break; case PathIterator.SEG_QUADTO: points.add(new Point2D.Double(coordinates[0], coordinates[1])); points.add(new Point2D.Double(coordinates[2], coordinates[3])); break; case PathIterator.SEG_CUBICTO: points.add(new Point2D.Double(coordinates[0], coordinates[1])); points.add(new Point2D.Double(coordinates[2], coordinates[3])); points.add(new Point2D.Double(coordinates[4], coordinates[5])); break; } } if (!points.isEmpty() && points.get(points.size() - 1).equals(points.get(0))) { points.remove(points.size() - 1); } return points; }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/ConvexHull.java
robustness-copilot_data_824
/** * Calculate the count of atoms of the largest pi system in the supplied {@link IAtomContainer}. * * <p>The method require one parameter: * <ol> * <li>if checkAromaticity is true, the method check the aromaticity, * <li>if false, means that the aromaticity has already been checked * </ol> * * @param container The {@link IAtomContainer} for which this descriptor is to be calculated * @return the number of atoms in the largest pi system of this AtomContainer * @see #setParameters */ public DescriptorValue calculate(IAtomContainer container){ boolean[] originalFlag4 = new boolean[container.getAtomCount()]; for (int i = 0; i < originalFlag4.length; i++) { originalFlag4[i] = container.getAtom(i).getFlag(CDKConstants.VISITED); } if (checkAromaticity) { try { AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(container); Aromaticity.cdkLegacy().apply(container); } catch (CDKException e) { return getDummyDescriptorValue(e); } } int largestPiSystemAtomsCount = 0; List<IAtom> startSphere; List<IAtom> path; for (int i = 0; i < container.getAtomCount(); i++) { container.getAtom(i).setFlag(CDKConstants.VISITED, false); } for (int i = 0; i < container.getAtomCount(); i++) { if ((container.getMaximumBondOrder(container.getAtom(i)) != IBond.Order.SINGLE || Math.abs(container.getAtom(i).getFormalCharge()) >= 1 || container.getAtom(i).getFlag(CDKConstants.ISAROMATIC) || container.getAtom(i).getAtomicNumber() == IElement.N || container.getAtom(i).getAtomicNumber() == IElement.O) && !container.getAtom(i).getFlag(CDKConstants.VISITED)) { startSphere = new ArrayList<IAtom>(); path = new ArrayList<IAtom>(); startSphere.add(container.getAtom(i)); try { breadthFirstSearch(container, startSphere, path); } catch (CDKException e) { return getDummyDescriptorValue(e); } if (path.size() > largestPiSystemAtomsCount) { largestPiSystemAtomsCount = path.size(); } } } for (int i = 0; i < originalFlag4.length; i++) { container.getAtom(i).setFlag(CDKConstants.VISITED, originalFlag4[i]); } return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new IntegerResult(largestPiSystemAtomsCount), getDescriptorNames()); }
/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/LargestPiSystemDescriptor.java
robustness-copilot_data_825
/** * See if any of the provided filter patterns match the current path. TRUE, if no filters are received. * * @param filters An array of string making up the regex to match with the path. They should never * be empty since there is a DEFAULT value. * @param path The path to interrogate. * @return true (match found) or false (no match) */ private boolean pathMatchesFilter(final String[] filters, String path){ boolean matches = false; for (String filter : filters) { try { if (filter.equals("*") || path.matches(filter)) { matches = true; break; } } catch (PatternSyntaxException ex) { logErrorMessage("Ignoring invalid regex filter: [" + filter + "]. Reason: " + ex.getMessage()); } } return matches; }
/bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/RefetchFlushContentBuilderImpl.java
robustness-copilot_data_826
/** * Abort call when a label could not be parsed. The tokens are cleared * and replaced with the original label. * * @param label the original label * @param tokens the current tokens * @return always returns false */ private static boolean failParse(String label, List<String> tokens){ tokens.clear(); tokens.add(label); return false; }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/AbbreviationLabel.java
robustness-copilot_data_827
/** * Returns the computed digest or null if overlapping writes have been detected. * * @return Checksum */ private Set<Checksum> finalizeChecksums(){ _ioStateWriteLock.lock(); try { _isWritable = false; } finally { _ioStateWriteLock.unlock(); } synchronized (_dataRangeSet) { synchronized (_digests) { try { if (_dataRangeSet.asRanges().size() != 1 || _nextChecksumOffset == 0) { feedZerosToDigesterForRangeGaps(); } return _digests.stream().map(Checksum::new).collect(Collectors.toSet()); } catch (IOException e) { _log.info("Unable to generate checksum of sparse file: {}", e.toString()); return Collections.emptySet(); } } } }
/modules/dcache/src/main/java/org/dcache/pool/movers/ChecksumChannel.java
robustness-copilot_data_828
/** * Method that can be used to serialize any Java value as * a String. Functionally equivalent to calling * {@link #writeValue(Writer,Object)} with {@link java.io.StringWriter} * and constructing String, but more efficient. *<p> * Note: prior to version 2.1, throws clause included {@link IOException}; 2.1 removed it. */ public String writeValueAsString(Object value) throws JsonProcessingException{ SegmentedStringWriter sw = new SegmentedStringWriter(_jsonFactory._getBufferRecycler()); try { _writeValueAndClose(createGenerator(sw), value); } catch (JsonProcessingException e) { throw e; } catch (IOException e) { throw JsonMappingException.fromUnexpectedIOE(e); } return sw.getAndClear(); }
/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java
robustness-copilot_data_829
/** Returns the base 10 log of the values in this column as a NumberColumn. */ DoubleColumn log10(){ DoubleColumn newColumn = DoubleColumn.create(name() + "[log10]", size()); for (int i = 0; i < size(); i++) { newColumn.set(i, Math.log10(getDouble(i))); } return newColumn; }
/core/src/main/java/tech/tablesaw/columns/numbers/NumberMapFunctions.java
robustness-copilot_data_830
/** * Writes a IChemObject to the MDL RXN file formated output. * It can only output ChemObjects of type Reaction * * @param object class must be of type Molecule or MoleculeSet. * * @see org.openscience.cdk.ChemFile */ public void write(IChemObject object) throws CDKException{ if (object instanceof IReactionSet) { writeReactionSet((IReactionSet) object); } else if (object instanceof IReaction) { writeReaction((IReaction) object); } else { throw new CDKException("Only supported is writing ReactionSet, Reaction objects."); } }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLRXNWriter.java
robustness-copilot_data_831
/** * Iterates through array items and replaces any placeholders found. * * @param node Array node * @param contentVariableReplacements current map of content variables */ private void replaceInArray(JsonNode node, Map<String, Object> contentVariableReplacements){ if (node.get(0) != null && node.get(0).isTextual()) { List<String> updated = new LinkedList<>(); for (JsonNode arrayItem : node) { String current = arrayItem.asText(); updated.add(replaceInString(current, contentVariableReplacements)); } ((ArrayNode) node).removeAll(); for (int i = 0; i < updated.size(); i++) { ((ArrayNode) node).insert(i, updated.get(i)); } } else if (node.get(0) != null && node.get(0).isContainerNode()) { for (JsonNode arrayItem : node) { replaceInElements(arrayItem, contentVariableReplacements); } } }
/bundle/src/main/java/com/adobe/acs/commons/ccvar/filter/ContentVariableJsonFilter.java
robustness-copilot_data_832
/** * if md5 is not the same as the original, then update lcoal cache. * @param group ConfigGroupEnum * @param <T> the type of class * @param data the new config data */ protected void updateCache(final ConfigGroupEnum group, final List<T> data){ String json = GsonUtils.getInstance().toJson(data); ConfigDataCache newVal = new ConfigDataCache(group.name(), json, Md5Utils.md5(json), System.currentTimeMillis()); ConfigDataCache oldVal = CACHE.put(newVal.getGroup(), newVal); LOG.info("update config cache[{}], old: {}, updated: {}", group, oldVal, newVal); }
/shenyu-admin/src/main/java/org/apache/shenyu/admin/listener/AbstractDataChangedListener.java
robustness-copilot_data_833
/** * Formats an int to fit into the connectiontable and changes it * to a String. * * @param i The int to be formated * @param l Length of the String * @return The String to be written into the connectiontable */ private String formatMDLInt(int i, int l){ String s = "", fs = ""; NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); nf.setParseIntegerOnly(true); nf.setMinimumIntegerDigits(1); nf.setMaximumIntegerDigits(l); nf.setGroupingUsed(false); s = nf.format(i); l = l - s.length(); for (int f = 0; f < l; f++) fs += " "; fs += s; return fs; }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLRXNWriter.java
robustness-copilot_data_834
/** * Process atom labels from extended SMILES in a char iter. * * @param iter char iteration * @param dest destination of labels (atomidx->label) * @return parse success/failure */ private static boolean processAtomLabels(final CharIter iter, final Map<Integer, String> dest){ int atomIdx = 0; while (iter.hasNext()) { // fast forward through empty labels while (iter.nextIf(';')) atomIdx++; char c = iter.next(); if (c == '$') { // optional iter.nextIf(','); // end of atom label return true; } else { // push back iter.pos--; int beg = iter.pos; int rollback = beg; while (iter.hasNext()) { if (iter.pos == beg && iter.curr() == '_' && iter.peek() == 'R') { ++beg; } // correct step over of escaped label if (iter.curr() == '&') { rollback = iter.pos; if (iter.nextIf('&') && iter.nextIf('#') && iter.nextIfDigit()) { // more digits while (iter.nextIfDigit()) { } if (!iter.nextIf(';')) { iter.pos = rollback; } else { } } else { iter.pos = rollback; } } else if (iter.curr() == ';') break; else if (iter.curr() == '$') break; else iter.next(); } dest.put(atomIdx, unescape(iter.substr(beg, iter.pos))); atomIdx++; if (iter.nextIf('$')) { // optional iter.nextIf(','); return true; } if (!iter.nextIf(';')) return false; } } return false; }
/storage/smiles/src/main/java/org/openscience/cdk/smiles/CxSmilesParser.java
robustness-copilot_data_835
/** * Method that will construct a POJONode and * insert it at specified position in this array. * * @return This array node, to allow chaining */ public ArrayNode insertPOJO(int index, Object pojo){ return _insert(index, (pojo == null) ? nullNode() : pojoNode(pojo)); }
/src/main/java/com/fasterxml/jackson/databind/node/ArrayNode.java
robustness-copilot_data_836
/** * Calculate new point(s) X in a B-A system to form B-A-X. Use C as reference * for * staggering about the B-A bond (1a) 1 ligand(B) of refAtom (A) which * itself has a ligand (C) (i) 1 points required; vector along AB vector (ii) * 2 points: 2 vectors in ABC plane, staggered and eclipsed wrt C (iii) 3 * points: 1 staggered wrt C, the others +- gauche wrt C If C is null, a * random non-colinear C is generated * *@param aPoint to which substituents are added *@param nwanted number of points to calculate (1-3) *@param length A-X length *@param angle B-A-X angle *@param bPoint Description of the Parameter *@param cPoint Description of the Parameter *@return Point3d[] nwanted points (or zero if failed) */ public Point3d[] calculate3DCoordinates1(Point3d aPoint, Point3d bPoint, Point3d cPoint, int nwanted, double length, double angle){ Point3d[] points = new Point3d[nwanted]; Vector3d ba = new Vector3d(aPoint); ba.sub(bPoint); ba.normalize(); if (cPoint == null) { Vector3d cVector = getNonColinearVector(ba); cPoint = new Point3d(cVector); } Vector3d cb = new Vector3d(bPoint); cb.sub(cPoint); cb.normalize(); double cbdotba = cb.dot(ba); if (cbdotba > 0.999999) { Vector3d cVector = getNonColinearVector(ba); cPoint = new Point3d(cVector); cb = new Vector3d(bPoint); cb.sub(cPoint); } Vector3d cbxba = new Vector3d(); cbxba.cross(cb, ba); cbxba.normalize(); Vector3d ax = new Vector3d(); ax.cross(cbxba, ba); ax.normalize(); double drot = Math.PI * 2.0 / (double) nwanted; for (int i = 0; i < nwanted; i++) { double rot = (double) i * drot; points[i] = new Point3d(aPoint); Vector3d vx = new Vector3d(ba); vx.scale(-Math.cos(angle) * length); Vector3d vy = new Vector3d(ax); vy.scale(Math.cos(rot) * length); Vector3d vz = new Vector3d(cbxba); vz.scale(Math.sin(rot) * length); points[i].add(vx); points[i].add(vy); points[i].add(vz); } return points; }
/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomTetrahedralLigandPlacer3D.java
robustness-copilot_data_837
/** * Takes the given Z Matrix coordinates and converts them to cartesian coordinates. * The first Atom end up in the origin, the second on on the x axis, and the third * one in the XY plane. The rest is added by applying the Zmatrix distances, angles * and dihedrals. Angles are in degrees. * * @param distances Array of distance variables of the Z matrix * @param angles Array of angle variables of the Z matrix * @param dihedrals Array of distance variables of the Z matrix * @param first_atoms Array of atom ids of the first invoked atom in distance, angle and dihedral * @param second_atoms Array of atom ids of the second invoked atom in angle and dihedral * @param third_atoms Array of atom ids of the third invoked atom in dihedral * * @cdk.dictref blue-obelisk:zmatrixCoordinatesIntoCartesianCoordinates */ public static Point3d[] zmatrixToCartesian(double[] distances, int[] first_atoms, double[] angles, int[] second_atoms, double[] dihedrals, int[] third_atoms){ Point3d[] cartesianCoords = new Point3d[distances.length]; for (int index = 0; index < distances.length; index++) { if (index == 0) { cartesianCoords[index] = new Point3d(0d, 0d, 0d); } else if (index == 1) { cartesianCoords[index] = new Point3d(distances[1], 0d, 0d); } else if (index == 2) { cartesianCoords[index] = new Point3d(-Math.cos((angles[2] / 180) * Math.PI) * distances[2] + distances[1], Math.sin((angles[2] / 180) * Math.PI) * distances[2], 0d); if (first_atoms[index] == 0) cartesianCoords[index].x = (cartesianCoords[index].x - distances[1]) * -1; } else { Vector3d cd = new Vector3d(); cd.sub(cartesianCoords[third_atoms[index]], cartesianCoords[second_atoms[index]]); Vector3d bc = new Vector3d(); bc.sub(cartesianCoords[second_atoms[index]], cartesianCoords[first_atoms[index]]); Vector3d n1 = new Vector3d(); n1.cross(cd, bc); Vector3d n2 = rotate(n1, bc, -dihedrals[index]); Vector3d ba = rotate(bc, n2, -angles[index]); ba.normalize(); ba.scale(distances[index]); Point3d result = new Point3d(); result.add(cartesianCoords[first_atoms[index]], ba); cartesianCoords[index] = result; } } return cartesianCoords; }
/storage/io/src/main/java/org/openscience/cdk/geometry/ZMatrixTools.java
robustness-copilot_data_838
/** * Adds or replaces a list subtag with a list of longs. * * @param key the key to write to * @param list the list contents as longs, to convert to long tags */ public void putLongList(@NonNls String key, List<Long> list){ putList(key, TagType.LONG, list, LongTag::new); }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_839
/** * Get the collection of job statistics in the most recent week. * * @return collection of running task statistics data objects */ public List<JobRunningStatistics> findJobRunningStatisticsWeekly(){ if (!isRdbConfigured()) { return Collections.emptyList(); } return rdbRepository.findJobRunningStatistics(StatisticTimeUtils.getStatisticTime(StatisticInterval.DAY, -7)); }
/elasticjob-cloud/elasticjob-cloud-scheduler/src/main/java/org/apache/shardingsphere/elasticjob/cloud/scheduler/statistics/StatisticManager.java
robustness-copilot_data_840
/** * Evaluates the valence corrected chi index for a set of fragments. * * This method takes into account the S and P atom types described in * Kier & Hall (1986), page 20 for which empirical delta V values are used. * * @param atomContainer The target <code>AtomContainer</code> * @param fragList A list of fragments * @return The valence corrected chi index * @throws CDKException if the <code>IsotopeFactory</code> cannot be created */ public static double evalValenceIndex(IAtomContainer atomContainer, List<List<Integer>> fragList) throws CDKException{ try { IsotopeFactory ifac = Isotopes.getInstance(); ifac.configureAtoms(atomContainer); } catch (IOException e) { throw new CDKException("IO problem occurred when using the CDK atom config\n" + e.getMessage(), e); } double sum = 0; for (List<Integer> aFragList : fragList) { List<Integer> frag = aFragList; double prod = 1.0; for (Object aFrag : frag) { int atomSerial = (Integer) aFrag; IAtom atom = atomContainer.getAtom(atomSerial); String sym = atom.getSymbol(); if (sym.equals("S")) { double tmp = deltavSulphur(atom, atomContainer); if (tmp != -1) { prod = prod * tmp; continue; } } if (sym.equals("P")) { double tmp = deltavPhosphorous(atom, atomContainer); if (tmp != -1) { prod = prod * tmp; continue; } } int z = atom.getAtomicNumber(); int zv = getValenceElectronCount(atom); int hsupp = atom.getImplicitHydrogenCount(); double deltav = (double) (zv - hsupp) / (double) (z - zv - 1); prod = prod * deltav; } if (prod != 0) sum += 1.0 / Math.sqrt(prod); } return sum; }
/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/ChiIndexUtils.java
robustness-copilot_data_841
/** * Associates the specified value with the specified coordinates in this * QuadTree. * * @param x x-coordinate where the specified value is to be associated. * @param y y-coordinate where the specified value is to be associated. * @param value value to be associated with the specified coordinates. * * @return true if insertion was successful and the data structure changed, * false otherwise. */ public boolean put(final double x, final double y, final T value){ if (!this.top.bounds.containsOrEquals(x, y)) { throw new IllegalArgumentException("cannot add a point at x=" + x + ", y=" + y + " with bounds " + this.top.bounds); } if (this.top.put(x, y, value)) { incrementSize(); return true; } return false; }
/matsim/src/main/java/org/matsim/core/utils/collections/QuadTree.java
robustness-copilot_data_842
/** * Clones this <code>Mapping</code> and the mapped <code>IChemObject</code>s. * * @return The cloned object */ public Object clone() throws CloneNotSupportedException{ Mapping clone = (Mapping) super.clone(); if (relation != null) { clone.relation = new IChemObject[relation.length]; for (int f = 0; f < relation.length; f++) { if (relation[f] != null) { clone.relation[f] = (IChemObject) relation[f].clone(); } } } return clone; }
/base/silent/src/main/java/org/openscience/cdk/silent/Mapping.java
robustness-copilot_data_843
/** * Adds rows to destination for each row in table1 with the columns from table2 added as missing * values. */ private void withMissingLeftJoin(Table destination, Table table1, Selection table1Rows, Set<Integer> ignoreColumns, boolean keepTable2JoinKeyColumns){ for (int c = 0; c < destination.columnCount(); c++) { if (!keepTable2JoinKeyColumns && ignoreColumns.contains(c)) { continue; } if (c < table1.columnCount()) { Column t1Col = table1.column(c); for (int index : table1Rows) { destination.column(c).append(t1Col, index); } } else { for (int r1 = 0; r1 < table1Rows.size(); r1++) { destination.column(c).appendMissing(); } } } }
/core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java
robustness-copilot_data_844
/** * Checks whether {@code this} dataset is locked for a given reason. * @param reason the reason we test for. * @return {@code true} iff the data set is locked for {@code reason}. */ public boolean isLockedFor(DatasetLock.Reason reason){ for (DatasetLock l : getLocks()) { if (l.getReason() == reason) { return true; } } return false; }
/src/main/java/edu/harvard/iq/dataverse/Dataset.java
robustness-copilot_data_845
/** * Clones this SingleElectron object, including a clone of the atom for which the * SingleElectron is defined. * * @return The cloned object */ public Object clone() throws CloneNotSupportedException{ SingleElectron clone = (SingleElectron) super.clone(); if (atom != null) { clone.atom = (IAtom) ((IAtom) atom).clone(); } return clone; }
/base/data/src/main/java/org/openscience/cdk/SingleElectron.java
robustness-copilot_data_846
/** * Evaluates the empirical delt V for some S environments. * * The method checks to see whether a S atom is in a -S-S-, * -SO-, -SO2- group and returns the empirical values noted * in Kier & Hall (1986), page 20. * * @param atom The S atom in question * @param atomContainer The molecule containing the S * @return The empirical delta V if it is present in one of the above * environments, -1 otherwise */ protected static double deltavSulphur(IAtom atom, IAtomContainer atomContainer){ if (atom.getAtomicNumber() != IElement.S) return -1; List<IAtom> connected = atomContainer.getConnectedAtomsList(atom); for (IAtom connectedAtom : connected) { if (connectedAtom.getAtomicNumber() == IElement.S && atomContainer.getBond(atom, connectedAtom).getOrder() == IBond.Order.SINGLE) return .89; } int count = 0; for (IAtom connectedAtom : connected) { if (connectedAtom.getAtomicNumber() == IElement.O && atomContainer.getBond(atom, connectedAtom).getOrder() == IBond.Order.DOUBLE) count++; } if (count == 1) return 1.33; else if (count == 2) return 2.67; return -1; }
/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/ChiIndexUtils.java
robustness-copilot_data_847
/** * Check if the admin protocol channel is using a secure protocol like T3S or HTTPS. * @return true is a secure protocol is being used */ public boolean isLocalAdminProtocolChannelSecure(){ boolean adminProtocolPortSecure = false; boolean adminProtocolPortFound = false; if (networkAccessPoints != null) { for (NetworkAccessPoint nap : networkAccessPoints) { if (nap.isAdminProtocol()) { adminProtocolPortFound = true; adminProtocolPortSecure = true; break; } } } if (!adminProtocolPortFound) { if (adminPort != null) { adminProtocolPortSecure = true; } else if (sslListenPort != null) { adminProtocolPortSecure = true; } else if (listenPort != null) { adminProtocolPortSecure = false; } } return adminProtocolPortSecure; }
/operator/src/main/java/oracle/kubernetes/operator/wlsconfig/WlsServerConfig.java
robustness-copilot_data_848
/** * When a job is submitted, it adds itself as the child of a parent job. When it terminates, it * removes itself from the parent list. The multimap implementation automatically removes the * parent key from the table when its child collection is empty. * <p> * Breadth-first directories do not remove themselves from the map until all their children are * registered. * <p> * Depth-first directories wait for their immediate children to terminate. Subdirectories of * the root expansion node do not add themselves as children, since the expansion is done by * recursion rather than exec'ing a new job (as in breadth-first). */ public void addChild(BulkJob job){ Preconditions.checkArgument(job.getParentKey().getRequestId().equals(job.getKey().getRequestId()), "Job completion listener is " + "being shared between two " + "different requests! " + "This is a bug."); synchronized (descendants) { Long parentId = job.getParentKey().getJobId(); Long childId = job.getKey().getJobId(); descendants.put(parentId, childId); LOGGER.trace("addChild: parent {}, child {}; descendants {}.", parentId, childId, descendants.size()); } }
/modules/dcache-bulk/src/main/java/org/dcache/services/bulk/handlers/BulkJobCompletionHandler.java
robustness-copilot_data_849
/** * Create the port and attach it to the process. * * @param userId the name of the calling user * @param port the port values * @param entityTpeName the type name * @param externalSourceName the unique name of the external source * @param processGUID the unique identifier of the process containing the port * * @return unique identifier of the port in the repository * * @throws InvalidParameterException the bean properties are invalid * @throws UserNotAuthorizedException user not authorized to issue this request * @throws PropertyServerException problem accessing the property server */ private String createPort(String userId, Port port, String entityTpeName, String processGUID, String externalSourceName) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException{ final String methodName = "createPort"; validatePortParameters(userId, port.getQualifiedName(), port.getDisplayName(), methodName); invalidParameterHandler.validateGUID(processGUID, CommonMapper.GUID_PROPERTY_NAME, methodName); String externalSourceGUID = registrationHandler.getExternalDataEngine(userId, externalSourceName); return portHandler.createPort(userId, externalSourceGUID, externalSourceName, processGUID, PROCESS_GUID_PARAMETER_NAME, port.getQualifiedName(), port.getDisplayName(), port.getPortType().getOrdinal(), port.getAdditionalProperties(), entityTpeName, null, methodName); }
/open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEnginePortHandler.java
robustness-copilot_data_850
/** * Parse a {@link JsonNode} and produce the corresponding {@link NodeWriter}. * * @param node the {@link JsonNode} to parse. * @return a {@link NodeWriter} corresponding to the given JSON node * @throws JsonPatternException denotes an invalid pattern */ private NodeWriter<Event> parseNode(JsonPointer location, JsonNode node) throws JsonPatternException{ if (node.isTextual()) { try { ValueGetter<Event, ?> getter = makeComputableValueGetter(node.asText()); return new ValueWriter<>(getter); } catch (RuntimeException e) { String msg = "Invalid JSON property '" + location + "' (was '" + node.asText() + "'): " + e.getMessage(); throw new JsonPatternException(msg, e); } } if (node.isArray()) { return parseArray(location, (ArrayNode) node); } if (node.isObject()) { return parseObject(location, (ObjectNode) node); } return new ValueWriter<>(g -> node); }
/src/main/java/net/logstash/logback/pattern/AbstractJsonPatternParser.java
robustness-copilot_data_851
/** * Creates a new sumo handler by reading data from xml file. */ static SumoNetworkHandler read(File file) throws ParserConfigurationException, SAXException, IOException{ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); SumoNetworkHandler sumoHandler = new SumoNetworkHandler(); saxParser.parse(file, sumoHandler); return sumoHandler; }
/contribs/sumo/src/main/java/org/matsim/contrib/sumo/SumoNetworkHandler.java
robustness-copilot_data_852
/** * Parse a string of namespace names and return them as a collection. * @param namespaceString a comma-separated list of namespace names * @return Namespace list */ public static Collection<String> parseNamespaceList(String namespaceString){ Collection<String> namespaces = Stream.of(namespaceString.split(",")).filter(s -> !isNullOrEmpty(s)).map(String::trim).collect(Collectors.toUnmodifiableList()); return namespaces.isEmpty() ? Collections.singletonList(getOperatorNamespace()) : namespaces; }
/operator/src/main/java/oracle/kubernetes/operator/helpers/NamespaceHelper.java
robustness-copilot_data_853
/** * Receive a binary encoded 'picture' message from the socket (or actor). * This method is similar to {@link org.zeromq.ZMQ.Socket#recv()}, except the arguments are encoded * in a binary format that is compatible with zproto, and is designed to * reduce memory allocations. * * @param picture The picture argument is a string that defines * the type of each argument. See {@link #sendBinaryPicture(Socket, String, Object...)} * for the supported argument types. * @return the picture elements as object array **/ public Object[] recvBinaryPicture(Socket socket, final String picture){ if (!BINARY_FORMAT.matcher(picture).matches()) { throw new ZMQException(picture + " is not in expected binary format " + BINARY_FORMAT.pattern(), ZError.EPROTO); } ZFrame frame = ZFrame.recvFrame(socket); if (frame == null) { return null; } ZNeedle needle = new ZNeedle(frame); Object[] results = new Object[picture.length()]; for (int index = 0; index < picture.length(); index++) { char pattern = picture.charAt(index); switch(pattern) { case '1': { results[index] = needle.getNumber1(); break; } case '2': { results[index] = needle.getNumber2(); break; } case '4': { results[index] = needle.getNumber4(); break; } case '8': { results[index] = needle.getNumber8(); break; } case 's': { results[index] = needle.getString(); break; } case 'S': { results[index] = needle.getLongString(); break; } case 'b': case 'c': { int size = needle.getNumber4(); results[index] = needle.getBlock(size); break; } case 'f': { results[index] = ZFrame.recvFrame(socket); break; } case 'm': { results[index] = ZMsg.recvMsg(socket); break; } default: assert (false) : "invalid picture element '" + pattern + "'"; } } return results; }
/src/main/java/org/zeromq/proto/ZPicture.java
robustness-copilot_data_854
/** Returns a column of the same type containing the last {@code numRows} of this column. */ Column<T> last(final int numRows){ int newRowCount = Math.min(numRows, size()); return inRange(size() - newRowCount, size()); }
/core/src/main/java/tech/tablesaw/columns/Column.java
robustness-copilot_data_855
/** * Iterates over keys to replace any placeholders in the values. * * @param node Object node * @param contentVariableReplacements current map of content variables */ private void replaceInObject(JsonNode node, Map<String, Object> contentVariableReplacements){ Iterator<String> fieldNames = node.fieldNames(); while (fieldNames.hasNext()) { String name = fieldNames.next(); JsonNode nodeValue = node.get(name); if (nodeValue.isContainerNode()) { replaceInElements(nodeValue, contentVariableReplacements); } else if (nodeValue.isTextual()) { String current = nodeValue.asText(); String replaced = replaceInString(current, contentVariableReplacements); if (!StringUtils.equals(current, replaced)) { ((ObjectNode) node).put(name, replaced); } } } }
/bundle/src/main/java/com/adobe/acs/commons/ccvar/filter/ContentVariableJsonFilter.java
robustness-copilot_data_856
/** * Non destructively split a molecule into two parts at the specified bond. * * Note that if a ring bond is specified, the resultant list will contain * teh opened ring twice. * * @param atomContainer The molecule to split * @param bond The bond to split at * @return A list containing the two parts of the molecule */ protected static List<IAtomContainer> splitMolecule(IAtomContainer atomContainer, IBond bond){ List<IAtomContainer> ret = new ArrayList<IAtomContainer>(); for (IAtom atom : bond.atoms()) { // later on we'll want to make sure that the fragment doesn't contain // the bond joining the current atom and the atom that is on the other side IAtom excludedAtom; if (atom.equals(bond.getBegin())) excludedAtom = bond.getEnd(); else excludedAtom = bond.getBegin(); List<IBond> part = new ArrayList<IBond>(); part.add(bond); part = traverse(atomContainer, atom, part); // at this point we have a partion which contains the bond we // split. This partition should actually 2 partitions: // - one with the splitting bond // - one without the splitting bond // note that this will lead to repeated fragments when we do this // with adjacent bonds, so when we gather all the fragments we need // to check for repeats IAtomContainer partContainer; partContainer = makeAtomContainer(atom, part, excludedAtom); // by checking for more than 2 atoms, we exclude single bond fragments // also if a fragment has the same number of atoms as the parent molecule, // it is the parent molecule, so we exclude it. if (partContainer.getAtomCount() > 2 && partContainer.getAtomCount() != atomContainer.getAtomCount()) ret.add(partContainer); part.remove(0); partContainer = makeAtomContainer(atom, part, excludedAtom); if (partContainer.getAtomCount() > 2 && partContainer.getAtomCount() != atomContainer.getAtomCount()) ret.add(partContainer); } return ret; }
/tool/fragment/src/main/java/org/openscience/cdk/fragment/FragmentUtils.java
robustness-copilot_data_857
/** * This makes atom map of matching atoms out of atom map of matching bonds as produced by the get(Subgraph|Ismorphism)Map methods. * Added by Asad since CDK one doesn't pick up the correct changes * @param list The list produced by the getMap method. * @param sourceGraph first molecule. Must not be an IQueryAtomContainer. * @param targetGraph second molecule. May be an IQueryAtomContainer. * @return The mapping found projected on sourceGraph. This is atom List of CDKRMap objects containing Ids of matching atoms. */ private static List<List<CDKRMap>> makeAtomsMapOfBondsMapSingleBond(List<CDKRMap> list, IAtomContainer sourceGraph, IAtomContainer targetGraph){ if (list == null) { return null; } Map<IBond, IBond> bondMap = new HashMap<IBond, IBond>(list.size()); for (CDKRMap solBondMap : list) { int id1 = solBondMap.getId1(); int id2 = solBondMap.getId2(); IBond qBond = sourceGraph.getBond(id1); IBond tBond = targetGraph.getBond(id2); bondMap.put(qBond, tBond); } List<CDKRMap> result1 = new ArrayList<CDKRMap>(); List<CDKRMap> result2 = new ArrayList<CDKRMap>(); for (IBond qbond : sourceGraph.bonds()) { if (bondMap.containsKey(qbond)) { IBond tbond = bondMap.get(qbond); CDKRMap map00 = null; CDKRMap map01 = null; CDKRMap map10 = null; CDKRMap map11 = null; if ((qbond.getBegin().getSymbol().equals(tbond.getBegin().getSymbol())) && (qbond.getEnd().getSymbol().equals(tbond.getEnd().getSymbol()))) { map00 = new CDKRMap(sourceGraph.indexOf(qbond.getBegin()), targetGraph.indexOf(tbond.getBegin())); map11 = new CDKRMap(sourceGraph.indexOf(qbond.getEnd()), targetGraph.indexOf(tbond.getEnd())); if (!result1.contains(map00)) { result1.add(map00); } if (!result1.contains(map11)) { result1.add(map11); } } if ((qbond.getBegin().getSymbol().equals(tbond.getEnd().getSymbol())) && (qbond.getEnd().getSymbol().equals(tbond.getBegin().getSymbol()))) { map01 = new CDKRMap(sourceGraph.indexOf(qbond.getBegin()), targetGraph.indexOf(tbond.getEnd())); map10 = new CDKRMap(sourceGraph.indexOf(qbond.getEnd()), targetGraph.indexOf(tbond.getBegin())); if (!result2.contains(map01)) { result2.add(map01); } if (!result2.contains(map10)) { result2.add(map10); } } } } List<List<CDKRMap>> result = new ArrayList<List<CDKRMap>>(); if (result1.size() == result2.size()) { result.add(result1); result.add(result2); } else if (result1.size() > result2.size()) { result.add(result1); } else { result.add(result2); } return result; }
/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKRMapHandler.java
robustness-copilot_data_858
/** * Return true if the SqlStatement class queries the database in any way to determine Statements to execute. * If the statement queries the database, it cannot be used in updateSql type operations */ public boolean generateStatementsVolatile(SqlStatement statement, Database database){ for (SqlGenerator generator : getGenerators(statement, database)) { if (generator.generateStatementsIsVolatile(database)) { return true; } } return false; }
/liquibase-core/src/main/java/liquibase/sqlgenerator/SqlGeneratorFactory.java
robustness-copilot_data_859
/** * Determines if, according to the algorithms implemented in this class, the given * AtomContainer has properly distributed double bonds. * * @param m {@link IAtomContainer} to check the bond orders for. * @return true, if bond orders are properly distributed * @throws CDKException thrown when something went wrong */ public boolean isOK(IAtomContainer m) throws CDKException{ // OK, we take advantage here from the fact that this class does not take // into account rings larger than 7 atoms. See fixAromaticBondOrders(). IRingSet rs = allRingsFinder.findAllRings(m, 7); storeRingSystem(m, rs); boolean StructureOK = this.isStructureOK(m); IRingSet irs = this.removeExtraRings(m); if (irs == null) throw new CDKException("error in AllRingsFinder.findAllRings"); int count = this.getBadCount(m, irs); return StructureOK && count == 0; }
/legacy/src/main/java/org/openscience/cdk/smiles/DeduceBondSystemTool.java
robustness-copilot_data_860
/** * Adds a new column to the column list of this PrimaryKey. The first column has the position 0. * If you specify a position that is greater than the number of columns present, undefined * columns (NULL expressions) will be added as padding. If a position that is already * occupied by a column is specified, that column will be replaced. * * @param position the position where to insert or replace the column * @param column the new column * @return a reference to the updated PrimaryKey object. */ public PrimaryKey addColumn(int position, Column column){ if (position >= getColumns().size()) { for (int i = getColumns().size() - 1; i < position; i++) { this.getColumns().add(null); } } this.getColumns().set(position, column); return this; }
/liquibase-core/src/main/java/liquibase/structure/core/PrimaryKey.java
robustness-copilot_data_861
/** * Repeat a String {@code repeat} times to form a new String. * * <pre> * StringUtils.repeat(null, 2) = null * StringUtils.repeat("", 0) = "" * StringUtils.repeat("", 2) = "" * StringUtils.repeat("a", 3) = "aaa" * StringUtils.repeat("ab", 2) = "abab" * StringUtils.repeat("a", -2) = "" * </pre> * * @param str the String to repeat, may be null * @param repeat number of times to repeat str, negative treated as zero * @return a new String consisting of the original String repeated, {@code null} if null String * input */ public static String repeat(final String str, final int repeat){ if (str == null) { return null; } if (repeat <= 0) { return EMPTY; } final int inputLength = str.length(); if (repeat == 1 || inputLength == 0) { return str; } if (inputLength == 1 && repeat <= PAD_LIMIT) { return repeat(str.charAt(0), repeat); } final int outputLength = inputLength * repeat; switch(inputLength) { case 1: return repeat(str.charAt(0), repeat); case 2: final char ch0 = str.charAt(0); final char ch1 = str.charAt(1); final char[] output2 = new char[outputLength]; for (int i = repeat * 2 - 2; i >= 0; i--, i--) { output2[i] = ch0; output2[i + 1] = ch1; } return new String(output2); default: final StringBuilder buf = new StringBuilder(outputLength); for (int i = 0; i < repeat; i++) { buf.append(str); } return buf.toString(); } }
/core/src/main/java/tech/tablesaw/util/StringUtils.java
robustness-copilot_data_862
/** * Calculates the cheapest route from Node 'fromNode' to Node 'toNode' at * starting time 'startTime'. * * @param fromNode * The Node at which the route should start. * @param toNode * The Node at which the route should end. * @param startTime * The time at which the route should start. * @see org.matsim.core.router.util.LeastCostPathCalculator#calcLeastCostPath(org.matsim.api.core.v01.network.Node, org.matsim.api.core.v01.network.Node, double, org.matsim.api.core.v01.population.Person, org.matsim.vehicles.Vehicle) */ public Path calcLeastCostPath(final Node fromNode, final Node toNode, final double startTime, final Person person2, final Vehicle vehicle2){ checkNodeBelongToNetwork(fromNode); checkNodeBelongToNetwork(toNode); augmentIterationId(); this.person = person2; this.vehicle = vehicle2; if (this.pruneDeadEnds) { this.deadEndEntryNode = getPreProcessData(toNode).getDeadEndEntryNode(); } RouterPriorityQueue<Node> pendingNodes = (RouterPriorityQueue<Node>) createRouterPriorityQueue(); initFromNode(fromNode, toNode, startTime, pendingNodes); Node foundToNode = searchLogic(fromNode, toNode, pendingNodes); if (foundToNode == null) return null; else { DijkstraNodeData outData = getData(foundToNode); double arrivalTime = outData.getTime(); return constructPath(fromNode, foundToNode, startTime, arrivalTime); } }
/matsim/src/main/java/org/matsim/core/router/Dijkstra.java
robustness-copilot_data_863
/** * Create a stereo encoder for all potential 2D and 3D double bond stereo * configurations. * * @param container an atom container * @param graph adjacency list representation of the container * @return a new encoder for tetrahedral elements */ public StereoEncoder create(IAtomContainer container, int[][] graph){ List<StereoEncoder> encoders = new ArrayList<StereoEncoder>(5); for (IBond bond : container.bonds()) { // if double bond and not E or Z query bond if (DOUBLE.equals(bond.getOrder()) && !E_OR_Z.equals(bond.getStereo())) { IAtom left = bond.getBegin(); IAtom right = bond.getEnd(); // skip -N=N- double bonds which exhibit inversion if (Integer.valueOf(7).equals(left.getAtomicNumber()) && Integer.valueOf(7).equals(right.getAtomicNumber())) continue; StereoEncoder encoder = newEncoder(container, left, right, right, left, graph); if (encoder != null) { encoders.add(encoder); } } } return encoders.isEmpty() ? StereoEncoder.EMPTY : new MultiStereoEncoder(encoders); }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricDoubleBondEncoderFactory.java
robustness-copilot_data_864
/** * Returns {@code this}' string representation. Differs from {@link #toString} * which can also contain debug data, if needed. * * @return The string representation of this global id. */ public String asString(){ if (protocol == null || authority == null || identifier == null) { return ""; } return protocol + ":" + authority + "/" + identifier; }
/src/main/java/edu/harvard/iq/dataverse/GlobalId.java
robustness-copilot_data_865
/** * Assigns a set of rings to groups each sharing a bond. * * @param rBondsArray * @return A List of Lists each containing the ring indices of a set of fused rings */ private List<List<Integer>> assignRingGroups(List<Integer[]> rBondsArray){ List<List<Integer>> ringGroups; ringGroups = new ArrayList<List<Integer>>(); for (int i = 0; i < rBondsArray.size() - 1; i++) { for (int j = 0; j < rBondsArray.get(i).length; j++) { for (int k = i + 1; k < rBondsArray.size(); k++) { for (int l = 0; l < rBondsArray.get(k).length; l++) { if (Objects.equals(rBondsArray.get(i)[j], rBondsArray.get(k)[l])) { if (i != k) { ringGroups.add(new ArrayList<Integer>()); ringGroups.get(ringGroups.size() - 1).add(i); ringGroups.get(ringGroups.size() - 1).add(k); } } } } } } while (combineGroups(ringGroups)) ; for (int i = 0; i < rBondsArray.size(); i++) { boolean found = false; for (int j = 0; j < ringGroups.size(); j++) { if (ringGroups.get(j).contains(i)) { found = true; break; } } if (!found) { ringGroups.add(new ArrayList<Integer>()); ringGroups.get(ringGroups.size() - 1).add(i); } } return ringGroups; }
/legacy/src/main/java/org/openscience/cdk/smiles/FixBondOrdersTool.java
robustness-copilot_data_866
/** * Access the default position of the hydrogen label when the atom has no * bonds. * * @param atom hydrogens will be labelled * @return the position */ static HydrogenPosition usingDefaultPlacement(final IAtom atom){ if (PREFIXED_H.contains(Elements.ofNumber(atom.getAtomicNumber()))) return Left; return Right; }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/HydrogenPosition.java
robustness-copilot_data_867
/** * Creates a WLSServerConfig object using an "servers" or "serverTemplates" item parsed from JSON * result from WLS REST call. * * @param serverConfigMap A Map containing the parsed "servers" or "serverTemplates" element for a * WLS server or WLS server template. * @return A new WlsServerConfig object using the provided configuration from the configuration * map */ static WlsServerConfig create(Map<String, Object> serverConfigMap){ // parse the configured network access points or channels Map networkAccessPointsMap = (Map<String, Object>) serverConfigMap.get("networkAccessPoints"); List<NetworkAccessPoint> networkAccessPoints = new ArrayList<>(); if (networkAccessPointsMap != null) { List<Map<String, Object>> networkAccessPointItems = (List<Map<String, Object>>) networkAccessPointsMap.get("items"); if (networkAccessPointItems != null && networkAccessPointItems.size() > 0) { for (Map<String, Object> networkAccessPointConfigMap : networkAccessPointItems) { NetworkAccessPoint networkAccessPoint = new NetworkAccessPoint(networkAccessPointConfigMap); networkAccessPoints.add(networkAccessPoint); } } } // parse the SSL configuration Map<String, Object> sslMap = (Map<String, Object>) serverConfigMap.get("SSL"); Integer sslListenPort = (sslMap == null) ? null : (Integer) sslMap.get("listenPort"); boolean sslPortEnabled = sslMap != null && sslMap.get("listenPort") != null; // parse the administration port return new WlsServerConfig((String) serverConfigMap.get("name"), (String) serverConfigMap.get("listenAddress"), getMachineNameFromJsonMap(serverConfigMap), (Integer) serverConfigMap.get("listenPort"), sslListenPort, (Integer) serverConfigMap.get("adminPort"), networkAccessPoints); }
/operator/src/main/java/oracle/kubernetes/operator/wlsconfig/WlsServerConfig.java
robustness-copilot_data_868
/** * Creates a schema generator, suitably customized for generating Kubernetes CRD schemas. */ public static SchemaGenerator createCrdSchemaGenerator(){ SchemaGenerator generator = new SchemaGenerator(); generator.defineAdditionalProperties(Quantity.class, "string"); generator.setForbidAdditionalProperties(false); generator.setSupportObjectReferences(false); generator.setIncludeSchemaReference(false); generator.addPackageToSuppressDescriptions("io.kubernetes.client.openapi.models"); generator.defineEnabledFeatures(Optional.ofNullable(TuningParameters.getInstance()).map(TuningParameters::getFeatureGates).map(TuningParameters.FeatureGates::getEnabledFeatures).orElse(Collections.emptyList())); return generator; }
/operator/src/main/java/oracle/kubernetes/weblogic/domain/model/CrdSchemaGenerator.java
robustness-copilot_data_869
/** * Finds the end character index of the parameter within the paramsString that starts at startIndex. * * Takes into account nesting of parameters. * * @param paramsString * @param startIndex index within paramsString to start looking * @return index at which the parameter string ends (e.g. the next comma, or paramsString length if no comma found) * * @throws IllegalArgumentException if the parameter is not well formed */ private static int findParamEndIndex(String paramsString, int startIndex){ int nestLevel = 0; for (int c = startIndex; c < paramsString.length(); c++) { char character = paramsString.charAt(c); if (character == PARAM_START_CHAR) { nestLevel++; } else if (character == PARAM_END_CHAR) { nestLevel--; if (nestLevel < 0) { throw new IllegalArgumentException(String.format("Unbalanced '}' at character position %d in %s", c, paramsString)); } } else if (character == PARAM_SEPARATOR_CHAR && nestLevel == 0) { return c; } } if (nestLevel != 0) { throw new IllegalArgumentException(String.format("Unbalanced '{' in %s", paramsString)); } return paramsString.length(); }
/src/main/java/net/logstash/logback/appender/WaitStrategyFactory.java
robustness-copilot_data_870
/** * Returns the Elements ordered according to (approximate) probability of occurrence. * * <p>This begins with the "elements of life" C, H, O, N, (Si, P, S, F, Cl), * then continues with the "common" chemical synthesis ingredients, closing off * with the tail-end of the periodic table in atom-number order and finally * the generic R-group. * * @return fixed-order array * */ public static String[] generateOrderEle(){ return new String[] { "C", "H", "O", "N", "Si", "P", "S", "F", "Cl", "Br", "I", "Sn", "B", "Pb", "Tl", "Ba", "In", "Pd", "Pt", "Os", "Ag", "Zr", "Se", "Zn", "Cu", "Ni", "Co", "Fe", "Cr", "Ti", "Ca", "K", "Al", "Mg", "Na", "Ce", "Hg", "Au", "Ir", "Re", "W", "Ta", "Hf", "Lu", "Yb", "Tm", "Er", "Ho", "Dy", "Tb", "Gd", "Eu", "Sm", "Pm", "Nd", "Pr", "La", "Cs", "Xe", "Te", "Sb", "Cd", "Rh", "Ru", "Tc", "Mo", "Nb", "Y", "Sr", "Rb", "Kr", "As", "Ge", "Ga", "Mn", "V", "Sc", "Ar", "Ne", "He", "Be", "Li", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn", "R" }; }
/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
robustness-copilot_data_871
/** * Converts a given string into a Bayesian model instance, or throws an exception if it is not valid. * * @param str string containing the serialised model * @return instantiated model that can be used for predictions */ public static Bayesian deserialise(String str) throws IOException{ BufferedReader rdr = new BufferedReader(new StringReader(str)); Bayesian model = deserialise(rdr); rdr.close(); return model; }
/tool/model/src/main/java/org/openscience/cdk/fingerprint/model/Bayesian.java
robustness-copilot_data_872
/** * Recycle the instance before returning it to the pool. * Sub-classes may override this method if they wish to implement their own custom logic. * * @param instance the instance to recycle * @return {@code true} if the instance can be recycled and returned to the pool, {@code false} if not. */ protected boolean recycleInstance(T instance){ if (instance instanceof Lifecycle) { return ((Lifecycle) instance).recycle(); } else { return true; } }
/src/main/java/net/logstash/logback/util/ThreadLocalHolder.java
robustness-copilot_data_873
/** * Renames any column header that appears more than once. Subsequent appearances have "-[count]" * appended; For example, the first (or only) appearance of "foo" is named "foo", the second * appearance is named "foo-2" The header array is modified in place. * * @param headerNames The header names to be potentially adjusted. */ private void renameDuplicateColumnHeaders(String[] headerNames){ Map<String, Integer> nameCounter = new HashMap<>(); for (int i = 0; i < headerNames.length; i++) { String name = headerNames[i]; Integer count = nameCounter.get(name); if (count == null) { nameCounter.put(name, 1); } else { count++; nameCounter.put(name, count); headerNames[i] = name + "-" + count; } } }
/core/src/main/java/tech/tablesaw/io/FileReader.java
robustness-copilot_data_874
/** * Partition the bonding partners of a given atom into placed (coordinates * assinged) and not placed. * *@param atom The atom whose bonding partners are to be * partitioned *@param unplacedPartners A vector for the unplaced bonding partners to go in *@param placedPartners A vector for the placed bonding partners to go in */ public void partitionPartners(IAtom atom, IAtomContainer unplacedPartners, IAtomContainer placedPartners){ List atoms = molecule.getConnectedAtomsList(atom); for (int i = 0; i < atoms.size(); i++) { IAtom curatom = (IAtom) atoms.get(i); if (curatom.getFlag(CDKConstants.ISPLACED)) { placedPartners.addAtom(curatom); } else { unplacedPartners.addAtom(curatom); } } }
/tool/sdg/src/main/java/org/openscience/cdk/layout/AtomPlacer.java
robustness-copilot_data_875
/** * Constructs a new {@link IDifference} object. * * @param name a name reflecting the nature of the created {@link IDifference} * @param first the first object to compare * @param second the second object to compare * @return an {@link IDifference} reflecting the differences between the first and second object */ public static IDifference construct(String name, Point3d first, Point3d second){ if (first == null && second == null) return null; Point3dDifference totalDiff = new Point3dDifference(name); totalDiff.addChild(DoubleDifference.construct("x", first == null ? null : first.x, second == null ? null : second.x)); totalDiff.addChild(DoubleDifference.construct("y", first == null ? null : first.y, second == null ? null : second.y)); totalDiff.addChild(DoubleDifference.construct("z", first == null ? null : first.z, second == null ? null : second.z)); if (totalDiff.childCount() == 0) { return null; } return totalDiff; }
/misc/diff/src/main/java/org/openscience/cdk/tools/diff/tree/Point3dDifference.java
robustness-copilot_data_876
/** * Creates a function to adjust the freespeed for urban links. * @see LinkProperties#DEFAULT_FREESPEED_FACTOR * * @apiNote Can be used as example, but no public access currently */ static AfterLinkCreated adjustFreespeed(final double factor){ return (link, osmTags, direction) -> { if (osmTags.containsKey(OsmTags.MAXSPEED)) { if (link.getFreespeed() < 51 / 3.6) link.setFreespeed(link.getFreespeed() * factor); } }; }
/contribs/osm/src/main/java/org/matsim/contrib/osm/networkReader/SupersonicOsmNetworkReader.java
robustness-copilot_data_877
/** * Returns a one line string representation of this LonePair. * This method is conform RFC #9. * * @return The string representation of this LonePair */ public String toString(){ StringBuffer resultString = new StringBuffer(); resultString.append("LonePair("); resultString.append(this.hashCode()); if (atom != null) { resultString.append(", ").append(atom.toString()); } resultString.append(')'); return resultString.toString(); }
/base/silent/src/main/java/org/openscience/cdk/silent/LonePair.java
robustness-copilot_data_878
/** * Parse a JSON pattern and produce the corresponding {@link NodeWriter}. * Returns <em>null</em> if the pattern is invalid, null or empty. An error status is * logged when the pattern is invalid and parsing failed. * * @param pattern the JSON pattern to parse * @return a {@link NodeWriter} configured according to the pattern * @throws JsonPatternException denotes an invalid pattern */ public NodeWriter<Event> parse(String pattern) throws JsonPatternException{ if (StringUtils.isEmpty(pattern)) { return null; } final ObjectNode node; try (JsonParser jsonParser = jsonFactory.createParser(pattern)) { node = JsonReadingUtils.readFullyAsObjectNode(jsonFactory, pattern); } catch (IOException e) { throw new JsonPatternException("pattern is not a valid JSON object", e); } NodeWriter<Event> nodeWriter = new RootWriter<>(parseObject(JsonPointer.compile("/"), node)); if (omitEmptyFields) { nodeWriter = new OmitEmptyFieldWriter<>(nodeWriter); } return nodeWriter; }
/src/main/java/net/logstash/logback/pattern/AbstractJsonPatternParser.java
robustness-copilot_data_879
/** * Adds or replaces a list subtag, converting the list entries to tags. * * @param <V> the list elements' Java type * @param key the key to write to * @param type the list elements' tag type * @param value the list contents, as objects to convert to tags * @param tagCreator a function that will convert each V to an element tag */ public void putList(@NonNls String key, TagType type, List<V> value, Function<? super V, ? extends Tag> tagCreator){ List<Tag> result = new ArrayList<>(value.size()); for (V item : value) { result.add(tagCreator.apply(item)); } put(key, new ListTag<>(type, result)); }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_880
/** * Locate a stereo bond adjacent to the {@code atom}. * * @param atom an atom * @return a stereo bond or null if non found */ private StereoBond findStereoBond(IAtom atom){ for (IBond bond : stereoBonds) if (bond.contains(atom)) return (StereoBond) bond; return null; }
/legacy/src/main/java/org/openscience/cdk/smiles/smarts/parser/SmartsQueryVisitor.java
robustness-copilot_data_881
/** * Gateway method the Filter uses to determine if the request is a candidate for processing by Assets Folder Properties Support. * These checks should be fast and fail broadest and fastest first. * * @param request the request * @return true if Assets Folder Properties Support should process this request. */ protected boolean accepts(SlingHttpServletRequest request){ if (!StringUtils.equalsIgnoreCase(POST_METHOD, request.getMethod())) { return false; } else if (!DAM_FOLDER_SHARE_OPERATION.equals(request.getParameter(OPERATION))) { return false; } else if (!StringUtils.startsWith(request.getResource().getPath(), DAM_PATH_PREFIX)) { return false; } else if (!request.getResource().isResourceType(JcrResourceConstants.NT_SLING_FOLDER) && !request.getResource().isResourceType(JcrResourceConstants.NT_SLING_ORDERED_FOLDER)) { return false; } return true; }
/bundle/src/main/java/com/adobe/acs/commons/dam/impl/AssetsFolderPropertiesSupport.java
robustness-copilot_data_882
/** * Generate a SMARTS for the substructure formed of the provided * atoms. * * @param atomIdxs atom indexes * @return SMARTS, null if an empty array is passed */ public String generate(int[] atomIdxs){ if (atomIdxs == null) throw new NullPointerException("No atom indexes provided"); if (atomIdxs.length == 0) return null; if (atomIdxs.length == 1 && mode == MODE_EXACT) return aexpr[atomIdxs[0]]; Arrays.fill(rbnds, 0); Arrays.fill(avisit, 0); for (int atmIdx : atomIdxs) avisit[atmIdx] = -1; numVisit = 1; for (int atomIdx : atomIdxs) { if (avisit[atomIdx] < 0) markRings(atomIdx, -1); } numVisit = 1; for (int atmIdx : atomIdxs) avisit[atmIdx] = -1; StringBuilder sb = new StringBuilder(); for (int i = 0; i < atomIdxs.length; i++) { if (avisit[atomIdxs[i]] < 0) { if (i > 0) sb.append('.'); encodeExpr(atomIdxs[i], -1, sb); } } return sb.toString(); }
/tool/smarts/src/main/java/org/openscience/cdk/smarts/SmartsFragmentExtractor.java
robustness-copilot_data_883
/** * Adds all rings of another RingSet if they are not already part of this ring set. * * If you want to add a single ring to the set use {@link #addAtomContainer(org.openscience.cdk.interfaces.IAtomContainer)} * * @param ringSet the ring set to be united with this one. */ public void add(IRingSet ringSet){ for (int f = 0; f < ringSet.getAtomContainerCount(); f++) { if (!contains(ringSet.getAtomContainer(f))) { addAtomContainer(ringSet.getAtomContainer(f)); } } }
/base/silent/src/main/java/org/openscience/cdk/silent/RingSet.java
robustness-copilot_data_884
/** * Initialise our expiry time to some point in the future. * * @param lifetime the time, in seconds. */ private void becomeMortal(long lifetime){ _whenIShouldExpire = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(lifetime)); }
/modules/dcache-info/src/main/java/org/dcache/services/info/base/StateComposite.java
robustness-copilot_data_885
/** * Iterate over the underlying rows in the source table. If you set one of the rows while * iterating it will change the row in the source table. */ public Iterator<Row> iterator(){ return new Iterator<Row>() { private final Row row = new Row(TableSlice.this); @Override public Row next() { return row.next(); } @Override public boolean hasNext() { return row.hasNext(); } }; }
/core/src/main/java/tech/tablesaw/table/TableSlice.java
robustness-copilot_data_886
/** * Capitalizes a String changing the first character to title case as per {@link * Character#toTitleCase(int)}. No other characters are changed. * * <p>A {@code null} input String returns {@code null}. * * <pre> * StringUtils.capitalize(null) = null * StringUtils.capitalize("") = "" * StringUtils.capitalize("cat") = "Cat" * StringUtils.capitalize("cAt") = "CAt" * StringUtils.capitalize("'cat'") = "'cat'" * </pre> * * @param str the String to capitalize, may be null * @return the capitalized String, {@code null} if null String input * @since 2.0 */ public static String capitalize(final String str){ int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } final int firstCodepoint = str.codePointAt(0); final int newCodePoint = Character.toTitleCase(firstCodepoint); if (firstCodepoint == newCodePoint) { return str; } final int[] newCodePoints = new int[strLen]; int outOffset = 0; newCodePoints[outOffset++] = newCodePoint; for (int inOffset = Character.charCount(firstCodepoint); inOffset < strLen; ) { final int codepoint = str.codePointAt(inOffset); newCodePoints[outOffset++] = codepoint; inOffset += Character.charCount(codepoint); } return new String(newCodePoints, 0, outOffset); }
/core/src/main/java/tech/tablesaw/util/StringUtils.java
robustness-copilot_data_887
/** * Access the bounds of a shape that have been transformed. * * @param shape any shape * @return the bounds of the shape transformed */ private Rectangle2D transformedBounds(Shape shape){ Rectangle2D rectangle2D = shape.getBounds2D(); Point2D minPoint = new Point2D.Double(rectangle2D.getMinX(), rectangle2D.getMinY()); Point2D maxPoint = new Point2D.Double(rectangle2D.getMaxX(), rectangle2D.getMaxY()); transform.transform(minPoint, minPoint); transform.transform(maxPoint, maxPoint); double minX = Math.min(minPoint.getX(), maxPoint.getX()); double maxX = Math.max(minPoint.getX(), maxPoint.getX()); double minY = Math.min(minPoint.getY(), maxPoint.getY()); double maxY = Math.max(minPoint.getY(), maxPoint.getY()); return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY); }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/TextOutline.java
robustness-copilot_data_888
/** * Actual conversion implementation: instead of using existing read * and write methods, much of code is inlined. Reason for this is * that we must avoid root value wrapping/unwrapping both for efficiency and * for correctness. If root value wrapping/unwrapping is actually desired, * caller must use explicit <code>writeValue</code> and * <code>readValue</code> methods. */ protected Object _convert(Object fromValue, JavaType toValueType) throws IllegalArgumentException{ final SerializationConfig config = getSerializationConfig().without(SerializationFeature.WRAP_ROOT_VALUE); final DefaultSerializerProvider context = _serializerProvider(config); TokenBuffer buf = context.bufferForValueConversion(this); if (isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) { buf = buf.forceUseOfBigDecimal(true); } try { context.serializeValue(buf, fromValue); final JsonParser p = buf.asParser(); Object result; final DeserializationConfig deserConfig = getDeserializationConfig(); JsonToken t = _initForReading(p, toValueType); if (t == JsonToken.VALUE_NULL) { DeserializationContext ctxt = createDeserializationContext(p, deserConfig); result = _findRootDeserializer(ctxt, toValueType).getNullValue(ctxt); } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) { result = null; } else { DeserializationContext ctxt = createDeserializationContext(p, deserConfig); JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, toValueType); result = deser.deserialize(p, ctxt); } p.close(); return result; } catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); } }
/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java
robustness-copilot_data_889
/** * In the minimal IMolecularFormula must contain all those IElement found in the * minimal IMolecularFormula. * * @param formulaMax A IMolecularFormula which contains the maximal representation of the Elements * @param formulaMin A IMolecularFormula which contains the minimal representation of the Elements * @return True, if the correlation is valid */ private static boolean validCorrelation(IMolecularFormula formulaMin, IMolecularFormula formulamax){ for (IElement element : MolecularFormulaManipulator.elements(formulaMin)) { if (!MolecularFormulaManipulator.containsElement(formulamax, element)) return false; } return true; }
/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaSetManipulator.java
robustness-copilot_data_890
/** * Collect and return a report row for the workflow status. Method is package scope for unit tests. * @param status the status to report upon. * @return the row of data */ EnumMap<ReportColumns, Object> report(WorkflowRemovalStatus status){ final EnumMap<ReportColumns, Object> row = new EnumMap<>(ReportColumns.class); row.put(ReportColumns.STARTED, status.getStartedAt()); row.put(ReportColumns.CHECKED, status.getChecked()); row.put(ReportColumns.REMOVED, status.getRemoved()); row.put(ReportColumns.COMPLETED, status.getCompletedAt()); row.put(ReportColumns.ERRED, status.getErredAt()); row.put(ReportColumns.INITIATED_BY, status.getInitiatedBy()); return row; }
/bundle/src/main/java/com/adobe/acs/commons/mcp/impl/processes/WorkflowRemover.java
robustness-copilot_data_891
/** * Creates a default configuration properties with some common values like: application.tmpdir, * application.charset and pid (process ID). * * @return A configuration object. */ public static Config defaults(){ Path tmpdir = Paths.get(System.getProperty("user.dir"), "tmp"); Map<String, String> defaultMap = new HashMap<>(); defaultMap.put("application.tmpdir", tmpdir.toString()); defaultMap.put("application.charset", "UTF-8"); String pid = pid(); if (pid != null) { System.setProperty("PID", pid); defaultMap.put("pid", pid); } return ConfigFactory.parseMap(defaultMap, "defaults"); }
/jooby/src/main/java/io/jooby/Environment.java
robustness-copilot_data_892
/** * Removes rings which do not have all sp2/planar3 aromatic atoms. * and also gets rid of rings that have more than 8 atoms in them. * * @param m The {@link IAtomContainer} from which we want to remove rings * @return The set of reduced rings */ private IRingSet removeExtraRings(IAtomContainer m) throws Exception{ IRingSet rs = Cycles.sssr(m).toRingSet(); Iterator<IAtomContainer> i = rs.atomContainers().iterator(); while (i.hasNext()) { IRing r = (IRing) i.next(); if (r.getAtomCount() > 8) { i.remove(); } else { for (IAtom a : r.atoms()) { Hybridization h = a.getHybridization(); if (h == CDKConstants.UNSET || !(h == Hybridization.SP2 || h == Hybridization.PLANAR3)) { i.remove(); break; } } } } return rs; }
/legacy/src/main/java/org/openscience/cdk/smiles/FixBondOrdersTool.java