id
stringlengths
25
27
content
stringlengths
190
15.4k
max_stars_repo_path
stringlengths
31
217
robustness-copilot_data_301
/** * Returns either {@code `text`} (backtick-quoted) or {@code [null]}. * * @since 2.9 */ public static String backticked(String text){ if (text == null) { return "[null]"; } return new StringBuilder(text.length() + 2).append('`').append(text).append('`').toString(); }
/src/main/java/com/fasterxml/jackson/databind/util/ClassUtil.java
robustness-copilot_data_302
/** * Performs that Bayesian model generation, using the {molecule:activity} pairs that have been submitted up to this * point. Once this method has finished, the object can be used to generate predictions, validation data or to * serialise for later use. */ public void build() throws CDKException{ trainingSize = training.size(); trainingActives = numActive; contribs.clear(); final int sz = training.size(); final double invSz = 1.0 / sz; final double P_AT = numActive * invSz; for (Integer hash : inHash.keySet()) { final int[] AT = inHash.get(hash); final int A = AT[0], T = AT[1]; final double Pcorr = (A + 1) / (T * P_AT + 1); final double P = Math.log(Pcorr); contribs.put(hash, P); } lowThresh = Double.POSITIVE_INFINITY; highThresh = Double.NEGATIVE_INFINITY; for (int[] fp : training) { double val = 0; for (int hash : fp) val += contribs.get(hash); lowThresh = Math.min(lowThresh, val); highThresh = Math.max(highThresh, val); } range = highThresh - lowThresh; invRange = range > 0 ? 1 / range : 0; }
/tool/model/src/main/java/org/openscience/cdk/fingerprint/model/Bayesian.java
robustness-copilot_data_303
/** * Position the hydrogen label relative to the element label. * * @param position relative position where the hydrogen is placed * @param element the outline of the element label * @param hydrogen the outline of the hydrogen * @return positioned hydrogen label */ TextOutline positionHydrogenLabel(HydrogenPosition position, TextOutline element, TextOutline hydrogen){ final Rectangle2D elementBounds = element.getBounds(); final Rectangle2D hydrogenBounds = hydrogen.getBounds(); switch(position) { case Above: return hydrogen.translate(0, (elementBounds.getMinY() - padding) - hydrogenBounds.getMaxY()); case Right: return hydrogen.translate((elementBounds.getMaxX() + padding) - hydrogenBounds.getMinX(), 0); case Below: return hydrogen.translate(0, (elementBounds.getMaxY() + padding) - hydrogenBounds.getMinY()); case Left: return hydrogen.translate((elementBounds.getMinX() - padding) - hydrogenBounds.getMaxX(), 0); } return hydrogen; }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardAtomGenerator.java
robustness-copilot_data_304
/** * Calculate the hash code and store it for later quick reference. */ void calcHashCode(){ int code = 0; int elementCount = 0; for (String element : _elements) { int stringHash = 0; if (element == null) { stringHash = NULL_ELEMENT_HASH; } else { byte[] bytes = element.getBytes(); int len = bytes.length > 10 ? 10 : bytes.length; for (int i = 0; i < len; i++) { stringHash ^= (bytes[i]) << (i * 5 + elementCount) % 24; } } code ^= stringHash; elementCount++; } _myHashCode = code; _haveHashCode = true; }
/modules/dcache-info/src/main/java/org/dcache/services/info/base/StatePath.java
robustness-copilot_data_305
/** * Checks whether the query angle constraint matches a target distance. * * This method checks whether a query constraint is satisfied by an observed * angle (represented by a {@link org.openscience.cdk.pharmacophore.PharmacophoreAngleBond} in the target molecule. * Note that angles are compared upto 2 decimal places. * * @param bond The angle relationship in a target molecule * @return true if the target angle lies within the range of the query constraint */ public boolean matches(IBond bond){ bond = BondRef.deref(bond); if (bond instanceof PharmacophoreAngleBond) { PharmacophoreAngleBond pbond = (PharmacophoreAngleBond) bond; double bondLength = round(pbond.getBondLength(), 2); return bondLength >= lower && bondLength <= upper; } else return false; }
/tool/pcore/src/main/java/org/openscience/cdk/pharmacophore/PharmacophoreQueryAngleBond.java
robustness-copilot_data_306
/** * Recursively encodes a SMARTS expression into the provides * string builder. * * @param idx atom index * @param bprev previous bond * @param sb destition to write SMARTS to */ private void encodeExpr(int idx, int bprev, StringBuilder sb){ avisit[idx] = numVisit++; sb.append(aexpr[idx]); final int d = deg[idx]; int remain = d; for (int j = 0; j < d; j++) { int nbr = atomAdj[idx][j]; int bidx = bondAdj[idx][j]; if (rbnds[bidx] < 0) { final int rnum = chooseRingNumber(); if (rnum > 9) sb.append('%'); sb.append(rnum); rbnds[bidx] = rnum; } else if (rbnds[bidx] > 0) { final int rnum = rbnds[bidx]; releaseRingNumber(rnum); if (rnum > 9) sb.append('%'); sb.append(rnum); } if (mode == MODE_EXACT && avisit[nbr] == 0 || bidx == bprev || rbnds[bidx] != 0) remain--; } for (int j = 0; j < d; j++) { int nbr = atomAdj[idx][j]; int bidx = bondAdj[idx][j]; if (mode == MODE_EXACT && avisit[nbr] == 0 || bidx == bprev || rbnds[bidx] != 0) continue; remain--; if (avisit[nbr] == 0) { if (remain > 0) sb.append('('); sb.append(bexpr[bidx]); sb.append(mol.getAtom(nbr).isAromatic() ? 'a' : '*'); if (remain > 0) sb.append(')'); } else { if (remain > 0) sb.append('('); sb.append(bexpr[bidx]); encodeExpr(nbr, bidx, sb); if (remain > 0) sb.append(')'); } } }
/tool/smarts/src/main/java/org/openscience/cdk/smarts/SmartsFragmentExtractor.java
robustness-copilot_data_307
/** * Find out if the Topic 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> findTopicEntity(String userId, String qualifiedName) throws UserNotAuthorizedException, PropertyServerException, InvalidParameterException{ return dataEngineCommonHandler.findEntity(userId, qualifiedName, TOPIC_TYPE_NAME); }
/open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEngineTopicHandler.java
robustness-copilot_data_308
/** * Extracts top-level coverage information from the JaCoCo report document. */ private static Map<Type, Coverage> loadRatios(JacocoReportDir layout, String[] includes, String... excludes) throws IOException{ Map<CoverageElement.Type, Coverage> ratios = new LinkedHashMap<>(); ExecutionFileLoader efl = layout.parse(includes, excludes); IBundleCoverage bundleCoverage = efl.getBundleCoverage(); if (bundleCoverage == null) { return null; } Coverage ratio = new Coverage(); ratio.accumulatePP(bundleCoverage.getClassCounter().getMissedCount(), bundleCoverage.getClassCounter().getCoveredCount()); ratios.put(CoverageElement.Type.CLASS, ratio); ratio = new Coverage(); ratio.accumulatePP(bundleCoverage.getBranchCounter().getMissedCount(), bundleCoverage.getBranchCounter().getCoveredCount()); ratios.put(CoverageElement.Type.BRANCH, ratio); ratio = new Coverage(); ratio.accumulatePP(bundleCoverage.getInstructionCounter().getMissedCount(), bundleCoverage.getInstructionCounter().getCoveredCount()); ratios.put(CoverageElement.Type.INSTRUCTION, ratio); ratio = new Coverage(); ratio.accumulatePP(bundleCoverage.getMethodCounter().getMissedCount(), bundleCoverage.getMethodCounter().getCoveredCount()); ratios.put(CoverageElement.Type.METHOD, ratio); ratio = new Coverage(); ratio.accumulatePP(bundleCoverage.getComplexityCounter().getMissedCount(), bundleCoverage.getComplexityCounter().getCoveredCount()); ratios.put(CoverageElement.Type.COMPLEXITY, ratio); ratio = new Coverage(); ratio.accumulatePP(bundleCoverage.getLineCounter().getMissedCount(), bundleCoverage.getLineCounter().getCoveredCount()); ratios.put(CoverageElement.Type.LINE, ratio); return ratios; }
/src/main/java/hudson/plugins/jacoco/JacocoBuildAction.java
robustness-copilot_data_309
/** * Use this to add yourself to this IChemObject as a listener. In order to do * so, you must implement the ChemObjectListener Interface. * *@param col the ChemObjectListener *@see #removeListener */ public void addListener(IChemObjectListener col){ List<IChemObjectListener> listeners = lazyChemObjectListeners(); if (!listeners.contains(col)) { listeners.add(col); } }
/base/data/src/main/java/org/openscience/cdk/ChemObject.java
robustness-copilot_data_310
/** * The number values to check is typically small ({@literal < 5}) and thus * we use brute-force to count the number of inversions. * *{@inheritDoc} */ public int parity(long[] current){ int count = 0; for (int i = 0, n = indices.length; i < n; i++) { for (int j = i + 1; j < n; j++) { int cmp = compare(current[indices[i]], current[indices[j]]); if (cmp == 0) return 0; else if (cmp > 0) count++; } } // value is odd, -1 or value is even +1 return Integer.lowestOneBit(count) == 1 ? -1 : +1; }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/BasicPermutationParity.java
robustness-copilot_data_311
/** * Equals method that returns true if containing properties are the same. * * @param objectToCompare object to compare * @return boolean result of comparison */ public boolean equals(Object objectToCompare){ if (this == objectToCompare) { return true; } if (objectToCompare == null || getClass() != objectToCompare.getClass()) { return false; } LogRecordRequestBody that = (LogRecordRequestBody) objectToCompare; return Objects.equals(getConnectorInstanceId(), that.getConnectorInstanceId()) && Objects.equals(getConnectionName(), that.getConnectionName()) && Objects.equals(getConnectorType(), that.getConnectorType()) && Objects.equals(getContextId(), that.getContextId()) && Objects.equals(getMessage(), that.getMessage()); }
/open-metadata-implementation/access-services/asset-consumer/asset-consumer-api/src/main/java/org/odpi/openmetadata/accessservices/assetconsumer/rest/LogRecordRequestBody.java
robustness-copilot_data_312
/** * Split a label it to recognised tokens for reversing, the * validity of the label is not checked! The method is intended * for zero/single attachments only and linkers are not supported. * * * Example: * {@code NHCH2Ph -> N,H,C,H2,Ph -> reverse/join -> PhH2CHN} * * * * The method return value signals whether formula * formatting (sub- and super- script) can be applied. * * @param label abbreviation label * @param tokens the list of tokens from the input (n>0) * @return whether the label parsed okay (i.e. apply formatting) */ static boolean parse(String label, List<String> tokens){ int i = 0; int len = label.length(); while (i < len) { int st = i; int last; char c = label.charAt(i); // BRACKETS we treat as separate if (c == '(' || c == ')') { tokens.add(Character.toString(c)); i++; // digits following closing brackets if (c == ')') { st = i; while (i < len && isDigit(c = label.charAt(i))) { i++; } if (i > st) tokens.add(label.substring(st, i)); } continue; } // separators if (c == '/' || c == '·' || c == '.' || c == '•' || c == '=') { tokens.add(Character.toString(c)); i++; int beg = i; while (i < label.length() && isDigit(label.charAt(i))) { i++; } if (i > beg) tokens.add(label.substring(beg, i)); continue; } // SYMBOL Tokens // optional prefix o- m- p- etc. if ((last = findPrefix(PREFIX_TRIE, label, i, -1)) > 0) { i += (last - i); } final int symSt = i; // a valid symbol token if ((last = findPrefix(SYMBOL_TRIE, label, i, -1)) > 0) { i += (last - i); // an optional number suffix e.g. O2 F3 Ph3 etc. while (i < len && isDigit(label.charAt(i))) { i++; } } else // a charge token, only if it's after some other parts if (i == st && st > 0) { c = norm(label.charAt(i)); if (c == '-' || c == '+') { i++; while (i < len && isDigit(label.charAt(i))) { i++; } // we expect charge at the end of the string.. if there is // still more it's not good input if (i < len) { return failParse(label, tokens); } } } if (i == st || i == symSt) { return failParse(label, tokens); } tokens.add(label.substring(st, i)); } return true; }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/AbbreviationLabel.java
robustness-copilot_data_313
/** * Builds a protein by connecting a new amino acid at the C-terminus of the * given strand. The acidic oxygen of the added amino acid is removed so that * additional amino acids can be added savely. But this also means that you * might want to add an oxygen at the end of the protein building! * * @param protein protein to which the strand belongs * @param aaToAdd amino acid to add to the strand of the protein * @param strand strand to which the protein is added */ public static IBioPolymer addAminoAcidAtCTerminus(IBioPolymer protein, IAminoAcid aaToAdd, IStrand strand, IAminoAcid aaToAddTo){ addAminoAcid(protein, aaToAdd, strand); if ((protein.getMonomerCount() != 0) && (aaToAddTo != null)) { protein.addBond(aaToAdd.getBuilder().newInstance(IBond.class, aaToAddTo.getCTerminus(), aaToAdd.getNTerminus(), IBond.Order.SINGLE)); } return protein; }
/storage/pdb/src/main/java/org/openscience/cdk/tools/ProteinBuilderTool.java
robustness-copilot_data_314
/** * Method to find all links in {@link Network} that intersect a given {@link Link}. Convenience method that * only uses MATSim objects. * * @param link * @param network * @return */ public static List<Link> findIntersectingLinks(Link link, final Network network){ LineString segment = GeometryUtils.createGeotoolsLineString(link); return GeometryUtils.findIntersectingLinks(segment, network); }
/matsim/src/main/java/org/matsim/core/utils/geometry/GeometryUtils.java
robustness-copilot_data_315
/** * Helper method for testing checks without having to deploy them on a Sonar instance. * * @param inputFile is the file to be checked * @param visitors AST checks and visitors to use * @return file checked with measures and issues */ public static SourceFile scanSingleInputFile(InputFile inputFile, SquidAstVisitor<Grammar>... visitors){ return scanSingleInputFileConfig(inputFile, new CxxSquidConfiguration(), visitors); }
/cxx-squid/src/main/java/org/sonar/cxx/CxxAstScanner.java
robustness-copilot_data_316
/** * Returns a new numeric column initialized with the given name and size. The values in the column * are integers beginning at startsWith and continuing through size (exclusive), monotonically * increasing by 1 TODO consider a generic fill function including steps or random samples from * various distributions */ public static IntColumn indexColumn(final String columnName, final int size, final int startsWith){ final IntColumn indexColumn = IntColumn.create(columnName, size); for (int i = 0; i < size; i++) { indexColumn.set(i, i + startsWith); } return indexColumn; }
/core/src/main/java/tech/tablesaw/api/IntColumn.java
robustness-copilot_data_317
/** * Checks the JSON result from the dynamic cluster size update REST request. * * @param jsonResult The JSON String result from the dynamic server cluster size update REST * request * @return true if the result means the update was successful, false otherwise */ static boolean checkUpdateDynamicClusterSizeJsonResult(String jsonResult){ final String expectedResult = "{}"; boolean result = false; if (expectedResult.equals(jsonResult)) { result = true; } return result; }
/operator/src/main/java/oracle/kubernetes/operator/wlsconfig/WlsClusterConfig.java
robustness-copilot_data_318
/** * Obtain the integer MMFF atom type for a given symbolic MMFF type. * * @param sym Symbolic MMFF type * @return integer MMFF type */ int intType(final String sym){ Integer intType = typeMap.get(sym); if (intType == null) { return 0; } return intType; }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffParamSet.java
robustness-copilot_data_319
/** * Given the service associated with a server service-deleted event, removes the service if it is * not older than the one recorded. * * @param serverName the name of the associated server * @param event the service associated with the event * @return true if the service was actually removed */ boolean deleteServerServiceFromEvent(String serverName, V1Service event){ if (serverName == null) { return false; } V1Service deletedService = getSko(serverName).getService().getAndAccumulate(event, this::getNewerCurrentOrNull); return deletedService != null; }
/operator/src/main/java/oracle/kubernetes/operator/helpers/DomainPresenceInfo.java
robustness-copilot_data_320
/** * Calculate the count of atoms of the longest aliphatic chain in the supplied {@link IAtomContainer}. * <p> * The method require one parameter: * if checkRingSyste is true the CDKConstant.ISINRING will be set * * @param mol The {@link IAtomContainer} for which this descriptor is to be calculated * @return the number of atoms in the longest aliphatic chain of this AtomContainer * @see #setParameters */ public DescriptorValue calculate(IAtomContainer mol){ if (checkRingSystem) Cycles.markRingAtomsAndBonds(mol); IAtomContainer aliphaticParts = mol.getBuilder().newAtomContainer(); for (IAtom atom : mol.atoms()) { if (isAcyclicCarbon(atom)) aliphaticParts.addAtom(atom); } for (IBond bond : mol.bonds()) { if (isAcyclicCarbon(bond.getBegin()) && isAcyclicCarbon(bond.getEnd())) aliphaticParts.addBond(bond); } int longest = 0; final int[][] adjlist = GraphUtil.toAdjList(aliphaticParts); for (int i = 0; i < adjlist.length; i++) { if (adjlist[i].length != 1) continue; int length = getMaxDepth(adjlist, i, -1); if (length > longest) longest = length; } return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new IntegerResult(longest), getDescriptorNames()); }
/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/LongestAliphaticChainDescriptor.java
robustness-copilot_data_321
/** * Builds the CDKRGraph ( resolution graph ), from two atomContainer * (description of the two molecules to compare) * This is the interface point between the CDK model and * the generic MCSS algorithm based on the RGRaph. * * @param sourceGraph Description of the first molecule * @param targetGraph Description of the second molecule * @param shouldMatchBonds * @return the rGraph * @throws CDKException */ public static CDKRGraph buildRGraph(IAtomContainer sourceGraph, IAtomContainer targetGraph, boolean shouldMatchBonds) throws CDKException{ CDKRGraph rGraph = new CDKRGraph(); nodeConstructor(rGraph, sourceGraph, targetGraph, shouldMatchBonds); arcConstructor(rGraph, sourceGraph, targetGraph); return rGraph; }
/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java
robustness-copilot_data_322
/** * Returns the lowest index at which the specific IAtomContainer appears in the list or -1 if is not found. * * A given IAtomContainer will occur in the list if the title matches the stored title for * the conformers in this container and if the coordinates for each atom in the specified molecule * are equal to the coordinates of the corresponding atoms in a conformer. * * @param o The IAtomContainer whose presence is being tested * @return The index where o was found */ public int indexOf(Object o){ IAtomContainer atomContainer = (IAtomContainer) o; if (!atomContainer.getTitle().equals(title)) return -1; if (atomContainer.getAtomCount() != this.atomContainer.getAtomCount()) return -1; boolean coordsMatch; int index = 0; for (Point3d[] coords : coordinates) { coordsMatch = true; for (int i = 0; i < atomContainer.getAtomCount(); i++) { Point3d p = atomContainer.getAtom(i).getPoint3d(); if (!(p.x == coords[i].x && p.y == coords[i].y && p.z == coords[i].z)) { coordsMatch = false; break; } } if (coordsMatch) return index; index++; } return -1; }
/base/data/src/main/java/org/openscience/cdk/ConformerContainer.java
robustness-copilot_data_323
/** * Internal - create a canonical SMILES string temporarily adjusting to default * hydrogen count. This method may be moved to the SMILESGenerator in future. * * @param mol molecule * @param ordering ordering output * @return SMILES * @throws CDKException SMILES could be generate */ private String cansmi(IAtomContainer mol, int[] ordering) throws CDKException{ Integer[] hcntBackup = new Integer[mol.getAtomCount()]; Map<IAtom, Integer> idxs = new HashMap<>(); for (int i = 0; i < mol.getAtomCount(); i++) { hcntBackup[i] = mol.getAtom(i).getImplicitHydrogenCount(); idxs.put(mol.getAtom(i), i); } int[] bondedValence = new int[mol.getAtomCount()]; for (int i = 0; i < mol.getBondCount(); i++) { IBond bond = mol.getBond(i); bondedValence[idxs.get(bond.getBegin())] += bond.getOrder().numeric(); bondedValence[idxs.get(bond.getEnd())] += bond.getOrder().numeric(); } for (int i = 0; i < mol.getAtomCount(); i++) { IAtom atom = mol.getAtom(i); atom.setImplicitHydrogenCount(0); switch(atom.getAtomicNumber()) { case 5: if (bondedValence[i] <= 3) atom.setImplicitHydrogenCount(3 - bondedValence[i]); break; case 6: if (bondedValence[i] <= 4) atom.setImplicitHydrogenCount(4 - bondedValence[i]); break; case 7: case 15: if (bondedValence[i] <= 3) atom.setImplicitHydrogenCount(3 - bondedValence[i]); else if (bondedValence[i] <= 5) atom.setImplicitHydrogenCount(5 - bondedValence[i]); break; case 8: if (bondedValence[i] <= 2) atom.setImplicitHydrogenCount(2 - bondedValence[i]); break; case 16: if (bondedValence[i] <= 2) atom.setImplicitHydrogenCount(2 - bondedValence[i]); else if (bondedValence[i] <= 4) atom.setImplicitHydrogenCount(4 - bondedValence[i]); else if (bondedValence[i] <= 6) atom.setImplicitHydrogenCount(6 - bondedValence[i]); break; case 9: case 17: case 35: case 53: if (bondedValence[i] <= 1) atom.setImplicitHydrogenCount(1 - bondedValence[i]); break; default: atom.setImplicitHydrogenCount(0); break; } } String smi = null; try { smi = smigen.create(mol, ordering); } finally { for (int i = 0; i < mol.getAtomCount(); i++) mol.getAtom(i).setImplicitHydrogenCount(hcntBackup[i]); } return smi; }
/tool/sdg/src/main/java/org/openscience/cdk/layout/IdentityTemplateLibrary.java
robustness-copilot_data_324
/** * Determines if 2 bondA1 have 1 atom in common if second is atom query AtomContainer * and wheter the order of the atoms is correct (atoms match). * * @param bondA1 first bondA1 * @param bond2 second bondA1 * @param queryBond1 first query bondA1 * @param queryBond2 second query bondA1 * @return the symbol of the common atom or "" if the 2 bonds have no common atom */ private static boolean queryAdjacencyAndOrder(IBond bond1, IBond bond2, IBond queryBond1, IBond queryBond2){ IAtom centralAtom = null; IAtom centralQueryAtom = null; if (bond1.contains(bond2.getBegin())) { centralAtom = bond2.getBegin(); } else if (bond1.contains(bond2.getEnd())) { centralAtom = bond2.getEnd(); } if (queryBond1.contains(queryBond2.getBegin())) { centralQueryAtom = queryBond2.getBegin(); } else if (queryBond1.contains(queryBond2.getEnd())) { centralQueryAtom = queryBond2.getEnd(); } if (centralAtom != null && centralQueryAtom != null && ((IQueryAtom) centralQueryAtom).matches(centralAtom)) { IQueryAtom queryAtom1 = (IQueryAtom) queryBond1.getOther(centralQueryAtom); IQueryAtom queryAtom2 = (IQueryAtom) queryBond2.getOther(centralQueryAtom); IAtom atom1 = bond1.getOther(centralAtom); IAtom atom2 = bond2.getOther(centralAtom); if (queryAtom1.matches(atom1) && queryAtom2.matches(atom2) || queryAtom1.matches(atom2) && queryAtom2.matches(atom1)) { return true; } else { return false; } } else { return centralAtom == null && centralQueryAtom == null; } }
/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java
robustness-copilot_data_325
/** * Reusable method to replace placeholders in the input string./ * * @param input String input * @param contentVariableReplacements current map of content variables * @return The replaced or original String */ private String replaceInString(String input, Map<String, Object> contentVariableReplacements){ final List<String> keys = ContentVariableReplacementUtil.getKeys(input); for (String key : keys) { if (ContentVariableReplacementUtil.hasKey(contentVariableReplacements, key)) { String replaceValue = (String) ContentVariableReplacementUtil.getValue(contentVariableReplacements, key); input = ContentVariableReplacementUtil.doReplacement(input, key, replaceValue, propertyConfigService.getAction(key)); } } return input; }
/bundle/src/main/java/com/adobe/acs/commons/ccvar/filter/ContentVariableJsonFilter.java
robustness-copilot_data_326
/** * Unregisters the application {@link HealthCheck} with the given name. * * @param name the name of the {@link HealthCheck} instance */ public void unregister(String name){ HealthCheck healthCheck; synchronized (lock) { healthCheck = healthChecks.remove(name); if (healthCheck instanceof AsyncHealthCheckDecorator) { ((AsyncHealthCheckDecorator) healthCheck).tearDown(); } } if (healthCheck != null) { onHealthCheckRemoved(name, healthCheck); } }
/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java
robustness-copilot_data_327
/** * Transform all services from the existing carrier to the new carrier with * shipments. The location of the depot from which the "old" carrier starts the * tour to the service is used as fromLocation for the new Shipment. * * @param carrierWS the "new" carrier with Shipments * @param carrier the already existing carrier */ private static void createShipmentsFromServices(Carrier carrierWS, Carrier carrier){ TreeMap<Id<CarrierService>, Id<Link>> depotServiceIsdeliveredFrom = new TreeMap<>(); try { carrier.getSelectedPlan(); } catch (Exception e) { throw new RuntimeException("Carrier " + carrier.getId() + " has NO selectedPlan. --> CanNOT create a new carrier from solution"); } Collection<ScheduledTour> tours; try { tours = carrier.getSelectedPlan().getScheduledTours(); } catch (Exception e) { throw new RuntimeException("Carrier " + carrier.getId() + " has NO ScheduledTours. --> CanNOT create a new carrier from solution"); } for (ScheduledTour tour : tours) { Id<Link> depotForTour = tour.getVehicle().getLocation(); for (TourElement te : tour.getTour().getTourElements()) { if (te instanceof ServiceActivity) { ServiceActivity act = (ServiceActivity) te; depotServiceIsdeliveredFrom.put(act.getService().getId(), depotForTour); } } } for (CarrierService carrierService : carrier.getServices().values()) { log.debug("Converting CarrierService to CarrierShipment: " + carrierService.getId()); CarrierShipment carrierShipment = CarrierShipment.Builder.newInstance(Id.create(carrierService.getId().toString(), CarrierShipment.class), depotServiceIsdeliveredFrom.get(carrierService.getId()), carrierService.getLocationLinkId(), carrierService.getCapacityDemand()).setDeliveryServiceTime(carrierService.getServiceDuration()).setDeliveryTimeWindow(carrierService.getServiceStartTimeWindow()).setPickupTimeWindow(TimeWindow.newInstance(0.0, carrierService.getServiceStartTimeWindow().getEnd())).build(); CarrierUtils.addShipment(carrierWS, carrierShipment); } }
/contribs/freight/src/main/java/org/matsim/contrib/freight/utils/FreightUtils.java
robustness-copilot_data_328
/** * Given the assigned preliminary MMFF atom types (symbs[]) update these to the aromatic types. * To begin, all the 5 and 6 member aromatic cycles are discovered. The symbolic types of five * and six member cycles are then update with {@link #updateAromaticTypesInFiveMemberRing(int[], * String[])} and {@link #updateAromaticTypesInSixMemberRing(int[], String[])}. * * @param container structure representation * @param symbs vector of symbolic types for the whole structure * @param bonds edge to bond map lookup * @param graph adjacency list graph representation of structure * @param mmffArom set of bonds that are aromatic */ void assign(IAtomContainer container, String[] symbs, EdgeToBondMap bonds, int[][] graph, Set<IBond> mmffArom){ int[] contribution = new int[graph.length]; int[] doubleBonds = new int[graph.length]; Arrays.fill(doubleBonds, -1); setupContributionAndDoubleBonds(container, bonds, graph, contribution, doubleBonds); int[][] cycles = findAromaticRings(cyclesOfSizeFiveOrSix(container, graph), contribution, doubleBonds); for (int[] cycle : cycles) { int len = cycle.length - 1; if (len == 6) { updateAromaticTypesInSixMemberRing(cycle, symbs); } if (len == 5 && normaliseCycle(cycle, contribution)) { updateAromaticTypesInFiveMemberRing(cycle, symbs); } // mark aromatic bonds for (int i = 1; i < cycle.length; i++) mmffArom.add(bonds.get(cycle[i], cycle[i - 1])); } }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAromaticTypeMapping.java
robustness-copilot_data_329
/** * Helper method that encapsulate logic in trying to close output generator * in case of failure; useful mostly in forcing flush()ing as otherwise * error conditions tend to be hard to diagnose. However, it is often the * case that output state may be corrupt so we need to be prepared for * secondary exception without masking original one. * * @since 2.8 */ public static void closeOnFailAndThrowAsIOE(JsonGenerator g, Exception fail) throws IOException{ g.disable(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT); try { g.close(); } catch (Exception e) { fail.addSuppressed(e); } throwIfIOE(fail); throwIfRTE(fail); throw new RuntimeException(fail); }
/src/main/java/com/fasterxml/jackson/databind/util/ClassUtil.java
robustness-copilot_data_330
/** * Simple helper function that sets all hydrogen counts to 0. * * @param container a structure representation * @return the input container */ private static IAtomContainer clearHydrogenCounts(IAtomContainer container){ for (IAtom atom : container.atoms()) atom.setImplicitHydrogenCount(0); return container; }
/tool/sdg/src/main/java/org/openscience/cdk/layout/StructureDiagramGenerator.java
robustness-copilot_data_331
/** * Compare two {@link IChemObject} classes and return the difference as a {@link String}. * * @param first the first of the two classes to compare * @param second the second of the two classes to compare * @return a {@link String} representation of the difference between the first and second {@link IChemObject}. */ public static String diff(IChemObject first, IChemObject second){ IDifference diff = difference(first, second); if (diff == null) { return ""; } else { return diff.toString(); } }
/misc/diff/src/main/java/org/openscience/cdk/tools/diff/AtomDiff.java
robustness-copilot_data_332
/** * Find a neutral oxygen bonded to the {@code atom} with a pi bond. * * @param container the container * @param atom an atom from the container * @return a pi bonded oxygen (or null if not found) */ private static IAtom findPiBondedOxygen(IAtomContainer container, IAtom atom){ for (IBond bond : container.getConnectedBondsList(atom)) { if (bond.getOrder() == IBond.Order.DOUBLE) { IAtom neighbor = bond.getOther(atom); int charge = neighbor.getFormalCharge() == null ? 0 : neighbor.getFormalCharge(); if (neighbor.getAtomicNumber() == 8 && charge == 0) return neighbor; } } return null; }
/storage/inchi/src/main/java/org/openscience/cdk/graph/invariant/InChINumbersTools.java
robustness-copilot_data_333
/** * Read a ChemFile from a file in MDL RDF format. * * @param chemFile The IChemFile * @return The IChemFile that was read from the RDF file. */ private IChemFile readChemFile(IChemFile chemFile) throws CDKException{ IChemSequence chemSequence = chemFile.getBuilder().newInstance(IChemSequence.class); IChemModel chemModel = chemFile.getBuilder().newInstance(IChemModel.class); chemSequence.addChemModel(readChemModel(chemModel)); chemFile.addChemSequence(chemSequence); return chemFile; }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLRXNReader.java
robustness-copilot_data_334
/** * Writes the values of the snapshot to the given stream. * * @param output an output stream */ public void dump(OutputStream output){ try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) { for (long value : values) { out.printf("%d%n", value); } } }
/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java
robustness-copilot_data_335
/** * Returns a StringColumn with the year and quarter 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 yearQuarter(){ StringColumn newColumn = StringColumn.create(this.name() + " year & quarter"); for (int r = 0; r < this.size(); r++) { int c1 = this.getIntInternal(r); if (DateColumn.valueIsMissing(c1)) { newColumn.appendMissing(); } else { String yq = String.valueOf(PackedLocalDate.getYear(c1)); yq = yq + "-" + Strings.padStart(String.valueOf(PackedLocalDate.getQuarter(c1)), 2, '0'); newColumn.append(yq); } } return newColumn; }
/core/src/main/java/tech/tablesaw/columns/dates/DateMapFunctions.java
robustness-copilot_data_336
/** * Mark the passage of time and decay the current rate accordingly. */ public void tick(){ final long count = uncounted.sumThenReset(); final double instantRate = count / interval; if (initialized) { final double oldRate = this.rate; rate = oldRate + (alpha * (instantRate - oldRate)); } else { rate = instantRate; initialized = true; } }
/metrics-core/src/main/java/io/dropwizard/metrics5/EWMA.java
robustness-copilot_data_337
/** * Locate all 5 and 6 member cycles (rings) in a structure representation. * * @param container structure representation * @param graph adjacency list graph representation of structure * @return closed walks (first = last vertex) of the cycles */ static int[][] cyclesOfSizeFiveOrSix(IAtomContainer container, int[][] graph){ try { return Cycles.all(6).find(container, graph, 6).paths(); } catch (Intractable intractable) { return new int[0][]; } }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAromaticTypeMapping.java
robustness-copilot_data_338
/** * Convert to a single value map, abandon values except the first of each parameter. * * @return single value map */ public Map<String, String> toSingleValueMap(){ return queryMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().get(0))); }
/elasticjob-infra/elasticjob-restful/src/main/java/org/apache/shardingsphere/elasticjob/restful/wrapper/QueryParameterMap.java
robustness-copilot_data_339
/** * Create a new chem model for a single {@link IAtomContainer}. * * @param container the container to create the model for * @return a new {@link IChemModel} */ private static IChemModel newModel(final IAtomContainer container){ if (container == null) throw new NullPointerException("cannot create chem model for a null container"); final IChemObjectBuilder builder = container.getBuilder(); final IChemModel model = builder.newInstance(IChemModel.class); final IAtomContainerSet containers = builder.newInstance(IAtomContainerSet.class); containers.addAtomContainer(container); model.setMoleculeSet(containers); return model; }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Reader.java
robustness-copilot_data_340
/** * Given an index of an atom in the query get the index of the other atom in * the double bond. * * @param i query atom index * @return the other atom index involved in a double bond */ private int otherIndex(int i){ IDoubleBondStereochemistry element = (IDoubleBondStereochemistry) queryElements[i]; return queryMap.get(element.getStereoBond().getOther(query.getAtom(i))); }
/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/StereoMatch.java
robustness-copilot_data_341
/** * Returns an Iterator for looping over all isotopes in this MolecularFormulaExpand. * * @return An Iterator with the isotopes in this MolecularFormulaExpand */ public Iterable<IIsotope> isotopes(){ return new Iterable<IIsotope>() { @Override public Iterator<IIsotope> iterator() { return isotopesMax.keySet().iterator(); } }; }
/tool/formula/src/main/java/org/openscience/cdk/formula/MolecularFormulaRange.java
robustness-copilot_data_342
/** * It is needed to call the addExplicitHydrogensToSatisfyValency method from * the class tools.HydrogenAdder, and 3D coordinates. * *@param atom The IAtom for which the DescriptorValue is requested *@param ac AtomContainer *@return a double with polarizability of the heavy atom */ public DescriptorValue calculate(IAtom atom, IAtomContainer ac){ if (factory == null) try { factory = AtomTypeFactory.getInstance("org/openscience/cdk/config/data/jmol_atomtypes.txt", ac.getBuilder()); } catch (Exception exception) { return getDummyDescriptorValue(exception); } double atomicHardness; double radiusTarget; Iterator<IAtom> allAtoms = ac.atoms().iterator(); atomicHardness = 0; double partial; double radius; String symbol; IAtomType type; try { symbol = atom.getSymbol(); type = factory.getAtomType(symbol); radiusTarget = type.getCovalentRadius(); } catch (Exception exception) { logger.debug(exception); return getDummyDescriptorValue(exception); } while (allAtoms.hasNext()) { IAtom curAtom = allAtoms.next(); if (atom.getPoint3d() == null || curAtom.getPoint3d() == null) { return getDummyDescriptorValue(new CDKException("The target atom or current atom had no 3D coordinates. These are required")); } if (!atom.equals(curAtom)) { partial = 0; symbol = curAtom.getSymbol(); try { type = factory.getAtomType(symbol); } catch (Exception exception) { logger.debug(exception); return getDummyDescriptorValue(exception); } radius = type.getCovalentRadius(); partial += radius * radius; partial += (radiusTarget * radiusTarget); partial = partial / (calculateSquareDistanceBetweenTwoAtoms(atom, curAtom)); atomicHardness += partial; } } atomicHardness = 2 * atomicHardness; atomicHardness = atomicHardness * 0.172; atomicHardness = 1 / atomicHardness; return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new DoubleResult(atomicHardness), NAMES); }
/descriptor/qsaratomic/src/main/java/org/openscience/cdk/qsar/descriptors/atomic/InductiveAtomicHardnessDescriptor.java
robustness-copilot_data_343
/** * Produces an ROC validation set, using the inputs provided prior to the model building, using leave-one-out. Note that * this should only be used for small datasets, since it is very thorough, and scales as O(N^2) relative to training set * size. */ public void validateLeaveOneOut(){ final int sz = training.size(); estimates = new double[sz]; for (int n = 0; n < sz; n++) estimates[n] = singleLeaveOneOut(n); calculateROC(); rocType = "leave-one-out"; }
/tool/model/src/main/java/org/openscience/cdk/fingerprint/model/Bayesian.java
robustness-copilot_data_344
/** * Creates a canonical request string out of HTTP request components. * * @param sortedIncludedHeaders the headers that should be included into canonical request string * @return a string representing the canonical request */ public String create(List<String> sortedIncludedHeaders){ // Add the method and uri StringBuilder canonicalRequest = new StringBuilder(); canonicalRequest.append(method).append(NEW_LINE); String canonicalUri = CANONICALIZE_PATH.apply(uri); canonicalRequest.append(canonicalUri).append(NEW_LINE); // Get the query args, replace whitespace and values that should be not encoded, sort and rejoin String canonicalQuery = CANONICALIZE_QUERY.apply(queryString); canonicalRequest.append(canonicalQuery).append(NEW_LINE); // Normalize all the headers Header[] normalizedHeaders = NORMALIZE_HEADERS.apply(headers); Map<String, List<String>> combinedHeaders = COMBINE_HEADERS.apply(normalizedHeaders); // Add the headers that we care about for (String header : sortedIncludedHeaders) { String lowercase = header.toLowerCase().trim(); if (combinedHeaders.containsKey(lowercase)) { List<String> values = combinedHeaders.get(lowercase); Collections.sort(values); canonicalRequest.append(lowercase).append(":").append(String.join(",", values)).append(NEW_LINE); } } canonicalRequest.append(NEW_LINE); // Mark the headers that we care about canonicalRequest.append(String.join(";", sortedIncludedHeaders)).append(NEW_LINE); // Hash and hex the request payload if (requestBody != null && !requestBody.isEmpty()) { String hashedPayload = DigestUtils.sha256Hex(requestBody); canonicalRequest.append(hashedPayload); } return canonicalRequest.toString(); }
/src/main/java/com/twilio/jwt/validation/RequestCanonicalizer.java
robustness-copilot_data_345
/** * Attempts to discover classes that are annotated with the annotation. Accumulated * classes can be accessed by calling {@link #getClasses()}. * * @param annotation * the annotation that should be present on matching classes * @param packageNames * one or more package names to scan (including subpackages) for classes * @return the resolver util */ public ResolverUtil<T> findAnnotated(Class<? extends Annotation> annotation, String... packageNames){ if (packageNames == null) { return this; } Test test = new AnnotatedWith(annotation); for (String pkg : packageNames) { find(test, pkg); } return this; }
/src/main/java/org/apache/ibatis/io/ResolverUtil.java
robustness-copilot_data_346
/** * Adds or replaces a list subtag with a list of compound tags. * * @param key the key to write to * @param list the list contents as compound tags */ public void putCompoundList(@NonNls String key, List<CompoundTag> list){ put(key, new ListTag<>(TagType.COMPOUND, list)); }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_347
/** * Determines if this AtomContainer contains 2D coordinates for some or all molecules. * See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets * * * @param container the molecule to be considered * @return 0 no 2d, 1=some, 2= for each atom * @deprecated use {@link #get2DCoordinateCoverage(org.openscience.cdk.interfaces.IAtomContainer)} for determining * partial coordinates * @see #get2DCoordinateCoverage(org.openscience.cdk.interfaces.IAtomContainer) */ public static int has2DCoordinatesNew(IAtomContainer container){ if (container == null) return 0; boolean no2d = false; boolean with2d = false; for (IAtom atom : container.atoms()) { if (atom.getPoint2d() == null) { no2d = true; } else { with2d = true; } } if (!no2d && with2d) { return 2; } else if (no2d && with2d) { return 1; } else { return 0; } }
/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java
robustness-copilot_data_348
/** * Create a copy of the list of V1EnvVar environment variables. * * @param envVars list of environment variables to copy * @return List containing a copy of the original list. */ public static List<V1EnvVar> createCopy(List<V1EnvVar> envVars){ ArrayList<V1EnvVar> copy = new ArrayList<>(); if (envVars != null) { for (V1EnvVar envVar : envVars) { copy.add(new V1EnvVarBuilder(envVar).build()); } } return copy; }
/operator/src/main/java/oracle/kubernetes/operator/helpers/PodHelper.java
robustness-copilot_data_349
/** * Assign non-planar, up and down labels to indicate tetrahedral configuration. Currently all * existing directional labels are removed before assigning new labels. * * @param container the structure to assign labels to * @return a container with assigned labels (currently the same as the input) * @throws IllegalArgumentException an atom had no 2D coordinates or labels could not be * assigned to a tetrahedral centre */ public static IAtomContainer assign(final IAtomContainer container){ GraphUtil.EdgeToBondMap edgeToBond = GraphUtil.EdgeToBondMap.withSpaceFor(container); new NonplanarBonds(container, GraphUtil.toAdjList(container, edgeToBond), edgeToBond); return container; }
/tool/sdg/src/main/java/org/openscience/cdk/layout/NonplanarBonds.java
robustness-copilot_data_350
/** * Initiate the MolecularFormulaExpand with the maximum and minimum occurrence of the Elements. * In this case all elements of the periodic table are loaded. */ private void ensureDefaultOccurElements(IChemObjectBuilder builder){ if (mfRange == null) { String[] elements = 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", "Be", "Li", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu" }; mfRange = new MolecularFormulaRange(); for (int i = 0; i < elements.length; i++) mfRange.addIsotope(builder.newInstance(IIsotope.class, elements[i]), 0, 50); } }
/tool/formula/src/main/java/org/openscience/cdk/formula/rules/ElementRule.java
robustness-copilot_data_351
/** * Adds a new data series to the chart with the specified title. * <code>xs<code> and <code>ys</code> should have the same length. If not, * only as many items are shown as the shorter array contains. * * @param title * @param xs * The x values. * @param ys * The y values. */ public void addSeries(final String title, final double[] xs, final double[] ys){ XYSeries series = new XYSeries(title, false, true); for (int i = 0, n = Math.min(xs.length, ys.length); i < n; i++) { series.add(xs[i], ys[i]); } this.dataset.addSeries(series); }
/matsim/src/main/java/org/matsim/core/utils/charts/XYScatterChart.java
robustness-copilot_data_352
/** * Check to see if the schema is a free form object. * * A free form object is an object (i.e. 'type: object' in a OAS document) that: * 1) Does not define properties, and * 2) Is not a composed schema (no anyOf, oneOf, allOf), and * 3) additionalproperties is not defined, or additionalproperties: true, or additionalproperties: {}. * * Examples: * * components: * schemas: * arbitraryObject: * type: object * description: This is a free-form object. * The value must be a map of strings to values. The value cannot be 'null'. * It cannot be array, string, integer, number. * arbitraryNullableObject: * type: object * description: This is a free-form object. * The value must be a map of strings to values. The value can be 'null', * It cannot be array, string, integer, number. * nullable: true * arbitraryTypeValue: * description: This is NOT a free-form object. * The value can be any type except the 'null' value. * * @param openAPI the object that encapsulates the OAS document. * @param schema potentially containing a '$ref' * @return true if it's a free-form object */ public static boolean isFreeFormObject(OpenAPI openAPI, Schema schema){ if (schema == null) { once(LOGGER).error("Schema cannot be null in isFreeFormObject check"); return false; } if (schema instanceof ComposedSchema) { ComposedSchema cs = (ComposedSchema) schema; List<Schema> interfaces = ModelUtils.getInterfaces(cs); if (interfaces != null && !interfaces.isEmpty()) { return false; } } if ("object".equals(schema.getType())) { if ((schema.getProperties() == null || schema.getProperties().isEmpty())) { Schema addlProps = getAdditionalProperties(openAPI, schema); if (schema.getExtensions() != null && schema.getExtensions().containsKey(freeFormExplicit)) { boolean isFreeFormExplicit = Boolean.parseBoolean(String.valueOf(schema.getExtensions().get(freeFormExplicit))); if (!isFreeFormExplicit && addlProps != null && addlProps.getProperties() != null && !addlProps.getProperties().isEmpty()) { once(LOGGER).error(String.format(Locale.ROOT, "Potentially confusing usage of %s within model which defines additional properties", freeFormExplicit)); } return isFreeFormExplicit; } if (addlProps == null) { return true; } else { if (addlProps instanceof ObjectSchema) { ObjectSchema objSchema = (ObjectSchema) addlProps; if (objSchema.getProperties() == null || objSchema.getProperties().isEmpty()) { return true; } } else if (addlProps instanceof Schema) { if (addlProps.getType() == null && addlProps.get$ref() == null && (addlProps.getProperties() == null || addlProps.getProperties().isEmpty())) { return true; } } } } } return false; }
/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java
robustness-copilot_data_353
/** * Return all molecular formulas but ordered according the tolerance difference between masses. * * @param mass The mass to analyze * @param formulaSet The IMolecularFormulaSet to order * @return The IMolecularFormulaSet ordered */ private IMolecularFormulaSet returnOrdered(double mass, IMolecularFormulaSet formulaSet){ IMolecularFormulaSet solutions_new = null; if (formulaSet.size() != 0) { double valueMin = 100; int i_final = 0; solutions_new = formulaSet.getBuilder().newInstance(IMolecularFormulaSet.class); List<Integer> listI = new ArrayList<Integer>(); for (int j = 0; j < formulaSet.size(); j++) { for (int i = 0; i < formulaSet.size(); i++) { if (listI.contains(i)) continue; double value = MolecularFormulaManipulator.getTotalExactMass(formulaSet.getMolecularFormula(i)); double diff = Math.abs(mass - Math.abs(value)); if (valueMin > diff) { valueMin = diff; i_final = i; } } valueMin = 100; solutions_new.addMolecularFormula(formulaSet.getMolecularFormula(i_final)); listI.add(i_final); } } return solutions_new; }
/legacy/src/main/java/org/openscience/cdk/formula/MassToFormulaTool.java
robustness-copilot_data_354
/** * Electron contribution of an element with the specified connectivity and valence. * * @param elem atomic number * @param x connectivity * @param v bonded valence * @return p electrons */ static int contribution(int elem, int x, int v){ switch(elem) { case 6: if (x == 3 && v == 4) return 1; break; case 7: if (x == 2 && v == 3) return 1; if (x == 3 && v == 4) return 1; if (x == 3 && v == 3) return 2; if (x == 2 && v == 2) return 2; break; case 8: case 16: if (x == 2 && v == 2) return 2; break; } return -1; }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAromaticTypeMapping.java
robustness-copilot_data_355
/** * isNullType returns true if the input schema is the 'null' type. * * The 'null' type is supported in OAS 3.1 and above. It is not supported * in OAS 2.0 and OAS 3.0.x. * * For example, the "null" type could be used to specify that a value must * either be null or a specified type: * * OptionalOrder: * oneOf: * - type: 'null' * - $ref: '#/components/schemas/Order' * * @param schema the OpenAPI schema * @return true if the schema is the 'null' type */ public static boolean isNullType(Schema schema){ if ("null".equals(schema.getType())) { return true; } return false; }
/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java
robustness-copilot_data_356
/** * Checks the current URL path against the included and excluded patterns. Exclusions hold priority. * * @param urlPath Current request path * @return if the request should be processed */ private boolean shouldProcess(String urlPath){ // If includes are specified but none are valid we skip all requests. if (allInvalidIncludes) { LOG.debug("Include patterns are empty due to invalid regex patterns, not processing any requests"); return false; } // If include and exclude lists are both empty we process all requests. if (includePatterns.isEmpty() && excludePatterns.isEmpty()) { LOG.debug("Include and Exclude patterns are empty, processing all requests"); return true; } boolean shouldProcess = false; for (Pattern pattern : includePatterns) { if (pattern.matcher(urlPath).matches()) { LOG.debug("URL path {} matches INCLUDE pattern {}", urlPath, pattern.toString()); shouldProcess = true; break; } } for (Pattern pattern : excludePatterns) { if (pattern.matcher(urlPath).matches()) { LOG.debug("URL path {} matches EXCLUDE pattern {}", urlPath, pattern.toString()); shouldProcess = false; break; } } LOG.debug("URL path {} is processed: {}", urlPath, shouldProcess); return shouldProcess; }
/bundle/src/main/java/com/adobe/acs/commons/ccvar/filter/ContentVariableJsonFilter.java
robustness-copilot_data_357
/** * Process De-Classified Entity event for lineage entity * The entity context is published if there is no lineage classification left. * The Classification Context event is sent if there are lineage classifications available on lineage entity. * * @param entityDetail the entity object that contains a classification that has been deleted * * @throws OCFCheckedExceptionBase unable to send the event due to connectivity issue * @throws JsonProcessingException exception parsing the event json */ private void processDeclassifiedEntityEvent(EntityDetail entityDetail) throws OCFCheckedExceptionBase, JsonProcessingException{ if (!immutableValidLineageEntityEvents.contains(entityDetail.getType().getTypeDefName())) { return; } log.debug(PROCESSING_ENTITY_DETAIL_DEBUG_MESSAGE, AssetLineageEventType.DECLASSIFIED_ENTITY_EVENT.getEventTypeName(), entityDetail.getGUID(), entityDetail.getType().getTypeDefName()); if (anyLineageClassificationsLeft(entityDetail)) { publisher.publishClassificationContext(entityDetail, AssetLineageEventType.DECLASSIFIED_ENTITY_EVENT); return; } publishEntityEvent(entityDetail, AssetLineageEventType.DECLASSIFIED_ENTITY_EVENT); }
/open-metadata-implementation/access-services/asset-lineage/asset-lineage-server/src/main/java/org/odpi/openmetadata/accessservices/assetlineage/listeners/AssetLineageOMRSTopicListener.java
robustness-copilot_data_358
/** * If any errors have been found, print the list of errors first, then print the command line help text. * * @param errorMessages List of error messages * @param stream the output stream to write the text to */ protected void printHelp(List<String> errorMessages, PrintStream stream){ stream.println(coreBundle.getString("errors")); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); }
/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java
robustness-copilot_data_359
/** * Gets whether there has been a position change between the two Locations. * * @param first The initial location. * @param second The final location. * @return A boolean. */ public static boolean hasMoved(Location first, Location second){ return first.getX() != second.getX() || first.getY() != second.getY() || first.getZ() != second.getZ(); }
/src/main/java/net/glowstone/util/Position.java
robustness-copilot_data_360
/** * Calculates the fingerprints for the given {@link IAtomContainer}, and stores them for subsequent retrieval. * * @param mol chemical structure; all nodes should be known legitimate elements */ public void calculate(IAtomContainer mol) throws CDKException{ this.mol = mol; fplist.clear(); atomClass = classType <= CLASS_ECFP6 ? ATOMCLASS_ECFP : ATOMCLASS_FCFP; excavateMolecule(); if (atomClass == ATOMCLASS_FCFP) calculateBioTypes(); final int na = mol.getAtomCount(); identity = new int[na]; resolvedChiral = new boolean[na]; atomGroup = new int[na][]; for (int n = 0; n < na; n++) if (amask[n]) { if (atomClass == ATOMCLASS_ECFP) identity[n] = initialIdentityECFP(n); else identity[n] = initialIdentityFCFP(n); atomGroup[n] = new int[] { n }; fplist.add(new FP(identity[n], 0, atomGroup[n])); } int niter = classType == CLASS_ECFP2 || classType == CLASS_FCFP2 ? 1 : classType == CLASS_ECFP4 || classType == CLASS_FCFP4 ? 2 : classType == CLASS_ECFP6 || classType == CLASS_FCFP6 ? 3 : 0; for (int iter = 1; iter <= niter; iter++) { final int[] newident = new int[na]; for (int n = 0; n < na; n++) if (amask[n]) newident[n] = circularIterate(iter, n); identity = newident; for (int n = 0; n < na; n++) if (amask[n]) { atomGroup[n] = growAtoms(atomGroup[n]); considerNewFP(new FP(identity[n], iter, atomGroup[n])); } } }
/descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/CircularFingerprinter.java
robustness-copilot_data_361
/** * Adds or replaces a list subtag with a list of floats. * * @param key the key to write to * @param list the list contents as floats, to convert to float tags */ public void putFloatList(@NonNls String key, List<Float> list){ putList(key, TagType.FLOAT, list, FloatTag::new); }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_362
/** * Applies the given function to a list subtag if it is present and its contents are string * 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 readStringList(@NonNls String key, Consumer<? super List<String>> consumer){ return readList(key, TagType.STRING, consumer); }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_363
/** * Access the index of Obj->Int map, if the entry isn't found we return -1. * * @param idxs index map * @param obj the object * @param <T> the object type * @return index or -1 if not found */ private static Integer findIdx(Map<T, Integer> idxs, T obj){ Integer idx = idxs.get(obj); if (idx == null) return -1; return idx; }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLV3000Writer.java
robustness-copilot_data_364
/** * Creates and adds a {@link Volume} to the {@link Count}ing station. * @param h indicating the hour-of-day. <b><i>Note: the hours for a counting * station must be from 1-24, and <b><i>not</i></b> from 0-23, * otherwise the {@link MatsimCountsReader} will throw an error. * </i></b> * @param val the total number of vehicles counted during hour <code>h</code>. * @return the {@link Count}ing station's {@link Volume}. */ public final Volume createVolume(final int h, final double val){ if (h < 1) { throw new RuntimeException("counts start at 1, not at 0. If you have a use case where you need to go below one, " + "let us know and we think about it, but so far we had numerous debugging sessions because someone inserted counts at 0."); } // overkill? Volume v = new Volume(h, val); this.volumes.put(Integer.valueOf(h), v); return v; }
/matsim/src/main/java/org/matsim/counts/Count.java
robustness-copilot_data_365
/** * Returns a one line string representation of this Atom. * Methods is conform RFC #9. * * @return The string representation of this Atom */ public String toString(){ StringBuffer stringContent = new StringBuffer(64); stringContent.append("Atom(").append(hashCode()); if (getSymbol() != null) { stringContent.append(", S:").append(getSymbol()); } if (getImplicitHydrogenCount() != null) { stringContent.append(", H:").append(getImplicitHydrogenCount()); } if (getStereoParity() != null) { stringContent.append(", SP:").append(getStereoParity()); } if (getPoint2d() != null) { stringContent.append(", 2D:[").append(getPoint2d()).append(']'); } if (getPoint3d() != null) { stringContent.append(", 3D:[").append(getPoint3d()).append(']'); } if (getFractionalPoint3d() != null) { stringContent.append(", F3D:[").append(getFractionalPoint3d()); } if (getCharge() != null) { stringContent.append(", C:").append(getCharge()); } stringContent.append(", ").append(super.toString()); stringContent.append(')'); return stringContent.toString(); }
/base/silent/src/main/java/org/openscience/cdk/silent/Atom.java
robustness-copilot_data_366
/** * Creates a binary encoded 'picture' message to the socket (or actor), so it can be sent. * 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. Supports these argument types: * <table> * <caption> </caption> * <tr><th style="text-align:left">pattern</th><th style="text-align:left">java type</th><th style="text-align:left">zproto type</th></tr> * <tr><td>1</td><td>int</td><td>type = "number" size = "1"</td></tr> * <tr><td>2</td><td>int</td><td>type = "number" size = "2"</td></tr> * <tr><td>4</td><td>long</td><td>type = "number" size = "3"</td></tr> * <tr><td>8</td><td>long</td><td>type = "number" size = "4"</td></tr> * <tr><td>s</td><td>String, 0-255 chars</td><td>type = "string"</td></tr> * <tr><td>S</td><td>String, 0-2^32-1 chars</td><td>type = "longstr"</td></tr> * <tr><td>b</td><td>byte[], 0-2^32-1 bytes</td><td>type = "chunk"</td></tr> * <tr><td>c</td><td>byte[], 0-2^32-1 bytes</td><td>type = "chunk"</td></tr> * <tr><td>f</td><td>ZFrame</td><td>type = "frame"</td></tr> * <tr><td>m</td><td>ZMsg</td><td>type = "msg" <b>Has to be the last element of the picture</b></td></tr> * </table> * @param args Arguments according to the picture * @return true when it has been queued on the socket and ØMQ has assumed responsibility for the message. * This does not indicate that the message has been transmitted to the network. * @apiNote Does not change or take ownership of any arguments. */ public ZMsg msgBinaryPicture(String picture, Object... args){ if (!BINARY_FORMAT.matcher(picture).matches()) { throw new ZMQException(picture + " is not in expected binary format " + BINARY_FORMAT.pattern(), ZError.EPROTO); } ZMsg msg = new ZMsg(); // Pass 1: calculate total size of data frame int frameSize = 0; for (int index = 0; index < picture.length(); index++) { char pattern = picture.charAt(index); switch(pattern) { case '1': { frameSize += 1; break; } case '2': { frameSize += 2; break; } case '4': { frameSize += 4; break; } case '8': { frameSize += 8; break; } case 's': { String string = (String) args[index]; frameSize += 1 + (string != null ? string.getBytes(ZMQ.CHARSET).length : 0); break; } case 'S': { String string = (String) args[index]; frameSize += 4 + (string != null ? string.getBytes(ZMQ.CHARSET).length : 0); break; } case 'b': case 'c': { byte[] block = (byte[]) args[index]; frameSize += 4 + block.length; break; } case 'f': { ZFrame frame = (ZFrame) args[index]; msg.add(frame); break; } case 'm': { ZMsg other = (ZMsg) args[index]; if (other == null) { msg.add(new ZFrame((byte[]) null)); } else { msg.addAll(other); } break; } default: assert (false) : "invalid picture element '" + pattern + "'"; } } // Pass 2: encode data into data frame ZFrame frame = new ZFrame(new byte[frameSize]); ZNeedle needle = new ZNeedle(frame); for (int index = 0; index < picture.length(); index++) { char pattern = picture.charAt(index); switch(pattern) { case '1': { needle.putNumber1((int) args[index]); break; } case '2': { needle.putNumber2((int) args[index]); break; } case '4': { needle.putNumber4((int) args[index]); break; } case '8': { needle.putNumber8((long) args[index]); break; } case 's': { needle.putString((String) args[index]); break; } case 'S': { needle.putLongString((String) args[index]); break; } case 'b': case 'c': { byte[] block = (byte[]) args[index]; needle.putNumber4(block.length); needle.putBlock(block, block.length); break; } case 'f': case 'm': break; default: assert (false) : "invalid picture element '" + pattern + "'"; } } msg.addFirst(frame); return msg; }
/src/main/java/org/zeromq/proto/ZPicture.java
robustness-copilot_data_367
/** * Encrypts the provided packet, so it's can't be eavesdropped during a transfer * to a CollectD server. Wire format: * <pre> * +---------------------------------+-------------------------------+ * ! Type (0x0210) ! Length ! * +---------------------------------+-------------------------------+ * ! Username length in bytes ! Username \ * +-----------------------------------------------------------------+ * ! Initialization Vector (IV) ! \ * +---------------------------------+-------------------------------+ * ! Encrypted bytes (AES (SHA1(packet) + packet)) \ * +---------------------------------+-------------------------------+ * </pre> * * @see <a href="https://collectd.org/wiki/index.php/Binary_protocol#Encrypted_part"> * Binary protocol - CollectD | Encrypted part</a> */ private ByteBuffer encryptPacket(ByteBuffer packet){ final ByteBuffer payload = (ByteBuffer) ByteBuffer.allocate(SHA1_LENGTH + packet.remaining()).put(sha1(packet)).put((ByteBuffer) packet.flip()).flip(); final EncryptionResult er = encrypt(password, payload); return (ByteBuffer) ByteBuffer.allocate(BUFFER_SIZE).putShort((short) TYPE_ENCR_AES256).putShort((short) (ENCRYPT_DATA_LEN + username.length + er.output.remaining())).putShort((short) username.length).put(username).put(er.iv).put(er.output).flip(); }
/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java
robustness-copilot_data_368
/** * Checks that all the cells are singletons - that is, they only have one * element. A discrete partition is equivalent to a permutation. * * @return true if all the cells are discrete */ public boolean isDiscrete(){ for (SortedSet<Integer> cell : cells) { if (cell.size() != 1) { return false; } } return true; }
/tool/group/src/main/java/org/openscience/cdk/group/Partition.java
robustness-copilot_data_369
/** * Calculate the nearest <i>N</i> words for a given input word. * * @param vectors vectors, keyed by word * @param word the input word * @param topN the number of similar word vectors to output * @return the {@code topN} similar words of the input word */ private static Set<String> nearestVector(Map<String, List<float[]>> vectors, String word, int topN){ Set<String> intermediate = new TreeSet<>(); List<float[]> inputs = vectors.get(word); String separateToken = "__"; for (Map.Entry<String, List<float[]>> entry : vectors.entrySet()) { for (float[] value : entry.getValue()) { for (float[] input : inputs) { float sim = 0; for (int i = 0; i < value.length; i++) { sim += value[i] * input[i]; } // store the words, sorted by decreasing distance using natural order (in the $dist__$word format) intermediate.add((1 - sim) + separateToken + entry.getKey()); } } } Set<String> result = new HashSet<>(); int i = 0; for (String w : intermediate) { if (i == topN) { break; } // only add actual word String (not the distance) to the result collection result.add(w.substring(w.indexOf(separateToken) + 2)); i++; } return result; }
/src/main/java/io/anserini/ann/ApproximateNearestNeighborEval.java
robustness-copilot_data_370
/** * Update aromatic atom types in a six member ring. The aromatic types here are hard coded from * the 'MMFFAROM.PAR' file. * * @param cycle 6-member aromatic cycle / ring * @param symbs vector of symbolic types for the whole structure */ static void updateAromaticTypesInSixMemberRing(int[] cycle, String[] symbs){ for (final int v : cycle) { if (NCN_PLUS.equals(symbs[v]) || "N+=C".equals(symbs[v]) || "N=+C".equals(symbs[v])) symbs[v] = "NPD+"; else if ("N2OX".equals(symbs[v])) symbs[v] = "NPOX"; else if ("N=C".equals(symbs[v]) || "N=N".equals(symbs[v])) symbs[v] = "NPYD"; else if (symbs[v].startsWith("C")) symbs[v] = "CB"; } }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAromaticTypeMapping.java
robustness-copilot_data_371
/** * Adjust all double bond elements in the provided structure. <b>IMPORTANT: * up/down labels should be adjusted before adjust double-bond * configurations. coordinates are reflected by this method which can lead * to incorrect tetrahedral specification.</b> * * @param container the structure to adjust * @throws IllegalArgumentException an atom had unset coordinates */ public static IAtomContainer correct(IAtomContainer container){ if (container.stereoElements().iterator().hasNext()) new CorrectGeometricConfiguration(container); return container; }
/tool/sdg/src/main/java/org/openscience/cdk/layout/CorrectGeometricConfiguration.java
robustness-copilot_data_372
/** * Given the current target candidate (m), find the next candidate. The next * candidate is the next vertex > m (in some ordering) that is unmapped and * is adjacent to a mapped vertex (terminal). If there is no such vertex * (disconnected) the next unmapped vertex is returned. If there are no more * candidates m == |V| of G2. * * @param m previous candidate m * @return the next value of m */ final int nextM(int n, int m){ if (size == 0) return m + 1; for (int i = m + 1; i < g2.length; i++) if (m2[i] == UNMAPPED && (t1[n] == 0 || t2[i] > 0)) return i; return mMax(); }
/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/AbstractVFState.java
robustness-copilot_data_373
/** * Adds an Isotope to this MolecularFormulaExpand in a number of * maximum and minimum occurrences allowed. * * @param isotope The isotope to be added to this MolecularFormulaExpand * @param countMax The maximal number of occurrences to add * @param countMin The minimal number of occurrences to add * */ public void addIsotope(IIsotope isotope, int countMin, int countMax){ if (isotope == null) throw new IllegalArgumentException("Isotope must not be null"); boolean flag = false; for (Iterator<IIsotope> it = isotopes().iterator(); it.hasNext(); ) { IIsotope thisIsotope = it.next(); if (isTheSame(thisIsotope, isotope)) { isotopesMax.put(thisIsotope, countMax); isotopesMin.put(thisIsotope, countMin); flag = true; break; } } if (!flag) { isotopesMax.put(isotope, countMax); isotopesMin.put(isotope, countMin); } }
/tool/formula/src/main/java/org/openscience/cdk/formula/MolecularFormulaRange.java
robustness-copilot_data_374
/** * Fetches the Lucene {@link Document} based on some field other than its unique collection docid. For example, * scientific articles might have DOIs. The method is named to be consistent with Lucene's * {@link IndexReader#document(int)}, contra Java's standard method naming conventions. * * @param reader index reader * @param field field * @param id unique id * @return corresponding Lucene {@link Document} based on the value of a specific field */ public static Document documentByField(IndexReader reader, String field, String id){ try { IndexSearcher searcher = new IndexSearcher(reader); Query q = new TermQuery(new Term(field, id)); TopDocs rs = searcher.search(q, 1); ScoreDoc[] hits = rs.scoreDocs; if (hits == null || hits.length == 0) { return null; } return reader.document(hits[0].doc); } catch (IOException e) { return null; } }
/src/main/java/io/anserini/index/IndexReaderUtils.java
robustness-copilot_data_375
/** * Due to the error with old implementation where total features * were passed instead of failures (and vice versa) following correction must be applied for trends generated * between release 3.0.0 and 3.1.0. */ private void applyPatchForFeatures(){ for (int i = 0; i < totalFeatures.length; i++) { int total = totalFeatures[i]; int failures = getFailedFeatures()[i]; if (total < failures) { int tmp = total; totalFeatures[i] = failures; failedFeatures[i] = tmp; } } }
/src/main/java/net/masterthought/cucumber/Trends.java
robustness-copilot_data_376
/** * Finds IChemFormats that provide a container for serialization for the * given features. The syntax of the integer is explained in the DataFeatures class. * * @param features the data features for which a IChemFormat is searched * @return an array of IChemFormat's that can contain the given features * * @see org.openscience.cdk.tools.DataFeatures */ public IChemFormat[] findChemFormats(int features){ if (formats == null) loadFormats(); Iterator<IChemFormat> iter = formats.iterator(); List<IChemFormat> matches = new ArrayList<IChemFormat>(); while (iter.hasNext()) { IChemFormat format = (IChemFormat) iter.next(); if ((format.getSupportedDataFeatures() & features) == features) matches.add(format); } return (IChemFormat[]) matches.toArray(new IChemFormat[matches.size()]); }
/storage/io/src/main/java/org/openscience/cdk/io/WriterFactory.java
robustness-copilot_data_377
/** * Layout the ring system, rotate and translate the template. * *@param originalCoord coordinates of the placedRingAtom from the template *@param placedRingAtom placedRingAtom *@param ringSet ring system which placedRingAtom is part of *@param centerPlacedMolecule the geometric center of the already placed molecule *@param atomB placed neighbour atom of placedRingAtom */ private void layoutRingSystem(Point3d originalCoord, IAtom placedRingAtom, IRingSet ringSet, Point3d centerPlacedMolecule, IAtom atomB, AtomPlacer3D ap3d){ IAtomContainer ac = RingSetManipulator.getAllInOneContainer(ringSet); Point3d newCoord = placedRingAtom.getPoint3d(); Vector3d axis = new Vector3d(atomB.getPoint3d().x - newCoord.x, atomB.getPoint3d().y - newCoord.y, atomB.getPoint3d().z - newCoord.z); translateStructure(originalCoord, newCoord, ac); Vector3d startAtomVector = new Vector3d(newCoord.x - atomB.getPoint3d().x, newCoord.y - atomB.getPoint3d().y, newCoord.z - atomB.getPoint3d().z); IAtom farthestAtom = ap3d.getFarthestAtom(placedRingAtom.getPoint3d(), ac); Vector3d farthestAtomVector = new Vector3d(farthestAtom.getPoint3d().x - newCoord.x, farthestAtom.getPoint3d().y - newCoord.y, farthestAtom.getPoint3d().z - newCoord.z); Vector3d n1 = new Vector3d(); n1.cross(axis, farthestAtomVector); n1.normalize(); double lengthFarthestAtomVector = farthestAtomVector.length(); Vector3d farthestVector = new Vector3d(startAtomVector); farthestVector.normalize(); farthestVector.scale((startAtomVector.length() + lengthFarthestAtomVector)); double dotProduct = farthestAtomVector.dot(farthestVector); double angle = Math.acos(dotProduct / (farthestAtomVector.length() * farthestVector.length())); Vector3d ringCenter = new Vector3d(); for (int i = 0; i < ac.getAtomCount(); i++) { if (!(ac.getAtom(i).getFlag(CDKConstants.ISPLACED))) { ringCenter.x = (ac.getAtom(i).getPoint3d()).x - newCoord.x; ringCenter.y = (ac.getAtom(i).getPoint3d()).y - newCoord.y; ringCenter.z = (ac.getAtom(i).getPoint3d()).z - newCoord.z; ringCenter = AtomTetrahedralLigandPlacer3D.rotate(ringCenter, n1, angle); ac.getAtom(i).setPoint3d(new Point3d(ringCenter.x + newCoord.x, ringCenter.y + newCoord.y, ringCenter.z + newCoord.z)); } } Point3d pointRingCenter = GeometryUtil.get3DCenter(ac); double distance = 0; double rotAngleMax = 0; angle = 1 / 180 * Math.PI; ringCenter = new Vector3d(pointRingCenter.x, pointRingCenter.y, pointRingCenter.z); ringCenter.x = ringCenter.x - newCoord.x; ringCenter.y = ringCenter.y - newCoord.y; ringCenter.z = ringCenter.z - newCoord.z; for (int i = 1; i < 360; i++) { ringCenter = AtomTetrahedralLigandPlacer3D.rotate(ringCenter, axis, angle); if (centerPlacedMolecule.distance(new Point3d(ringCenter.x, ringCenter.y, ringCenter.z)) > distance) { rotAngleMax = i; distance = centerPlacedMolecule.distance(new Point3d(ringCenter.x, ringCenter.y, ringCenter.z)); } } rotAngleMax = (rotAngleMax / 180) * Math.PI; for (int i = 0; i < ac.getAtomCount(); i++) { if (!(ac.getAtom(i).getFlag(CDKConstants.ISPLACED))) { ringCenter.x = (ac.getAtom(i).getPoint3d()).x; ringCenter.y = (ac.getAtom(i).getPoint3d()).y; ringCenter.z = (ac.getAtom(i).getPoint3d()).z; ringCenter = AtomTetrahedralLigandPlacer3D.rotate(ringCenter, axis, rotAngleMax); ac.getAtom(i).setPoint3d(new Point3d(ringCenter.x, ringCenter.y, ringCenter.z)); ac.getAtom(i).setFlag(CDKConstants.ISPLACED, true); } } }
/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/ModelBuilder3D.java
robustness-copilot_data_378
/** * Access the neighbors of {@code element} as their indices. * * @param element tetrahedral element * @param map atom index lookup * @return the neighbors */ private int[] neighbors(ITetrahedralChirality element, Map<IAtom, Integer> map){ IAtom[] atoms = element.getLigands(); int[] vs = new int[atoms.length]; for (int i = 0; i < atoms.length; i++) vs[i] = map.get(atoms[i]); return vs; }
/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/StereoMatch.java
robustness-copilot_data_379
/** * Adds the cq:ReplicationStatus mixin if the node doesnt already have it or does have it as its jcr:supertype * already. * * @param node the node obj * @throws RepositoryException */ private void addReplicationStatusMixin(final Node node) throws RepositoryException{ if (!this.hasMixin(node, ReplicationStatus.NODE_TYPE) && node.canAddMixin(ReplicationStatus.NODE_TYPE)) { node.addMixin(ReplicationStatus.NODE_TYPE); } }
/bundle/src/main/java/com/adobe/acs/commons/replication/status/impl/ReplicationStatusManagerImpl.java
robustness-copilot_data_380
/** * Returns an Iterator for looping over all isotopes in this adduct formula. * * @return An Iterator with the isotopes in this adduct formula */ public Iterable<IIsotope> isotopes(){ return new Iterable<IIsotope>() { @Override public Iterator<IIsotope> iterator() { return isotopesList().iterator(); } }; }
/base/silent/src/main/java/org/openscience/cdk/silent/AdductFormula.java
robustness-copilot_data_381
/** * Create an instance of a {@link ValidationRule} which should result in an error should the evaluate of this rule fail. * * @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing). * @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>, * the evaluated instance will be considered "valid" according to this rule. * @param <T> The type of the object being evaluated. * * @return A new instance of a {@link ValidationRule} */ public static ValidationRule error(String failureMessage, Function<T, Result> fn){ return new ValidationRule(Severity.ERROR, null, failureMessage, (Function<Object, Result>) fn); }
/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/validation/ValidationRule.java
robustness-copilot_data_382
/** * Generate the OAuth2 Provider URL to be used in the login page link for the provider. * @param idpId Unique ID for the provider (used to lookup in authn service bean) * @param redirectPage page part of URL where we should be redirected after login (e.g. "dataverse.xhtml") * @return A generated link for the OAuth2 provider login */ public String linkFor(String idpId, String redirectPage){ AbstractOAuth2AuthenticationProvider idp = authenticationSvc.getOAuth2Provider(idpId); String state = createState(idp, toOption(redirectPage)); return idp.buildAuthzUrl(state, systemConfig.getOAuth2CallbackUrl()); }
/src/main/java/edu/harvard/iq/dataverse/authorization/providers/oauth2/OAuth2LoginBackingBean.java
robustness-copilot_data_383
/** * Splits the table into two stratified samples, this uses the specified column to divide the * table into groups, randomly assigning records to each according to the proportion given in * trainingProportion. * * @param column the column to be used for the stratified sampling * @param table1Proportion The proportion to go in the first table * @return An array two tables, with the first table having the proportion specified in the method * parameter, and the second table having the balance of the rows */ public Table[] stratifiedSampleSplit(CategoricalColumn<?> column, double table1Proportion){ Preconditions.checkArgument(containsColumn(column), "The categorical column must be part of the table, you can create a string column and add it to this table before sampling."); final Table first = emptyCopy(); final Table second = emptyCopy(); splitOn(column).asTableList().forEach(tab -> { Table[] splits = tab.sampleSplit(table1Proportion); first.append(splits[0]); second.append(splits[1]); }); return new Table[] { first, second }; }
/core/src/main/java/tech/tablesaw/api/Table.java
robustness-copilot_data_384
/** * Test whether we accept atom and it's connected bonds for inclusion in a * double bond configuration. This method checks for query bonds (up/down) * as well as double bond counts. If there is more then one double bond in * the connect bonds then it cannot have Z/E configuration. * * @param atom a double bonded atom * @param bonds all bonds connected to the atom * @return whether the atom is accepted for configuration */ static boolean accept(IAtom atom, List<IBond> bonds){ int dbCount = 0; if (!IAtomType.Hybridization.SP2.equals(atom.getHybridization())) return false; if (bonds.size() == 1) return false; for (IBond bond : bonds) { if (DOUBLE.equals(bond.getOrder())) dbCount++; IBond.Stereo stereo = bond.getStereo(); if (IBond.Stereo.UP_OR_DOWN.equals(stereo) || IBond.Stereo.UP_OR_DOWN_INVERTED.equals(stereo)) return false; } return dbCount == 1; }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricDoubleBondEncoderFactory.java
robustness-copilot_data_385
/** * Create a new Precondition subclass based on the given tag name. */ public Precondition create(String tagName){ Class<?> aClass = preconditions.get(tagName); if (aClass == null) { return null; } try { return (Precondition) aClass.getConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } }
/liquibase-core/src/main/java/liquibase/precondition/PreconditionFactory.java
robustness-copilot_data_386
/** * Initialize the surface, generating the points on the accessible surface * area of each atom as well as calculating the surface area of each atom. */ private void init(){ for (IAtom atom : atoms) { if (atom.getPoint3d() == null) throw new IllegalArgumentException("One or more atoms had no 3D coordinate set"); } Point3d cp = new Point3d(0, 0, 0); double maxRadius = 0; for (IAtom atom : atoms) { double vdwr = PeriodicTable.getVdwRadius(atom.getSymbol()); if (vdwr + solventRadius > maxRadius) maxRadius = PeriodicTable.getVdwRadius(atom.getSymbol()) + solventRadius; cp.x = cp.x + atom.getPoint3d().x; cp.y = cp.y + atom.getPoint3d().y; cp.z = cp.z + atom.getPoint3d().z; } cp.x = cp.x / atoms.length; cp.y = cp.y / atoms.length; cp.z = cp.z / atoms.length; Tessellate tess = new Tessellate("ico", tesslevel); tess.doTessellate(); logger.info("Got tesselation, number of triangles = " + tess.getNumberOfTriangles()); NeighborList nbrlist = new NeighborList(atoms, maxRadius + solventRadius); logger.info("Got neighbor list"); this.surfPoints = (List<Point3d>[]) new List[atoms.length]; this.areas = new double[atoms.length]; this.volumes = new double[atoms.length]; for (int i = 0; i < atoms.length; i++) { int pointDensity = tess.getNumberOfTriangles() * 3; Point3d[][] points = atomicSurfacePoints(nbrlist, i, atoms[i], tess); translatePoints(i, points, pointDensity, atoms[i], cp); } logger.info("Obtained points, areas and volumes"); }
/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/geometry/surface/NumericalSurface.java
robustness-copilot_data_387
/** * Returns all the groups that are in, of are ancestors of a group in * the passed group collection. * * @param groups * @return {@code groups} and their ancestors. */ public Set<Group> collectAncestors(Collection<Group> groups){ Set<Group> retVal = new HashSet<>(); Set<Group> perimeter = new HashSet<>(groups); while (!perimeter.isEmpty()) { Group next = perimeter.iterator().next(); retVal.add(next); perimeter.remove(next); explicitGroupService.findDirectlyContainingGroups(next).forEach(g -> { if (!retVal.contains(g)) { perimeter.add(g); } }); } return retVal; }
/src/main/java/edu/harvard/iq/dataverse/authorization/groups/GroupServiceBean.java
robustness-copilot_data_388
/** * Return the isotope pattern sorted by intensity * to the highest abundance. * * @param isotopeP The IsotopePattern object to sort * @return The IsotopePattern sorted */ public static IsotopePattern sortByIntensity(IsotopePattern isotopeP){ try { IsotopePattern isoSort = (IsotopePattern) isotopeP.clone(); if (isoSort.getNumberOfIsotopes() == 0) return isoSort; List<IsotopeContainer> listISO = isoSort.getIsotopes(); Collections.sort(listISO, new Comparator<IsotopeContainer>() { @Override public int compare(IsotopeContainer o1, IsotopeContainer o2) { return Double.compare(o2.getIntensity(), o1.getIntensity()); } }); isoSort.setMonoIsotope(listISO.get(0)); return isoSort; } catch (CloneNotSupportedException e) { e.printStackTrace(); } return null; }
/tool/formula/src/main/java/org/openscience/cdk/formula/IsotopePatternManipulator.java
robustness-copilot_data_389
/** * Processes a collection of {@link ExecutionEntity} instances, which form on execution tree. * All the executions share the same rootProcessInstanceId (which is provided). * The return value will be the root {@link ExecutionEntity} instance, with all child {@link ExecutionEntity} * instances populated and set using the {@link ExecutionEntity} instances from the provided collections */ protected ExecutionEntity processExecutionTree(String rootProcessInstanceId, List<ExecutionEntity> executions){ ExecutionEntity rootExecution = null; // Collect executions Map<String, ExecutionEntity> executionMap = new HashMap<String, ExecutionEntity>(executions.size()); for (ExecutionEntity executionEntity : executions) { if (executionEntity.getId().equals(rootProcessInstanceId)) { rootExecution = executionEntity; } executionMap.put(executionEntity.getId(), executionEntity); } // Set relationships for (ExecutionEntity executionEntity : executions) { // Root process instance relationship if (executionEntity.getRootProcessInstanceId() != null) { executionEntity.setRootProcessInstance(executionMap.get(executionEntity.getRootProcessInstanceId())); } // Process instance relationship if (executionEntity.getProcessInstanceId() != null) { executionEntity.setProcessInstance(executionMap.get(executionEntity.getProcessInstanceId())); } // Parent - child relationship if (executionEntity.getParentId() != null) { ExecutionEntity parentExecutionEntity = executionMap.get(executionEntity.getParentId()); executionEntity.setParent(parentExecutionEntity); parentExecutionEntity.addChildExecution(executionEntity); } // Super - sub execution relationship if (executionEntity.getSuperExecution() != null) { ExecutionEntity superExecutionEntity = executionMap.get(executionEntity.getSuperExecutionId()); executionEntity.setSuperExecution(superExecutionEntity); superExecutionEntity.setSubProcessInstance(executionEntity); } } return rootExecution; }
/activiti-core/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/ExecutionEntityManagerImpl.java
robustness-copilot_data_390
/** * Test if the MII domain wants to use online update. * * @return true if using online update */ boolean isUseOnlineUpdate(){ return Optional.ofNullable(configuration).map(Configuration::getModel).map(Model::getOnlineUpdate).map(OnlineUpdate::getEnabled).orElse(false); }
/operator/src/main/java/oracle/kubernetes/weblogic/domain/model/DomainSpec.java
robustness-copilot_data_391
/** * If cachedBytes are not null, returns a Reader created from the cachedBytes. Otherwise, returns * a Reader from the underlying source. */ public Reader createReader(byte[] cachedBytes) throws IOException{ if (cachedBytes != null) { return charset != null ? new InputStreamReader(new ByteArrayInputStream(cachedBytes), charset) : new InputStreamReader(new ByteArrayInputStream(cachedBytes)); } if (inputStream != null) { return new InputStreamReader(inputStream, charset); } if (reader != null) { return reader; } return new InputStreamReader(new FileInputStream(file), charset); }
/core/src/main/java/tech/tablesaw/io/Source.java
robustness-copilot_data_392
/** * Create a new encoder for the specified left and right atoms. The parent * is the atom which is connected by a double bond to the left and right * atom. For simple double bonds the parent of each is the other atom, in * cumulenes the parents are not the same. * * @param container the molecule * @param left the left atom * @param leftParent the left atoms parent (usually {@literal right}) * @param right the right atom * @param rightParent the right atoms parent (usually {@literal left}) * @param graph adjacency list representation of the molecule * @return a stereo encoder (or null) */ static StereoEncoder newEncoder(IAtomContainer container, IAtom left, IAtom leftParent, IAtom right, IAtom rightParent, int[][] graph){ List<IBond> leftBonds = container.getConnectedBondsList(left); List<IBond> rightBonds = container.getConnectedBondsList(right); if (accept(left, leftBonds) && accept(right, rightBonds)) { int leftIndex = container.indexOf(left); int rightIndex = container.indexOf(right); int leftParentIndex = container.indexOf(leftParent); int rightParentIndex = container.indexOf(rightParent); int[] leftNeighbors = moveToBack(graph[leftIndex], leftParentIndex); int[] rightNeighbors = moveToBack(graph[rightIndex], rightParentIndex); int l1 = leftNeighbors[0]; int l2 = leftNeighbors[1] == leftParentIndex ? leftIndex : leftNeighbors[1]; int r1 = rightNeighbors[0]; int r2 = rightNeighbors[1] == rightParentIndex ? rightIndex : rightNeighbors[1]; GeometricParity geometric = geometric(container, leftIndex, rightIndex, l1, l2, r1, r2); if (geometric != null) { return new GeometryEncoder(new int[] { leftIndex, rightIndex }, new CombinedPermutationParity(permutation(leftNeighbors), permutation(rightNeighbors)), geometric); } } return null; }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricDoubleBondEncoderFactory.java
robustness-copilot_data_393
/** * Create the charge adjunct text for the specified charge and number of unpaired electrons. * * @param charge formal charge * @param unpaired number of unpaired electrons * @return adjunct text */ static String chargeAdjunctText(final int charge, final int unpaired){ StringBuilder sb = new StringBuilder(); if (unpaired == 1) { if (charge != 0) { sb.append('(').append(BULLET).append(')'); } else { sb.append(BULLET); } } else if (unpaired > 1) { if (charge != 0) { sb.append('(').append(unpaired).append(BULLET).append(')'); } else { sb.append(unpaired).append(BULLET); } } final char sign = charge < 0 ? MINUS : PLUS; final int coefficient = Math.abs(charge); if (coefficient > 1) sb.append(coefficient); if (coefficient > 0) sb.append(sign); return sb.toString(); }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardAtomGenerator.java
robustness-copilot_data_394
/** * Generates a random float between {@code -range} and {@code range}. * * @param range the bounds of the random float. * @return A randomly generated float. */ public static float randomReal(float range){ ThreadLocalRandom rand = ThreadLocalRandom.current(); return (2.0F * rand.nextFloat() - 1.0F) * range; }
/src/main/java/net/glowstone/util/SoundUtil.java
robustness-copilot_data_395
/** * Apache and Nginx default to legacy CGI behavior in which header with underscore are ignored. Raise this for awareness to the user. * * @param parameter Any spec doc parameter. The method will handle {@link HeaderParameter} evaluation. * @return {@link ValidationRule.Pass} if the check succeeds, otherwise {@link ValidationRule.Fail} with details "[key] contains an underscore." */ private static ValidationRule.Result apacheNginxHeaderCheck(ParameterWrapper parameterWrapper){ Parameter parameter = parameterWrapper.getParameter(); if (parameter == null || !"header".equals(parameter.getIn())) return ValidationRule.Pass.empty(); ValidationRule.Result result = ValidationRule.Pass.empty(); String headerName = parameter.getName(); if (StringUtils.isNotEmpty(headerName) && StringUtils.contains(headerName, '_')) { result = new ValidationRule.Fail(); result.setDetails(String.format(Locale.ROOT, "%s contains an underscore.", headerName)); } return result; }
/modules/openapi-generator/src/main/java/org/openapitools/codegen/validations/oas/OpenApiParameterValidations.java
robustness-copilot_data_396
/** * Disables an index, so it's no longer updated by Oak. * * @param oakIndex the index * @throws PersistenceException */ public void disableIndex(@Nonnull Resource oakIndex) throws PersistenceException{ final ModifiableValueMap oakIndexProperties = oakIndex.adaptTo(ModifiableValueMap.class); oakIndexProperties.put(PN_TYPE, DISABLED); log.info("Disabled index at {}", oakIndex.getPath()); }
/bundle/src/main/java/com/adobe/acs/commons/oak/impl/EnsureOakIndexJobHandler.java
robustness-copilot_data_397
/** * Adds a {@link HealthCheckRegistryListener} to a collection of listeners that will be notified on health check * registration. Listeners will be notified in the order in which they are added. The listener will be notified of all * existing health checks when it first registers. * * @param listener listener to add */ public void addListener(HealthCheckRegistryListener listener){ listeners.add(listener); for (Map.Entry<String, HealthCheck> entry : healthChecks.entrySet()) { listener.onHealthCheckAdded(entry.getKey(), entry.getValue()); } }
/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java
robustness-copilot_data_398
/** * Factory method that should be used to construct instances. * For some common cases, can reuse canonical instances: currently * this is the case for empty Strings, in future possible for * others as well. If null is passed, will return null. * * @return Resulting {@link TextNode} object, if <b>v</b> * is NOT null; null if it is. */ public static TextNode valueOf(String v){ if (v == null) { return null; } if (v.isEmpty()) { return EMPTY_STRING_NODE; } return new TextNode(v); }
/src/main/java/com/fasterxml/jackson/databind/node/TextNode.java
robustness-copilot_data_399
/** * Projects a CDKRGraph bitset on the source graph G2. * @param set CDKRGraph BitSet to project * @return The associate BitSet in G2 */ public BitSet projectG2(BitSet set){ BitSet projection = new BitSet(getSecondGraphSize()); CDKRNode xNode = null; for (int x = set.nextSetBit(0); x >= 0; x = set.nextSetBit(x + 1)) { xNode = getGraph().get(x); projection.set(xNode.getRMap().getId2()); } return projection; }
/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKRGraph.java
robustness-copilot_data_400
/** * Check if a ring in a ring set is a macro cycle. We define this as a * ring with >= 10 atom and has at least one bond that isn't contained * in any other rings. * * @param ring ring to check * @param rs rest of ring system * @return ring is a macro cycle */ private boolean isMacroCycle(IRing ring, IRingSet rs){ if (ring.getAtomCount() < 8) return false; for (IBond bond : ring.bonds()) { boolean found = false; for (IAtomContainer other : rs.atomContainers()) { if (ring == other) continue; if (other.contains(bond)) { found = true; break; } } if (!found) return true; } return false; }
/tool/sdg/src/main/java/org/openscience/cdk/layout/StructureDiagramGenerator.java