Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
25
27
content
stringlengths
190
15.4k
max_stars_repo_path
stringlengths
31
217
robustness-copilot_data_1
/** * Internal - load the SMARTS patterns for each atom type from MMFFSYMB.sma. * * @param smaIn input stream of MMFFSYMB.sma * @return array of patterns * @throws IOException */ static AtomTypePattern[] loadPatterns(InputStream smaIn) throws IOException{ List<AtomTypePattern> matchers = new ArrayList<AtomTypePattern>(); BufferedReader br = new BufferedReader(new InputStreamReader(smaIn)); String line = null; while ((line = br.readLine()) != null) { if (skipLine(line)) continue; String[] cols = line.split(" "); String sma = cols[0]; String symb = cols[1]; try { matchers.add(new AtomTypePattern(SmartsPattern.create(sma).setPrepare(false), symb)); } catch (IllegalArgumentException ex) { throw new IOException(ex); } } return matchers.toArray(new AtomTypePattern[matchers.size()]); }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAtomTypeMatcher.java
robustness-copilot_data_2
/** * Translates a attribute name into a name suitable for a named capturing group. */ private static String toGroupName(String attribute){ int pos = attribute.indexOf(';'); if (pos > -1) { attribute = attribute.substring(0, pos); } return attribute.replace("X", "XX").replace(".", "X"); }
/modules/dcache/src/main/java/org/dcache/services/billing/text/BillingParserBuilder.java
robustness-copilot_data_3
/** * Changes the position of the given Node n in the pendingNodes queue and * updates its time and cost information. * * @param n * The Node that is revisited. * @param data * The data for n. * @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 outLink * The link from which we came visiting n. */ void revisitNode(final Node n, final DijkstraNodeData data, final RouterPriorityQueue<Node> pendingNodes, final double time, final double cost, final Link outLink){ pendingNodes.remove(n); data.visit(outLink, cost, time, getIterationId()); pendingNodes.add(n, getPriority(data)); }
/matsim/src/main/java/org/matsim/pt/router/TransitLeastCostPathTree.java
robustness-copilot_data_4
/** * Insert the vertex 'v' into sorted position in the array 'vs'. * * @param v a vertex (int id) * @param vs array of vertices (int ids) * @return array with 'u' inserted in sorted order */ private static int[] insert(int v, int[] vs){ final int n = vs.length; final int[] ws = Arrays.copyOf(vs, n + 1); ws[n] = v; for (int i = n; i > 0 && ws[i] < ws[i - 1]; i--) { int tmp = ws[i]; ws[i] = ws[i - 1]; ws[i - 1] = tmp; } return ws; }
/storage/smiles/src/main/java/org/openscience/cdk/smiles/BeamToCDK.java
robustness-copilot_data_5
/** * Handler for when a JSON element is an Object, representing a resource. * * @param key String * @param parentResource Resource * @throws IOException exception * @throws RepositoryException exception */ private void createOrUpdateNodesForJsonObject(final ResourceResolver remoteAssetsResolver, final String key, final Resource parentResource) throws IOException, RepositoryException{ if (PROTECTED_NODES.contains(key)) { return; } String objectPath = String.format("%s/%s", parentResource.getPath(), key); JsonObject jsonObjectWithChildren = getJsonFromUri(objectPath); String resourcePrimaryType = jsonObjectWithChildren.getAsJsonPrimitive(JcrConstants.JCR_PRIMARYTYPE).getAsString(); Resource resource = getOrCreateNode(remoteAssetsResolver, objectPath, resourcePrimaryType); createOrUpdateNodes(remoteAssetsResolver, jsonObjectWithChildren, resource); ValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class); if (DamConstants.NT_DAM_ASSET.equals(parentResource.getValueMap().get(JcrConstants.JCR_PRIMARYTYPE, String.class)) && DamConstants.NT_DAM_ASSETCONTENT.equals(resourceProperties.get(JcrConstants.JCR_PRIMARYTYPE, String.class))) { resourceProperties.put(RemoteAssets.IS_REMOTE_ASSET, true); LOG.trace("Property '{}' added for resource '{}'.", RemoteAssets.IS_REMOTE_ASSET, resource.getPath()); this.saveRefreshCount++; if (this.saveRefreshCount == this.remoteAssetsConfig.getSaveInterval()) { this.saveRefreshCount = 0; remoteAssetsResolver.commit(); remoteAssetsResolver.refresh(); LOG.info("Executed incremental save of node sync."); } } }
/bundle/src/main/java/com/adobe/acs/commons/remoteassets/impl/RemoteAssetsNodeSyncImpl.java
robustness-copilot_data_6
/** * Converts a JSON workflow configuration to a workflow object. * * @param json JSON for workflow * @return a workflow rule target object * @throws IOException if unable to create object */ public static Workflow fromJson(String json) throws IOException{ ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, Workflow.class); }
/src/main/java/com/twilio/taskrouter/Workflow.java
robustness-copilot_data_7
/** * Returns the time in millisecond until the next ticket. * @return the time in millisecond until the next ticket. */ public long timeout(){ if (tickets.isEmpty()) { return -1; } sortIfNeeded(); Ticket first = tickets.get(0); return first.start - now() + first.delay; }
/src/main/java/org/zeromq/timer/ZTicket.java
robustness-copilot_data_8
/** * Specifies the version of the Kubernetes schema to use. * * @param version a Kubernetes version string, such as "1.9.0" * @throws IOException if no schema for that version is cached. */ public void useKubernetesVersion(String version) throws IOException{ KubernetesSchemaReference reference = KubernetesSchemaReference.create(version); URL cacheUrl = reference.getKubernetesSchemaCacheUrl(); if (cacheUrl == null) { throw new IOException("No schema cached for Kubernetes " + version); } addExternalSchema(reference.getKubernetesSchemaUrl(), cacheUrl); }
/json-schema-generator/src/main/java/oracle/kubernetes/json/SchemaGenerator.java
robustness-copilot_data_9
/** * adds a CacheEntry to the list of HSM storage requests. * * @param entry */ public synchronized void addCacheEntry(CacheEntry entry) throws CacheException, InterruptedException{ FileAttributes fileAttributes = entry.getFileAttributes(); String storageClass = fileAttributes.getStorageClass(); String hsmName = fileAttributes.getHsm().toLowerCase(); String composedName = storageClass + "@" + hsmName; StorageClassInfo classInfo = _storageClasses.get(composedName); if (classInfo == null) { classInfo = new StorageClassInfo(_storageHandler, hsmName, storageClass); StorageClassInfo tmpInfo = _storageClasses.get("*@" + hsmName); if (tmpInfo != null) { classInfo.setExpiration(tmpInfo.getExpiration()); classInfo.setPending(tmpInfo.getPending()); classInfo.setMaxSize(tmpInfo.getMaxSize()); classInfo.setOpen(tmpInfo.isOpen()); } _storageClasses.put(composedName, classInfo); } classInfo.add(entry); _pnfsIds.put(entry.getPnfsId(), classInfo); }
/modules/dcache/src/main/java/org/dcache/pool/classic/StorageClassContainer.java
robustness-copilot_data_10
/** * Find the longest prefix from position (i) in this string that * is present in the trie symbol table. * * @param trie trie node (start with root) * @param string string to find a prefix of * @param i the position in the string * @param best best score so far (-1 to start) * @return the length of the prefix */ private static int findPrefix(Trie trie, String string, int i, int best){ if (trie == null) return best; if (trie.token != null) best = i; if (i == string.length()) return best; final char c = norm(string.charAt(i)); if (c > 128) return best; return findPrefix(trie.children[c], string, i + 1, best); }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/AbbreviationLabel.java
robustness-copilot_data_11
/** * Returns a hash code for {@code obj}. * * @param obj * The object to get a hash code for. May be an array or <code>null</code>. * @return A hash code of {@code obj} or 0 if {@code obj} is <code>null</code> */ public static int hashCode(Object obj){ if (obj == null) { // for consistency with Arrays#hashCode() and Objects#hashCode() return 0; } final Class<?> clazz = obj.getClass(); if (!clazz.isArray()) { return obj.hashCode(); } final Class<?> componentType = clazz.getComponentType(); if (long.class.equals(componentType)) { return Arrays.hashCode((long[]) obj); } else if (int.class.equals(componentType)) { return Arrays.hashCode((int[]) obj); } else if (short.class.equals(componentType)) { return Arrays.hashCode((short[]) obj); } else if (char.class.equals(componentType)) { return Arrays.hashCode((char[]) obj); } else if (byte.class.equals(componentType)) { return Arrays.hashCode((byte[]) obj); } else if (boolean.class.equals(componentType)) { return Arrays.hashCode((boolean[]) obj); } else if (float.class.equals(componentType)) { return Arrays.hashCode((float[]) obj); } else if (double.class.equals(componentType)) { return Arrays.hashCode((double[]) obj); } else { return Arrays.hashCode((Object[]) obj); } }
/src/main/java/org/apache/ibatis/reflection/ArrayUtil.java
robustness-copilot_data_12
/** * Writes a single frame in XYZ format to the Writer. * * @param mol the Molecule to write * @throws java.io.IOException if there is an error during writing */ public void writeMolecule(IAtomContainer mol) throws IOException{ matcher = SybylAtomTypeMatcher.getInstance(mol.getBuilder()); try { logger.debug("Writing header..."); if (mol.getTitle() != null) { writer.write("# Name: " + mol.getTitle()); writer.write('\n'); } writer.write('\n'); logger.debug("Writing molecule block..."); writer.write("@<TRIPOS>MOLECULE"); writer.write('\n'); if (mol.getID() == null) { writer.write("CDKMolecule"); } else { writer.write(mol.getID()); } writer.write('\n'); writer.write(mol.getAtomCount() + " " + mol.getBondCount()); writer.write('\n'); writer.write("SMALL"); writer.write('\n'); writer.write("NO CHARGES"); writer.write('\n'); logger.debug("Writing atom block..."); writer.write("@<TRIPOS>ATOM"); writer.write('\n'); for (int i = 0; i < mol.getAtomCount(); i++) { IAtom atom = mol.getAtom(i); writer.write((i + 1) + " " + atom.getSymbol() + (mol.indexOf(atom) + 1) + " "); if (atom.getPoint3d() != null) { writer.write(atom.getPoint3d().x + " "); writer.write(atom.getPoint3d().y + " "); writer.write(atom.getPoint3d().z + " "); } else if (atom.getPoint2d() != null) { writer.write(atom.getPoint2d().x + " "); writer.write(atom.getPoint2d().y + " "); writer.write(" 0.000 "); } else { writer.write("0.000 0.000 0.000 "); } IAtomType sybylType = null; try { sybylType = matcher.findMatchingAtomType(mol, atom); } catch (CDKException e) { e.printStackTrace(); } if (sybylType != null) { writer.write(sybylType.getAtomTypeName()); } else { writer.write(atom.getSymbol()); } writer.write('\n'); } logger.debug("Writing bond block..."); writer.write("@<TRIPOS>BOND"); writer.write('\n'); int counter = 0; for (IBond bond : mol.bonds()) { String sybylBondOrder = "-1"; if (bond.getOrder().equals(IBond.Order.SINGLE)) sybylBondOrder = "1"; else if (bond.getOrder().equals(IBond.Order.DOUBLE)) sybylBondOrder = "2"; else if (bond.getOrder().equals(IBond.Order.TRIPLE)) sybylBondOrder = "3"; if (bond.getFlag(CDKConstants.ISAROMATIC)) sybylBondOrder = "ar"; final IAtom bondAtom1 = bond.getBegin(); final IAtom bondAtom2 = bond.getEnd(); try { final IAtomType bondAtom1Type = matcher.findMatchingAtomType(mol, bondAtom1); final IAtomType bondAtom2Type = matcher.findMatchingAtomType(mol, bondAtom2); if (bondAtom1Type != null && bondAtom2Type != null && ((bondAtom1Type.getAtomTypeName().equals("N.am") && bondAtom2Type.getAtomTypeName().equals("C.2")) || (bondAtom2Type.getAtomTypeName().equals("N.am") && bondAtom1Type.getAtomTypeName().equals("C.2")))) { sybylBondOrder = "am"; } } catch (CDKException e) { e.printStackTrace(); } writer.write((counter + 1) + " " + (mol.indexOf(bond.getBegin()) + 1) + " " + (mol.indexOf(bond.getEnd()) + 1) + " " + sybylBondOrder); writer.write('\n'); counter++; } } catch (IOException e) { throw e; } }
/storage/io/src/main/java/org/openscience/cdk/io/Mol2Writer.java
robustness-copilot_data_13
/** * True is all the atoms in the given AtomContainer have been placed. * * @param ac The AtomContainer to be searched * @return True is all the atoms in the given AtomContainer have been placed */ public boolean allHeavyAtomsPlaced(IAtomContainer ac){ for (int i = 0; i < ac.getAtomCount(); i++) { if (isUnplacedHeavyAtom(ac.getAtom(i))) { return false; } } return true; }
/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java
robustness-copilot_data_14
/** * Enqueue an event in the ring buffer, retrying if allowed by the configuration. * * @param event the event to add to the ring buffer * @return {@code true} if the event is successfully enqueued, {@code false} if the event * could not be added to the ring buffer. * @throws ShutdownInProgressException thrown when the appender is shutdown while retrying * to enqueue the event * @throws InterruptedException thrown when the logging thread is interrupted while retrying */ private boolean enqueue(Event event) throws ShutdownInProgressException, InterruptedException{ if (this.disruptor.getRingBuffer().tryPublishEvent(this.eventTranslator, event)) { return true; } if (this.appendTimeout.getMilliseconds() == 0) { return false; } long deadline = Long.MAX_VALUE; if (this.appendTimeout.getMilliseconds() < 0) { lock.lockInterruptibly(); } else { deadline = System.currentTimeMillis() + this.appendTimeout.getMilliseconds(); if (!lock.tryLock(this.appendTimeout.getMilliseconds(), TimeUnit.MILLISECONDS)) { return false; } } long backoff = 1L; long backoffLimit = TimeUnit.MILLISECONDS.toNanos(this.appendRetryFrequency.getMilliseconds()); try { do { if (!isStarted()) { throw new ShutdownInProgressException(); } if (deadline <= System.currentTimeMillis()) { return false; } if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } LockSupport.parkNanos(backoff); backoff = Math.min(backoff * 2, backoffLimit); } while (!this.disruptor.getRingBuffer().tryPublishEvent(this.eventTranslator, event)); return true; } finally { lock.unlock(); } }
/src/main/java/net/logstash/logback/appender/AsyncDisruptorAppender.java
robustness-copilot_data_15
/** * Draw some random numbers to better initialize the pseudo-random number generator. * * @param rng the random number generator to initialize. */ private static void prepareRNG(final Random rng){ for (int i = 0; i < 100; i++) { rng.nextDouble(); } }
/matsim/src/main/java/org/matsim/core/gbl/MatsimRandom.java
robustness-copilot_data_16
/** * Encode the provided path of atoms to a string. * * @param path inclusive array of vertex indices * @return encoded path */ private String encode(int[] path){ StringBuilder sb = new StringBuilder(path.length * 3); for (int i = 0, n = path.length - 1; i <= n; i++) { IAtom atom = container.getAtom(path[i]); sb.append(toAtomPattern(atom)); if (i < n) { IBond bond = container.getBond(container.getAtom(path[i]), container.getAtom(path[i + 1])); sb.append(getBondSymbol(bond)); } } return sb.toString(); }
/descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/ShortestPathWalker.java
robustness-copilot_data_17
/** * Maps the view row number to the row number on the underlying source table. * * @param rowNumber the row number in the view. * @return the matching row number in the underlying table. */ public int mappedRowNumber(int rowNumber){ if (isSorted()) { return sortOrder[rowNumber]; } else if (hasSelection()) { return selection.get(rowNumber); } return rowNumber; }
/core/src/main/java/tech/tablesaw/table/TableSlice.java
robustness-copilot_data_18
/** * Adds an {@link CarrierService} to the {@link Carrier}. * @param carrier * @param carrierService */ public static void addService(Carrier carrier, CarrierService carrierService){ carrier.getServices().put(carrierService.getId(), carrierService); }
/contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierUtils.java
robustness-copilot_data_19
/** * Applies the given function to a list subtag if it is present and its contents are compound * tags. Processes the list as a single object; to process each tag separately, instead use * {@link #iterateCompoundList(String, Consumer)}. * * @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 readCompoundList(@NonNls String key, Consumer<? super List<CompoundTag>> consumer){ return readList(key, TagType.COMPOUND, consumer); }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_20
/** * Creates a web hook object to track config map calls. * * @param namespace the namespace * @return the active web hook * @throws ApiException if there is an error on the call that sets up the web hook. */ public Watchable<V1ConfigMap> createConfigMapWatch(String namespace) throws ApiException{ return FACTORY.createWatch(callParams, V1ConfigMap.class, new ListNamespacedConfigMapCall(namespace)); }
/operator/src/main/java/oracle/kubernetes/operator/builders/WatchBuilder.java
robustness-copilot_data_21
/** * Creates a Function that returns a On instance with zero value. * * @param name - Cron field name * @return new CronField -> CronField instance, never null */ static Function<CronField, CronField> returnOnZeroExpression(final CronFieldName name){ return field -> { final FieldConstraints constraints = FieldConstraintsBuilder.instance().forField(name).createConstraintsInstance(); return new CronField(name, new On(new IntegerFieldValue(0)), constraints); }; }
/src/main/java/com/cronutils/mapper/CronMapper.java
robustness-copilot_data_22
/** * This uses an exponential distance weighting to calculate the impact of point based emissions onto the centroid of * a grid cell. The calculation is described in Kickhoefer's PhD thesis https://depositonce.tu-berlin.de/handle/11303/4386 * in Appendix A.2 * * @param emissionSource Centroid of the link * @param cellCentroid Centroid of the impacted cell * @return weight factor by which the emission value should be multiplied to calculate the impact of the cell */ public static double calculateWeightFromPoint(final Coordinate emissionSource, final Coordinate cellCentroid, double smoothingRadius){ if (smoothingRadius <= 0) throw new IllegalArgumentException("smoothing radius must be greater 0"); double dist = emissionSource.distance(cellCentroid); return Math.exp((-dist * dist) / (smoothingRadius * smoothingRadius)); }
/contribs/analysis/src/main/java/org/matsim/contrib/analysis/spatial/SpatialInterpolation.java
robustness-copilot_data_23
/** * Parses mobile H group(s) in an InChI String. * <p> * Multiple InChI sequences of mobile hydrogens are joined into a single sequence (list), * see step 1 of algorithm in paper. * <br> * Mobile H group has syntax (H[n][-[m]],a1,a2[,a3[,a4...]]) * Brackets [ ] surround optional terms. * <ul> * <li>Term H[n] stands for 1 or, if the number n (n>1) is present, n mobile hydrogen atoms.</li> * <li>Term [-[m]], if present, stands for 1 or, if the number m (m>1) is present, m mobile negative charges.</li> * <li>a1,a2[,a3[,a4...]] are canonical numbers of atoms in the mobile H group.</li> * <li>no two mobile H groups may have an atom (a canonical number) in common.</li> * </ul> * @param mobHydrAttachPositions list of positions where mobile H can attach * @param inputInchi InChI input * @return overall count of hydrogens to be dispersed over the positions */ private int parseMobileHydrogens(List<Integer> mobHydrAttachPositions, String inputInchi){ int totalMobHydrCount = 0; String hydrogens = ""; String inchi = inputInchi; if (inchi.indexOf("/h") != -1) { hydrogens = inchi.substring(inchi.indexOf("/h") + 2); if (hydrogens.indexOf('/') != -1) { hydrogens = hydrogens.substring(0, hydrogens.indexOf('/')); } String mobileHydrogens = hydrogens.substring(hydrogens.indexOf('(')); Pattern mobileHydrPattern = Pattern.compile("\\((.)*?\\)"); Matcher match = mobileHydrPattern.matcher(mobileHydrogens); while (match.find()) { String mobileHGroup = match.group(); int mobHCount = 0; String head = mobileHGroup.substring(0, mobileHGroup.indexOf(',') + 1); if (head.contains("H,")) head = head.replace("H,", "H1,"); if (head.contains("-,")) head = head.replace("-,", "-1,"); head = head.substring(2); Pattern subPattern = Pattern.compile("[0-9]*"); Matcher subMatch = subPattern.matcher(head); while (subMatch.find()) { if (!subMatch.group().equals("")) { mobHCount += Integer.valueOf(subMatch.group()); } } totalMobHydrCount += mobHCount; mobileHGroup = mobileHGroup.substring(mobileHGroup.indexOf(',') + 1).replace(")", ""); StringTokenizer tokenizer = new StringTokenizer(mobileHGroup, ","); while (tokenizer.hasMoreTokens()) { Integer position = Integer.valueOf(tokenizer.nextToken()); mobHydrAttachPositions.add(position); } } } LOGGER.debug("#total mobile hydrogens: ", totalMobHydrCount); return totalMobHydrCount; }
/tool/tautomer/src/main/java/org/openscience/cdk/tautomers/InChITautomerGenerator.java
robustness-copilot_data_24
/** * Scan for help fields: fh_(= full help) or hh_(= help hint). */ private static void scanFields(Object obj, Map<List<String>, AcCommandExecutor> commands){ for (Field field : obj.getClass().getFields()) { Iterator<String> i = Splitter.on('_').split(field.getName()).iterator(); FieldType helpMode; String helpType = i.next(); switch(helpType) { case "hh": helpMode = FieldType.HELP_HINT; break; case "fh": helpMode = FieldType.FULL_HELP; break; case "acl": helpMode = FieldType.ACL; break; default: continue; } if (!i.hasNext()) { continue; } List<String> name = Lists.newArrayList(i); AcCommandExecutor command = getCommandExecutor(obj, commands, name); switch(helpMode) { case FULL_HELP: command.setFullHelpField(field); break; case HELP_HINT: command.setHelpHintField(field); break; case ACL: command.setAclField(field); break; } } }
/modules/cells/src/main/java/dmg/util/command/AcCommandScanner.java
robustness-copilot_data_25
/** * Find out if the SchemaAttribute 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 */ private Optional<EntityDetail> findSchemaAttributeEntity(String userId, String qualifiedName) throws UserNotAuthorizedException, PropertyServerException, InvalidParameterException{ return dataEngineCommonHandler.findEntity(userId, qualifiedName, SCHEMA_ATTRIBUTE_TYPE_NAME); }
/open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEngineSchemaAttributeHandler.java
robustness-copilot_data_26
/** * batch delete some plugin handles by some id list. * @param ids plugin handle id list. * @return {@linkplain ShenyuAdminResult} */ public ShenyuAdminResult deletePluginHandles(@RequestBody @NotEmpty final List<@NotBlank String> ids){ return ShenyuAdminResult.success(ShenyuResultMessage.DELETE_SUCCESS, pluginHandleService.deletePluginHandles(ids)); }
/shenyu-admin/src/main/java/org/apache/shenyu/admin/controller/PluginHandleController.java
robustness-copilot_data_27
/** * Parse and return a JsonNode representation of the input OAS document. * * @param location the URL of the OAS document. * @param auths the list of authorization values to access the remote URL. * * @throws java.lang.Exception if an error occurs while retrieving the OpenAPI document. * * @return A JsonNode representation of the input OAS document. */ public static JsonNode readWithInfo(String location, List<AuthorizationValue> auths) throws Exception{ String data; location = location.replaceAll("\\\\", "/"); if (location.toLowerCase(Locale.ROOT).startsWith("http")) { data = RemoteUrl.urlToString(location, auths); } else { final String fileScheme = "file:"; Path path; if (location.toLowerCase(Locale.ROOT).startsWith(fileScheme)) { path = Paths.get(URI.create(location)); } else { path = Paths.get(location); } if (Files.exists(path)) { data = FileUtils.readFileToString(path.toFile(), "UTF-8"); } else { data = ClasspathHelper.loadFileFromClasspath(location); } } return getRightMapper(data).readTree(data); }
/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java
robustness-copilot_data_28
/** * Adds a strategy to this manager with the specified weight. This weight * compared to the sum of weights of all strategies in this manager defines * the probability this strategy will be used for an agent. * */ public final void addStrategy(final PlanStrategy strategy, final String subpopulation, final double weight){ delegate.addStrategy(strategy, subpopulation, weight); }
/matsim/src/main/java/org/matsim/core/replanning/StrategyManager.java
robustness-copilot_data_29
/** * Generate a transversal of a subgroup in this group. * * @param subgroup the subgroup to use for the transversal * @return a list of permutations */ public List<Permutation> transversal(final PermutationGroup subgroup){ final long m = this.order() / subgroup.order(); final List<Permutation> results = new ArrayList<Permutation>(); Backtracker transversalBacktracker = new Backtracker() { private boolean finished = false; @Override public void applyTo(Permutation p) { for (Permutation f : results) { Permutation h = f.invert().multiply(p); if (subgroup.test(h) == size) { return; } } results.add(p); if (results.size() >= m) { this.finished = true; } } @Override public boolean isFinished() { return finished; } }; this.apply(transversalBacktracker); return results; }
/tool/group/src/main/java/org/openscience/cdk/group/PermutationGroup.java
robustness-copilot_data_30
/** * When resolving a remote asset, first sync the asset from the remote server. * @param resource The resource being resolved. * @return The current resource. If the resource is a "remote" asset, it will * first be converted to a true local AEM asset by sync'ing in the rendition * binaries from the remote server. */ public Resource decorate(final Resource resource){ try { if (!this.accepts(resource)) { return resource; } } catch (Exception e) { // Logging at debug level b/c if this happens it could represent a ton of logging LOG.debug("Failed binary sync check for remote asset: {}", resource.getPath()); return resource; } boolean syncSuccessful = false; if (isAlreadySyncing(resource.getPath())) { syncSuccessful = waitForSyncInProgress(resource); } else { syncSuccessful = syncAssetBinaries(resource); } if (syncSuccessful) { LOG.trace("Refreshing resource after binary sync of {}", resource.getPath()); resource.getResourceResolver().refresh(); return resource.getResourceResolver().getResource(resource.getPath()); } else { return resource; } }
/bundle/src/main/java/com/adobe/acs/commons/remoteassets/impl/RemoteAssetDecorator.java
robustness-copilot_data_31
/** * Projects a CDKRGraph bitset on the source graph G1. * @param set CDKRGraph BitSet to project * @return The associate BitSet in G1 */ public BitSet projectG1(BitSet set){ BitSet projection = new BitSet(getFirstGraphSize()); CDKRNode xNode = null; for (int x = set.nextSetBit(0); x >= 0; x = set.nextSetBit(x + 1)) { xNode = getGraph().get(x); projection.set(xNode.getRMap().getId1()); } return projection; }
/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKRGraph.java
robustness-copilot_data_32
/** * Read the SMILES given in the input line - or return an empty container. * * @param line input line * @return the read container (or an empty one) */ private IAtomContainer readSmiles(final String line){ try { return sp.parseSmiles(line); } catch (CDKException e) { logger.error("Error while reading the SMILES from: " + line + ", ", e); final IAtomContainer empty = builder.newInstance(IAtomContainer.class, 0, 0, 0, 0); empty.setProperty(BAD_SMILES_INPUT, line); empty.setTitle(suffix(line)); return empty; } }
/storage/smiles/src/main/java/org/openscience/cdk/io/iterator/IteratingSMILESReader.java
robustness-copilot_data_33
/** * Attempt to create/parse a cookie from application configuration object. The namespace given * must be present and must defined a <code>name</code> property. * * The namespace might optionally defined: value, path, domain, secure, httpOnly and maxAge. * * @param namespace Cookie namespace/prefix. * @param conf Configuration object. * @return Parsed cookie or empty. */ public static Optional<Cookie> create(@Nonnull String namespace, @Nonnull Config conf){ if (conf.hasPath(namespace)) { Cookie cookie = new Cookie(conf.getString(namespace + ".name")); value(conf, namespace + ".value", Config::getString, cookie::setValue); value(conf, namespace + ".path", Config::getString, cookie::setPath); value(conf, namespace + ".domain", Config::getString, cookie::setDomain); value(conf, namespace + ".secure", Config::getBoolean, cookie::setSecure); value(conf, namespace + ".httpOnly", Config::getBoolean, cookie::setHttpOnly); value(conf, namespace + ".maxAge", (c, path) -> c.getDuration(path, TimeUnit.SECONDS), cookie::setMaxAge); value(conf, namespace + ".sameSite", (c, path) -> SameSite.of(c.getString(path)), cookie::setSameSite); return Optional.of(cookie); } return Optional.empty(); }
/jooby/src/main/java/io/jooby/Cookie.java
robustness-copilot_data_34
/** * Returns an iterator over elements of type {@code T}. * * @return an Iterator. */ public Iterator<LocalTime> iterator(){ return new Iterator<LocalTime>() { final IntIterator intIterator = intIterator(); @Override public boolean hasNext() { return intIterator.hasNext(); } @Override public LocalTime next() { return PackedLocalTime.asLocalTime(intIterator.nextInt()); } }; }
/core/src/main/java/tech/tablesaw/api/TimeColumn.java
robustness-copilot_data_35
/** * Using a fast identity template library, lookup the the ring system and assign coordinates. * The method indicates whether a match was found and coordinates were assigned. * * @param rs the ring set * @param molecule the rest of the compound * @param anon check for anonmised templates * @return coordinates were assigned */ private boolean lookupRingSystem(IRingSet rs, IAtomContainer molecule, boolean anon){ if (!useIdentTemplates) return false; final IChemObjectBuilder bldr = molecule.getBuilder(); final IAtomContainer ringSystem = bldr.newInstance(IAtomContainer.class); for (IAtomContainer container : rs.atomContainers()) ringSystem.add(container); final Set<IAtom> ringAtoms = new HashSet<>(); for (IAtom atom : ringSystem.atoms()) ringAtoms.add(atom); final IAtomContainer ringWithStubs = bldr.newInstance(IAtomContainer.class); ringWithStubs.add(ringSystem); for (IBond bond : molecule.bonds()) { IAtom atom1 = bond.getBegin(); IAtom atom2 = bond.getEnd(); if (isHydrogen(atom1) || isHydrogen(atom2)) continue; if (ringAtoms.contains(atom1) ^ ringAtoms.contains(atom2)) { ringWithStubs.addAtom(atom1); ringWithStubs.addAtom(atom2); ringWithStubs.addBond(bond); } } final IAtomContainer skeletonStub = clearHydrogenCounts(AtomContainerManipulator.skeleton(ringWithStubs)); final IAtomContainer skeleton = clearHydrogenCounts(AtomContainerManipulator.skeleton(ringSystem)); final IAtomContainer anonymous = clearHydrogenCounts(AtomContainerManipulator.anonymise(ringSystem)); for (IAtomContainer container : Arrays.asList(skeletonStub, skeleton, anonymous)) { if (!anon && container == anonymous) continue; if (identityLibrary.assignLayout(container)) { for (int i = 0; i < ringSystem.getAtomCount(); i++) { IAtom atom = ringSystem.getAtom(i); atom.setPoint2d(container.getAtom(i).getPoint2d()); atom.setFlag(CDKConstants.ISPLACED, true); } return true; } } return false; }
/tool/sdg/src/main/java/org/openscience/cdk/layout/StructureDiagramGenerator.java
robustness-copilot_data_36
/** * Returns the sum of the weights of all edges in this cycle. * * @return the sum of the weights of all edges in this cycle */ public double weight(){ double result = 0; Iterator edgeIterator = edgeSet().iterator(); while (edgeIterator.hasNext()) { result += ((Edge) edgeIterator.next()).getWeight(); } return result; }
/legacy/src/main/java/org/openscience/cdk/ringsearch/cyclebasis/SimpleCycle.java
robustness-copilot_data_37
/** * Whether the WebLogic domain contains a cluster with the given cluster name. * * @param clusterName cluster name to be checked * @return True if the WebLogic domain contains a cluster with the given cluster name */ public synchronized boolean containsCluster(String clusterName){ if (clusterName != null) { for (WlsClusterConfig clusterConfig : configuredClusters) { if (clusterConfig.getClusterName().equals(clusterName)) { return true; } } } return false; }
/operator/src/main/java/oracle/kubernetes/operator/wlsconfig/WlsDomainConfig.java
robustness-copilot_data_38
/** * Retrieve settings from the database via service and update cache. */ public static void updateProperties(){ if (settingsSvc == null) { return; } properties.clear(); Set<Setting> dbSettings = settingsSvc.listAll(); dbSettings.forEach(s -> properties.put(PREFIX + "." + s.getName().substring(1) + (s.getLang() == null ? "" : "." + s.getLang()), s.getContent())); lastUpdate = Instant.now(); }
/src/main/java/edu/harvard/iq/dataverse/settings/source/DbSettingConfigSource.java
robustness-copilot_data_39
/** * On windows machines, it splits args on '=' signs. Put it back like it was. */ protected String[] fixupArgs(String[] args){ List<String> fixedArgs = new ArrayList<>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if ((i + 1) < args.length) { nextArg = args[i + 1]; } if ((nextArg != null) && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } arg = arg.replace("\\,", ","); fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); }
/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java
robustness-copilot_data_40
/** * Matching the given data with the set of compiled patterns. * * @param patterns * @param data * @return */ private boolean matches(List<Pattern> patterns, String data){ for (Pattern pattern : patterns) { final Matcher matcher = pattern.matcher(data); if (matcher.matches()) { return true; } } return false; }
/bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/HttpCacheConfigImpl.java
robustness-copilot_data_41
/** * Applies the given function to an integer subtag if it is present. * * @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 readInt(@NonNls String key, IntConsumer consumer){ if (isInt(key)) { consumer.accept(getInt(key)); return true; } return false; }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_42
/** * As the main goal is to minimise bus operation time, this method calculates how much longer the bus will operate * after insertion. By returning INFEASIBLE_SOLUTION_COST, the insertion is considered infeasible * <p> * The insertion is invalid if some maxTravel/Wait constraints for the already scheduled requests are not fulfilled. * This is denoted by returning INFEASIBLE_SOLUTION_COST. * <p> * * @param drtRequest the request * @param insertion the insertion to be considered here * @return cost of insertion (INFEASIBLE_SOLUTION_COST represents an infeasible insertion) */ public double calculate(DrtRequest drtRequest, InsertionWithDetourData<D> insertion){ // TODO precompute time slacks for each stop to filter out even more infeasible insertions ??????????? var detourTimeInfo = detourTimeCalculator.calculateDetourTimeInfo(insertion); if (!checkTimeConstraintsForScheduledRequests(insertion.getInsertion(), detourTimeInfo.pickupTimeLoss, detourTimeInfo.getTotalTimeLoss())) { return INFEASIBLE_SOLUTION_COST; } double vehicleSlackTime = calcVehicleSlackTime(insertion.getVehicleEntry(), timeOfDay.getAsDouble()); return costCalculationStrategy.calcCost(drtRequest, insertion.getInsertion(), vehicleSlackTime, detourTimeInfo); }
/contribs/drt/src/main/java/org/matsim/contrib/drt/optimizer/insertion/InsertionCostCalculator.java
robustness-copilot_data_43
/** * Given a map, splits it so that no map has more total data than the specified limit, and returns a list of * target objects built from the resultant maps. This may result in some maps receiving partial value for the largest * items. If the target type implements CountRecorder, the 'recordCount' method of the first target will be invoked * with the number of targets created. * * @param data the map to split. */ public List<T> split(Map<String, String> data){ startSplitResult(); for (DataEntry dataEntry : getSortedEntrySizes(data)) { addToSplitResult(dataEntry); } recordSplitResult(); recordTargetInfo(result.get(0), result.size()); return result; }
/operator/src/main/java/oracle/kubernetes/operator/helpers/ConfigMapSplitter.java
robustness-copilot_data_44
/** * Read a IChemModel from a file in MDL RDF format. * * @param chemModel The IChemModel * @return The IChemModel that was read from the RDF file */ private IChemModel readChemModel(IChemModel chemModel) throws CDKException{ IReactionSet setOfReactions = chemModel.getReactionSet(); if (setOfReactions == null) { setOfReactions = chemModel.getBuilder().newInstance(IReactionSet.class); } chemModel.setReactionSet(readReactionSet(setOfReactions)); return chemModel; }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLRXNReader.java
robustness-copilot_data_45
/** * Invert the permutation, so that for all i : inv[p[i]] = i. * * @return the inverse of this permutation */ public Permutation invert(){ Permutation inversion = new Permutation(values.length); for (int i = 0; i < values.length; i++) { inversion.values[this.values[i]] = i; } return inversion; }
/tool/group/src/main/java/org/openscience/cdk/group/Permutation.java
robustness-copilot_data_46
/** * Add authentication methods to the given map * This adds a boolean and a collection for each authentication type to the map. * <p> * Examples: * <p> * boolean hasOAuthMethods * <p> * List&lt;CodegenSecurity&gt; oauthMethods * * @param bundle the map which the booleans and collections will be added */ void addAuthenticationSwitches(Map<String, Object> bundle){ Map<String, SecurityScheme> securitySchemeMap = openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null; List<CodegenSecurity> authMethods = config.fromSecurity(securitySchemeMap); if (authMethods != null && !authMethods.isEmpty()) { bundle.put("authMethods", authMethods); bundle.put("hasAuthMethods", true); if (ProcessUtils.hasOAuthMethods(authMethods)) { bundle.put("hasOAuthMethods", true); bundle.put("oauthMethods", ProcessUtils.getOAuthMethods(authMethods)); } if (ProcessUtils.hasHttpBearerMethods(authMethods)) { bundle.put("hasHttpBearerMethods", true); bundle.put("httpBearerMethods", ProcessUtils.getHttpBearerMethods(authMethods)); } if (ProcessUtils.hasHttpSignatureMethods(authMethods)) { bundle.put("hasHttpSignatureMethods", true); bundle.put("httpSignatureMethods", ProcessUtils.getHttpSignatureMethods(authMethods)); } if (ProcessUtils.hasHttpBasicMethods(authMethods)) { bundle.put("hasHttpBasicMethods", true); bundle.put("httpBasicMethods", ProcessUtils.getHttpBasicMethods(authMethods)); } if (ProcessUtils.hasApiKeyMethods(authMethods)) { bundle.put("hasApiKeyMethods", true); bundle.put("apiKeyMethods", ProcessUtils.getApiKeyMethods(authMethods)); } } }
/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java
robustness-copilot_data_47
/** * Outputs system properties for the operating system and the java * version. More specifically: os.name, os.version, os.arch, java.version * and java.vendor. */ public void dumpSystemProperties(){ debug("os.name : " + System.getProperty("os.name")); debug("os.version : " + System.getProperty("os.version")); debug("os.arch : " + System.getProperty("os.arch")); debug("java.version : " + System.getProperty("java.version")); debug("java.vendor : " + System.getProperty("java.vendor")); }
/misc/log4j/src/main/java/org/openscience/cdk/tools/LoggingTool.java
robustness-copilot_data_48
/** * Recursively list the full resource path of all the resources that are children of all the * resources found at the specified path. * * @param path The path of the resource(s) to list. * @return A list containing the names of the child resources. * @throws IOException If I/O errors occur */ public List<String> list(String path) throws IOException{ List<String> names = new ArrayList<>(); for (URL url : getResources(path)) { names.addAll(list(url, path)); } return names; }
/src/main/java/org/apache/ibatis/io/VFS.java
robustness-copilot_data_49
/** * Combines data with Collector identified by the given name. * * @param name String * @param data Object */ public void combineWithCollector(String name, Object data){ Object object = collectorMap.get(name); if (object instanceof Collector<?>) { Collector<?> collector = (Collector<?>) object; collector.combine(data); } }
/src/main/java/com/networknt/schema/CollectorContext.java
robustness-copilot_data_50
/** * These are the attributes we are getting from the IdP at testshib.org, a * dump from https://pdurbin.pagekite.me/Shibboleth.sso/Session * * Miscellaneous * * Session Expiration (barring inactivity): 479 minute(s) * * Client Address: 10.0.2.2 * * SSO Protocol: urn:oasis:names:tc:SAML:2.0:protocol * * Identity Provider: https://idp.testshib.org/idp/shibboleth * * Authentication Time: 2014-09-12T17:07:36.137Z * * Authentication Context Class: * urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport * * Authentication Context Decl: (none) * * * * Attributes * * affiliation: Member@testshib.org;Staff@testshib.org * * cn: Me Myself And I * * entitlement: urn:mace:dir:entitlement:common-lib-terms * * eppn: myself@testshib.org * * givenName: Me Myself * * persistent-id: * https://idp.testshib.org/idp/shibboleth!https://pdurbin.pagekite.me/shibboleth!zylzL+NruovU5OOGXDOL576jxfo= * * sn: And I * * telephoneNumber: 555-5555 * * uid: myself * * unscoped-affiliation: Member;Staff * */ public static void printAttributes(HttpServletRequest request){ List<String> shibValues = new ArrayList<>(); if (request == null) { logger.fine("HttpServletRequest was null. No shib values to print."); return; } for (String attr : shibAttrs) { Object attrObject = request.getAttribute(attr); if (attrObject != null) { shibValues.add(attr + ": " + attrObject.toString()); } } logger.fine("shib values: " + shibValues); }
/src/main/java/edu/harvard/iq/dataverse/authorization/providers/shib/ShibUtil.java
robustness-copilot_data_51
/** * Correct the mass according the charge of the IMmoleculeFormula. * Negative charge will add the mass of one electron to the mass. * * @param mass The mass to correct * @param charge The charge * @return The mass with the correction */ private static double correctMass(double mass, Integer charge){ if (charge == null) return mass; double massE = 0.00054857990927; if (charge > 0) mass -= massE * charge; else if (charge < 0) mass += massE * Math.abs(charge); return mass; }
/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
robustness-copilot_data_52
/** * The starting with numeric value is used to show a quantity by which a formula is multiplied. * For example: 2H2O really means that a H4O2 unit. * * @param formula Formula to correct * @return Formula with the correction */ private static String multipleExtractor(String formula){ String recentCompoundCount = "0"; String recentCompound = ""; boolean found = false; for (int f = 0; f < formula.length(); f++) { char thisChar = formula.charAt(f); if (thisChar >= '0' && thisChar <= '9') { if (!found) recentCompoundCount += thisChar; else recentCompound += thisChar; } else { found = true; recentCompound += thisChar; } } return muliplier(recentCompound, Integer.valueOf(recentCompoundCount)); }
/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
robustness-copilot_data_53
/** * Parse the InChI canonical atom numbers (from the AuxInfo) to use in * Universal SMILES. * * The parsing follows: "Rule A: The correspondence between the input atom * order and the InChI canonical labels should be obtained from the * reconnected metal layer (/R:) in preference to the initial layer, and * then from the fixed hydrogen labels (/F:) in preference to the standard * labels (/N:)." * * The labels are also adjust for "Rule E: If the start atom is a negatively * charged oxygen atom, start instead at any carbonyl oxygen attached to the * same neighbour." * * All unlabelled atoms (e.g. hydrogens) are assigned the same label which * is different but larger then all other labels. The hydrogen * labelling then needs to be adjusted externally as universal SMILES * suggests hydrogens should be visited first. * * @param aux inchi AuxInfo * @param container the structure to obtain the numbering of * @return the numbers string to use */ static long[] parseUSmilesNumbers(String aux, IAtomContainer container){ int index; long[] numbers = new long[container.getAtomCount()]; int[] first = null; int label = 1; if ((index = aux.indexOf("/R:")) >= 0) { int endIndex = aux.indexOf('/', index + 8); if (endIndex < 0) endIndex = aux.length(); String[] baseNumbers = aux.substring(index + 8, endIndex).split(";"); first = new int[baseNumbers.length]; Arrays.fill(first, -1); for (int i = 0; i < baseNumbers.length; i++) { String[] numbering = baseNumbers[i].split(","); first[i] = Integer.parseInt(numbering[0]) - 1; for (String number : numbering) { numbers[Integer.parseInt(number) - 1] = label++; } } } else if ((index = aux.indexOf("/N:")) >= 0) { String[] baseNumbers = aux.substring(index + 3, aux.indexOf('/', index + 3)).split(";"); first = new int[baseNumbers.length]; Arrays.fill(first, -1); if ((index = aux.indexOf("/F:")) >= 0) { String[] fixedHNumbers = aux.substring(index + 3, aux.indexOf('/', index + 3)).split(";"); for (int i = 0; i < fixedHNumbers.length; i++) { String component = fixedHNumbers[i]; if (component.charAt(component.length() - 1) == 'm') { int n = component.length() > 1 ? Integer.parseInt(component.substring(0, component.length() - 1)) : 1; for (int j = 0; j < n; j++) { String[] numbering = baseNumbers[i + j].split(","); first[i + j] = Integer.parseInt(numbering[0]) - 1; for (String number : numbering) numbers[Integer.parseInt(number) - 1] = label++; } } else { String[] numbering = component.split(","); for (String number : numbering) numbers[Integer.parseInt(number) - 1] = label++; } } } else { for (int i = 0; i < baseNumbers.length; i++) { String[] numbering = baseNumbers[i].split(","); first[i] = Integer.parseInt(numbering[0]) - 1; for (String number : numbering) numbers[Integer.parseInt(number) - 1] = label++; } } } else { throw new IllegalArgumentException("AuxInfo did not contain extractable base numbers (/N: or /R:)."); } for (int v : first) { if (v >= 0) { IAtom atom = container.getAtom(v); if (atom.getFormalCharge() == null) continue; if (atom.getAtomicNumber() == 8 && atom.getFormalCharge() == -1) { List<IAtom> neighbors = container.getConnectedAtomsList(atom); if (neighbors.size() == 1) { IAtom correctedStart = findPiBondedOxygen(container, neighbors.get(0)); if (correctedStart != null) exch(numbers, v, container.indexOf(correctedStart)); } } } } for (int i = 0; i < numbers.length; i++) if (numbers[i] == 0) numbers[i] = label++; return numbers; }
/storage/inchi/src/main/java/org/openscience/cdk/graph/invariant/InChINumbersTools.java
robustness-copilot_data_54
/** * Factory method for constructing {@link ObjectReader} that will * update given Object (usually Bean, but can be a Collection or Map * as well, but NOT an array) with JSON data. Deserialization occurs * normally except that the root-level value in JSON is not used for * instantiating a new object; instead give updateable object is used * as root. * Runtime type of value object is used for locating deserializer, * unless overridden by other factory methods of {@link ObjectReader} */ public ObjectReader readerForUpdating(Object valueToUpdate){ JavaType t = _typeFactory.constructType(valueToUpdate.getClass()); return _newReader(getDeserializationConfig(), t, valueToUpdate, null, _injectableValues); }
/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java
robustness-copilot_data_55
/** * Helper method used to weed out dynamic Proxy types; types that do * not expose concrete method API that we could use to figure out * automatic Bean (property) based serialization. */ public static boolean isProxyType(Class<?> type){ String name = type.getName(); if (name.startsWith("net.sf.cglib.proxy.") || name.startsWith("org.hibernate.proxy.")) { return true; } return false; }
/src/main/java/com/fasterxml/jackson/databind/util/ClassUtil.java
robustness-copilot_data_56
/** * Constructs {@link InetSocketAddress}es by parsing the given {@link String} value. * <p> * The string is a comma separated list of destinations in the form of hostName[:portNumber]. * <p> * * For example, "host1.domain.com,host2.domain.com:5560" * <p> * * If portNumber is not provided, then the given defaultPort will be used. * * @param destinations comma-separated list of destinations in the form of {@code hostName[:portNumber]} * @param defaultPort the port number to use when a destination does not specify one explicitly * @return ordered list of {@link InetSocketAddress} instances */ public static List<InetSocketAddress> parse(String destinations, int defaultPort){ /* * Multiple destinations can be specified on one single line, separated by comma */ String[] destinationStrings = (destinations == null ? "" : destinations.trim()).split("\\s*,\\s*"); List<InetSocketAddress> destinationList = new ArrayList<>(destinationStrings.length); for (String entry : destinationStrings) { /* * For #134, check to ensure properties are defined when destinations * are set using properties. */ if (entry.contains(CoreConstants.UNDEFINED_PROPERTY_SUFFIX)) { throw new IllegalArgumentException("Invalid destination '" + entry + "': unparseable value (expected format 'host[:port]')."); } Matcher matcher = DESTINATION_PATTERN.matcher(entry); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid destination '" + entry + "': unparseable value (expected format 'host[:port]')."); } String host = matcher.group(HOSTNAME_GROUP); String portString = matcher.group(PORT_GROUP); int port; try { port = (portString != null) ? Integer.parseInt(portString) : defaultPort; } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid destination '" + entry + "': unparseable port (was '" + portString + "')."); } destinationList.add(InetSocketAddress.createUnresolved(host, port)); } return destinationList; }
/src/main/java/net/logstash/logback/appender/destination/DestinationParser.java
robustness-copilot_data_57
/** * True, if the IMolecularFormulaSet contains the given IMolecularFormula but not * as object. It compare according contains the same number and type of Isotopes. * It is not based on compare objects. * * @param formulaSet The IMolecularFormulaSet * @param formula The IMolecularFormula this IMolecularFormulaSet is searched for * @return True, if the IMolecularFormulaSet contains the given formula * * @see IMolecularFormulaSet#contains(IMolecularFormula) */ public static boolean contains(IMolecularFormulaSet formulaSet, IMolecularFormula formula){ for (IMolecularFormula fm : formulaSet.molecularFormulas()) { if (MolecularFormulaManipulator.compare(fm, formula)) { return true; } } return false; }
/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaSetManipulator.java
robustness-copilot_data_58
/** * Returns either {@code 'text'} (single-quoted) or {@code [null]}. * * @since 2.9 */ public static String apostrophed(String text){ if (text == null) { return "[null]"; } return new StringBuilder(text.length() + 2).append('\'').append(text).append('\'').toString(); }
/src/main/java/com/fasterxml/jackson/databind/util/ClassUtil.java
robustness-copilot_data_59
/** * Store a template library to the provided output stream. * * @param out output stream * @throws IOException low level IO error */ void store(OutputStream out) throws IOException{ BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); for (Entry<String, List<Point2d[]>> e : templateMap.entrySet()) { for (Point2d[] val : e.getValue()) { bw.write(encodeEntry(new AbstractMap.SimpleImmutableEntry<>(e.getKey(), val))); bw.write('\n'); } } bw.close(); }
/tool/sdg/src/main/java/org/openscience/cdk/layout/IdentityTemplateLibrary.java
robustness-copilot_data_60
/** * Read an unsigned int value from the given index with the expected number * of digits. * * @param line input line * @param index start index * @param digits number of digits (max) * @return an unsigned int */ private static int readUInt(final String line, int index, int digits){ int result = 0; while (digits-- > 0) result = (result * 10) + toInt(line.charAt(index++)); return result; }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Reader.java
robustness-copilot_data_61
/** * Generates a new unique filename by adding -[number] to the base name. * * @param fileName original filename * @return a new unique filename */ public static String generateNewFileName(final String fileName){ String newName; String baseName; String extension = null; int extensionIndex = fileName.lastIndexOf("."); if (extensionIndex != -1) { extension = fileName.substring(extensionIndex + 1); baseName = fileName.substring(0, extensionIndex); } else { baseName = fileName; } if (baseName.matches(".*-[0-9][0-9]*$")) { int dashIndex = baseName.lastIndexOf("-"); String numSuffix = baseName.substring(dashIndex + 1); String basePrefix = baseName.substring(0, dashIndex); int numSuffixValue = Integer.parseInt(numSuffix); numSuffixValue++; baseName = basePrefix + "-" + numSuffixValue; } else { baseName = baseName + "-1"; } newName = baseName; if (extension != null) { newName = newName + "." + extension; } return newName; }
/src/main/java/edu/harvard/iq/dataverse/ingest/IngestUtil.java
robustness-copilot_data_62
/** * Add timer to the set, timer repeats forever, or until cancel is called. * @param interval the interval of repetition in milliseconds. * @param handler the callback called at the expiration of the timer. * @param args the optional arguments for the handler. * @return an opaque handle for further cancel. */ public Timer add(long interval, Handler handler, Object... args){ if (handler == null) { return null; } Utils.checkArgument(interval > 0, "Delay of a timer has to be strictly greater than 0"); final Timer timer = new Timer(this, interval, handler, args); final boolean rc = insert(timer); assert (rc); return timer; }
/src/main/java/zmq/util/Timers.java
robustness-copilot_data_63
/** * Converts the OpenAPI schema name to a model name suitable for the current code generator. * May be overridden for each programming language. * In case the name belongs to the TypeSystem it won't be renamed. * * @param name the name of the model * @return capitalized model name */ public String toModelName(final String name){ if (schemaKeyToModelNameCache.containsKey(name)) { return schemaKeyToModelNameCache.get(name); } String camelizedName = camelize(modelNamePrefix + "_" + name + "_" + modelNameSuffix); schemaKeyToModelNameCache.put(name, camelizedName); return camelizedName; }
/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
robustness-copilot_data_64
/** * Cast the value if the current type doesn't match the required type. * <br> * Given the following example: * <code> * int withoutCast = 1; * double withCast = (double) 1; * </code> * The variable withoutCast doesn't need to be casted, since we have int as required type and int as value type. * While in the variable withCast we have double as required type and int as value type. * * @param value The value to be returned. * @param requiredType The expected type to be casted if needed. * @param valueType The type of the value to be returned. * * @return The value casted if needed. */ public static String castValue(String value, Type requiredType, String valueType){ String requiredTypeName = requiredType.asString(); if (requiredTypeName.equals(valueType)) return value; else return String.format("(%s) %s", requiredTypeName, value); }
/javaparser-core-generators/src/main/java/com/github/javaparser/generator/core/utils/CodeUtils.java
robustness-copilot_data_65
/** * Creates a ligand attached to a single chiral atom, where the involved * atoms are identified by there index in the {@link IAtomContainer}. For ligand * atom, {@link #HYDROGEN} can be passed as index, which will indicate the presence of * an implicit hydrogen, not explicitly present in the chemical graph of the * given <code>container</code>. * * @param container {@link IAtomContainer} for which the returned {@link ILigand}s are defined * @param visitedAtoms a list of atoms already visited in the analysis * @param chiralAtom an integer pointing to the {@link IAtom} index of the chiral atom * @param ligandAtom an integer pointing to the {@link IAtom} index of the {@link ILigand} * @return the created {@link ILigand} */ public static ILigand defineLigand(IAtomContainer container, VisitedAtoms visitedAtoms, int chiralAtom, int ligandAtom){ if (ligandAtom == HYDROGEN) { return new ImplicitHydrogenLigand(container, visitedAtoms, container.getAtom(chiralAtom)); } else { return new Ligand(container, visitedAtoms, container.getAtom(chiralAtom), container.getAtom(ligandAtom)); } }
/descriptor/cip/src/main/java/org/openscience/cdk/geometry/cip/CIPTool.java
robustness-copilot_data_66
/** * Checks whether all the settings make sense or if there are some * problems with the parameters currently set. Currently, this checks * that for at least one activity type opening AND closing times are * defined. */ public void checkConsistency(Config config){ super.checkConsistency(config); boolean hasOpeningAndClosingTime = false; boolean hasOpeningTimeAndLatePenalty = false; for (ActivityParams actType : this.getActivityParams()) { if (actType.isScoringThisActivityAtAll()) { if (actType.getOpeningTime().isDefined() && actType.getClosingTime().isDefined()) { hasOpeningAndClosingTime = true; if (actType.getOpeningTime().seconds() == 0. && actType.getClosingTime().seconds() > 24. * 3600 - 1) { log.error("it looks like you have an activity type with opening time set to 0:00 and closing " + "time set to 24:00. This is most probably not the same as not setting them at all. " + "In particular, activities which extend past midnight may not accumulate scores."); } } if (actType.getOpeningTime().isDefined() && (getLateArrival_utils_hr() < -0.001)) { hasOpeningTimeAndLatePenalty = true; } } } if (!hasOpeningAndClosingTime && !hasOpeningTimeAndLatePenalty) { log.info("NO OPENING OR CLOSING TIMES DEFINED!\n\n" + "There is no activity type that has an opening *and* closing time (or opening time and late penalty) defined.\n" + "This usually means that the activity chains can be shifted by an arbitrary\n" + "number of hours without having an effect on the score of the plans, and thus\n" + "resulting in wrong results / traffic patterns.\n" + "If you are using MATSim without time adaptation, you can ignore this warning.\n\n"); } if (this.getMarginalUtlOfWaiting_utils_hr() != 0.0) { log.warn("marginal utl of wait set to: " + this.getMarginalUtlOfWaiting_utils_hr() + ". Setting this different from zero is " + "discouraged since there is already the marginal utility of time as a resource. The parameter was also used " + "in the past for pt routing; if you did that, consider setting the new " + "parameter waitingPt instead."); } }
/matsim/src/main/java/org/matsim/core/config/groups/PlanCalcScoreConfigGroup.java
robustness-copilot_data_67
/** * This method calculates the ionization potential of an atom. * *@param atom The IAtom to ionize. *@param container Parameter is the IAtomContainer. *@return The ionization potential. Not possible the ionization. */ public DescriptorValue calculate(IAtom atom, IAtomContainer container){ double value; String originalAtomtypeName = atom.getAtomTypeName(); Integer originalNeighborCount = atom.getFormalNeighbourCount(); Integer originalValency = atom.getValency(); Double originalBondOrderSum = atom.getBondOrderSum(); Order originalMaxBondOrder = atom.getMaxBondOrder(); IAtomType.Hybridization originalHybridization = atom.getHybridization(); if (!isCachedAtomContainer(container)) { try { AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(container); LonePairElectronChecker lpcheck = new LonePairElectronChecker(); lpcheck.saturate(container); } catch (CDKException e) { return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new DoubleResult(Double.NaN), NAMES, e); } } value = db.extractIP(container, atom); atom.setAtomTypeName(originalAtomtypeName); atom.setFormalNeighbourCount(originalNeighborCount); atom.setValency(originalValency); atom.setHybridization(originalHybridization); atom.setMaxBondOrder(originalMaxBondOrder); atom.setBondOrderSum(originalBondOrderSum); return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new DoubleResult(value), NAMES); }
/descriptor/qsaratomic/src/main/java/org/openscience/cdk/qsar/descriptors/atomic/IPAtomicHOSEDescriptor.java
robustness-copilot_data_68
/** * Return true if the specified schema is an object with a fixed number of properties. * * A ObjectSchema differs from an MapSchema 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. * * For example, an OpenAPI schema is considered an ObjectSchema in the following scenarios: * * type: object * additionalProperties: false * properties: * name: * type: string * address: * type: string * * @param schema the OAS schema * @return true if the specified schema is an Object schema. */ public static boolean isObjectSchema(Schema schema){ if (schema instanceof ObjectSchema) { return true; } if (SchemaTypeUtil.OBJECT_TYPE.equals(schema.getType()) && !(schema instanceof MapSchema)) { return true; } if (schema.getType() == null && schema.getProperties() != null && !schema.getProperties().isEmpty()) { return true; } return false; }
/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java
robustness-copilot_data_69
/** * Inserts a leg and a following act at position <code>pos</code> into the plan. * @param pos the position where to insert the leg-act-combo. acts and legs are both counted from the beginning starting at 0. * @param leg the leg to insert * @param act the act to insert, following the leg * * @throws IllegalArgumentException If the leg and act cannot be inserted at the specified position without retaining the correct order of legs and acts. */ public static void insertLegAct(Plan plan, int pos, Leg leg, Activity act){ if (pos < plan.getPlanElements().size()) { Object o = plan.getPlanElements().get(pos); if (!(o instanceof Leg)) { throw new IllegalArgumentException("Position to insert leg and act is not valid (act instead of leg at position)."); } } else if (pos > plan.getPlanElements().size()) { throw new IllegalArgumentException("Position to insert leg and act is not valid."); } plan.getPlanElements().add(pos, act); plan.getPlanElements().add(pos, leg); }
/matsim/src/main/java/org/matsim/core/population/PopulationUtils.java
robustness-copilot_data_70
/** * Generates an object representing a JSON schema for the specified class. * * @param someClass the class for which the schema should be generated * @return a map of maps, representing the computed JSON */ public Map<String, Object> generate(Class<?> someClass){ Map<String, Object> result = new HashMap<>(); if (includeSchemaReference) { result.put("$schema", JSON_SCHEMA_REFERENCE); } generateObjectTypeIn(result, someClass); if (!definedObjects.isEmpty()) { Map<String, Object> definitions = new TreeMap<>(); result.put("definitions", definitions); for (Class<?> type : definedObjects.keySet()) { if (!definedObjects.get(type).equals(EXTERNAL_CLASS)) { definitions.put(getDefinitionKey(type), definedObjects.get(type)); } } } return result; }
/json-schema-generator/src/main/java/oracle/kubernetes/json/SchemaGenerator.java
robustness-copilot_data_71
/** * Checks to make sure the given aggregate function is compatible with the type of the source * column. */ private void validateColumn(FunctionMetaData function, Column<?> sourceColumn){ if (!function.isCompatibleColumn(sourceColumn.type())) { throw new IllegalArgumentException("Function: " + function.functionName() + " Is not compatible with column type: " + sourceColumn.type()); } }
/core/src/main/java/tech/tablesaw/analytic/AnalyticQueryEngine.java
robustness-copilot_data_72
/** * Executes all on-deploy scripts on bind of a script provider. */ protected void bindScriptProvider(OnDeployScriptProvider scriptProvider){ logger.info("Executing on-deploy scripts from scriptProvider: {}", scriptProvider.getClass().getName()); scriptProviders.add(scriptProvider); List<OnDeployScript> scripts = scriptProvider.getScripts(); if (scripts.size() == 0) { logger.debug("No on-deploy scripts found."); return; } try (ResourceResolver resourceResolver = logIn()) { runScripts(resourceResolver, scripts); } }
/bundle/src/main/java/com/adobe/acs/commons/ondeploy/impl/OnDeployExecutorImpl.java
robustness-copilot_data_73
/** * Tests the <code>ring</code> in the <code>molecule</code> for aromaticity. Uses the * H&uuml;ckel rule (4n + 2) pie electrons. sp<sup>2</sup> hybridized C contibute 1 electron non * sp<sup>2</sup> hybridized heteroatoms contribute 2 electrons (N and O should never be sp in * or anything else in a ring and d electron elements get to complicated) * sp<sup>2</sup> hybridized heteroatoms contribute 1 electron hybridization is worked out by * counting the number of bonds with order 2. Therefore sp<sup>2</sup> hybridization is assumed * if there is one bond of order 2. Otherwise sp<sup>3</sup> hybridization is assumed. * * @param ring the ring to test * @param atomContainer the AtomContainer the ring is in * @return true if the ring is aromatic false otherwise. */ public static boolean isAromatic(IRing ring, IAtomContainer atomContainer){ java.util.Iterator<IAtom> ringAtoms = ring.atoms().iterator(); int eCount = 0; java.util.List<IBond> conectedBonds; int numDoubleBond = 0; boolean allConnectedBondsSingle; while (ringAtoms.hasNext()) { IAtom atom = ringAtoms.next(); numDoubleBond = 0; allConnectedBondsSingle = true; conectedBonds = atomContainer.getConnectedBondsList(atom); for (IBond conectedBond : conectedBonds) { if (conectedBond.getOrder() == IBond.Order.DOUBLE && ring.contains(conectedBond)) { numDoubleBond++; } else // Count the Electron if bond order = 1.5 if (conectedBond.getFlag(CDKConstants.ISAROMATIC) && ring.contains(conectedBond)) { numDoubleBond = 1; } if (conectedBond.getOrder() != IBond.Order.SINGLE) { allConnectedBondsSingle = false; } } if (numDoubleBond == 1) { // C or heteroatoms both contibute 1 electron in sp2 hybridized form eCount++; } else if (!atom.getSymbol().equals("C")) { // Heteroatom probably in sp3 hybrid therefore 2 electrons contributed. eCount = eCount + 2; } else if (atom.getFlag(CDKConstants.ISAROMATIC)) { eCount++; } else if (allConnectedBondsSingle && atom.getSymbol().equals("C") && atom.getFormalCharge() == 1.0) { // This is for tropylium and kinds. // Dependence on hybridisation would be better: // empty p-orbital is needed continue; } else { return false; } } return eCount - 2 != 0 && (eCount - 2) % 4 == 0; }
/legacy/src/main/java/org/openscience/cdk/aromaticity/AromaticityCalculator.java
robustness-copilot_data_74
/** * Computes the Murcko Scaffold for the provided molecule in linear time. * Note the return value contains the same atoms/bonds as in the input * and an additional clone and valence adjustments may be required. * * @param mol the molecule * @return the atoms and bonds in the scaffold */ public static IAtomContainer scaffold(final IAtomContainer mol){ if (!mol.isEmpty() && mol.getAtom(0).getContainer() == null) return null; Deque<IAtom> queue = new ArrayDeque<>(); int[] bcount = new int[mol.getAtomCount()]; for (IAtom atom : mol.atoms()) { int numBonds = atom.getBondCount(); bcount[atom.getIndex()] = numBonds; if (numBonds == 1) queue.add(atom); } while (!queue.isEmpty()) { IAtom atom = queue.poll(); if (atom == null) continue; bcount[atom.getIndex()] = 0; for (IBond bond : atom.bonds()) { IAtom nbr = bond.getOther(atom); bcount[nbr.getIndex()]--; if (bcount[nbr.getIndex()] == 1) queue.add(nbr); } } IAtomContainer scaffold = mol.getBuilder().newAtomContainer(); for (int i = 0; i < mol.getAtomCount(); i++) { IAtom atom = mol.getAtom(i); if (bcount[i] > 0) scaffold.addAtom(atom); } for (int i = 0; i < mol.getBondCount(); i++) { IBond bond = mol.getBond(i); if (bcount[bond.getBegin().getIndex()] > 0 && bcount[bond.getEnd().getIndex()] > 0) scaffold.addBond(bond); } return scaffold; }
/tool/fragment/src/main/java/org/openscience/cdk/fragment/MurckoFragmenter.java
robustness-copilot_data_75
/** * Method for registering a module that can extend functionality * provided by this mapper; for example, by adding providers for * custom serializers and deserializers. * * @param module Module to register */ public ObjectMapper registerModule(Module module){ _assertNotNull("module", module); String name = module.getModuleName(); if (name == null) { throw new IllegalArgumentException("Module without defined name"); } Version version = module.version(); if (version == null) { throw new IllegalArgumentException("Module without defined version"); } for (Module dep : module.getDependencies()) { registerModule(dep); } if (isEnabled(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS)) { Object typeId = module.getTypeId(); if (typeId != null) { if (_registeredModuleTypes == null) { _registeredModuleTypes = new LinkedHashSet<Object>(); } if (!_registeredModuleTypes.add(typeId)) { return this; } } } module.setupModule(new Module.SetupContext() { @Override public Version getMapperVersion() { return version(); } @SuppressWarnings("unchecked") @Override public <C extends ObjectCodec> C getOwner() { return (C) ObjectMapper.this; } @Override public TypeFactory getTypeFactory() { return _typeFactory; } @Override public boolean isEnabled(MapperFeature f) { return ObjectMapper.this.isEnabled(f); } @Override public boolean isEnabled(DeserializationFeature f) { return ObjectMapper.this.isEnabled(f); } @Override public boolean isEnabled(SerializationFeature f) { return ObjectMapper.this.isEnabled(f); } @Override public boolean isEnabled(JsonFactory.Feature f) { return ObjectMapper.this.isEnabled(f); } @Override public boolean isEnabled(JsonParser.Feature f) { return ObjectMapper.this.isEnabled(f); } @Override public boolean isEnabled(JsonGenerator.Feature f) { return ObjectMapper.this.isEnabled(f); } @Override public MutableConfigOverride configOverride(Class<?> type) { return ObjectMapper.this.configOverride(type); } @Override public void addDeserializers(Deserializers d) { DeserializerFactory df = _deserializationContext._factory.withAdditionalDeserializers(d); _deserializationContext = _deserializationContext.with(df); } @Override public void addKeyDeserializers(KeyDeserializers d) { DeserializerFactory df = _deserializationContext._factory.withAdditionalKeyDeserializers(d); _deserializationContext = _deserializationContext.with(df); } @Override public void addBeanDeserializerModifier(BeanDeserializerModifier modifier) { DeserializerFactory df = _deserializationContext._factory.withDeserializerModifier(modifier); _deserializationContext = _deserializationContext.with(df); } @Override public void addSerializers(Serializers s) { _serializerFactory = _serializerFactory.withAdditionalSerializers(s); } @Override public void addKeySerializers(Serializers s) { _serializerFactory = _serializerFactory.withAdditionalKeySerializers(s); } @Override public void addBeanSerializerModifier(BeanSerializerModifier modifier) { _serializerFactory = _serializerFactory.withSerializerModifier(modifier); } @Override public void addAbstractTypeResolver(AbstractTypeResolver resolver) { DeserializerFactory df = _deserializationContext._factory.withAbstractTypeResolver(resolver); _deserializationContext = _deserializationContext.with(df); } @Override public void addTypeModifier(TypeModifier modifier) { TypeFactory f = _typeFactory; f = f.withModifier(modifier); setTypeFactory(f); } @Override public void addValueInstantiators(ValueInstantiators instantiators) { DeserializerFactory df = _deserializationContext._factory.withValueInstantiators(instantiators); _deserializationContext = _deserializationContext.with(df); } @Override public void setClassIntrospector(ClassIntrospector ci) { _deserializationConfig = _deserializationConfig.with(ci); _serializationConfig = _serializationConfig.with(ci); } @Override public void insertAnnotationIntrospector(AnnotationIntrospector ai) { _deserializationConfig = _deserializationConfig.withInsertedAnnotationIntrospector(ai); _serializationConfig = _serializationConfig.withInsertedAnnotationIntrospector(ai); } @Override public void appendAnnotationIntrospector(AnnotationIntrospector ai) { _deserializationConfig = _deserializationConfig.withAppendedAnnotationIntrospector(ai); _serializationConfig = _serializationConfig.withAppendedAnnotationIntrospector(ai); } @Override public void registerSubtypes(Class<?>... subtypes) { ObjectMapper.this.registerSubtypes(subtypes); } @Override public void registerSubtypes(NamedType... subtypes) { ObjectMapper.this.registerSubtypes(subtypes); } @Override public void registerSubtypes(Collection<Class<?>> subtypes) { ObjectMapper.this.registerSubtypes(subtypes); } @Override public void setMixInAnnotations(Class<?> target, Class<?> mixinSource) { addMixIn(target, mixinSource); } @Override public void addDeserializationProblemHandler(DeserializationProblemHandler handler) { addHandler(handler); } @Override public void setNamingStrategy(PropertyNamingStrategy naming) { setPropertyNamingStrategy(naming); } }); return this; }
/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java
robustness-copilot_data_76
/** * Updates feature's elements with items from the @elements list if an Id of the item coincides * with an Id of any element from the @feature object. If there is no element in the @feature object * then the item is appended to the end of the elements' list of the @feature. * * @param feature - target object of Feature class. * @param elements - list of elements which need to be inserted to the @feature with replacing * or adding to the end. */ void updateElements(Feature feature, Element[] elements){ for (int i = 0; i < elements.length; i++) { Element current = elements[i]; if (current.isScenario()) { checkArgument(current.getStartTime() != null, ERROR); int indexOfPreviousResult = find(feature.getElements(), current); boolean hasBackground = isBackground(i - 1, elements); if (indexOfPreviousResult < 0) { feature.addElements(hasBackground ? new Element[] { elements[i - 1], current } : new Element[] { current }); } else { if (replaceIfExists(feature.getElements()[indexOfPreviousResult], current)) { feature.getElements()[indexOfPreviousResult] = current; if (hasBackground && isBackground(indexOfPreviousResult - 1, feature.getElements())) { feature.getElements()[indexOfPreviousResult - 1] = elements[i - 1]; } } } } } }
/src/main/java/net/masterthought/cucumber/reducers/ReportFeatureWithRetestMerger.java
robustness-copilot_data_77
/** * Obtain an optional port number based on supplied URI. Use the defined port number, if the * URI defines one; otherwise use the default port number for URI's schema, if one is known. * Otherwise return an empty Optional. */ public static Optional<Integer> optionalPortWithDefault(URI uri){ int port = portWithDefault(uri, null, -1); return port > -1 ? Optional.of(port) : Optional.<Integer>empty(); }
/modules/common/src/main/java/org/dcache/util/URIs.java
robustness-copilot_data_78
/** * Reducing the network so it only contains nodes included in the biggest Cluster. * Loop over all nodes and check if they are in the cluster, if not, remove them from the network */ public static void reduceToBiggestCluster(Network network, Map<Id<Node>, Node> biggestCluster){ List<Node> allNodes2 = new ArrayList<>(network.getNodes().values()); for (Node node : allNodes2) { if (!biggestCluster.containsKey(node.getId())) { network.removeNode(node.getId()); } } log.info(" resulting network contains " + network.getNodes().size() + " nodes and " + network.getLinks().size() + " links."); log.info("done."); }
/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkCleaner.java
robustness-copilot_data_79
/** * Create a unit partition - in other words, the coarsest possible partition * where all the elements are in one cell. * * @param size the number of elements * @return a new Partition with one cell containing all the elements */ public static Partition unit(int size){ Partition unit = new Partition(); unit.cells.add(new TreeSet<Integer>()); for (int i = 0; i < size; i++) { unit.cells.get(0).add(i); } return unit; }
/tool/group/src/main/java/org/openscience/cdk/group/Partition.java
robustness-copilot_data_80
/** * Returns a collection view of the values contained in this map. The * collection's iterator will return the values in the order that their * corresponding keys appear in the tree. The collection is backed by * this <tt>QuadMap</tt> instance, so changes to this map are reflected in * the collection. * * @return a collection view of the values contained in this map. */ public Collection<T> values(){ if (this.values == null) { this.values = new AbstractCollection<T>() { @Override public Iterator<T> iterator() { Iterator<T> iterator = new Iterator<T>() { private final int expectedModCount = QuadTree.this.modCount; private Leaf<T> currentLeaf = firstLeaf(); private int nextIndex = 0; private T next = first(); private T first() { if (this.currentLeaf == null) { return null; } this.nextIndex = 0; loadNext(); return this.next; } @Override public boolean hasNext() { return this.next != null; } @Override public T next() { if (this.next == null) { return null; } if (QuadTree.this.modCount != this.expectedModCount) { throw new ConcurrentModificationException(); } T current = this.next; loadNext(); return current; } private void loadNext() { boolean searching = true; while (searching) { int size = this.currentLeaf.value != null ? 1 : this.currentLeaf.values.size(); if (this.nextIndex < size) { this.nextIndex++; this.next = this.currentLeaf.value != null ? this.currentLeaf.value : this.currentLeaf.values.get(this.nextIndex - 1); searching = false; } else { this.currentLeaf = nextLeaf(this.currentLeaf); if (this.currentLeaf == null) { this.next = null; searching = false; } else { this.nextIndex = 0; } } } } @Override public void remove() { throw new UnsupportedOperationException(); } }; return iterator; } @Override public int size() { return QuadTree.this.size; } }; } return this.values; }
/matsim/src/main/java/org/matsim/core/utils/collections/QuadTree.java
robustness-copilot_data_81
/** * Method used for serialization and introspection by core Jackson code. */ public EnumMap<?, SerializableString> internalMap(){ EnumMap<?, SerializableString> result = _asMap; if (result == null) { Map<Enum<?>, SerializableString> map = new LinkedHashMap<Enum<?>, SerializableString>(); for (Enum<?> en : _values) { map.put(en, _textual[en.ordinal()]); } result = new EnumMap(map); } return result; }
/src/main/java/com/fasterxml/jackson/databind/util/EnumValues.java
robustness-copilot_data_82
/** * Calculates lane capacities, according to {@link LanesUtils}. */ public void calculateLaneCapacities(Network network, Lanes lanes){ for (LanesToLinkAssignment l2l : lanes.getLanesToLinkAssignments().values()) { Link link = network.getLinks().get(l2l.getLinkId()); for (Lane lane : l2l.getLanes().values()) { calculateAndSetCapacity(lane, lane.getToLaneIds() == null || lane.getToLaneIds().isEmpty(), link, network); } } }
/contribs/sumo/src/main/java/org/matsim/contrib/sumo/SumoNetworkConverter.java
robustness-copilot_data_83
/** * The Graham Scan algorithm determines the points belonging to the convex hull in O(n lg n). * * @param points set of points * @return points in the convex hull * @see <a href="http://en.wikipedia.org/wiki/Graham_scan">Graham scan, Wikipedia</a> */ static List<Point2D> grahamScan(final List<Point2D> points){ if (points.size() <= 3) return new ArrayList<Point2D>(points); Collections.sort(points, new CompareYThenX()); Collections.sort(points, new PolarComparator(points.get(0))); Deque<Point2D> hull = new ArrayDeque<Point2D>(); hull.push(points.get(0)); hull.push(points.get(1)); hull.push(points.get(2)); for (int i = 3; i < points.size(); i++) { Point2D top = hull.pop(); while (!hull.isEmpty() && !isLeftTurn(hull.peek(), top, points.get(i))) { top = hull.pop(); } hull.push(top); hull.push(points.get(i)); } return new ArrayList<Point2D>(hull); }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/ConvexHull.java
robustness-copilot_data_84
/** * Validates that the passed password is indeed the password of the user. * @param userIdInProvider * @param password * @return {@code true} if the password matches the user's password; {@code false} otherwise. */ public Boolean verifyPassword(String userIdInProvider, String password){ BuiltinUser biUser = bean.findByUserName(userIdInProvider); if (biUser == null) return null; return PasswordEncryption.getVersion(biUser.getPasswordEncryptionVersion()).check(password, biUser.getEncryptedPassword()); }
/src/main/java/edu/harvard/iq/dataverse/authorization/providers/builtin/BuiltinAuthenticationProvider.java
robustness-copilot_data_85
/** * Maps the input bonds to a map of Atom->Elevation where the elevation is * whether the bond is off the plane with respect to the central atom. * * @param atom central atom * @param bonds bonds connected to the central atom * @param map map to load with elevation values (can be reused) */ private static void makeElevationMap(IAtom atom, List<IBond> bonds, Map<IAtom, Integer> map){ map.clear(); for (IBond bond : bonds) { int elevation = 0; switch(bond.getStereo()) { case UP: case DOWN_INVERTED: elevation = +1; break; case DOWN: case UP_INVERTED: elevation = -1; break; } if (bond.getBegin().equals(atom)) { map.put(bond.getEnd(), elevation); } else { map.put(bond.getBegin(), -1 * elevation); } } }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricTetrahedralEncoderFactory.java
robustness-copilot_data_86
/** * {@inheritDoc} * * Return comparison result based on the content of the properties. */ public boolean equals(Object objectToCompare){ if (this == objectToCompare) { return true; } if (!(objectToCompare instanceof DigitalService)) { return false; } DigitalService asset = (DigitalService) objectToCompare; return Objects.equals(getVersion(), asset.getVersion()) && Objects.equals(getDisplayName(), asset.getDisplayName()) && Objects.equals(getDescription(), asset.getDescription()); }
/open-metadata-implementation/access-services/digital-service/digital-service-api/src/main/java/org/odpi/openmetadata/accessservices/digitalservice/properties/DigitalService.java
robustness-copilot_data_87
/** * Returns true if the given main command arg needs no special parameters. * * @param arg the main command to test * @return true if arg is a valid main command and needs no special parameters, false in all other cases */ private static boolean isNoArgCommand(String arg){ return COMMANDS.MIGRATE.equals(arg) || COMMANDS.MIGRATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE.equalsIgnoreCase(arg) || COMMANDS.UPDATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TESTING_ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.LIST_LOCKS.equalsIgnoreCase(arg) || COMMANDS.RELEASE_LOCKS.equalsIgnoreCase(arg) || COMMANDS.VALIDATE.equalsIgnoreCase(arg) || COMMANDS.HELP.equalsIgnoreCase(arg) || COMMANDS.CLEAR_CHECKSUMS.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(arg); }
/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java
robustness-copilot_data_88
/** * Computes the score of a document with respect to a query given a scoring function. Assumes Anserini's default * analyzer. * * @param reader index reader * @param docid docid of the document to score * @param q query * @param similarity scoring function * @return the score of the document with respect to the query * @throws IOException if error encountered during query */ public static float computeQueryDocumentScoreWithSimilarity(IndexReader reader, String docid, String q, Similarity similarity) throws IOException{ return computeQueryDocumentScoreWithSimilarityAndAnalyzer(reader, docid, q, similarity, IndexCollection.DEFAULT_ANALYZER); }
/src/main/java/io/anserini/index/IndexReaderUtils.java
robustness-copilot_data_89
/** * Generate the next name for the given name, i.e. append "2" to the base name if not ending with a number, * otherwise increase the number by 1. For example: * status => status2 * status2 => status3 * myName100 => myName101 * * @param name The base name * @return The next name for the base name */ private static String generateNextName(String name){ Pattern pattern = Pattern.compile("\\d+\\z"); Matcher matcher = pattern.matcher(name); if (matcher.find()) { String numStr = matcher.group(); int num = Integer.parseInt(numStr) + 1; return name.substring(0, name.length() - numStr.length()) + num; } else { return name + "2"; } }
/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
robustness-copilot_data_90
/** * Makes combinations recursively of all possible mobile Hydrogen positions. * @param taken positions taken by hydrogen * @param combinations combinations made so far * @param skeleton container to work on * @param totalMobHydrCount * @param mobHydrAttachPositions */ private void combineHydrogenPositions(List<Integer> taken, List<List<Integer>> combinations, IAtomContainer skeleton, int totalMobHydrCount, List<Integer> mobHydrAttachPositions){ if (taken.size() != totalMobHydrCount) { for (int i = 0; i < mobHydrAttachPositions.size(); i++) { int pos = mobHydrAttachPositions.get(i); IAtom atom = findAtomByPosition(skeleton, pos); int conn = getConnectivity(atom, skeleton); int hCnt = 0; for (int t : taken) if (t == pos) hCnt++; if (atom.getValency() - atom.getFormalCharge() > (hCnt + conn)) { taken.add(pos); combineHydrogenPositions(taken, combinations, skeleton, totalMobHydrCount, mobHydrAttachPositions); taken.remove(taken.size() - 1); } } } else { List<Integer> addList = new ArrayList<Integer>(taken.size()); addList.addAll(taken); Collections.sort(addList); if (!combinations.contains(addList)) { combinations.add(addList); } } }
/tool/tautomer/src/main/java/org/openscience/cdk/tautomers/InChITautomerGenerator.java
robustness-copilot_data_91
/** * Ostensibly, we iterate over all children to find Mortal children that should be removed. In * practise, cached knowledge of Mortal child expiry Dates means this iterates over only those * StateComponents that contain children that have actually expired. * * @param ourPath * @param transition * @param forced */ public void buildRemovalTransition(StatePath ourPath, StateTransition transition, boolean forced){ LOGGER.trace("entering buildRemovalTransition: path={}", ourPath); Date now = new Date(); for (Map.Entry<String, StateComponent> entry : _children.entrySet()) { StateComponent childValue = entry.getValue(); String childName = entry.getKey(); boolean shouldRemoveThisChild = forced; boolean shouldItr = forced; if (childValue.hasExpired()) { LOGGER.trace("registering {} (in path {}) for removal.", childName, ourPath); shouldRemoveThisChild = shouldItr = true; } Date childExp = childValue.getEarliestChildExpiryDate(); if (childExp != null && !now.before(childExp)) { shouldItr = true; } if (shouldItr || shouldRemoveThisChild) { StateChangeSet changeSet = transition.getOrCreateChangeSet(ourPath); if (shouldRemoveThisChild) { changeSet.recordRemovedChild(childName); } if (shouldItr) { changeSet.recordChildItr(childName); childValue.buildRemovalTransition(buildChildPath(ourPath, childName), transition, shouldRemoveThisChild); } } } }
/modules/dcache-info/src/main/java/org/dcache/services/info/base/StateComposite.java
robustness-copilot_data_92
/** * Create an encoder for axial 3D stereochemistry for the given start and * end atoms. * * @param container the molecule * @param start start of the cumulated system * @param startBonds bonds connected to the start * @param end end of the cumulated system * @param endBonds bonds connected to the end * @return an encoder */ private static StereoEncoder axial3DEncoder(IAtomContainer container, IAtom start, List<IBond> startBonds, IAtom end, List<IBond> endBonds){ Point3d[] coordinates = new Point3d[4]; PermutationParity perm = new CombinedPermutationParity(fill3DCoordinates(container, start, startBonds, coordinates, 0), fill3DCoordinates(container, end, endBonds, coordinates, 2)); GeometricParity geom = new Tetrahedral3DParity(coordinates); int u = container.indexOf(start); int v = container.indexOf(end); return new GeometryEncoder(new int[] { u, v }, perm, geom); }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java
robustness-copilot_data_93
/** * Create a new Change implementation for the given change name. The class of the constructed object will be the Change implementation with the highest priority. * Each call to create will return a new instance of the Change. */ public Change create(String name){ Change plugin = getPlugin(name); if (plugin == null) { return null; } try { return plugin.getClass().getConstructor().newInstance(); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } }
/liquibase-core/src/main/java/liquibase/change/ChangeFactory.java
robustness-copilot_data_94
/** * Check if the user is allowed to sync binaries. * * Service users, as well as the admin user, are prevented from sync'ing * binaries to ensure that some back end procress traversing the DAM doesn't * trigger a sync of the entire DAM, thus subverting the benefits of * remote assets. * * Service users can be whitelisted via remote aseets configuration if it * is desired for a particular service user to be able to sync binaries. * * @param resource The asset content Resource to sync binaries for. * @return True if user is allowed to sync binaries, else false. * @throws RepositoryException */ private boolean isAllowedUser(Resource resource) throws RepositoryException{ ResourceResolver resourceResolver = resource.getResourceResolver(); String userId = resourceResolver.getUserID(); if (!userId.equals(ADMIN_ID)) { if (this.config.getWhitelistedServiceUsers().contains(userId)) { return true; } Session session = resourceResolver.adaptTo(Session.class); User currentUser = (User) getUserManager(session).getAuthorizable(userId); if (currentUser != null && !currentUser.isSystemUser()) { return true; } else { LOG.trace("Avoiding binary sync b/c this is a non-whitelisted service user: {}", session.getUserID()); } } else { LOG.trace("Avoiding binary sync for admin user"); } return false; }
/bundle/src/main/java/com/adobe/acs/commons/remoteassets/impl/RemoteAssetDecorator.java
robustness-copilot_data_95
/** * Method that is reverse of {@link #treeToValue}: it * will convert given Java value (usually bean) into its * equivalent Tree mode {@link JsonNode} representation. * Functionally similar to serializing value into token stream and parsing that * stream back as tree model node, * but more efficient as {@link TokenBuffer} is used to contain the intermediate * representation instead of fully serialized contents. *<p> * NOTE: while results are usually identical to that of serialization followed * by deserialization, this is not always the case. In some cases serialization * into intermediate representation will retain encapsulation of things like * raw value ({@link com.fasterxml.jackson.databind.util.RawValue}) or basic * node identity ({@link JsonNode}). If so, result is a valid tree, but values * are not re-constructed through actual format representation. So if transformation * requires actual materialization of encoded content, * it will be necessary to do actual serialization. * * @param <T> Actual node type; usually either basic {@link JsonNode} or * {@link com.fasterxml.jackson.databind.node.ObjectNode} * @param fromValue Java value to convert * * @return (non-null) Root node of the resulting content tree: in case of * {@code null} value node for which {@link JsonNode#isNull()} returns {@code true}. */ public T valueToTree(Object fromValue) throws IllegalArgumentException{ if (fromValue == null) { return (T) getNodeFactory().nullNode(); } final SerializationConfig config = getSerializationConfig().without(SerializationFeature.WRAP_ROOT_VALUE); final DefaultSerializerProvider context = _serializerProvider(config); TokenBuffer buf = context.bufferForValueConversion(this); if (isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) { buf = buf.forceUseOfBigDecimal(true); } try { context.serializeValue(buf, fromValue); try (JsonParser p = buf.asParser()) { return readTree(p); } } catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); } }
/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java
robustness-copilot_data_96
/** * Fill the {@literal coordinates} and {@literal elevation} from the given * offset index. If there is only one connection then the second entry (from * the offset) will use the coordinates of <i>a</i>. The permutation parity * is also built and returned. * * @param container atom container * @param a the central atom * @param connected bonds connected to the central atom * @param coordinates the coordinates array to fill * @param elevations the elevations of the connected atoms * @param offset current location in the offset array * @return the permutation parity */ private static PermutationParity fill2DCoordinates(IAtomContainer container, IAtom a, List<IBond> connected, Point2d[] coordinates, int[] elevations, int offset){ int i = 0; coordinates[offset + 1] = a.getPoint2d(); elevations[offset + 1] = 0; int[] indices = new int[2]; for (IBond bond : connected) { if (!isDoubleBond(bond)) { IAtom other = bond.getOther(a); coordinates[i + offset] = other.getPoint2d(); elevations[i + offset] = elevation(bond, a); indices[i] = container.indexOf(other); i++; } } if (i == 1) { return PermutationParity.IDENTITY; } else { return new BasicPermutationParity(indices); } }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java
robustness-copilot_data_97
/** * Constructs the path after the algorithm has been run. * * @param fromNode * The node where the path starts. * @param toNode * The node where the path ends. * @param startTime * The time when the trip starts. */ protected Path constructPath(Node fromNode, Node toNode, double startTime, double arrivalTime){ List<Node> nodes = new ArrayList<>(); List<Link> links = new ArrayList<>(); nodes.add(0, toNode); Link tmpLink = getData(toNode).getPrevLink(); if (tmpLink != null) { while (tmpLink.getFromNode() != fromNode) { links.add(0, tmpLink); nodes.add(0, tmpLink.getFromNode()); tmpLink = getData(tmpLink.getFromNode()).getPrevLink(); } links.add(0, tmpLink); nodes.add(0, tmpLink.getFromNode()); } DijkstraNodeData toNodeData = getData(toNode); Path path = new Path(nodes, links, arrivalTime - startTime, toNodeData.getCost()); return path; }
/matsim/src/main/java/org/matsim/core/router/Dijkstra.java
robustness-copilot_data_98
/** * Adds the mappings from "from" to "to". Nothing is done to copy the Object themselves, * which should be fine for 99.9% of the usecases of Attributes (value objects) */ public static void copyTo(Attributes from, Attributes to){ for (var entry : from.getAsMap().entrySet()) { to.putAttribute(entry.getKey(), entry.getValue()); } }
/matsim/src/main/java/org/matsim/utils/objectattributes/attributable/AttributesUtils.java
robustness-copilot_data_99
/** * Method for replacing value of specific property with passed * value, and returning value (or null if none). * * @param propertyName Property of which value to replace * @param value Value to set property to, replacing old value if any * * @return Old value of the property; null if there was no such property * with value * * @since 2.1 */ public JsonNode replace(String propertyName, JsonNode value){ if (value == null) { value = nullNode(); } return _children.put(propertyName, value); }
/src/main/java/com/fasterxml/jackson/databind/node/ObjectNode.java
robustness-copilot_data_100
/** * Formats a float to fit into the connectiontable and changes it * to a String. * * @param fl The float to be formated * @return The String to be written into the connectiontable */ protected static String formatMDLFloat(float fl){ String s = "", fs = ""; int l; NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); nf.setMinimumIntegerDigits(1); nf.setMaximumIntegerDigits(4); nf.setMinimumFractionDigits(4); nf.setMaximumFractionDigits(4); nf.setGroupingUsed(false); if (Double.isNaN(fl) || Double.isInfinite(fl)) s = "0.0000"; else s = nf.format(fl); l = 10 - s.length(); for (int f = 0; f < l; f++) fs += " "; fs += s; return fs; }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Writer.java
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1