id
stringlengths
25
27
content
stringlengths
190
15.4k
max_stars_repo_path
stringlengths
31
217
robustness-copilot_data_701
/** * Writes the fields of the given node into the generator. */ private void writeFieldsOfNode(JsonGenerator generator, JsonNode node) throws IOException{ if (node != null) { for (Iterator<Entry<String, JsonNode>> fields = node.fields(); fields.hasNext(); ) { Entry<String, JsonNode> field = fields.next(); generator.writeFieldName(field.getKey()); generator.writeTree(field.getValue()); } } }
/src/main/java/net/logstash/logback/composite/GlobalCustomFieldsJsonProvider.java
robustness-copilot_data_702
/** * Method to deal with distance calculation when only the x and y-components * of the coordinates are used. The elevation (z component) is ignored, * whether it is available or not. * (xy-plane) * @param coord * @param other * @return */ public static double calcProjectedEuclideanDistance(Coord coord, Coord other){ double xDiff = other.getX() - coord.getX(); double yDiff = other.getY() - coord.getY(); return Math.sqrt((xDiff * xDiff) + (yDiff * yDiff)); }
/matsim/src/main/java/org/matsim/core/utils/geometry/CoordUtils.java
robustness-copilot_data_703
/** * Create the port alias and attach it to the process. * * @param userId the name of the calling user * @param portAlias the port alias values * @param processGUID the unique identifier of the process * @param externalSourceName the unique name of the external source * * @return unique identifier of the port alias in the repository * * @throws InvalidParameterException the bean properties are invalid * @throws UserNotAuthorizedException user not authorized to issue this request * @throws PropertyServerException problem accessing the property server */ public String createPortAlias(String userId, PortAlias portAlias, String processGUID, String externalSourceName) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException{ return createPort(userId, portAlias, PORT_ALIAS_TYPE_NAME, processGUID, externalSourceName); }
/open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEnginePortHandler.java
robustness-copilot_data_704
/** * Private method that actually parses the input to read a ChemFile * object. * * Each PMP frame is stored as a Crystal in a ChemModel. The PMP * file is stored as a ChemSequence of ChemModels. * * @return A ChemFile containing the data parsed from input. */ private IChemFile readChemFile(IChemFile chemFile){ IChemSequence chemSequence; IChemModel chemModel; ICrystal crystal; try { String line = readLine(); while (input.ready() && line != null) { if (line.startsWith("%%Header Start")) { while (input.ready() && line != null && !(line.startsWith("%%Header End"))) { if (line.startsWith("%%Version Number")) { String version = readLine().trim(); if (!version.equals("3.00")) { logger.error("The PMPReader only supports PMP files with version 3.00"); return null; } } line = readLine(); } } else if (line.startsWith("%%Model Start")) { modelStructure = chemFile.getBuilder().newInstance(IAtomContainer.class); while (input.ready() && line != null && !(line.startsWith("%%Model End"))) { Matcher objHeaderMatcher = objHeader.matcher(line); if (objHeaderMatcher.matches()) { String object = objHeaderMatcher.group(2); constructObject(chemFile.getBuilder(), object); int id = Integer.parseInt(objHeaderMatcher.group(1)); line = readLine(); while (input.ready() && line != null && !(line.trim().equals(")"))) { Matcher objCommandMatcher = objCommand.matcher(line); objHeaderMatcher = objHeader.matcher(line); if (objHeaderMatcher.matches()) { object = objHeaderMatcher.group(2); id = Integer.parseInt(objHeaderMatcher.group(1)); constructObject(chemFile.getBuilder(), object); } else if (objCommandMatcher.matches()) { String format = objCommandMatcher.group(1); String command = objCommandMatcher.group(2); String field = objCommandMatcher.group(3); processModelCommand(object, command, format, field); } else { logger.warn("Skipping line: " + line); } line = readLine(); } if (chemObject instanceof IAtom) { atomids.put(id, modelStructure.getAtomCount()); atomGivenIds.put(Integer.valueOf((String) chemObject.getProperty(PMP_ID)), id); modelStructure.addAtom((IAtom) chemObject); } else if (chemObject instanceof IBond) { } else { logger.error("chemObject is not initialized or of bad class type"); } } line = readLine(); } assert line != null; if (line.startsWith("%%Model End")) { int bondsFound = bondids.size(); logger.debug("Found #bonds: ", bondsFound); logger.debug("#atom ones: ", bondAtomOnes.size()); logger.debug("#atom twos: ", bondAtomTwos.size()); logger.debug("#orders: ", bondOrders.size()); for (Integer index : bondids.keySet()) { double order = (bondOrders.get(index) != null ? bondOrders.get(index) : 1.0); logger.debug("index: ", index); logger.debug("ones: ", bondAtomOnes.get(index)); IAtom atom1 = modelStructure.getAtom(atomids.get(bondAtomOnes.get(index))); IAtom atom2 = modelStructure.getAtom(atomids.get(bondAtomTwos.get(index))); IBond bond = modelStructure.getBuilder().newInstance(IBond.class, atom1, atom2); if (order == 1.0) { bond.setOrder(IBond.Order.SINGLE); } else if (order == 2.0) { bond.setOrder(IBond.Order.DOUBLE); } else if (order == 3.0) { bond.setOrder(IBond.Order.TRIPLE); } else if (order == 4.0) { bond.setOrder(IBond.Order.QUADRUPLE); } modelStructure.addBond(bond); } } } else if (line.startsWith("%%Traj Start")) { chemSequence = chemFile.getBuilder().newInstance(IChemSequence.class); double energyFragment = 0.0; double energyTotal = 0.0; int Z = 1; while (input.ready() && line != null && !(line.startsWith("%%Traj End"))) { if (line.startsWith("%%Start Frame")) { chemModel = chemFile.getBuilder().newInstance(IChemModel.class); crystal = chemFile.getBuilder().newInstance(ICrystal.class); while (input.ready() && line != null && !(line.startsWith("%%End Frame"))) { if (line.startsWith("%%Atom Coords")) { if (energyFragment != 0.0 && energyTotal != 0.0) { Z = (int) Math.round(energyTotal / energyFragment); logger.debug("Z derived from energies: ", Z); } int expatoms = modelStructure.getAtomCount(); for (int molCount = 1; molCount <= Z; molCount++) { IAtomContainer clone = modelStructure.getBuilder().newInstance(IAtomContainer.class); for (int i = 0; i < expatoms; i++) { line = readLine(); IAtom a = clone.getBuilder().newInstance(IAtom.class); StringTokenizer st = new StringTokenizer(line, " "); a.setPoint3d(new Point3d(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()))); a.setCovalentRadius(0.6); IAtom modelAtom = modelStructure.getAtom(atomids.get(atomGivenIds.get(i + 1))); a.setSymbol(modelAtom.getSymbol()); clone.addAtom(a); } rebonder.rebond(clone); crystal.add(clone); } } else if (line.startsWith("%%E/Frag")) { line = readLine().trim(); energyFragment = Double.parseDouble(line); } else if (line.startsWith("%%Tot E")) { line = readLine().trim(); energyTotal = Double.parseDouble(line); } else if (line.startsWith("%%Lat Vects")) { StringTokenizer st; line = readLine(); st = new StringTokenizer(line, " "); crystal.setA(new Vector3d(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()))); line = readLine(); st = new StringTokenizer(line, " "); crystal.setB(new Vector3d(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()))); line = readLine(); st = new StringTokenizer(line, " "); crystal.setC(new Vector3d(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()))); } else if (line.startsWith("%%Space Group")) { line = readLine().trim(); if ("P 21 21 21 (1)".equals(line)) { crystal.setSpaceGroup("P 2_1 2_1 2_1"); } else { crystal.setSpaceGroup("P1"); } } line = readLine(); } chemModel.setCrystal(crystal); chemSequence.addChemModel(chemModel); } line = readLine(); } chemFile.addChemSequence(chemSequence); } line = readLine(); } } catch (IOException e) { logger.error("An IOException happened: ", e.getMessage()); logger.debug(e); chemFile = null; } catch (CDKException e) { logger.error("An CDKException happened: ", e.getMessage()); logger.debug(e); chemFile = null; } return chemFile; }
/storage/io/src/main/java/org/openscience/cdk/io/PMPReader.java
robustness-copilot_data_705
/** * Destroys this entity by removing it from the world and marking it as not being active. */ public void remove(){ removed = true; active = false; boundingBox = null; world.getEntityManager().unregister(this); server.getEntityIdManager().deallocate(this); this.setPassenger(null); leaveVehicle(); ImmutableList.copyOf(this.leashedEntities).forEach(e -> unleash(e, UnleashReason.HOLDER_GONE)); if (isLeashed()) { unleash(this, UnleashReason.HOLDER_GONE); } }
/src/main/java/net/glowstone/entity/GlowEntity.java
robustness-copilot_data_706
/** * Obtain the permutation parity (-1,0,+1) to put the ligands in descending * order (highest first). A parity of 0 indicates two or more ligands were * equivalent. * * @param ligands the ligands to sort * @return parity, odd (-1), even (+1) or none (0) */ private static int permParity(final ILigand[] ligands){ int swaps = 0; for (int j = 1, hi = ligands.length; j < hi; j++) { ILigand ligand = ligands[j]; int i = j - 1; int cmp = 0; while ((i >= 0) && (cmp = cipRule.compare(ligand, ligands[i])) > 0) { ligands[i + 1] = ligands[i--]; swaps++; } if (cmp == 0) return 0; ligands[i + 1] = ligand; } return (swaps & 0x1) == 0x1 ? -1 : +1; }
/descriptor/cip/src/main/java/org/openscience/cdk/geometry/cip/CIPTool.java
robustness-copilot_data_707
/** * Hydrogen atom types are assigned based on their parent types. The mmff-symb-mapping file * provides this mapping. * * @param hdefIn input stream of mmff-symb-mapping.tsv * @return mapping of parent to hydrogen definitions * @throws IOException */ private Map<String, String> loadHydrogenDefinitions(InputStream hdefIn) throws IOException{ final Map<String, String> hdefs = new HashMap<String, String>(200); BufferedReader br = new BufferedReader(new InputStreamReader(hdefIn)); br.readLine(); String line = null; while ((line = br.readLine()) != null) { String[] cols = line.split("\t"); hdefs.put(cols[0].trim(), cols[3].trim()); } return hdefs; }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAtomTypeMatcher.java
robustness-copilot_data_708
/** * Returns a map from appenders to levels for a logger. * <p> * The map contains the effective log levels, that is, the levels used for filtering log * events. */ private synchronized Map<String, Level> computeEffectiveMap(LoggerName logger){ Map<String, Level> inheritedMap = getInheritedMap(logger); if (!isRoot(logger)) { LoggerName parent = logger.getParent(); if (parent != null) { Map<String, Level> mergedMap = computeEffectiveMap(parent); mergedMap.putAll(inheritedMap); return mergedMap; } } return inheritedMap; }
/modules/cells/src/main/java/dmg/util/logback/FilterThresholdSet.java
robustness-copilot_data_709
/** * Removes all isotopes from a given element in the MolecularFormula. * * @param formula IMolecularFormula molecularFormula * @param element The IElement of the IIsotopes to be removed * @return The molecularFormula with the isotopes removed */ public static IMolecularFormula removeElement(IMolecularFormula formula, IElement element){ for (IIsotope isotope : getIsotopes(formula, element)) { formula.removeIsotope(isotope); } return formula; }
/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
robustness-copilot_data_710
/** * Adds or replaces a list subtag with a list of doubles. * * @param key the key to write to * @param list the list contents as doubles, to convert to double tags */ public void putDoubleList(@NonNls String key, List<Double> list){ putList(key, TagType.DOUBLE, list, DoubleTag::new); }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_711
/** * True, if the MolecularFormula contains the given IIsotope object and not * the instance. The method looks for other isotopes which has the same * symbol, natural abundance and exact mass. * * @param isotope The IIsotope this MolecularFormula is searched for * @return True, if the MolecularFormula contains the given isotope object */ public boolean contains(IIsotope isotope){ for (IIsotope thisIsotope : isotopes()) { if (isTheSame(thisIsotope, isotope)) { return true; } } return false; }
/base/data/src/main/java/org/openscience/cdk/formula/MolecularFormula.java
robustness-copilot_data_712
/** * Parses the pattern into a {@link NodeWriter}. * * @return a {@link NodeWriter} * @throws JsonPatternException thrown in case of invalid pattern */ private NodeWriter<Event> initializeNodeWriter() throws JsonPatternException{ AbstractJsonPatternParser<Event> parser = createParser(this.jsonFactory); parser.setOmitEmptyFields(omitEmptyFields); return parser.parse(pattern); }
/src/main/java/net/logstash/logback/composite/AbstractPatternJsonProvider.java
robustness-copilot_data_713
/** * Method for constructing a new instance with configuration that * updates passed Object (as root value), instead of constructing * a new value. *<p> * Note that the method does NOT change state of this reader, but * rather construct and returns a newly configured instance. */ public ObjectReader withValueToUpdate(Object value){ if (value == _valueToUpdate) return this; if (value == null) { return _new(this, _config, _valueType, _rootDeserializer, null, _schema, _injectableValues, _dataFormatReaders); } JavaType t; if (_valueType == null) { t = _config.constructType(value.getClass()); } else { t = _valueType; } return _new(this, _config, t, _rootDeserializer, value, _schema, _injectableValues, _dataFormatReaders); }
/src/main/java/com/fasterxml/jackson/databind/ObjectReader.java
robustness-copilot_data_714
/** * Returns a list of the vertices contained in this cycle. * The vertices are in the order of a traversal of the cycle. * * @return a list of the vertices contained in this cycle */ public List vertexList(){ List vertices = new ArrayList(edgeSet().size()); Object startVertex = vertexSet().iterator().next(); Object vertex = startVertex; Object previousVertex = null; Object nextVertex = null; while (nextVertex != startVertex) { assert (degreeOf(vertex) == 2); List edges = edgesOf(vertex); vertices.add(vertex); Edge edge = (Edge) edges.get(0); nextVertex = edge.oppositeVertex(vertex); if (nextVertex == previousVertex) { edge = (Edge) edges.get(1); nextVertex = edge.oppositeVertex(vertex); } previousVertex = vertex; vertex = nextVertex; } return vertices; }
/legacy/src/main/java/org/openscience/cdk/ringsearch/cyclebasis/SimpleCycle.java
robustness-copilot_data_715
/** * Create the oak index based on the ensure definition. * * @param ensuredDefinition the ensure definition * @param oakIndexes the parent oak index folder * @return the updated oak index resource * @throws PersistenceException * @throws RepositoryException */ public Resource create(@Nonnull final Resource ensuredDefinition, @Nonnull final Resource oakIndexes) throws RepositoryException{ final Node oakIndex = JcrUtil.copy(ensuredDefinition.adaptTo(Node.class), oakIndexes.adaptTo(Node.class), ensuredDefinition.getName()); oakIndex.setPrimaryType(NT_OAK_QUERY_INDEX_DEFINITION); oakIndex.setProperty(JcrConstants.JCR_CREATED, Calendar.getInstance()); oakIndex.setProperty(JcrConstants.JCR_CREATED_BY, ENSURE_OAK_INDEX_USER_NAME); log.info("Created Oak Index at [ {} ] with Ensure Definition [ {} ]", oakIndex.getPath(), ensuredDefinition.getPath()); return ensuredDefinition.getResourceResolver().getResource(oakIndex.getPath()); }
/bundle/src/main/java/com/adobe/acs/commons/oak/impl/EnsureOakIndexJobHandler.java
robustness-copilot_data_716
/** * Test a permutation to see if it is in the group. Note that this also * alters the permutation passed in. * * @param permutation the one to test * @return the position it should be in the group, if any */ public int test(Permutation permutation){ for (int i = 0; i < size; i++) { int x = permutation.get(base.get(i)); Permutation h = permutations[i][x]; if (h == null) { return i; } else { permutation.setTo(h.invert().multiply(permutation)); } } return size; }
/tool/group/src/main/java/org/openscience/cdk/group/PermutationGroup.java
robustness-copilot_data_717
/** * Create a {@link CoordinatorRegistryCenter} or return the existing one if there is one set up with the same {@code connectionString}, {@code namespace} and {@code digest} already. * * @param connectString registry center connect string * @param namespace registry center namespace * @param digest registry center digest * @return registry center */ public static CoordinatorRegistryCenter createCoordinatorRegistryCenter(final String connectString, final String namespace, final String digest){ Hasher hasher = Hashing.sha256().newHasher().putString(connectString, StandardCharsets.UTF_8).putString(namespace, StandardCharsets.UTF_8); if (!Strings.isNullOrEmpty(digest)) { hasher.putString(digest, StandardCharsets.UTF_8); } HashCode hashCode = hasher.hash(); return REG_CENTER_REGISTRY.computeIfAbsent(hashCode, unused -> { CoordinatorRegistryCenter result = newCoordinatorRegistryCenter(connectString, namespace, digest); result.init(); return result; }); }
/elasticjob-lite/elasticjob-lite-lifecycle/src/main/java/org/apache/shardingsphere/elasticjob/lite/lifecycle/internal/reg/RegistryCenterFactory.java
robustness-copilot_data_718
/** * Build a new StatePath that points to the same location from the immediate child's * point-of-view. For example, if the current path is characterised as <tt>aa.bb.cc</tt>, then * the returned StatePath is characterised by <tt>bb.cc</tt>. * <p> * If the path has no children of children, null is returned. * * @return the path for the child element, or null if there is no child. */ public StatePath childPath(){ if (_elements == null || _elements.size() <= 1) { return null; } return new StatePath(_elements.subList(1, _elements.size()), _elements.size() - 1); }
/modules/dcache-info/src/main/java/org/dcache/services/info/base/StatePath.java
robustness-copilot_data_719
/** * Create a dynamic server config using server template and index number of this server. * * @param name Name of the server * @param index index of this server within the cluster, for example, the index of dserver-2 would * be 2 * @param clusterName name of the WLS cluster that this server belongs to * @param domainName name of the WLS domain that this server belongs to * @param calculatedListenPorts whether listen ports are calculated according to configuration in * the dynamic cluster * @param serverTemplate server template used for servers in the dynamic cluster * @return a dynamic server configuration object containing configuration of this dynamic server */ static WlsDynamicServerConfig create(String name, int index, String clusterName, String domainName, boolean calculatedListenPorts, WlsServerConfig serverTemplate){ Integer listenPort = serverTemplate.getListenPort(); Integer sslListenPort = serverTemplate.getSslListenPort(); List<NetworkAccessPoint> networkAccessPoints = new ArrayList<>(); if (serverTemplate.getNetworkAccessPoints() != null) { for (NetworkAccessPoint networkAccessPoint : serverTemplate.getNetworkAccessPoints()) { Integer networkAccessPointListenPort = networkAccessPoint.getListenPort(); if (calculatedListenPorts) { networkAccessPointListenPort = networkAccessPointListenPort == null ? (DEFAULT_NAP_LISTEN_PORT_RANGE_BASE + index) : networkAccessPointListenPort + index; } networkAccessPoints.add(new NetworkAccessPoint(networkAccessPoint.getName(), networkAccessPoint.getProtocol(), networkAccessPointListenPort, networkAccessPoint.getPublicPort())); } } // calculate listen ports if configured to do so if (calculatedListenPorts) { listenPort = (listenPort == null) ? (DEFAULT_LISTEN_PORT_RANGE_BASE + index) : (listenPort + index); sslListenPort = (sslListenPort == null) ? (DEFAULT_SSL_LISTEN_PORT_RANGE_BASE + index) : (sslListenPort + index); } MacroSubstitutor macroSubstitutor = new MacroSubstitutor(index, name, clusterName, domainName, serverTemplate.getMachineName()); return new WlsDynamicServerConfig(name, listenPort, macroSubstitutor.substituteMacro(serverTemplate.getListenAddress()), sslListenPort, macroSubstitutor.substituteMacro(serverTemplate.getMachineName()), serverTemplate.getAdminPort(), networkAccessPoints); }
/operator/src/main/java/oracle/kubernetes/operator/wlsconfig/WlsDynamicServerConfig.java
robustness-copilot_data_720
/** * For links with unknown max speed we assume that links with a length of less than 300m are urban links. For urban * links with a length of 0m the speed is 10km/h. For links with a length of 300m the speed is the default freespeed * property for that highway type. For links with a length between 0 and 300m the speed is interpolated linearly. * (2.778m/s ~ 10km/h) * * All links longer than 300m the default freesped property is assumed */ public static double calculateSpeedIfNoSpeedTag(double linkLength, LinkProperties properties){ if (properties.hierarchyLevel > LinkProperties.LEVEL_MOTORWAY && properties.hierarchyLevel <= LinkProperties.LEVEL_TERTIARY && linkLength <= 300) { return ((2.7778 + (properties.freespeed - 2.7778) / 300 * linkLength)); } return properties.freespeed; }
/contribs/osm/src/main/java/org/matsim/contrib/osm/networkReader/LinkProperties.java
robustness-copilot_data_721
/** * This function takes a path and tries to find the file in the file system or * in the resource path. The order of resolution is as follows: * * <ol> * <li>Find path in file system</li> * <li>Find path in file system with compression extension (e.g. *.gz)</li> * <li>Find path in class path as resource</li> * <li>Find path in class path with compression extension</li> * </ol> * * In case the filename is a URL (i.e. starting with "file:" or "jar:file:"), * then no resolution is done but the provided filename returned as URL. * * @throws UncheckedIOException */ public static URL resolveFileOrResource(String filename) throws UncheckedIOException{ try { // I) do not handle URLs if (filename.startsWith("jar:file:") || filename.startsWith("file:") || filename.startsWith("https:")) { // looks like an URI return new URL(filename); } // II) Replace home identifier if (filename.startsWith("~" + File.separator)) { filename = System.getProperty("user.home") + filename.substring(1); } // III.1) First, try to find the file in the file system File file = new File(filename); if (file.exists()) { logger.info(String.format("Resolved %s to %s", filename, file)); return file.toURI().toURL(); } // III.2) Try to find file with an additional postfix for compression for (String postfix : COMPRESSION_EXTENSIONS.keySet()) { file = new File(filename + "." + postfix); if (file.exists()) { logger.info(String.format("Resolved %s to %s", filename, file)); return file.toURI().toURL(); } } // IV.1) First, try to find the file in the class path URL resource = IOUtils.class.getClassLoader().getResource(filename); if (resource != null) { logger.info(String.format("Resolved %s to %s", filename, resource)); return resource; } // IV.2) Second, try to find the resource with a compression extension for (String postfix : COMPRESSION_EXTENSIONS.keySet()) { resource = IOUtils.class.getClassLoader().getResource(filename + "." + postfix); if (resource != null) { logger.info(String.format("Resolved %s to %s", filename, resource)); return resource; } } throw new FileNotFoundException(filename); } catch (FileNotFoundException | MalformedURLException e) { throw new UncheckedIOException(e); } }
/matsim/src/main/java/org/matsim/core/utils/io/IOUtils.java
robustness-copilot_data_722
/** * Adds a Molecule to the list of templates use by this TemplateHandler. * * @param molecule The molecule to be added to the TemplateHandler */ public void addMolecule(IAtomContainer molecule){ if (!GeometryUtil.has2DCoordinates(molecule)) throw new IllegalArgumentException("Template did not have 2D coordinates"); GeometryUtil.scaleMolecule(molecule, GeometryUtil.getScaleFactor(molecule, StructureDiagramGenerator.DEFAULT_BOND_LENGTH)); templates.add(molecule); anonPatterns.add(VentoFoggia.findSubstructure(molecule, anonAtomMatcher, anonBondMatcher)); elemPatterns.add(VentoFoggia.findSubstructure(molecule, elemAtomMatcher, anonBondMatcher)); }
/tool/sdg/src/main/java/org/openscience/cdk/layout/TemplateHandler.java
robustness-copilot_data_723
/** * Return true if the specified 'schema' is an object that can be extended with additional properties. * Additional properties means a Schema should support all explicitly defined properties plus any * undeclared properties. * * A MapSchema differs from an ObjectSchema in the following way: * - An ObjectSchema is not extensible, i.e. it has a fixed number of properties. * - A MapSchema is an object that can be extended with an arbitrary set of properties. * The payload may include dynamic properties. * * Note that isMapSchema returns true for a composed schema (allOf, anyOf, oneOf) that also defines * additionalproperties. * * For example, an OpenAPI schema is considered a MapSchema in the following scenarios: * * type: object * additionalProperties: true * * type: object * additionalProperties: * type: object * properties: * code: * type: integer * * allOf: * - $ref: '#/components/schemas/Class1' * - $ref: '#/components/schemas/Class2' * additionalProperties: true * * @param schema the OAS schema * @return true if the specified schema is a Map schema. */ public static boolean isMapSchema(Schema schema){ if (schema instanceof MapSchema) { return true; } if (schema == null) { return false; } if (schema.getAdditionalProperties() instanceof Schema) { return true; } if (schema.getAdditionalProperties() instanceof Boolean && (Boolean) schema.getAdditionalProperties()) { return true; } return false; }
/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java
robustness-copilot_data_724
/** * Sort the {@code indices}, which correspond to an index in the {@code atoms} array in * clockwise order. * * @param indices indices, 0 to n * @param focus the central atom * @param atoms the neighbors of the focus * @param n the number of neighbors * @return the permutation parity of the sort */ private int sortClockwise(int[] indices, IAtom focus, IAtom[] atoms, int n){ int x = 0; for (int j = 1; j < n; j++) { int v = indices[j]; int i = j - 1; while ((i >= 0) && less(v, indices[i], atoms, focus.getPoint2d())) { indices[i + 1] = indices[i--]; x++; } indices[i + 1] = v; } return indexParity(x); }
/tool/sdg/src/main/java/org/openscience/cdk/layout/NonplanarBonds.java
robustness-copilot_data_725
/** * Open a regular property file (not embedded in a resource - use {@link #parseDefaultPropertyFileFromResource} * for that) and parse it. * * @param potentialPropertyFile path and file name to the the property file * @throws IOException if the file cannot be opened * @throws CommandLineParsingException if an error occurs during parsing */ private void parseDefaultPropertyFileFromFile(File potentialPropertyFile) throws IOException, CommandLineParsingException{ try (FileInputStream stream = new FileInputStream(potentialPropertyFile)) { parsePropertiesFile(stream); } }
/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java
robustness-copilot_data_726
/** * Inserts the given Node n into the pendingNodes queue and updates its time and cost information. * * @param n The Node that is revisited. * @param data The data for node. * @param pendingNodes The nodes visited and not processed yet. * @param time The time of the visit of n. * @param cost The accumulated cost at the time of the visit of n. * @param expectedRemainingCost The expected remaining travel cost when * traveling from n to the target node of the route. * @param outLink The link from which we came visiting n. */ private void visitNode(final Node n, final AStarNodeData data, final RouterPriorityQueue<Node> pendingNodes, final double time, final double cost, final double expectedRemainingCost, final Link outLink){ data.setExpectedRemainingCost(expectedRemainingCost); super.visitNode(n, data, pendingNodes, time, cost, outLink); }
/matsim/src/main/java/org/matsim/core/router/AStarEuclidean.java
robustness-copilot_data_727
/** * Find a specific mail domain group by it's alias. * @param groupAlias * @return */ Optional<MailDomainGroup> findByAlias(String groupAlias){ try { return Optional.of(em.createNamedQuery("MailDomainGroup.findByPersistedGroupAlias", MailDomainGroup.class).setParameter("persistedGroupAlias", groupAlias).getSingleResult()); } catch (NoResultException nre) { return Optional.empty(); } }
/src/main/java/edu/harvard/iq/dataverse/authorization/groups/impl/maildomain/MailDomainGroupServiceBean.java
robustness-copilot_data_728
/** * Adds a {@link MetricRegistryListener} to a collection of listeners that will be notified on * metric creation. Listeners will be notified in the order in which they are added. * <p> * <b>N.B.:</b> The listener will be notified of all existing metrics when it first registers. * * @param listener the listener that will be notified */ public void addListener(MetricRegistryListener listener){ listeners.add(listener); for (Map.Entry<MetricName, Metric> entry : metrics.entrySet()) { notifyListenerOfAddedMetric(listener, entry.getValue(), entry.getKey()); } }
/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java
robustness-copilot_data_729
/** * Removes a particular monomer, specified by its name. * * @param name The name of the monomer to remove */ public void removeMonomer(String name){ if (monomers.containsKey(name)) { Monomer monomer = (Monomer) monomers.get(name); this.remove(monomer); monomers.remove(name); } }
/base/data/src/main/java/org/openscience/cdk/Polymer.java
robustness-copilot_data_730
/** * Calculates the number of bits that would be needed to store the given value. * * @param number the value * @return The number of bits that would be needed to store the value. */ public static int calculateNeededBits(int number){ int count = 0; do { count++; number >>>= 1; } while (number != 0); return count; }
/src/main/java/net/glowstone/util/VariableValueArray.java
robustness-copilot_data_731
/** * Returns an iterator over the elements in this queue. The iterator * does not return the elements in any particular order. Removing * elements is not supported via the iterator. * * @return an iterator over the elements in this queue. */ public Iterator<E> iterator(){ return new Iterator<E>() { final Iterator<E> iterDelegate = PseudoRemovePriorityQueue.this.lastEntry.keySet().iterator(); @Override public boolean hasNext() { return this.iterDelegate.hasNext(); } @Override public E next() { return this.iterDelegate.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
/matsim/src/main/java/org/matsim/core/utils/collections/PseudoRemovePriorityQueue.java
robustness-copilot_data_732
/** * Create a CompletableFuture from guava's ListenableFuture to help migration from Guava to * Java8. * * @param listenable ListenableFuture to convert. * @return new CompletableFuture. */ public static CompletableFuture<T> fromListenableFuture(ListenableFuture<T> listenable){ final CompletableFuture<T> completable = new CompletableFuture<T>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { boolean result = listenable.cancel(mayInterruptIfRunning); super.cancel(mayInterruptIfRunning); return result; } }; Futures.addCallback(listenable, new FutureCallback<T>() { @Override public void onSuccess(T result) { completable.complete(result); } @Override public void onFailure(Throwable t) { completable.completeExceptionally(t); } }, MoreExecutors.directExecutor()); return completable; }
/modules/common/src/main/java/org/dcache/util/CompletableFutures.java
robustness-copilot_data_733
/** * Check if all atoms in the bond list have 2D coordinates. There is some * redundant checking but the list will typically be short. * * @param bonds the bonds to check * @return whether all atoms have 2D coordinates */ private static boolean has2DCoordinates(List<IBond> bonds){ for (IBond bond : bonds) { if (bond.getBegin().getPoint2d() == null || bond.getEnd().getPoint2d() == null) return false; } return true; }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java
robustness-copilot_data_734
/** * Shift the container horizontally to the right to make its bounds not * overlap with the other bounds. * * @param container the {@link IAtomContainer} to shift to the right * @param bounds the {@link Rectangle2D} of the {@link IAtomContainer} * to shift * @param last the bounds that is used as reference * @param gap the gap between the two {@link Rectangle2D}s * @return the {@link Rectangle2D} of the {@link IAtomContainer} * after the shift */ public static Rectangle2D shiftContainer(IAtomContainer container, Rectangle2D bounds, Rectangle2D last, double gap){ if (last.getMaxX() + gap >= bounds.getMinX()) { double xShift = last.getMaxX() + gap - bounds.getMinX(); Vector2d shift = new Vector2d(xShift, 0.0); GeometryTools.translate2D(container, shift); return new Rectangle2D.Double(bounds.getX() + xShift, bounds.getY(), bounds.getWidth(), bounds.getHeight()); } else { return bounds; } }
/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java
robustness-copilot_data_735
/** * Returns true if another {@link IAtomContainer} can be read. */ public boolean hasNext(){ if (nextAvailableIsKnown) { return hasNext; } hasNext = false; nextMolecule = null; try { currentFormat = (IChemFormat) MDLFormat.getInstance(); int lineNum = 0; buffer.setLength(0); while ((currentLine = input.readLine()) != null) { buffer.append(currentLine).append(LINE_SEPARATOR); lineNum++; if (lineNum == 4) { Matcher versionMatcher = MDL_VERSION.matcher(currentLine); if (versionMatcher.find()) { currentFormat = "2000".equals(versionMatcher.group(1)) ? (IChemFormat) MDLV2000Format.getInstance() : (IChemFormat) MDLV3000Format.getInstance(); } } if (currentLine.startsWith(M_END)) { logger.debug("MDL file part read: ", buffer); IAtomContainer molecule = null; try { ISimpleChemObjectReader reader = getReader(currentFormat); reader.setReader(new StringReader(buffer.toString())); molecule = reader.read(builder.newAtomContainer()); } catch (Exception exception) { logger.error("Error while reading next molecule: " + exception.getMessage()); logger.debug(exception); } if (molecule != null) { readDataBlockInto(molecule); hasNext = true; nextAvailableIsKnown = true; nextMolecule = molecule; return true; } else if (skip) { String line; while ((line = input.readLine()) != null) { if (line.startsWith(SDF_RECORD_SEPARATOR)) { break; } } } else { return false; } buffer.setLength(0); lineNum = 0; } if (currentLine.startsWith(SDF_RECORD_SEPARATOR)) { buffer.setLength(0); lineNum = 0; } } } catch (IOException exception) { logger.error("Error while reading next molecule: " + exception.getMessage()); logger.debug(exception); } return false; }
/storage/ctab/src/main/java/org/openscience/cdk/io/iterator/IteratingSDFReader.java
robustness-copilot_data_736
/** * Positions an outline in the subscript position relative to another 'primary' label. * * @param label a label outline * @param subscript the label outline to position as subscript * @return positioned subscript outline */ TextOutline positionSubscript(TextOutline label, TextOutline subscript){ final Rectangle2D hydrogenBounds = label.getBounds(); final Rectangle2D hydrogenCountBounds = subscript.getBounds(); subscript = subscript.translate((hydrogenBounds.getMaxX() + padding) - hydrogenCountBounds.getMinX(), (hydrogenBounds.getMaxY() + (hydrogenCountBounds.getHeight() / 2)) - hydrogenCountBounds.getMaxY()); return subscript; }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardAtomGenerator.java
robustness-copilot_data_737
/** * Find an r such that this[r] != other[r]. * @param other the other permutation to compare with * @return the first point at which the two permutations differ */ public int firstIndexOfDifference(Permutation other){ int r = 0; while ((r < values.length) && values[r] == other.get(r)) { r++; } return r; }
/tool/group/src/main/java/org/openscience/cdk/group/Permutation.java
robustness-copilot_data_738
/** * IntIterator of source table row numbers that are present in this view. This can be used to in * combination with the source table to iterate over the cells of a column in a sorted order * without copying the column. * * @return an int iterator of row numbers in the source table that are present in this view. */ protected PrimitiveIterator.OfInt sourceRowNumberIterator(){ if (this.isSorted()) { return Arrays.stream(sortOrder).iterator(); } else if (this.hasSelection()) { return selection.iterator(); } return Selection.withRange(0, table.rowCount()).iterator(); }
/core/src/main/java/tech/tablesaw/table/TableSlice.java
robustness-copilot_data_739
/** * Apply the MDL valence model to the provided atom container. * * @param container an atom container loaded from an MDL format * @return the container (for convenience) */ static IAtomContainer apply(IAtomContainer container){ int n = container.getAtomCount(); int[] valences = new int[n]; Map<IAtom, Integer> atomToIndex = new HashMap<>(2 * n); for (IAtom atom : container.atoms()) atomToIndex.put(atom, atomToIndex.size()); // compute the bond order sums for (IBond bond : container.bonds()) { int u = atomToIndex.get(bond.getBegin()); int v = atomToIndex.get(bond.getEnd()); int bondOrder = bond.getOrder().numeric(); valences[u] += bondOrder; valences[v] += bondOrder; } for (int i = 0; i < n; i++) { IAtom atom = container.getAtom(i); Integer charge = atom.getFormalCharge(); Integer element = atom.getAtomicNumber(); if (element == null) continue; // unset = 0 in this case charge = charge == null ? 0 : charge; int explicit = valences[i]; // if there was a valence read from the mol file use that otherwise // use the default value from the valence model to set the correct // number of implied hydrogens if (atom.getValency() != null) { atom.setImplicitHydrogenCount(atom.getValency() - explicit); } else { int implicit = implicitValence(element, charge, valences[i]); atom.setImplicitHydrogenCount(implicit - explicit); atom.setValency(implicit); } } return container; }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLValence.java
robustness-copilot_data_740
/** * Choose any possible quadruple of the set of atoms * in ac and establish all of the possible bonding schemes according to * Faulon's equations. */ public static List<IAtomContainer> sample(IAtomContainer ac){ LOGGER.debug("RandomGenerator->mutate() Start"); List<IAtomContainer> structures = new ArrayList<IAtomContainer>(); int nrOfAtoms = ac.getAtomCount(); double a11 = 0, a12 = 0, a22 = 0, a21 = 0; double b11 = 0, lowerborder = 0, upperborder = 0; double b12 = 0; double b21 = 0; double b22 = 0; double[] cmax = new double[4]; double[] cmin = new double[4]; IAtomContainer newAc = null; IAtom ax1 = null, ax2 = null, ay1 = null, ay2 = null; IBond b1 = null, b2 = null, b3 = null, b4 = null; // int[] choices = new int[3]; /* We need at least two non-zero bonds in order to be successful */ int nonZeroBondsCounter = 0; for (int x1 = 0; x1 < nrOfAtoms; x1++) { for (int x2 = x1 + 1; x2 < nrOfAtoms; x2++) { for (int y1 = x2 + 1; y1 < nrOfAtoms; y1++) { for (int y2 = y1 + 1; y2 < nrOfAtoms; y2++) { nonZeroBondsCounter = 0; ax1 = ac.getAtom(x1); ay1 = ac.getAtom(y1); ax2 = ac.getAtom(x2); ay2 = ac.getAtom(y2); /* Get four bonds for these four atoms */ b1 = ac.getBond(ax1, ay1); if (b1 != null) { a11 = BondManipulator.destroyBondOrder(b1.getOrder()); nonZeroBondsCounter++; } else { a11 = 0; } b2 = ac.getBond(ax1, ay2); if (b2 != null) { a12 = BondManipulator.destroyBondOrder(b2.getOrder()); nonZeroBondsCounter++; } else { a12 = 0; } b3 = ac.getBond(ax2, ay1); if (b3 != null) { a21 = BondManipulator.destroyBondOrder(b3.getOrder()); nonZeroBondsCounter++; } else { a21 = 0; } b4 = ac.getBond(ax2, ay2); if (b4 != null) { a22 = BondManipulator.destroyBondOrder(b4.getOrder()); nonZeroBondsCounter++; } else { a22 = 0; } if (nonZeroBondsCounter > 1) { /* * Compute the range for b11 (see Faulons formulae * for details) */ cmax[0] = 0; cmax[1] = a11 - a22; cmax[2] = a11 + a12 - 3; cmax[3] = a11 + a21 - 3; cmin[0] = 3; cmin[1] = a11 + a12; cmin[2] = a11 + a21; cmin[3] = a11 - a22 + 3; lowerborder = MathTools.max(cmax); upperborder = MathTools.min(cmin); for (b11 = lowerborder; b11 <= upperborder; b11++) { if (b11 != a11) { b12 = a11 + a12 - b11; b21 = a11 + a21 - b11; b22 = a22 - a11 + b11; LOGGER.debug("Trying atom combination : " + x1 + ":" + x2 + ":" + y1 + ":" + y2); try { newAc = (IAtomContainer) ac.clone(); change(newAc, x1, y1, x2, y2, b11, b12, b21, b22); if (ConnectivityChecker.isConnected(newAc)) { structures.add(newAc); } else { LOGGER.debug("not connected"); } } catch (CloneNotSupportedException e) { LOGGER.error("Cloning exception: " + e.getMessage()); LOGGER.debug(e); } } } } } } } } return structures; }
/tool/structgen/src/main/java/org/openscience/cdk/structgen/VicinitySampler.java
robustness-copilot_data_741
/** * Helper method that locates an atom based on its InChI atom table * position, which has been set as ID. * @param container input container * @param position InChI atom table position * @return atom on the position */ private IAtom findAtomByPosition(IAtomContainer container, int position){ String pos = String.valueOf(position); for (IAtom atom : container.atoms()) { if (atom.getID().equals(pos)) return atom; } return null; }
/tool/tautomer/src/main/java/org/openscience/cdk/tautomers/InChITautomerGenerator.java
robustness-copilot_data_742
/** * generate the order of the Elements according probability occurrence., * beginning the 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. * * @return Array with the elements ordered. * */ private String[] generateOrderE(){ String[] listElements = 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" }; return listElements; }
/legacy/src/main/java/org/openscience/cdk/formula/MassToFormulaTool.java
robustness-copilot_data_743
/** * the method take a boolean checkAromaticity: if the boolean is true, it means that * aromaticity has to be checked. * *@param mol AtomContainer for which this descriptor is to be calculated *@return The number of failures of the Lipinski rule */ public DescriptorValue calculate(IAtomContainer mol){ mol = clone(mol); int lipinskifailures = 0; IMolecularDescriptor xlogP = new XLogPDescriptor(); Object[] xlogPparams = { checkAromaticity, Boolean.TRUE }; try { xlogP.setParameters(xlogPparams); double xlogPvalue = ((DoubleResult) xlogP.calculate(mol).getValue()).doubleValue(); IMolecularDescriptor acc = new HBondAcceptorCountDescriptor(); Object[] hBondparams = { checkAromaticity }; acc.setParameters(hBondparams); int acceptors = ((IntegerResult) acc.calculate(mol).getValue()).intValue(); IMolecularDescriptor don = new HBondDonorCountDescriptor(); don.setParameters(hBondparams); int donors = ((IntegerResult) don.calculate(mol).getValue()).intValue(); IMolecularDescriptor mw = new WeightDescriptor(); Object[] mwparams = { "*" }; mw.setParameters(mwparams); double mwvalue = ((DoubleResult) mw.calculate(mol).getValue()).doubleValue(); IMolecularDescriptor rotata = new RotatableBondsCountDescriptor(); Object[] rotatableBondsParams = { false, true }; rotata.setParameters(rotatableBondsParams); int rotatablebonds = ((IntegerResult) rotata.calculate(mol).getValue()).intValue(); if (xlogPvalue > 5.0) { lipinskifailures += 1; } if (acceptors > 10) { lipinskifailures += 1; } if (donors > 5) { lipinskifailures += 1; } if (mwvalue > 500.0) { lipinskifailures += 1; } if (rotatablebonds > 10.0) { lipinskifailures += 1; } } catch (CDKException e) { new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new IntegerResult((int) Double.NaN), getDescriptorNames(), e); } return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new IntegerResult(lipinskifailures), getDescriptorNames()); }
/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/RuleOfFiveDescriptor.java
robustness-copilot_data_744
/** * Get the collection of task statistics in the most recent week. * * @return Collection of running task statistics data objects */ public List<TaskRunningStatistics> findTaskRunningStatisticsWeekly(){ if (!isRdbConfigured()) { return Collections.emptyList(); } return rdbRepository.findTaskRunningStatistics(StatisticTimeUtils.getStatisticTime(StatisticInterval.DAY, -7)); }
/elasticjob-cloud/elasticjob-cloud-scheduler/src/main/java/org/apache/shardingsphere/elasticjob/cloud/scheduler/statistics/StatisticManager.java
robustness-copilot_data_745
/** * Pop a ZFrame and return the toString() representation of it. * * @return toString version of pop'ed frame, or null if no frame exists. */ public String popString(){ ZFrame frame = pop(); if (frame == null) { return null; } return frame.toString(); }
/src/main/java/org/zeromq/ZMsg.java
robustness-copilot_data_746
/** * Applies the given function to a list subtag if it is present and its contents are float * 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 readFloatList(@NonNls String key, Consumer<? super List<Float>> consumer){ return readList(key, TagType.FLOAT, consumer); }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_747
/** * Evaluate the square of the Euclidean distance between two atoms. * *@param atom1 first atom *@param atom2 second atom *@return squared distance between the 2 atoms */ private double calculateSquaredDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2){ double distance = 0; double tmp = 0; Point3d firstPoint = atom1.getPoint3d(); Point3d secondPoint = atom2.getPoint3d(); tmp = firstPoint.distance(secondPoint); distance = tmp * tmp; return distance; }
/tool/charges/src/main/java/org/openscience/cdk/charges/InductivePartialCharges.java
robustness-copilot_data_748
/** * Reverse a list of tokens for display, flipping * brackets as needed. * * @param tokens list of tokens */ static void reverse(List<String> tokens){ Collections.reverse(tokens); Deque<String> numbers = new ArrayDeque<>(); for (int i = 0; i < tokens.size(); i++) { String token = tokens.get(i); if (token.equals("(")) { tokens.set(i, ")"); String num = numbers.pop(); if (!num.isEmpty()) { tokens.add(i + 1, num); i++; } } else if (token.equals(")")) { tokens.set(i, "("); if (i > 0 && isNumber(tokens.get(i - 1))) { numbers.push(tokens.remove(i - 1)); i--; } else { numbers.push(""); } } } }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/AbbreviationLabel.java
robustness-copilot_data_749
/** * Returns a string representation of the object: XML/UTF-8 encoded. * * @return object XML encoded */ public String toString(){ var stream = new ByteArrayOutputStream(); save(stream); return stream.toString(StandardCharsets.UTF_8); }
/cxx-squid/src/main/java/org/sonar/cxx/config/CxxSquidConfiguration.java
robustness-copilot_data_750
/** * Use this fiber's executor to schedule an operation for some time in the future. * @param timeout the interval before the check should run, in units * @param unit the unit of time that defines the interval * @param runnable the operation to run */ public void scheduleOnce(long timeout, TimeUnit unit, Runnable runnable){ this.owner.getExecutor().schedule(runnable, timeout, unit); }
/operator/src/main/java/oracle/kubernetes/operator/work/Fiber.java
robustness-copilot_data_751
/** * A line is skipped if it is empty or is a comment. MMFF files use '*' to mark comments and '$' * for end of file. * * @param line an input line * @return whether to skip this line */ private static boolean skipLine(String line){ return line.isEmpty() || line.charAt(0) == '*' || line.charAt(0) == '$'; }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAtomTypeMatcher.java
robustness-copilot_data_752
/** * Normalize a path by removing consecutive <code>/</code>(slashes). * * @param path Path to process. * @return Safe path pattern. */ static String normalizePath(@Nullable String path){ if (path == null || path.length() == 0 || path.equals("/")) { return "/"; } int len = path.length(); boolean modified = false; int p = 0; char[] buff = new char[len + 1]; if (path.charAt(0) != '/') { buff[p++] = '/'; modified = true; } for (int i = 0; i < path.length(); i++) { char ch = path.charAt(i); if (ch != '/') { buff[p++] = ch; } else if (i == 0 || path.charAt(i - 1) != '/') { buff[p++] = ch; } else { modified = true; } } return modified ? new String(buff, 0, p) : path; }
/jooby/src/main/java/io/jooby/Router.java
robustness-copilot_data_753
/** * Converts a JSON workflow configuration to a workflow configuration object. * * @param json JSON for workflow rule target * @return a workflow rule target object * @throws IOException if unable to create object */ public static WorkflowRuleTarget fromJson(String json) throws IOException{ ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, WorkflowRuleTarget.class); }
/src/main/java/com/twilio/taskrouter/WorkflowRuleTarget.java
robustness-copilot_data_754
/** * Find out if the Process 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> findProcessEntity(String userId, String qualifiedName) throws UserNotAuthorizedException, PropertyServerException, InvalidParameterException{ return dataEngineCommonHandler.findEntity(userId, qualifiedName, PROCESS_TYPE_NAME); }
/open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEngineProcessHandler.java
robustness-copilot_data_755
/** * Add a custom encoder to the hash generator which will be built. Although * not enforced, the encoder should be stateless and should not modify any * passed inputs. * * @param encoder an atom encoder * @return fluent API reference (self) * @throws NullPointerException no encoder provided */ public HashGeneratorMaker encode(AtomEncoder encoder){ if (encoder == null) throw new NullPointerException("no encoder provided"); customEncoders.add(encoder); return this; }
/tool/hash/src/main/java/org/openscience/cdk/hash/HashGeneratorMaker.java
robustness-copilot_data_756
/** * Load a list of SMARTS patterns from the specified file. * * Each line in the file corresponds to a pattern with the following structure: * PATTERN_DESCRIPTION: SMARTS_PATTERN, <i>e.g., Thioketone: [#6][CX3](=[SX1])[#6]</i> * * Empty lines and lines starting with a "#" are skipped. * * @param filename list of the SMARTS pattern to be loaded * @return list of strings containing the loaded SMARTS pattern * @throws Exception if there is an error parsing SMILES patterns */ private static String[] readSMARTSPattern(String filename) throws Exception{ InputStream ins = StandardSubstructureSets.class.getClassLoader().getResourceAsStream(filename); BufferedReader reader = new BufferedReader(new InputStreamReader(ins)); List<String> tmp = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { if (line.startsWith("#") || line.trim().length() == 0) continue; String[] toks = line.split(":"); StringBuffer s = new StringBuffer(); for (int i = 1; i < toks.length - 1; i++) s.append(toks[i] + ":"); s.append(toks[toks.length - 1]); tmp.add(s.toString().trim()); } return tmp.toArray(new String[] {}); }
/descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/StandardSubstructureSets.java
robustness-copilot_data_757
/** * Choose a random plan from the person and return it. * @return The newly selected plan for this person; <code>null</code> if the person has no plans. */ public T selectPlan(final HasPlansAndId<T, I> person){ // this used to use person.getRandomPlan(), but I inlined the function here in order to get rid of the function of the data class. // kai, nov'13 if (person.getPlans().size() == 0) { return null; } int index = (int) (MatsimRandom.getRandom().nextDouble() * person.getPlans().size()); // yyyy As far as I can tell, this produces race conditions when running multi-threaded. I.e. when running the same // setup twice, this function may return different results per thread or per person. kai, jun'14 return person.getPlans().get(index); }
/matsim/src/main/java/org/matsim/core/replanning/selectors/RandomPlanSelector.java
robustness-copilot_data_758
/** * Persists the Users to CSV form data to the underlying jcr:content node. * @param request the Sling HTTP Request object * @param response the Sling HTTP Response object * @throws IOException * @throws ServletException */ public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, ServletException{ response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); final ValueMap properties = request.getResource().adaptTo(ModifiableValueMap.class); final Parameters parameters = new Parameters(request); properties.put(GROUP_FILTER, parameters.getGroupFilter()); properties.put(GROUPS, parameters.getGroups()); properties.put(CUSTOM_PROPERTIES, parameters.getCustomProperties()); request.getResourceResolver().commit(); }
/bundle/src/main/java/com/adobe/acs/commons/exporters/impl/users/UsersSaveServlet.java
robustness-copilot_data_759
/** * Return the enum value in the language specified format * e.g. status becomes "status" * * @param value enum variable name * @param datatype data type * @return the sanitized value for enum */ public String toEnumValue(String value, String datatype){ if ("number".equalsIgnoreCase(datatype) || "boolean".equalsIgnoreCase(datatype)) { return value; } else { return "\"" + escapeText(value) + "\""; } }
/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
robustness-copilot_data_760
/** * Overridable factory method called by {@link #writeValues(OutputStream)} * method (and its various overrides), and initializes it as necessary. * * @since 2.5 */ protected SequenceWriter _newSequenceWriter(boolean wrapInArray, JsonGenerator gen, boolean managedInput) throws IOException{ return new SequenceWriter(_serializerProvider(), _configureGenerator(gen), managedInput, _prefetch).init(wrapInArray); }
/src/main/java/com/fasterxml/jackson/databind/ObjectWriter.java
robustness-copilot_data_761
/** * Given the current configuration create an {@link AtomHashGenerator}. * * @return instance of the generator * @throws IllegalArgumentException no depth or encoders were configured */ public AtomHashGenerator atomic(){ if (depth < 0) throw new IllegalArgumentException("no depth specified, use .depth(int)"); List<AtomEncoder> encoders = new ArrayList<AtomEncoder>(); for (AtomEncoder encoder : encoderSet) { encoders.add(encoder); } encoders.addAll(this.customEncoders); boolean suppress = suppression != AtomSuppression.unsuppressed(); AtomEncoder encoder = new ConjugatedAtomEncoder(encoders); SeedGenerator seeds = new SeedGenerator(encoder, suppression); AbstractAtomHashGenerator simple = suppress ? new SuppressedAtomHashGenerator(seeds, new Xorshift(), makeStereoEncoderFactory(), suppression, depth) : new BasicAtomHashGenerator(seeds, new Xorshift(), makeStereoEncoderFactory(), depth); if (equivSetFinder != null) { return new PerturbedAtomHashGenerator(seeds, simple, new Xorshift(), makeStereoEncoderFactory(), equivSetFinder, suppression); } else { return simple; } }
/tool/hash/src/main/java/org/openscience/cdk/hash/HashGeneratorMaker.java
robustness-copilot_data_762
/** * Normalises a 5-member 'cycle' such that the hetroatom contributing the lone-pair is in * position 1 (index 0). The alpha atoms are then in index 1 and 4 whilst the beta atoms are in * index 2 and 3. If the ring contains more than one hetroatom the cycle is not normalised * (return=false). * * @param cycle aromatic cycle to normalise, |C| = 5 * @param contribution vector of p electron contributions from each vertex (size |V|) * @return whether the cycle was normalised */ static boolean normaliseCycle(int[] cycle, int[] contribution){ int offset = indexOfHetro(cycle, contribution); if (offset < 0) return false; if (offset == 0) return true; int[] cpy = Arrays.copyOf(cycle, cycle.length); int len = cycle.length - 1; for (int j = 0; j < len; j++) { cycle[j] = cpy[(offset + j) % len]; } cycle[len] = cycle[0]; return true; }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAromaticTypeMapping.java
robustness-copilot_data_763
/** * Will return the name of the last folder in pathName. Takes root folder into account. * When called with argument "/folder", return value is "folder". * When called with argument "/", return value is "/" * * @param pathName path * * @return folder name */ private String computeDisplayName(String pathName){ return new File(pathName).getName().length() < 1 ? pathName : new File(pathName).getName(); }
/open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEngineFolderHierarchyHandler.java
robustness-copilot_data_764
/** * Combines the values in an n x m matrix into a single array of size n. * This process scans the rows and xors all unique values in the row * together. If a duplicate value is found it is rotated using a * pseudorandom number generator. * * @param perturbed n x m, matrix * @return the combined values of each row */ long[] combine(long[][] perturbed){ int n = perturbed.length; int m = perturbed[0].length; long[] combined = new long[n]; long[] rotated = new long[m]; for (int i = 0; i < n; i++) { Arrays.sort(perturbed[i]); for (int j = 0; j < m; j++) { if (j > 0 && perturbed[i][j] == perturbed[i][j - 1]) { combined[i] ^= rotated[j] = rotate(rotated[j - 1]); } else { combined[i] ^= rotated[j] = perturbed[i][j]; } } } return combined; }
/tool/hash/src/main/java/org/openscience/cdk/hash/PerturbedAtomHashGenerator.java
robustness-copilot_data_765
/** * Ensure that a Checksum is calculated for the supplied ChecksumType. If the ChecksumType is * already registered then this method does nothing, otherwise the ChecksumChannel is updated to * calculate the new ChecksumType. If the ChecksumChannel has accepted a contiguous range of * data from offset 0 then this method will reread that contiguous range. * * @param type The algorithm this ChecksumChannel should calculate. * @throws IOException if the Channel has already started accepting data and an attempt to * reread data from disk fails. */ public void addType(ChecksumType type) throws IOException{ synchronized (_digests) { if (_digests.stream().map(MessageDigest::getAlgorithm).noneMatch(t -> t.equals(type.getName()))) { MessageDigest digest = type.createMessageDigest(); if (_isChecksumViable) { try { updateFromChannel(Collections.singleton(digest), 0L, _nextChecksumOffset); } catch (IOException e) { throw new IOException("Failed when reading received data: " + messageOrClassName(e), e); } } _digests.add(digest); } } }
/modules/dcache/src/main/java/org/dcache/pool/movers/ChecksumChannel.java
robustness-copilot_data_766
/** * Method that will set value of specified property if (and only if) * it had no set value previously. * Note that explicitly set {@code null} is a value. * Functionally equivalent to: *<code> * if (get(propertyName) == null) { * set(propertyName, value); * return null; * } else { * return get(propertyName); * } *</code> * * @param propertyName Name of property to set * @param value Value to set to property (if and only if it had no value previously); * if null, will be converted to a {@link NullNode} first. * * @return Old value of the property, if any (in which case value was not changed); * null if there was no old value (in which case value is now set) * * @since 2.13 */ public JsonNode putIfAbsent(String propertyName, JsonNode value){ if (value == null) { value = nullNode(); } return _children.putIfAbsent(propertyName, value); }
/src/main/java/com/fasterxml/jackson/databind/node/ObjectNode.java
robustness-copilot_data_767
/** * Pop frame off front of message, caller now owns frame. * If next frame is empty, pops and destroys that empty frame * (e.g. useful when unwrapping ROUTER socket envelopes) * @return * Unwrapped frame */ public ZFrame unwrap(){ if (size() == 0) { return null; } ZFrame f = pop(); ZFrame empty = getFirst(); if (empty.hasData() && empty.size() == 0) { empty = pop(); empty.destroy(); } return f; }
/src/main/java/org/zeromq/ZMsg.java
robustness-copilot_data_768
/** * Appends a throwable and recursively appends its causedby/suppressed throwables * in "normal" order (Root cause last). */ private void appendRootCauseLast(StringBuilder builder, String prefix, int indent, IThrowableProxy throwableProxy, Deque<String> stackHashes){ if (throwableProxy == null || builder.length() > maxLength) { return; } String hash = stackHashes == null || stackHashes.isEmpty() ? null : stackHashes.removeFirst(); appendFirstLine(builder, prefix, indent, throwableProxy, hash); appendStackTraceElements(builder, indent, throwableProxy); IThrowableProxy[] suppressedThrowableProxies = throwableProxy.getSuppressed(); if (suppressedThrowableProxies != null) { for (IThrowableProxy suppressedThrowableProxy : suppressedThrowableProxies) { appendRootCauseLast(builder, CoreConstants.SUPPRESSED, indent + ThrowableProxyUtil.SUPPRESSED_EXCEPTION_INDENT, suppressedThrowableProxy, null); } } appendRootCauseLast(builder, CoreConstants.CAUSED_BY, indent, throwableProxy.getCause(), stackHashes); }
/src/main/java/net/logstash/logback/stacktrace/ShortenedThrowableConverter.java
robustness-copilot_data_769
/** * Locates by query all the ACLs that the principal participates in. * * @param resourceResolver the resource resolver to perform the user management * @param principalName the principal name * @param accessControlManager Jackrabbit access control manager * @return a list of ACLs that principal participates in. */ private List<JackrabbitAccessControlList> findAcls(ResourceResolver resourceResolver, String principalName, JackrabbitAccessControlManager accessControlManager){ final Set<String> paths = new HashSet<String>(); final List<JackrabbitAccessControlList> acls = new ArrayList<JackrabbitAccessControlList>(); final Map<String, String> params = new HashMap<String, String>(); params.put("type", PROP_NT_REP_ACE); params.put("property", PROP_REP_PRINCIPAL_NAME); params.put("property.value", principalName); params.put("p.limit", "-1"); Query query = queryBuilder.createQuery(PredicateGroup.create(params), resourceResolver.adaptTo(Session.class)); QueryUtil.setResourceResolverOn(resourceResolver, query); for (final Hit hit : query.getResult().getHits()) { try { final Resource aceResource = resourceResolver.getResource(hit.getPath()); final Resource contentResource = aceResource.getParent().getParent(); if (!paths.contains(contentResource.getPath())) { paths.add(contentResource.getPath()); for (AccessControlPolicy policy : accessControlManager.getPolicies(contentResource.getPath())) { if (policy instanceof JackrabbitAccessControlList) { acls.add((JackrabbitAccessControlList) policy); break; } } } } catch (RepositoryException e) { log.error("Failed to get resource for query result.", e); } } return acls; }
/bundle/src/main/java/com/adobe/acs/commons/users/impl/EnsureAce.java
robustness-copilot_data_770
/** * Special case, 'NCN+' matches entries that the validation suite say should actually be 'NC=N'. * We can achieve 100% compliance by checking if NCN+ is still next to CNN+ or CIM+ after * aromatic types are assigned * * @param symbs symbolic types * @param graph adjacency list graph */ private void fixNCNTypes(String[] symbs, int[][] graph){ for (int v = 0; v < graph.length; v++) { if ("NCN+".equals(symbs[v])) { boolean foundCNN = false; for (int w : graph[v]) { foundCNN = foundCNN || "CNN+".equals(symbs[w]) || "CIM+".equals(symbs[w]); } if (!foundCNN) { symbs[v] = "NC=N"; } } } }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAtomTypeMatcher.java
robustness-copilot_data_771
/** * Test if set sourceBitSet is contained in set targetBitSet. * @param sourceBitSet a bitSet * @param targetBitSet a bitSet * @return true if sourceBitSet is contained in targetBitSet */ private boolean isContainedIn(BitSet sourceBitSet, BitSet targetBitSet){ boolean result = false; if (sourceBitSet.isEmpty()) { return true; } BitSet setA = (BitSet) sourceBitSet.clone(); setA.and(targetBitSet); if (setA.equals(sourceBitSet)) { result = true; } return result; }
/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKRGraph.java
robustness-copilot_data_772
/** * Takes the passed info object and updated the internal fields according to it. * @param inf the info from which we update the fields. */ public void applyDisplayInfo(AuthenticatedUserDisplayInfo inf){ setFirstName(inf.getFirstName()); setLastName(inf.getLastName()); if (nonEmpty(inf.getEmailAddress())) { setEmail(inf.getEmailAddress()); } if (nonEmpty(inf.getAffiliation())) { setAffiliation(inf.getAffiliation()); } if (nonEmpty(inf.getPosition())) { setPosition(inf.getPosition()); } }
/src/main/java/edu/harvard/iq/dataverse/authorization/users/AuthenticatedUser.java
robustness-copilot_data_773
/** * Method called to ensure that given parser is ready for reading * content for data binding. * * @return First token to be used for data binding after this call: * can never be null as exception will be thrown if parser cannot * provide more tokens. * * @throws IOException if the underlying input source has problems during * parsing */ protected JsonToken _initForReading(JsonParser p, JavaType targetType) throws IOException{ _deserializationConfig.initialize(p); JsonToken t = p.currentToken(); if (t == null) { t = p.nextToken(); if (t == null) { throw MismatchedInputException.from(p, targetType, "No content to map due to end-of-input"); } } return t; }
/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java
robustness-copilot_data_774
/** * Adds a change listener to the list of listeners. * * @param listener * The listener added to the list */ public void addCDKChangeListener(ICDKChangeListener listener){ if (listeners == null) { listeners = new ArrayList<ICDKChangeListener>(); } if (!listeners.contains(listener)) { listeners.add(listener); } }
/display/render/src/main/java/org/openscience/cdk/renderer/RendererModel.java
robustness-copilot_data_775
/** * Execute the task while the Thread Context Class Loader is set to the provided * Class Loader. * * @param classLoader the requested class loader * @param task the task * @param <V> the return type of the task * @return the return value * @throws Exception the exception throw, if any, by the task */ public static V doWithTccl(ClassLoader classLoader, Callable<V> task) throws Exception{ ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); try { return task.call(); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } }
/bundle/src/main/java/com/adobe/acs/commons/util/ThreadContextClassLoaderTaskExecutor.java
robustness-copilot_data_776
/** * Adds patches to the specified patch builder to correct differences in the current vs required * maps. * * @param patchBuilder a builder for the patches * @param basePath the base for the patch path (excluding the name) * @param current a map of the values found in a Kubernetes resource * @param required a map of the values specified for the resource by the domain */ static void addPatches(JsonPatchBuilder patchBuilder, String basePath, Map<String, String> current, Map<String, String> required){ for (String name : required.keySet()) { String encodedPath = basePath + name.replace("~", "~0").replace("/", "~1"); if (!current.containsKey(name)) { patchBuilder.add(encodedPath, required.get(name)); } else { patchBuilder.replace(encodedPath, required.get(name)); } } }
/operator/src/main/java/oracle/kubernetes/operator/helpers/KubernetesUtils.java
robustness-copilot_data_777
/** * Splits this partition by taking the cell at cellIndex and making two * new cells - the first with the the rest of the elements from that cell * and the second with the singleton splitElement. * * @param cellIndex the index of the cell to split on * @param splitElement the element to put in its own cell * @return a new (finer) Partition */ public Partition splitAfter(int cellIndex, int splitElement){ Partition r = new Partition(); for (int j = 0; j < cellIndex; j++) { r.addCell(this.copyBlock(j)); } SortedSet<Integer> splitBlock = this.copyBlock(cellIndex); splitBlock.remove(splitElement); r.addCell(splitBlock); r.addSingletonCell(splitElement); for (int j = cellIndex + 1; j < this.size(); j++) { r.addCell(this.copyBlock(j)); } return r; }
/tool/group/src/main/java/org/openscience/cdk/group/Partition.java
robustness-copilot_data_778
/** * Finds a neighbor attached to 'atom' that is singley bonded and isn't * 'exclude'. If no such atom exists, the 'atom' is returned. * * @param container a molecule container * @param atom the atom to find the neighbor or * @param exclude don't find this atom * @return the other atom (or 'atom') */ private static IAtom findOtherSinglyBonded(IAtomContainer container, IAtom atom, IAtom exclude){ for (final IBond bond : container.getConnectedBondsList(atom)) { if (!IBond.Order.SINGLE.equals(bond.getOrder()) || bond.contains(exclude)) continue; return bond.getOther(atom); } return atom; }
/storage/inchi/src/main/java/org/openscience/cdk/inchi/InChIToStructure.java
robustness-copilot_data_779
/** * Creates a new discretizer with bin borders defined such that each bin * would contain approximately <tt>size</tt> samples from <tt>samples</tt>. * * Samples are sorted into bins in ascending order. If there are not * sufficient (less than <tt>size</tt>) samples to fill a further bin, the * remaining samples are sorted into the last bin. That is, the last bin is * the only bin that may contain more than <tt>size</tt> samples. * * @param samples * an array with samples. * @param size * the number of samples per bin. * @return a new discretizer. */ public static FixedBordersDiscretizer create(double[] samples, int size){ TDoubleArrayList borders; double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; TDoubleIntHashMap hist = new TDoubleIntHashMap(samples.length); for (int i = 0; i < samples.length; i++) { hist.adjustOrPutValue(samples[i], 1, 1); min = Math.min(min, samples[i]); max = Math.max(max, samples[i]); } double[] keys = hist.keys(); Arrays.sort(keys); borders = new TDoubleArrayList(keys.length); borders.add(min - 1E-10); int binsize = 0; int n = 0; for (int i = 0; i < keys.length; i++) { int nBin = hist.get(keys[i]); binsize += nBin; n += nBin; if (binsize >= size && i > 0) { // sufficient samples for the // current bin if (samples.length - n >= binsize) { // sufficient remaining // samples to fill the // next bin borders.add(keys[i]); binsize = 0; } } } if (binsize > 0) borders.add(max); return new FixedBordersDiscretizer(borders.toArray()); }
/contribs/common/src/main/java/org/matsim/contrib/common/stats/FixedSampleSizeDiscretizer.java
robustness-copilot_data_780
/** * Reads partial atomic charges and add the to the given ChemModel. * * @param model Description of the Parameter * @throws CDKException Description of the Exception * @throws IOException Description of the Exception */ private void readPartialCharges(IChemModel model) throws CDKException, IOException{ logger.info("Reading partial atomic charges"); IAtomContainerSet moleculeSet = model.getMoleculeSet(); IAtomContainer molecule = moleculeSet.getAtomContainer(0); String line = input.readLine(); while (input.ready()) { line = input.readLine(); logger.debug("Read charge block line: " + line); if ((line == null) || (line.indexOf("Sum of Mulliken charges") >= 0)) { logger.debug("End of charge block found"); break; } StringReader sr = new StringReader(line); StreamTokenizer tokenizer = new StreamTokenizer(sr); if (tokenizer.nextToken() == StreamTokenizer.TT_NUMBER) { int atomCounter = (int) tokenizer.nval; tokenizer.nextToken(); double charge; if (tokenizer.nextToken() == StreamTokenizer.TT_NUMBER) { charge = tokenizer.nval; logger.debug("Found charge for atom " + atomCounter + ": " + charge); } else { throw new CDKException("Error while reading charge: expected double."); } IAtom atom = molecule.getAtom(atomCounter - 1); atom.setCharge(charge); } } }
/storage/io/src/main/java/org/openscience/cdk/io/Gaussian98Reader.java
robustness-copilot_data_781
/** * Reorders the {@link ILigand} objects in the array according to the CIP rules. * * @param ligands Array of {@link ILigand}s to be reordered. * @return Reordered array of {@link ILigand}s. */ public static ILigand[] order(ILigand[] ligands){ ILigand[] newLigands = new ILigand[ligands.length]; System.arraycopy(ligands, 0, newLigands, 0, ligands.length); Arrays.sort(newLigands, cipRule); return newLigands; }
/descriptor/cip/src/main/java/org/openscience/cdk/geometry/cip/CIPTool.java
robustness-copilot_data_782
/** * Connect and initialize a channel from {@link ConnectionBuilder}. * * @param connectionBuilder must not be {@code null}. * @return the {@link ConnectionFuture} to synchronize the connection process. * @since 4.4 */ protected ConnectionFuture<T> initializeChannelAsync(ConnectionBuilder connectionBuilder){ Mono<SocketAddress> socketAddressSupplier = connectionBuilder.socketAddress(); if (clientResources.eventExecutorGroup().isShuttingDown()) { throw new IllegalStateException("Cannot connect, Event executor group is terminated."); } CompletableFuture<SocketAddress> socketAddressFuture = new CompletableFuture<>(); CompletableFuture<Channel> channelReadyFuture = new CompletableFuture<>(); socketAddressSupplier.doOnError(socketAddressFuture::completeExceptionally).doOnNext(socketAddressFuture::complete).subscribe(redisAddress -> { if (channelReadyFuture.isCancelled()) { return; } initializeChannelAsync0(connectionBuilder, channelReadyFuture, redisAddress); }, channelReadyFuture::completeExceptionally); return new DefaultConnectionFuture<>(socketAddressFuture, channelReadyFuture.thenApply(channel -> (T) connectionBuilder.connection())); }
/src/main/java/io/lettuce/core/AbstractRedisClient.java
robustness-copilot_data_783
/** * Tries double bond combinations for a certain input container of which the double bonds have been stripped * around the mobile hydrogen positions. Recursively. * * @param container * @param dblBondsAdded counts double bonds added so far * @param bondOffSet offset for next double bond position to consider * @param doubleBondMax maximum number of double bonds to add * @param atomsInNeedOfFix atoms that require more bonds * @return a list of double bond positions (index) that make a valid combination, null if none found */ private List<Integer> tryDoubleBondCombinations(IAtomContainer container, int dblBondsAdded, int bondOffSet, int doubleBondMax, List<IAtom> atomsInNeedOfFix){ int offSet = bondOffSet; List<Integer> dblBondPositions = null; while (offSet < container.getBondCount() && dblBondPositions == null) { IBond bond = container.getBond(offSet); if (atomsInNeedOfFix.contains(bond.getBegin()) && atomsInNeedOfFix.contains(bond.getEnd())) { bond.setOrder(IBond.Order.DOUBLE); dblBondsAdded = dblBondsAdded + 1; if (dblBondsAdded == doubleBondMax) { boolean validDoubleBondConfig = true; CHECK: for (IAtom atom : container.atoms()) { if (atom.getValency() != atom.getImplicitHydrogenCount() + getConnectivity(atom, container)) { validDoubleBondConfig = false; break CHECK; } } if (validDoubleBondConfig) { dblBondPositions = new ArrayList<Integer>(); for (int idx = 0; idx < container.getBondCount(); idx++) { if (container.getBond(idx).getOrder().equals(IBond.Order.DOUBLE)) dblBondPositions.add(idx); } return dblBondPositions; } } else { dblBondPositions = tryDoubleBondCombinations(container, dblBondsAdded, offSet + 1, doubleBondMax, atomsInNeedOfFix); } bond.setOrder(IBond.Order.SINGLE); dblBondsAdded = dblBondsAdded - 1; } offSet++; } return dblBondPositions; }
/tool/tautomer/src/main/java/org/openscience/cdk/tautomers/InChITautomerGenerator.java
robustness-copilot_data_784
/** * Extract the charge position given a molecular formula format [O3S]2-. * * @param formula The formula to inspect * @return The charge position in the string */ private static int findChargePosition(String formula){ int end = formula.length() - 1; int pos = end; while (pos >= 0 && isSign(formula.charAt(pos))) pos--; int mark1 = pos; while (pos >= 0 && isDigit(formula.charAt(pos))) pos--; int mark2 = pos; while (pos >= 0 && isSign(formula.charAt(pos))) pos--; if (pos == mark2 && formula.charAt(pos) != ']') pos = mark1; return pos + 1; }
/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
robustness-copilot_data_785
/** * Judge whether current sharding items are all register start success. * * @param shardingItems current sharding items * @return current sharding items are all start success or not */ public boolean isRegisterStartSuccess(final Collection<Integer> shardingItems){ for (int each : shardingItems) { if (!jobNodeStorage.isJobNodeExisted(GuaranteeNode.getStartedNode(each))) { return false; } } return true; }
/elasticjob-lite/elasticjob-lite-core/src/main/java/org/apache/shardingsphere/elasticjob/lite/internal/guarantee/GuaranteeService.java
robustness-copilot_data_786
/** * Obtain the parity (winding) of a tetrahedral element. The parity is -1 * for clockwise (odd), +1 for anticlockwise (even) and 0 for unspecified. * * @param stereo configuration * @return the parity */ private int parity(ITetrahedralChirality.Stereo stereo){ switch(stereo) { case CLOCKWISE: return -1; case ANTI_CLOCKWISE: return +1; default: return 0; } }
/tool/sdg/src/main/java/org/openscience/cdk/layout/NonplanarBonds.java
robustness-copilot_data_787
/** * Main method which assigns Gasteiger Marisili partial sigma charges. * *@param ac AtomContainer *@param setCharge The Charge *@return AtomContainer with partial charges *@exception Exception Possible Exceptions */ public IAtomContainer assignGasteigerMarsiliSigmaPartialCharges(IAtomContainer ac, boolean setCharge) throws Exception{ for (int i = 0; i < ac.getAtomCount(); i++) ac.getAtom(i).setCharge(0.0); double[] gasteigerFactors = assignGasteigerSigmaMarsiliFactors(ac); double alpha = 1.0; double q; double deoc; IAtom[] atoms = null; int atom1 = 0; int atom2 = 0; double[] q_old = new double[ac.getAtomCount()]; for (int i = 0; i < q_old.length; i++) q_old[0] = 20.0; out: for (int i = 0; i < MX_ITERATIONS; i++) { alpha *= MX_DAMP; boolean isDifferent = false; for (int j = 0; j < ac.getAtomCount(); j++) { q = gasteigerFactors[STEP_SIZE * j + j + 5]; double difference = Math.abs(q_old[j]) - Math.abs(q); if (Math.abs(difference) > 0.001) isDifferent = true; q_old[j] = q; gasteigerFactors[STEP_SIZE * j + j + 4] = gasteigerFactors[STEP_SIZE * j + j + 2] * q * q + gasteigerFactors[STEP_SIZE * j + j + 1] * q + gasteigerFactors[STEP_SIZE * j + j]; } if (!isDifferent) break out; Iterator<IBond> bonds = ac.bonds().iterator(); while (bonds.hasNext()) { IBond bond = (IBond) bonds.next(); atom1 = ac.indexOf(bond.getBegin()); atom2 = ac.indexOf(bond.getEnd()); if (gasteigerFactors[STEP_SIZE * atom1 + atom1 + 4] >= gasteigerFactors[STEP_SIZE * atom2 + atom2 + 4]) { if ("H".equals(ac.getAtom(atom2).getSymbol())) { deoc = DEOC_HYDROGEN; } else { deoc = gasteigerFactors[STEP_SIZE * atom2 + atom2 + 3]; } } else { if ("H".equals(ac.getAtom(atom1).getSymbol())) { deoc = DEOC_HYDROGEN; } else { deoc = gasteigerFactors[STEP_SIZE * atom1 + atom1 + 3]; } } q = (gasteigerFactors[STEP_SIZE * atom1 + atom1 + 4] - gasteigerFactors[STEP_SIZE * atom2 + atom2 + 4]) / deoc; gasteigerFactors[STEP_SIZE * atom1 + atom1 + 5] -= (q * alpha); gasteigerFactors[STEP_SIZE * atom2 + atom2 + 5] += (q * alpha); } } for (int i = 0; i < ac.getAtomCount(); i++) { ac.getAtom(i).setCharge(gasteigerFactors[STEP_SIZE * i + i + 5]); } return ac; }
/tool/charges/src/main/java/org/openscience/cdk/charges/GasteigerMarsiliPartialCharges.java
robustness-copilot_data_788
/** * Performs a breadthFirstSearch in an AtomContainer starting with a * particular sphere, which usually consists of one start atom, and searches * for the longest aliphatic chain which is yet unplaced. If the search * encounters an unplaced ring atom, it is also appended to the chain so that * this last bond of the chain can also be laid out. This gives us the * orientation for the attachment of the ring system. * *@param ac The AtomContainer to * be searched *@param sphere A sphere of atoms to * start the search with *@param pathes A vector of N pathes * (N = no of heavy atoms). *@exception org.openscience.cdk.exception.CDKException Description of the * Exception */ public static void breadthFirstSearch(IAtomContainer ac, List<IAtom> sphere, IAtomContainer[] pathes) throws CDKException{ IAtom atom = null; IAtom nextAtom = null; int atomNr; int nextAtomNr; List<IAtom> newSphere = new ArrayList<IAtom>(); logger.debug("Start of breadthFirstSearch"); for (int f = 0; f < sphere.size(); f++) { atom = sphere.get(f); if (!atom.getFlag(CDKConstants.ISINRING)) { atomNr = ac.indexOf(atom); logger.debug("BreadthFirstSearch around atom " + (atomNr + 1)); List bonds = ac.getConnectedBondsList(atom); for (int g = 0; g < bonds.size(); g++) { IBond curBond = (IBond) bonds.get(g); nextAtom = curBond.getOther(atom); if (!nextAtom.getFlag(CDKConstants.VISITED) && !nextAtom.getFlag(CDKConstants.ISPLACED)) { nextAtomNr = ac.indexOf(nextAtom); logger.debug("BreadthFirstSearch is meeting new atom " + (nextAtomNr + 1)); pathes[nextAtomNr] = ac.getBuilder().newInstance(IAtomContainer.class, pathes[atomNr]); logger.debug("Making copy of path " + (atomNr + 1) + " to form new path " + (nextAtomNr + 1)); pathes[nextAtomNr].addAtom(nextAtom); logger.debug("Adding atom " + (nextAtomNr + 1) + " to path " + (nextAtomNr + 1)); pathes[nextAtomNr].addBond(curBond); if (ac.getConnectedBondsCount(nextAtom) > 1) { newSphere.add(nextAtom); } } } } } if (newSphere.size() > 0) { for (int f = 0; f < newSphere.size(); f++) { newSphere.get(f).setFlag(CDKConstants.VISITED, true); } breadthFirstSearch(ac, newSphere, pathes); } logger.debug("End of breadthFirstSearch"); }
/tool/sdg/src/main/java/org/openscience/cdk/layout/AtomPlacer.java
robustness-copilot_data_789
/** * Exclude subsequent generated nodes, if they are consecutive and on the same line. */ private static boolean isGeneratedNodeExcluded(AstNode astNode){ var prev = astNode.getPreviousAstNode(); return prev != null && prev.getTokenLine() == astNode.getTokenLine() && prev.isCopyBookOrGeneratedNode(); }
/cxx-checks/src/main/java/org/sonar/cxx/checks/metrics/TooManyStatementsPerLineCheck.java
robustness-copilot_data_790
/** * Creates a new module / config-group with the specified name. * * @param name * The name of the config-group to be created. * * @return the newly created config group * @throws IllegalArgumentException * if a config-group with the specified name already exists. */ public final ConfigGroup createModule(final String name){ if (this.modules.containsKey(name)) { throw new IllegalArgumentException("Module " + name + " exists already."); } ConfigGroup m = new ConfigGroup(name); this.modules.put(name, m); return m; }
/matsim/src/main/java/org/matsim/core/config/Config.java
robustness-copilot_data_791
/** * Method called to locate deserializer ahead of time, if permitted * by configuration. Method also is NOT to throw an exception if * access fails. */ protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType){ if ((valueType == null) || !_config.isEnabled(DeserializationFeature.EAGER_DESERIALIZER_FETCH)) { return null; } JsonDeserializer<Object> deser = _rootDeserializers.get(valueType); if (deser == null) { try { DeserializationContext ctxt = createDummyDeserializationContext(); deser = ctxt.findRootValueDeserializer(valueType); if (deser != null) { _rootDeserializers.put(valueType, deser); } return deser; } catch (JacksonException e) { } } return deser; }
/src/main/java/com/fasterxml/jackson/databind/ObjectReader.java
robustness-copilot_data_792
/** * Generate a new geometric parity (2D or 3D) for the given molecule and * atom indices. This method ensure that 2D and 3D coordinates are available * on the specified atoms and returns null if the 2D or 3D coordinates are * not fully available. * * @param mol a molecule * @param l left double bonded atom * @param r right double bonded atom * @param l1 first substituent atom of <i>l</i> * @param l2 second substituent atom of <i>l</i> or <i>l</i> if there is * none * @param r1 first substituent atom of <i>r</i> * @param r2 second substituent atom of <i>r</i> or <i>r</i> if there is * none * @return geometric parity or null */ static GeometricParity geometric(IAtomContainer mol, int l, int r, int l1, int l2, int r1, int r2){ Point2d l2d = mol.getAtom(l).getPoint2d(); Point2d r2d = mol.getAtom(r).getPoint2d(); Point2d l12d = mol.getAtom(l1).getPoint2d(); Point2d l22d = mol.getAtom(l2).getPoint2d(); Point2d r12d = mol.getAtom(r1).getPoint2d(); Point2d r22d = mol.getAtom(r2).getPoint2d(); if (l2d != null && r2d != null && l12d != null && l22d != null && r12d != null && r22d != null) { return new DoubleBond2DParity(l2d, r2d, l12d, l22d, r12d, r22d); } Point3d l3d = mol.getAtom(l).getPoint3d(); Point3d r3d = mol.getAtom(r).getPoint3d(); Point3d l13d = mol.getAtom(l1).getPoint3d(); Point3d r13d = mol.getAtom(r1).getPoint3d(); if (l3d != null && r3d != null && l13d != null && r13d != null) return new DoubleBond3DParity(l3d, r3d, l13d, r13d); return null; }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricDoubleBondEncoderFactory.java
robustness-copilot_data_793
/** * Given a file path, loads the contents of the files into a map. * * @param rootDir the path to the top-level directory * @return a map of file names to string contents. * @throws IOException if an error occurs during the read */ static Map<String, String> loadContents(Path rootDir) throws IOException{ try (Stream<Path> walk = Files.walk(rootDir, 1)) { return walk.filter(path -> !Files.isDirectory(path)).collect(Collectors.toMap(FileGroupReader::asString, FileGroupReader::readContents)); } }
/operator/src/main/java/oracle/kubernetes/operator/helpers/FileGroupReader.java
robustness-copilot_data_794
/** * Find out if the entity 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 entity to be searched * @param entityTypeName the type name of the entity * * @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> findEntity(String userId, String qualifiedName, String entityTypeName) throws UserNotAuthorizedException, PropertyServerException, InvalidParameterException{ final String methodName = "findEntity"; invalidParameterHandler.validateUserId(userId, methodName); invalidParameterHandler.validateName(qualifiedName, CommonMapper.QUALIFIED_NAME_PROPERTY_NAME, methodName); qualifiedName = repositoryHelper.getExactMatchRegex(qualifiedName); InstanceProperties properties = repositoryHelper.addStringPropertyToInstance(serviceName, null, CommonMapper.QUALIFIED_NAME_PROPERTY_NAME, qualifiedName, methodName); TypeDef entityTypeDef = repositoryHelper.getTypeDefByName(userId, entityTypeName); Optional<EntityDetail> retrievedEntity = Optional.ofNullable(repositoryHandler.getUniqueEntityByName(userId, qualifiedName, CommonMapper.QUALIFIED_NAME_PROPERTY_NAME, properties, entityTypeDef.getGUID(), entityTypeDef.getName(), methodName)); log.trace("Searching for entity with qualifiedName: {}. Result is {}", qualifiedName, retrievedEntity.map(InstanceHeader::getGUID).orElse(null)); return retrievedEntity; }
/open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEngineCommonHandler.java
robustness-copilot_data_795
/** * Atom-atom mapping of the input molecule to the bare container constructed from the InChI connection table. * This makes it possible to map the positions of the mobile hydrogens in the InChI back to the input molecule. * @param inchiMolGraph molecule (bare) as defined in InChI * @param mol user input molecule * @throws CDKException */ private void mapInputMoleculeToInchiMolgraph(IAtomContainer inchiMolGraph, IAtomContainer mol) throws CDKException{ Iterator<Map<IAtom, IAtom>> iter = org.openscience.cdk.isomorphism.VentoFoggia.findIdentical(inchiMolGraph, AtomMatcher.forElement(), BondMatcher.forAny()).matchAll(mol).limit(1).toAtomMap().iterator(); if (iter.hasNext()) { for (Map.Entry<IAtom, IAtom> e : iter.next().entrySet()) { IAtom src = e.getKey(); IAtom dst = e.getValue(); String position = src.getID(); dst.setID(position); LOGGER.debug("Mapped InChI ", src.getSymbol(), " ", src.getID(), " to ", dst.getSymbol(), " " + dst.getID()); } } else { throw new IllegalArgumentException(CANSMI.create(inchiMolGraph) + " " + CANSMI.create(mol)); } }
/tool/tautomer/src/main/java/org/openscience/cdk/tautomers/InChITautomerGenerator.java
robustness-copilot_data_796
/** * Waits for the counter to change to a value different from * <code>value</code>. * <p> * The method returns when one of the following happens: * <p> * * The current counter value is different from the * <code>value</code> argument; or * <p> * * Some other thread invokes the <code>increment</code> method for this AtomicCounter; or * <p> * * Some other thread interrupts the current thread; or * <p> * * The specified deadline elapses; or * <p> * * A "spurious wakeup" occurs. * * @param value the value to wait for the counter to change away from * @param deadline the absolute time to wait until * @return true if the counter has a different value than {@code value} upon return * @throw InterruptedException if the current thread is interrupted */ public boolean awaitChangeUntil(int value, Date deadline) throws InterruptedException{ _lock.lock(); try { inLock(); return _counter != value || _updated.awaitUntil(deadline); } finally { _lock.unlock(); } }
/modules/common/src/main/java/org/dcache/util/AtomicCounter.java
robustness-copilot_data_797
/** * Shift the containers in a reaction vertically upwards to not overlap * with the reference Rectangle2D. The shift is such that the given * gap is realized, but only if the reactions are actually overlapping. * * @param reaction the reaction to shift * @param bounds the bounds of the reaction to shift * @param last the bounds of the last reaction * @return the Rectangle2D of the shifted reaction */ public static Rectangle2D shiftReactionVertical(IReaction reaction, Rectangle2D bounds, Rectangle2D last, double gap){ if (last.getMaxY() + gap >= bounds.getMinY()) { double yShift = bounds.getHeight() + last.getHeight() + gap; Vector2d shift = new Vector2d(0, yShift); List<IAtomContainer> containers = ReactionManipulator.getAllAtomContainers(reaction); for (IAtomContainer container : containers) { translate2D(container, shift); } return new Rectangle2D.Double(bounds.getX(), bounds.getY() + yShift, bounds.getWidth(), bounds.getHeight()); } else { return bounds; } }
/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java
robustness-copilot_data_798
/** * Add a new singleton cell to the end of the partition containing only * this element. * * @param element the element to add in its own cell */ public void addSingletonCell(int element){ SortedSet<Integer> cell = new TreeSet<Integer>(); cell.add(element); this.cells.add(cell); }
/tool/group/src/main/java/org/openscience/cdk/group/Partition.java
robustness-copilot_data_799
/** * Convert a binary representation back into an event receiver's list of desired events. * * @param data the binary data * @return a Map between the target and its set of desired event types. * @throws IllegalArgumentException if the data is badly formatted. */ public static Map<PnfsId, EnumSet<EventType>> fromZkData(byte[] data){ checkArgument(data.length > 1, "Too little data"); checkArgument(data[0] == 0, "Wrong format"); Map<PnfsId, EnumSet<EventType>> deserialised = new HashMap<>(); int index = 1; while (index < data.length) { checkArgument(data.length - index >= 3, "Too little data for bitmask"); short bitmask = (short) (data[index++] << 8 | data[index++] & 0xFF); EnumSet<EventType> eventTypes = Arrays.stream(EventType.values()).filter(t -> (bitmask & 1 << t.ordinal()) != 0).collect(Collectors.toCollection(() -> EnumSet.noneOf(EventType.class))); byte length = data[index++]; checkArgument(data.length - index >= length, "Too little data for PNFSID"); PnfsId id = new PnfsId(BaseEncoding.base16().encode(data, index, length)); index += length; deserialised.put(id, eventTypes); LOGGER.debug("Adding id={} bitmask={} types={}", id, bitmask, eventTypes); } return deserialised; }
/modules/dcache/src/main/java/diskCacheV111/namespace/EventNotifier.java
robustness-copilot_data_800
/** * Exchange the elements at index i with that at index j. * * @param values an array of values * @param i an index * @param j another index */ private static void exch(long[] values, int i, int j){ long k = values[i]; values[i] = values[j]; values[j] = k; }
/storage/inchi/src/main/java/org/openscience/cdk/graph/invariant/InChINumbersTools.java