_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q3300
AbstractListCommandWithoutFurnace.printValuesSorted
train
protected static void printValuesSorted(String message, Set<String> values) { System.out.println(); System.out.println(message + ":"); List<String> sorted = new ArrayList<>(values); Collections.sort(sorted); for (String value : sorted) { System.out.println("\t" + value); } }
java
{ "resource": "" }
q3301
GraphTypeManager.getTypeValue
train
public static String getTypeValue(Class<? extends WindupFrame> clazz) { TypeValue typeValueAnnotation = clazz.getAnnotation(TypeValue.class); if (typeValueAnnotation == null) throw new IllegalArgumentException("Class " + clazz.getCanonicalName() + " lacks a @TypeValue annotation"); return typeValueAnnotation.value(); }
java
{ "resource": "" }
q3302
FreeMarkerUtil.getDefaultFreemarkerConfiguration
train
public static Configuration getDefaultFreemarkerConfiguration() { freemarker.template.Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_26); DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26); objectWrapperBuilder.setUseAdaptersForContainers(true); objectWrapperBuilder.setIterableSupport(true); configuration.setObjectWrapper(objectWrapperBuilder.build()); configuration.setAPIBuiltinEnabled(true); configuration.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader()); configuration.setTemplateUpdateDelayMilliseconds(3600); return configuration; }
java
{ "resource": "" }
q3303
FreeMarkerUtil.findFreeMarkerContextVariables
train
public static Map<String, Object> findFreeMarkerContextVariables(Variables variables, String... varNames) { Map<String, Object> results = new HashMap<>(); for (String varName : varNames) { WindupVertexFrame payload = null; try { payload = Iteration.getCurrentPayload(variables, null, varName); } catch (IllegalStateException | IllegalArgumentException e) { // oh well } if (payload != null) { results.put(varName, payload); } else { Iterable<? extends WindupVertexFrame> var = variables.findVariable(varName); if (var != null) { results.put(varName, var); } } } return results; }
java
{ "resource": "" }
q3304
ClassificationService.attachLink
train
public ClassificationModel attachLink(ClassificationModel classificationModel, LinkModel linkModel) { for (LinkModel existing : classificationModel.getLinks()) { if (StringUtils.equals(existing.getLink(), linkModel.getLink())) { return classificationModel; } } classificationModel.addLink(linkModel); return classificationModel; }
java
{ "resource": "" }
q3305
DiscoverMavenProjectsRuleProvider.getMavenStubProject
train
private MavenProjectModel getMavenStubProject(MavenProjectService mavenProjectService, String groupId, String artifactId, String version) { Iterable<MavenProjectModel> mavenProjectModels = mavenProjectService.findByGroupArtifactVersion(groupId, artifactId, version); if (!mavenProjectModels.iterator().hasNext()) { return null; } for (MavenProjectModel mavenProjectModel : mavenProjectModels) { if (mavenProjectModel.getRootFileModel() == null) { // this is a stub... we can fill it in with details return mavenProjectModel; } } return null; }
java
{ "resource": "" }
q3306
PathUtil.getRootFolderForSource
train
public static Path getRootFolderForSource(Path sourceFilePath, String packageName) { if (packageName == null || packageName.trim().isEmpty()) { return sourceFilePath.getParent(); } String[] packageNameComponents = packageName.split("\\."); Path currentPath = sourceFilePath.getParent(); for (int i = packageNameComponents.length; i > 0; i--) { String packageComponent = packageNameComponents[i - 1]; if (!StringUtils.equals(packageComponent, currentPath.getFileName().toString())) { return null; } currentPath = currentPath.getParent(); } return currentPath; }
java
{ "resource": "" }
q3307
PathUtil.isInSubDirectory
train
public static boolean isInSubDirectory(File dir, File file) { if (file == null) return false; if (file.equals(dir)) return true; return isInSubDirectory(dir, file.getParentFile()); }
java
{ "resource": "" }
q3308
PathUtil.createDirectory
train
public static void createDirectory(Path dir, String dirDesc) { try { Files.createDirectories(dir); } catch (IOException ex) { throw new WindupException("Error creating " + dirDesc + " folder: " + dir.toString() + " due to: " + ex.getMessage(), ex); } }
java
{ "resource": "" }
q3309
ReferenceResolvingVisitor.processType
train
private ClassReference processType(Type type, TypeReferenceLocation typeReferenceLocation, int lineNumber, int columnNumber, int length, String line) { if (type == null) return null; ITypeBinding resolveBinding = type.resolveBinding(); if (resolveBinding == null) { ResolveClassnameResult resolvedResult = resolveClassname(type.toString()); ResolutionStatus status = resolvedResult.found ? ResolutionStatus.RECOVERED : ResolutionStatus.UNRESOLVED; PackageAndClassName packageAndClassName = PackageAndClassName.parseFromQualifiedName(resolvedResult.result); return processTypeAsString(resolvedResult.result, packageAndClassName.packageName, packageAndClassName.className, status, typeReferenceLocation, lineNumber, columnNumber, length, line); } else { return processTypeBinding(type.resolveBinding(), ResolutionStatus.RESOLVED, typeReferenceLocation, lineNumber, columnNumber, length, line); } }
java
{ "resource": "" }
q3310
ReferenceResolvingVisitor.addAnnotationValues
train
private void addAnnotationValues(ClassReference annotatedReference, AnnotationClassReference typeRef, Annotation node) { Map<String, AnnotationValue> annotationValueMap = new HashMap<>(); if (node instanceof SingleMemberAnnotation) { SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) node; AnnotationValue value = getAnnotationValueForExpression(annotatedReference, singleMemberAnnotation.getValue()); annotationValueMap.put("value", value); } else if (node instanceof NormalAnnotation) { @SuppressWarnings("unchecked") List<MemberValuePair> annotationValues = ((NormalAnnotation) node).values(); for (MemberValuePair annotationValue : annotationValues) { String key = annotationValue.getName().toString(); Expression expression = annotationValue.getValue(); AnnotationValue value = getAnnotationValueForExpression(annotatedReference, expression); annotationValueMap.put(key, value); } } typeRef.setAnnotationValues(annotationValueMap); }
java
{ "resource": "" }
q3311
ReferenceResolvingVisitor.visit
train
@Override public boolean visit(VariableDeclarationStatement node) { for (int i = 0; i < node.fragments().size(); ++i) { String nodeType = node.getType().toString(); VariableDeclarationFragment frag = (VariableDeclarationFragment) node.fragments().get(i); state.getNames().add(frag.getName().getIdentifier()); state.getNameInstance().put(frag.getName().toString(), nodeType.toString()); } processType(node.getType(), TypeReferenceLocation.VARIABLE_DECLARATION, compilationUnit.getLineNumber(node.getStartPosition()), compilationUnit.getColumnNumber(node.getStartPosition()), node.getLength(), node.toString()); return super.visit(node); }
java
{ "resource": "" }
q3312
Query.excludingType
train
@Override public QueryBuilderFind excludingType(final Class<? extends WindupVertexFrame> type) { pipelineCriteria.add(new QueryGremlinCriterion() { @Override public void query(GraphRewrite event, GraphTraversal<?, Vertex> pipeline) { pipeline.filter(it -> !GraphTypeManager.hasType(type, it.get())); } }); return this; }
java
{ "resource": "" }
q3313
CssJsResourceRenderingRuleProvider.addonDependsOnReporting
train
private boolean addonDependsOnReporting(Addon addon) { for (AddonDependency dep : addon.getDependencies()) { if (dep.getDependency().equals(this.addon)) { return true; } boolean subDep = addonDependsOnReporting(dep.getDependency()); if (subDep) { return true; } } return false; }
java
{ "resource": "" }
q3314
TagGraphService.getSingleParent
train
public static TagModel getSingleParent(TagModel tag) { final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator(); if (!parents.hasNext()) throw new WindupException("Tag is not designated by any tags: " + tag); final TagModel maybeOnlyParent = parents.next(); if (parents.hasNext()) { StringBuilder sb = new StringBuilder(); tag.getDesignatedByTags().iterator().forEachRemaining(x -> sb.append(x).append(", ")); throw new WindupException(String.format("Tag %s is designated by multiple tags: %s", tag, sb.toString())); } return maybeOnlyParent; }
java
{ "resource": "" }
q3315
QueryTypeCriterion.addPipeFor
train
public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline, Class<? extends WindupVertexFrame> clazz) { pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz)); return pipeline; }
java
{ "resource": "" }
q3316
TagUtil.strictCheckMatchingTags
train
public static boolean strictCheckMatchingTags(Collection<String> tags, Set<String> includeTags, Set<String> excludeTags) { boolean includeTagsEnabled = !includeTags.isEmpty(); for (String tag : tags) { boolean isIncluded = includeTags.contains(tag); boolean isExcluded = excludeTags.contains(tag); if ((includeTagsEnabled && isIncluded) || (!includeTagsEnabled && !isExcluded)) { return true; } } return false; }
java
{ "resource": "" }
q3317
RunWindupCommand.expandMultiAppInputDirs
train
private static List<Path> expandMultiAppInputDirs(List<Path> input) { List<Path> expanded = new LinkedList<>(); for (Path path : input) { if (Files.isRegularFile(path)) { expanded.add(path); continue; } if (!Files.isDirectory(path)) { String pathString = (path == null) ? "" : path.toString(); log.warning("Neither a file or directory found in input: " + pathString); continue; } try { try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) { for (Path subpath : directoryStream) { if (isJavaArchive(subpath)) { expanded.add(subpath); } } } } catch (IOException e) { throw new WindupException("Failed to read directory contents of: " + path); } } return expanded; }
java
{ "resource": "" }
q3318
RuleUtils.ruleToRuleContentsString
train
public static String ruleToRuleContentsString(Rule originalRule, int indentLevel) { if (originalRule instanceof Context && ((Context) originalRule).containsKey(RuleMetadataType.RULE_XML)) { return (String) ((Context) originalRule).get(RuleMetadataType.RULE_XML); } if (!(originalRule instanceof RuleBuilder)) { return wrap(originalRule.toString(), MAX_WIDTH, indentLevel); } final RuleBuilder rule = (RuleBuilder) originalRule; StringBuilder result = new StringBuilder(); if (indentLevel == 0) result.append("addRule()"); for (Condition condition : rule.getConditions()) { String conditionToString = conditionToString(condition, indentLevel + 1); if (!conditionToString.isEmpty()) { result.append(System.lineSeparator()); insertPadding(result, indentLevel + 1); result.append(".when(").append(wrap(conditionToString, MAX_WIDTH, indentLevel + 2)).append(")"); } } for (Operation operation : rule.getOperations()) { String operationToString = operationToString(operation, indentLevel + 1); if (!operationToString.isEmpty()) { result.append(System.lineSeparator()); insertPadding(result, indentLevel + 1); result.append(".perform(").append(wrap(operationToString, MAX_WIDTH, indentLevel + 2)).append(")"); } } if (rule.getId() != null && !rule.getId().isEmpty()) { result.append(System.lineSeparator()); insertPadding(result, indentLevel); result.append("withId(\"").append(rule.getId()).append("\")"); } if (rule.priority() != 0) { result.append(System.lineSeparator()); insertPadding(result, indentLevel); result.append(".withPriority(").append(rule.priority()).append(")"); } return result.toString(); }
java
{ "resource": "" }
q3319
SetInPropertiesHandler.processMethod
train
@Override public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation) { String methodName = method.getName(); if (ReflectionUtility.isGetMethod(method)) return createInterceptor(builder, method); else if (ReflectionUtility.isSetMethod(method)) return createInterceptor(builder, method); else if (methodName.startsWith("addAll")) return createInterceptor(builder, method); else if (methodName.startsWith("add")) return createInterceptor(builder, method); else throw new WindupException("Only get*, set*, add*, and addAll* method names are supported for @" + SetInProperties.class.getSimpleName() + ", found at: " + method.getName()); }
java
{ "resource": "" }
q3320
JNDIResourceService.associateTypeJndiResource
train
public void associateTypeJndiResource(JNDIResourceModel resource, String type) { if (type == null || resource == null) { return; } if (StringUtils.equals(type, "javax.sql.DataSource") && !(resource instanceof DataSourceModel)) { DataSourceModel ds = GraphService.addTypeToModel(this.getGraphContext(), resource, DataSourceModel.class); } else if (StringUtils.equals(type, "javax.jms.Queue") && !(resource instanceof JmsDestinationModel)) { JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class); jms.setDestinationType(JmsDestinationType.QUEUE); } else if (StringUtils.equals(type, "javax.jms.QueueConnectionFactory") && !(resource instanceof JmsConnectionFactoryModel)) { JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class); jms.setConnectionFactoryType(JmsDestinationType.QUEUE); } else if (StringUtils.equals(type, "javax.jms.Topic") && !(resource instanceof JmsDestinationModel)) { JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class); jms.setDestinationType(JmsDestinationType.TOPIC); } else if (StringUtils.equals(type, "javax.jms.TopicConnectionFactory") && !(resource instanceof JmsConnectionFactoryModel)) { JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class); jms.setConnectionFactoryType(JmsDestinationType.TOPIC); } }
java
{ "resource": "" }
q3321
FeatureBasedApiDependenciesDeducer.addDeploymentTypeBasedDependencies
train
private boolean addDeploymentTypeBasedDependencies(ProjectModel projectModel, Pom modulePom) { if (projectModel.getProjectType() == null) return true; switch (projectModel.getProjectType()){ case "ear": break; case "war": modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_SERVLET_31)); break; case "ejb": modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_32)); modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_CDI)); modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_JAVAX_ANN)); break; case "ejb-client": modulePom.getDependencies().add(new SimpleDependency(Dependency.Role.API, ApiDependenciesData.DEP_API_EJB_CLIENT)); break; } return false; }
java
{ "resource": "" }
q3322
TagService.readTags
train
public void readTags(InputStream tagsXML) { SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser saxParser = factory.newSAXParser(); saxParser.parse(tagsXML, new TagsSaxHandler(this)); } catch (ParserConfigurationException | SAXException | IOException ex) { throw new RuntimeException("Failed parsing the tags definition: " + ex.getMessage(), ex); } }
java
{ "resource": "" }
q3323
TagService.getPrimeTags
train
public List<Tag> getPrimeTags() { return this.definedTags.values().stream() .filter(Tag::isPrime) .collect(Collectors.toList()); }
java
{ "resource": "" }
q3324
TagService.getRootTags
train
public List<Tag> getRootTags() { return this.definedTags.values().stream() .filter(Tag::isRoot) .collect(Collectors.toList()); }
java
{ "resource": "" }
q3325
TagService.getAncestorTags
train
public Set<Tag> getAncestorTags(Tag tag) { Set<Tag> ancestors = new HashSet<>(); getAncestorTags(tag, ancestors); return ancestors; }
java
{ "resource": "" }
q3326
TagService.writeTagsToJavaScript
train
public void writeTagsToJavaScript(Writer writer) throws IOException { writer.append("function fillTagService(tagService) {\n"); writer.append("\t// (name, isPrime, isPseudo, color), [parent tags]\n"); for (Tag tag : definedTags.values()) { writer.append("\ttagService.registerTag(new Tag("); escapeOrNull(tag.getName(), writer); writer.append(", "); escapeOrNull(tag.getTitle(), writer); writer.append(", ").append("" + tag.isPrime()) .append(", ").append("" + tag.isPseudo()) .append(", "); escapeOrNull(tag.getColor(), writer); writer.append(")").append(", ["); // We only have strings, not references, so we're letting registerTag() getOrCreate() the tag. for (Tag parentTag : tag.getParentTags()) { writer.append("'").append(StringEscapeUtils.escapeEcmaScript(parentTag.getName())).append("',"); } writer.append("]);\n"); } writer.append("}\n"); }
java
{ "resource": "" }
q3327
ReportService.getReportDirectory
train
public Path getReportDirectory() { WindupConfigurationModel cfg = WindupConfigurationService.getConfigurationModel(getGraphContext()); Path path = cfg.getOutputPath().asFile().toPath().resolve(REPORTS_DIR); createDirectoryIfNeeded(path); return path.toAbsolutePath(); }
java
{ "resource": "" }
q3328
ReportService.getReportByName
train
@SuppressWarnings("unchecked") public <T extends ReportModel> T getReportByName(String name, Class<T> clazz) { WindupVertexFrame model = this.getUniqueByProperty(ReportModel.REPORT_NAME, name); try { return (T) model; } catch (ClassCastException ex) { throw new WindupException("The vertex is not of expected frame type " + clazz.getName() + ": " + model.toPrettyString()); } }
java
{ "resource": "" }
q3329
ReportService.getUniqueFilename
train
public String getUniqueFilename(String baseFileName, String extension, boolean cleanBaseFileName, String... ancestorFolders) { if (cleanBaseFileName) { baseFileName = PathUtil.cleanFileName(baseFileName); } if (ancestorFolders != null) { Path pathToFile = Paths.get("", Stream.of(ancestorFolders).map(ancestor -> PathUtil.cleanFileName(ancestor)).toArray(String[]::new)).resolve(baseFileName); baseFileName = pathToFile.toString(); } String filename = baseFileName + "." + extension; // FIXME this looks nasty while (usedFilenames.contains(filename)) { filename = baseFileName + "." + index.getAndIncrement() + "." + extension; } usedFilenames.add(filename); return filename; }
java
{ "resource": "" }
q3330
TagSetService.getOrCreate
train
public TagSetModel getOrCreate(GraphRewrite event, Set<String> tags) { Map<Set<String>, Vertex> cache = getCache(event); Vertex vertex = cache.get(tags); if (vertex == null) { TagSetModel model = create(); model.setTags(tags); cache.put(tags, model.getElement()); return model; } else { return frame(vertex); } }
java
{ "resource": "" }
q3331
GetTechReportPunchCardStatsMethod.getAllApplications
train
private static Set<ProjectModel> getAllApplications(GraphContext graphContext) { Set<ProjectModel> apps = new HashSet<>(); Iterable<ProjectModel> appProjects = graphContext.findAll(ProjectModel.class); for (ProjectModel appProject : appProjects) apps.add(appProject); return apps; }
java
{ "resource": "" }
q3332
TechReportService.processPlaceLabels
train
private static TechReportPlacement processPlaceLabels(GraphContext graphContext, Set<String> tagNames) { TagGraphService tagService = new TagGraphService(graphContext); if (tagNames.size() < 3) throw new WindupException("There should always be exactly 3 placement labels - row, sector, column/box. It was: " + tagNames); if (tagNames.size() > 3) LOG.severe("There should always be exactly 3 placement labels - row, sector, column/box. It was: " + tagNames); TechReportPlacement placement = new TechReportPlacement(); final TagModel placeSectorsTag = tagService.getTagByName("techReport:placeSectors"); final TagModel placeBoxesTag = tagService.getTagByName("techReport:placeBoxes"); final TagModel placeRowsTag = tagService.getTagByName("techReport:placeRows"); Set<String> unknownTags = new HashSet<>(); for (String name : tagNames) { final TagModel tag = tagService.getTagByName(name); if (null == tag) continue; if (TagGraphService.isTagUnderTagOrSame(tag, placeSectorsTag)) { placement.sector = tag; } else if (TagGraphService.isTagUnderTagOrSame(tag, placeBoxesTag)) { placement.box = tag; } else if (TagGraphService.isTagUnderTagOrSame(tag, placeRowsTag)) { placement.row = tag; } else { unknownTags.add(name); } } placement.unknown = unknownTags; LOG.fine(String.format("\t\tLabels %s identified as: sector: %s, box: %s, row: %s", tagNames, placement.sector, placement.box, placement.row)); if (placement.box == null || placement.row == null) { LOG.severe(String.format( "There should always be exactly 3 placement labels - row, sector, column/box. Found: %s, of which box: %s, row: %s", tagNames, placement.box, placement.row)); } return placement; }
java
{ "resource": "" }
q3333
Artifact.withVersion
train
public static Artifact withVersion(Version v) { Artifact artifact = new Artifact(); artifact.version = v; return artifact; }
java
{ "resource": "" }
q3334
Artifact.withGroupId
train
public static Artifact withGroupId(String groupId) { Artifact artifact = new Artifact(); artifact.groupId = new RegexParameterizedPatternParser(groupId); return artifact; }
java
{ "resource": "" }
q3335
Artifact.withArtifactId
train
public static Artifact withArtifactId(String artifactId) { Artifact artifact = new Artifact(); artifact.artifactId = new RegexParameterizedPatternParser(artifactId); return artifact; }
java
{ "resource": "" }
q3336
Variables.setSingletonVariable
train
public void setSingletonVariable(String name, WindupVertexFrame frame) { setVariable(name, Collections.singletonList(frame)); }
java
{ "resource": "" }
q3337
Variables.setVariable
train
public void setVariable(String name, Iterable<? extends WindupVertexFrame> frames) { Map<String, Iterable<? extends WindupVertexFrame>> frame = peek(); if (!Iteration.DEFAULT_VARIABLE_LIST_STRING.equals(name) && findVariable(name) != null) { throw new IllegalArgumentException("Variable \"" + name + "\" has already been assigned and cannot be reassigned"); } frame.put(name, frames); }
java
{ "resource": "" }
q3338
Variables.removeVariable
train
public void removeVariable(String name) { Map<String, Iterable<? extends WindupVertexFrame>> frame = peek(); frame.remove(name); }
java
{ "resource": "" }
q3339
Variables.findVariable
train
public Iterable<? extends WindupVertexFrame> findVariable(String name, int maxDepth) { int currentDepth = 0; Iterable<? extends WindupVertexFrame> result = null; for (Map<String, Iterable<? extends WindupVertexFrame>> frame : deque) { result = frame.get(name); if (result != null) { break; } currentDepth++; if (currentDepth >= maxDepth) break; } return result; }
java
{ "resource": "" }
q3340
Variables.findVariableOfType
train
@SuppressWarnings("unchecked") public <T extends WindupVertexFrame> Iterable<T> findVariableOfType(Class<T> type) { for (Map<String, Iterable<? extends WindupVertexFrame>> topOfStack : deque) { for (Iterable<? extends WindupVertexFrame> frames : topOfStack.values()) { boolean empty = true; for (WindupVertexFrame frame : frames) { if (!type.isAssignableFrom(frame.getClass())) { break; } else { empty = false; } } // now we know all the frames are of the chosen type if (!empty) return (Iterable<T>) frames; } } return null; }
java
{ "resource": "" }
q3341
AbstractIterationFilter.checkVariableName
train
protected void checkVariableName(GraphRewrite event, EvaluationContext context) { if (getInputVariablesName() == null) { setInputVariablesName(Iteration.getPayloadVariableName(event, context)); } }
java
{ "resource": "" }
q3342
DiscoverPackagesCommand.findClasses
train
private static Map<String, Integer> findClasses(Path path) { List<String> paths = findPaths(path, true); Map<String, Integer> results = new HashMap<>(); for (String subPath : paths) { if (subPath.endsWith(".java") || subPath.endsWith(".class")) { String qualifiedName = PathUtil.classFilePathToClassname(subPath); addClassToMap(results, qualifiedName); } } return results; }
java
{ "resource": "" }
q3343
XsltTransformationService.getTransformedXSLTPath
train
public Path getTransformedXSLTPath(FileModel payload) { ReportService reportService = new ReportService(getGraphContext()); Path outputPath = reportService.getReportDirectory(); outputPath = outputPath.resolve(this.getRelativeTransformedXSLTPath(payload)); if (!Files.isDirectory(outputPath)) { try { Files.createDirectories(outputPath); } catch (IOException e) { throw new WindupException("Failed to create output directory at: " + outputPath + " due to: " + e.getMessage(), e); } } return outputPath; }
java
{ "resource": "" }
q3344
HibernateDialectDataSourceTypeResolver.resolveDataSourceTypeFromDialect
train
public static String resolveDataSourceTypeFromDialect(String dialect) { if (StringUtils.contains(dialect, "Oracle")) { return "Oracle"; } else if (StringUtils.contains(dialect, "MySQL")) { return "MySQL"; } else if (StringUtils.contains(dialect, "DB2390Dialect")) { return "DB2/390"; } else if (StringUtils.contains(dialect, "DB2400Dialect")) { return "DB2/400"; } else if (StringUtils.contains(dialect, "DB2")) { return "DB2"; } else if (StringUtils.contains(dialect, "Ingres")) { return "Ingres"; } else if (StringUtils.contains(dialect, "Derby")) { return "Derby"; } else if (StringUtils.contains(dialect, "Pointbase")) { return "Pointbase"; } else if (StringUtils.contains(dialect, "Postgres")) { return "Postgres"; } else if (StringUtils.contains(dialect, "SQLServer")) { return "SQLServer"; } else if (StringUtils.contains(dialect, "Sybase")) { return "Sybase"; } else if (StringUtils.contains(dialect, "HSQLDialect")) { return "HyperSQL"; } else if (StringUtils.contains(dialect, "H2Dialect")) { return "H2"; } return dialect; }
java
{ "resource": "" }
q3345
SkippedArchives.load
train
public static void load(File file) { try(FileInputStream inputStream = new FileInputStream(file)) { LineIterator it = IOUtils.lineIterator(inputStream, "UTF-8"); while (it.hasNext()) { String line = it.next(); if (!line.startsWith("#") && !line.trim().isEmpty()) { add(line); } } } catch (Exception e) { throw new WindupException("Failed loading archive ignore patterns from [" + file.toString() + "]", e); } }
java
{ "resource": "" }
q3346
Iteration.perform
train
@Override public void perform(Rewrite event, EvaluationContext context) { perform((GraphRewrite) event, context); }
java
{ "resource": "" }
q3347
MetadataBuilder.join
train
@SafeVarargs private final <T> Set<T> join(Set<T>... sets) { Set<T> result = new HashSet<>(); if (sets == null) return result; for (Set<T> set : sets) { if (set != null) result.addAll(set); } return result; }
java
{ "resource": "" }
q3348
IssueCategoryRegistry.getIssueCategories
train
public List<IssueCategory> getIssueCategories() { return this.issueCategories.values().stream() .sorted((category1, category2) -> category1.getPriority() - category2.getPriority()) .collect(Collectors.toList()); }
java
{ "resource": "" }
q3349
IssueCategoryRegistry.addDefaults
train
private void addDefaults() { this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Mandatory", MANDATORY, 1000, true)); this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), "Optional", OPTIONAL, 1000, true)); this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), "Potential Issues", POTENTIAL, 1000, true)); this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Cloud Mandatory", CLOUD_MANDATORY, 1000, true)); this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), "Information", INFORMATION, 1000, true)); }
java
{ "resource": "" }
q3350
MavenStructureRenderer.renderFreemarkerTemplate
train
private static void renderFreemarkerTemplate(Path templatePath, Map vars, Path outputPath) throws IOException, TemplateException { if(templatePath == null) throw new WindupException("templatePath is null"); freemarker.template.Configuration freemarkerConfig = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_26); DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); objectWrapperBuilder.setUseAdaptersForContainers(true); objectWrapperBuilder.setIterableSupport(true); freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build()); freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader()); Template template = freemarkerConfig.getTemplate(templatePath.toString().replace('\\', '/')); try (FileWriter fw = new FileWriter(outputPath.toFile())) { template.process(vars, fw); } }
java
{ "resource": "" }
q3351
ExecutionStatistics.get
train
public static synchronized ExecutionStatistics get() { Thread currentThread = Thread.currentThread(); if (stats.get(currentThread) == null) { stats.put(currentThread, new ExecutionStatistics()); } return stats.get(currentThread); }
java
{ "resource": "" }
q3352
ExecutionStatistics.merge
train
public void merge() { Thread currentThread = Thread.currentThread(); if(!stats.get(currentThread).equals(this) || currentThread instanceof WindupChildThread) { throw new IllegalArgumentException("Trying to merge executionstatistics from a " + "different thread that is not registered as main thread of application run"); } for (Thread thread : stats.keySet()) { if(thread instanceof WindupChildThread && ((WindupChildThread) thread).getParentThread().equals(currentThread)) { merge(stats.get(thread)); } } }
java
{ "resource": "" }
q3353
ExecutionStatistics.merge
train
private void merge(ExecutionStatistics otherStatistics) { for (String s : otherStatistics.executionInfo.keySet()) { TimingData thisStats = this.executionInfo.get(s); TimingData otherStats = otherStatistics.executionInfo.get(s); if(thisStats == null) { this.executionInfo.put(s,otherStats); } else { thisStats.merge(otherStats); } } }
java
{ "resource": "" }
q3354
ExecutionStatistics.serializeTimingData
train
public void serializeTimingData(Path outputPath) { //merge subThreads instances into the main instance merge(); try (FileWriter fw = new FileWriter(outputPath.toFile())) { fw.write("Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\n"); for (Map.Entry<String, TimingData> timing : executionInfo.entrySet()) { TimingData data = timing.getValue(); long totalMillis = (data.totalNanos / 1000000); double millisPerExecution = (double) totalMillis / (double) data.numberOfExecutions; fw.write(String.format("%6d, %6d, %8.2f, %s\n", data.numberOfExecutions, totalMillis, millisPerExecution, StringEscapeUtils.escapeCsv(timing.getKey()) )); } } catch (Exception e) { e.printStackTrace(); } }
java
{ "resource": "" }
q3355
ExecutionStatistics.begin
train
public void begin(String key) { if (key == null) { return; } TimingData data = executionInfo.get(key); if (data == null) { data = new TimingData(key); executionInfo.put(key, data); } data.begin(); }
java
{ "resource": "" }
q3356
ExecutionStatistics.end
train
public void end(String key) { if (key == null) { return; } TimingData data = executionInfo.get(key); if (data == null) { LOG.info("Called end with key: " + key + " without ever calling begin"); return; } data.end(); }
java
{ "resource": "" }
q3357
PackagesToContainingMavenArtifactsIndex.registerPackageInTypeInterestFactory
train
private void registerPackageInTypeInterestFactory(String pkg) { TypeInterestFactory.registerInterest(pkg + "_pkg", pkg.replace(".", "\\."), pkg, TypeReferenceLocation.IMPORT); // TODO: Finish the implementation }
java
{ "resource": "" }
q3358
XMLDocumentCache.cache
train
public static void cache(XmlFileModel key, Document document) { String cacheKey = getKey(key); map.put(cacheKey, new CacheDocument(false, document)); }
java
{ "resource": "" }
q3359
XMLDocumentCache.cacheParseFailure
train
public static void cacheParseFailure(XmlFileModel key) { map.put(getKey(key), new CacheDocument(true, null)); }
java
{ "resource": "" }
q3360
XMLDocumentCache.get
train
public static Result get(XmlFileModel key) { String cacheKey = getKey(key); Result result = null; CacheDocument reference = map.get(cacheKey); if (reference == null) return new Result(false, null); if (reference.parseFailure) return new Result(true, null); Document document = reference.getDocument(); if (document == null) LOG.info("Cache miss on XML document: " + cacheKey); return new Result(false, document); }
java
{ "resource": "" }
q3361
LineNumberFormatter.reformatFile
train
public void reformatFile() throws IOException { List<LineNumberPosition> lineBrokenPositions = new ArrayList<>(); List<String> brokenLines = breakLines(lineBrokenPositions); emitFormatted(brokenLines, lineBrokenPositions); }
java
{ "resource": "" }
q3362
PackageNameMapping.fromPackage
train
public static PackageNameMappingWithPackagePattern fromPackage(String packagePattern) { PackageNameMapping packageNameMapping = new PackageNameMapping(); packageNameMapping.setPackagePattern(packagePattern); return packageNameMapping; }
java
{ "resource": "" }
q3363
PackageNameMapping.isExclusivelyKnownArchive
train
public static boolean isExclusivelyKnownArchive(GraphRewrite event, String filePath) { String extension = StringUtils.substringAfterLast(filePath, "."); if (!StringUtils.equalsIgnoreCase(extension, "jar")) return false; ZipFile archive; try { archive = new ZipFile(filePath); } catch (IOException e) { return false; } WindupJavaConfigurationService javaConfigurationService = new WindupJavaConfigurationService(event.getGraphContext()); WindupJavaConfigurationModel javaConfigurationModel = WindupJavaConfigurationService.getJavaConfigurationModel(event.getGraphContext()); // indicates that the user did specify some packages to scan explicitly (as opposed to scanning everything) boolean customerPackagesSpecified = javaConfigurationModel.getScanJavaPackages().iterator().hasNext(); // this should only be true if: // 1) the package does not contain *any* customer packages. // 2) the package contains "known" vendor packages. boolean exclusivelyKnown = false; String organization = null; Enumeration<?> e = archive.entries(); // go through all entries... ZipEntry entry; while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); String entryName = entry.getName(); if (entry.isDirectory() || !StringUtils.endsWith(entryName, ".class")) continue; String classname = PathUtil.classFilePathToClassname(entryName); // if the package isn't current "known", try to match against known packages for this entry. if (!exclusivelyKnown) { organization = getOrganizationForPackage(event, classname); if (organization != null) { exclusivelyKnown = true; } else { // we couldn't find a package definitively, so ignore the archive exclusivelyKnown = false; break; } } // If the user specified package names and this is in those package names, then scan it anyway if (customerPackagesSpecified && javaConfigurationService.shouldScanPackage(classname)) { return false; } } if (exclusivelyKnown) LOG.info("Known Package: " + archive.getName() + "; Organization: " + organization); // Return the evaluated exclusively known value. return exclusivelyKnown; }
java
{ "resource": "" }
q3364
HullWhiteModel.getShortRate
train
private RandomVariable getShortRate(int timeIndex) throws CalculationException { double time = getProcess().getTime(timeIndex); double timePrev = timeIndex > 0 ? getProcess().getTime(timeIndex-1) : time; double timeNext = getProcess().getTime(timeIndex+1); RandomVariable zeroRate = getZeroRateFromForwardCurve(time); //getDiscountFactorFromForwardCurve(time).div(getDiscountFactorFromForwardCurve(timeNext)).log().div(timeNext-time); RandomVariable alpha = getDV(0, time); RandomVariable value = getProcess().getProcessValue(timeIndex, 0); value = value.add(alpha); // value = value.sub(Math.log(value.exp().getAverage())); value = value.add(zeroRate); return value; }
java
{ "resource": "" }
q3365
AnalyticFormulas.blackScholesATMOptionValue
train
public static double blackScholesATMOptionValue( double volatility, double optionMaturity, double forward, double payoffUnit) { if(optionMaturity < 0) { return 0.0; } // Calculate analytic value double dPlus = 0.5 * volatility * Math.sqrt(optionMaturity); double dMinus = -dPlus; double valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit; return valueAnalytic; }
java
{ "resource": "" }
q3366
AnalyticFormulas.blackScholesOptionRho
train
public static double blackScholesOptionRho( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate rho double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return rho; } }
java
{ "resource": "" }
q3367
AnalyticFormulas.blackScholesDigitalOptionValue
train
public static double blackScholesDigitalOptionValue( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0) { // The Black-Scholes model does not consider it being an option return 1.0; } else { // Calculate analytic value double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return valueAnalytic; } }
java
{ "resource": "" }
q3368
AnalyticFormulas.blackScholesDigitalOptionDelta
train
public static double blackScholesDigitalOptionDelta( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate delta double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double delta = Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility); return delta; } }
java
{ "resource": "" }
q3369
AnalyticFormulas.blackScholesDigitalOptionVega
train
public static double blackScholesDigitalOptionVega( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate vega double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility; return vega; } }
java
{ "resource": "" }
q3370
AnalyticFormulas.blackScholesDigitalOptionRho
train
public static double blackScholesDigitalOptionRho( double initialStockValue, double riskFreeRate, double volatility, double optionMaturity, double optionStrike) { if(optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else if(optionStrike <= 0.0) { double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity); return rho; } else { // Calculate rho double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus) + Math.sqrt(optionMaturity)/volatility * Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI); return rho; } }
java
{ "resource": "" }
q3371
AnalyticFormulas.blackModelCapletValue
train
public static double blackModelCapletValue( double forward, double volatility, double optionMaturity, double optionStrike, double periodLength, double discountFactor) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor); }
java
{ "resource": "" }
q3372
AnalyticFormulas.blackModelDgitialCapletValue
train
public static double blackModelDgitialCapletValue( double forward, double volatility, double periodLength, double discountFactor, double optionMaturity, double optionStrike) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor; }
java
{ "resource": "" }
q3373
AnalyticFormulas.blackModelSwaptionValue
train
public static double blackModelSwaptionValue( double forwardSwaprate, double volatility, double optionMaturity, double optionStrike, double swapAnnuity) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity); }
java
{ "resource": "" }
q3374
AnalyticFormulas.huntKennedyCMSOptionValue
train
public static double huntKennedyCMSOptionValue( double forwardSwaprate, double volatility, double swapAnnuity, double optionMaturity, double swapMaturity, double payoffUnit, double optionStrike) { double a = 1.0/swapMaturity; double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate; double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity); double valueUnadjusted = blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity); double valueAdjusted = blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity); return a * valueUnadjusted + b * forwardSwaprate * valueAdjusted; }
java
{ "resource": "" }
q3375
AnalyticFormulas.huntKennedyCMSFloorValue
train
public static double huntKennedyCMSFloorValue( double forwardSwaprate, double volatility, double swapAnnuity, double optionMaturity, double swapMaturity, double payoffUnit, double optionStrike) { double huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike); // A floor is an option plus the strike (max(X,K) = max(X-K,0) + K) return huntKennedyCMSOptionValue + optionStrike * payoffUnit; }
java
{ "resource": "" }
q3376
AnalyticFormulas.huntKennedyCMSAdjustedRate
train
public static double huntKennedyCMSAdjustedRate( double forwardSwaprate, double volatility, double swapAnnuity, double optionMaturity, double swapMaturity, double payoffUnit) { double a = 1.0/swapMaturity; double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate; double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity); double rateUnadjusted = forwardSwaprate; double rateAdjusted = forwardSwaprate * convexityAdjustment; return (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit; }
java
{ "resource": "" }
q3377
AnalyticFormulas.volatilityConversionLognormalATMtoNormalATM
train
public static double volatilityConversionLognormalATMtoNormalATM(double forward, double displacement, double maturity, double lognormalVolatiltiy) { double x = lognormalVolatiltiy * Math.sqrt(maturity / 8); double y = org.apache.commons.math3.special.Erf.erf(x); double normalVol = Math.sqrt(2*Math.PI / maturity) * (forward+displacement) * y; return normalVol; }
java
{ "resource": "" }
q3378
FIPXMLParser.getSwapLegProductDescriptor
train
private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName, DayCountConvention daycountConvention) { boolean isFixed = leg.getElementsByTagName("interestType").item(0).getTextContent().equalsIgnoreCase("FIX"); ArrayList<Period> periods = new ArrayList<>(); ArrayList<Double> notionalsList = new ArrayList<>(); ArrayList<Double> rates = new ArrayList<>(); //extracting data for each period NodeList periodsXML = leg.getElementsByTagName("incomePayment"); for(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) { Element periodXML = (Element) periodsXML.item(periodIndex); LocalDate startDate = LocalDate.parse(periodXML.getElementsByTagName("startDate").item(0).getTextContent()); LocalDate endDate = LocalDate.parse(periodXML.getElementsByTagName("endDate").item(0).getTextContent()); LocalDate fixingDate = startDate; LocalDate paymentDate = LocalDate.parse(periodXML.getElementsByTagName("payDate").item(0).getTextContent()); if(! isFixed) { fixingDate = LocalDate.parse(periodXML.getElementsByTagName("fixingDate").item(0).getTextContent()); } periods.add(new Period(fixingDate, paymentDate, startDate, endDate)); double notional = Double.parseDouble(periodXML.getElementsByTagName("nominal").item(0).getTextContent()); notionalsList.add(new Double(notional)); if(isFixed) { double fixedRate = Double.parseDouble(periodXML.getElementsByTagName("fixedRate").item(0).getTextContent()); rates.add(new Double(fixedRate)); } else { rates.add(new Double(0)); } } ScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention); double[] notionals = notionalsList.stream().mapToDouble(Double::doubleValue).toArray(); double[] spreads = rates.stream().mapToDouble(Double::doubleValue).toArray(); return new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false); }
java
{ "resource": "" }
q3379
InterestRateMonteCarloProductFactory.constructLiborIndex
train
private static AbstractIndex constructLiborIndex(String forwardCurveName, Schedule schedule) { if(forwardCurveName != null) { //determine average fixing offset and period length double fixingOffset = 0; double periodLength = 0; for(int i = 0; i < schedule.getNumberOfPeriods(); i++) { fixingOffset *= ((double) i) / (i+1); fixingOffset += (schedule.getPeriodStart(i) - schedule.getFixing(i)) / (i+1); periodLength *= ((double) i) / (i+1); periodLength += schedule.getPeriodLength(i) / (i+1); } return new LIBORIndex(forwardCurveName, fixingOffset, periodLength); } else { return null; } }
java
{ "resource": "" }
q3380
SwaptionATM.getImpliedBachelierATMOptionVolatility
train
public RandomVariable getImpliedBachelierATMOptionVolatility(RandomVariable optionValue, double optionMaturity, double swapAnnuity){ return optionValue.average().mult(Math.sqrt(2.0 * Math.PI / optionMaturity) / swapAnnuity); }
java
{ "resource": "" }
q3381
BermudanSwaption.getBasisFunctions
train
public RandomVariable[] getBasisFunctions(double fixingDate, LIBORModelMonteCarloSimulationModel model) throws CalculationException { ArrayList<RandomVariable> basisFunctions = new ArrayList<>(); // Constant RandomVariable basisFunction = new RandomVariableFromDoubleArray(1.0);//.getRandomVariableForConstant(1.0); basisFunctions.add(basisFunction); int fixingDateIndex = Arrays.binarySearch(fixingDates, fixingDate); if(fixingDateIndex < 0) { fixingDateIndex = -fixingDateIndex; } if(fixingDateIndex >= fixingDates.length) { fixingDateIndex = fixingDates.length-1; } // forward rate to the next period RandomVariable rateShort = model.getLIBOR(fixingDate, fixingDate, paymentDates[fixingDateIndex]); RandomVariable discountShort = rateShort.mult(paymentDates[fixingDateIndex]-fixingDate).add(1.0).invert(); basisFunctions.add(discountShort); basisFunctions.add(discountShort.pow(2.0)); // basisFunctions.add(rateShort.pow(3.0)); // forward rate to the end of the product RandomVariable rateLong = model.getLIBOR(fixingDate, fixingDates[fixingDateIndex], paymentDates[paymentDates.length-1]); RandomVariable discountLong = rateLong.mult(paymentDates[paymentDates.length-1]-fixingDates[fixingDateIndex]).add(1.0).invert(); basisFunctions.add(discountLong); basisFunctions.add(discountLong.pow(2.0)); // basisFunctions.add(rateLong.pow(3.0)); // Numeraire RandomVariable numeraire = model.getNumeraire(fixingDate).invert(); basisFunctions.add(numeraire); // basisFunctions.add(numeraire.pow(2.0)); // basisFunctions.add(numeraire.pow(3.0)); return basisFunctions.toArray(new RandomVariable[basisFunctions.size()]); }
java
{ "resource": "" }
q3382
LIBORMarketModelStandard.getDrift
train
private RandomVariableInterface getDrift(int timeIndex, int componentIndex, RandomVariableInterface[] realizationAtTimeIndex, RandomVariableInterface[] realizationPredictor) { // Check if this LIBOR is already fixed if(getTime(timeIndex) >= this.getLiborPeriod(componentIndex)) { return null; } /* * We implemented several different methods to calculate the drift */ if(driftApproximationMethod == Driftapproximation.PREDICTOR_CORRECTOR && realizationPredictor != null) { RandomVariableInterface drift = getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex); RandomVariableInterface driftEulerWithPredictor = getDriftEuler(timeIndex, componentIndex, realizationPredictor); drift = drift.add(driftEulerWithPredictor).div(2.0); return drift; } else if(driftApproximationMethod == Driftapproximation.LINE_INTEGRAL && realizationPredictor != null) { return getDriftLineIntegral(timeIndex, componentIndex, realizationAtTimeIndex, realizationPredictor); } else { return getDriftEuler(timeIndex, componentIndex, realizationAtTimeIndex); } }
java
{ "resource": "" }
q3383
HaltonSequence.getHaltonNumberForGivenBase
train
public static double getHaltonNumberForGivenBase(long index, int base) { index += 1; double x = 0.0; double factor = 1.0 / base; while(index > 0) { x += (index % base) * factor; factor /= base; index /= base; } return x; }
java
{ "resource": "" }
q3384
RandomVariableAAD.getGradient
train
public Map<Integer, RandomVariable> getGradient(){ int numberOfCalculationSteps = getFunctionList().size(); RandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps]; omegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0); for(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){ omegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0); ArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices(); for(int functionIndex:childrenList){ RandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex); omegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]); } } ArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables(); Map<Integer, RandomVariable> gradient = new HashMap<Integer, RandomVariable>(); for(Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){ gradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]); } return gradient; }
java
{ "resource": "" }
q3385
DiscountCurveInterpolation.getZeroRates
train
public double[] getZeroRates(double[] maturities) { double[] values = new double[maturities.length]; for(int i=0; i<maturities.length; i++) { values[i] = getZeroRate(maturities[i]); } return values; }
java
{ "resource": "" }
q3386
LinearAlgebra.invert
train
public static double[][] invert(double[][] matrix) { if(isSolverUseApacheCommonsMath) { // Use LU from common math LUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix)); double[][] matrixInverse = lu.getSolver().getInverse().getData(); return matrixInverse; } else { return org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2(); } }
java
{ "resource": "" }
q3387
LinearAlgebra.factorReductionUsingCommonsMath
train
public static double[][] factorReductionUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = getFactorMatrix(correlationMatrix, numberOfFactors); // Renormalize rows for (int row = 0; row < correlationMatrix.length; row++) { double sumSquared = 0; for (int factor = 0; factor < numberOfFactors; factor++) { sumSquared += factorMatrix[row][factor] * factorMatrix[row][factor]; } if(sumSquared != 0) { for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = factorMatrix[row][factor] / Math.sqrt(sumSquared); } } else { // This is a rare case: The factor reduction of a completely decorrelated system to 1 factor for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = 1.0; } } } // Orthogonalized again double[][] reducedCorrelationMatrix = (new Array2DRowRealMatrix(factorMatrix).multiply(new Array2DRowRealMatrix(factorMatrix).transpose())).getData(); return getFactorMatrix(reducedCorrelationMatrix, numberOfFactors); }
java
{ "resource": "" }
q3388
LinearAlgebra.pseudoInverse
train
public static double[][] pseudoInverse(double[][] matrix){ if(isSolverUseApacheCommonsMath) { // Use LU from common math SingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix)); double[][] matrixInverse = svd.getSolver().getInverse().getData(); return matrixInverse; } else { return org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2(); } }
java
{ "resource": "" }
q3389
LinearAlgebra.diag
train
public static double[][] diag(double[] vector){ // Note: According to the Java Language spec, an array is initialized with the default value, here 0. double[][] diagonalMatrix = new double[vector.length][vector.length]; for(int index = 0; index < vector.length; index++) { diagonalMatrix[index][index] = vector[index]; } return diagonalMatrix; }
java
{ "resource": "" }
q3390
CalibratedModel.formatTargetValuesForOptimizer
train
private double[] formatTargetValuesForOptimizer() { //Put all values in an array for the optimizer. int numberOfMaturities = surface.getMaturities().length; double mats[] = surface.getMaturities(); ArrayList<Double> vals = new ArrayList<Double>(); for(int t = 0; t<numberOfMaturities; t++) { double mat = mats[t]; double[] myStrikes = surface.getSurface().get(mat).getStrikes(); OptionSmileData smileOfInterest = surface.getSurface().get(mat); for(int k = 0; k < myStrikes.length; k++) { vals.add(smileOfInterest.getSmile().get(myStrikes[k]).getValue()); } } Double[] targetVals = new Double[vals.size()]; return ArrayUtils.toPrimitive(vals.toArray(targetVals)); }
java
{ "resource": "" }
q3391
ForwardCurveInterpolation.createForwardCurveFromDiscountFactors
train
public static ForwardCurveInterpolation createForwardCurveFromDiscountFactors(String name, double[] times, RandomVariable[] givenDiscountFactors, double paymentOffset) { ForwardCurveInterpolation forwardCurveInterpolation = new ForwardCurveInterpolation(name, paymentOffset, InterpolationEntityForward.FORWARD, null); if(times.length == 0) { throw new IllegalArgumentException("Vector of times must not be empty."); } if(times[0] > 0) { // Add first forward RandomVariable forward = givenDiscountFactors[0].sub(1.0).pow(-1.0).div(times[0]); forwardCurveInterpolation.addForward(null, 0.0, forward, true); } for(int timeIndex=0; timeIndex<times.length-1;timeIndex++) { RandomVariable forward = givenDiscountFactors[timeIndex].div(givenDiscountFactors[timeIndex+1].sub(1.0)).div(times[timeIndex+1] - times[timeIndex]); double fixingTime = times[timeIndex]; boolean isParameter = (fixingTime > 0); forwardCurveInterpolation.addForward(null, fixingTime, forward, isParameter); } return forwardCurveInterpolation; }
java
{ "resource": "" }
q3392
ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel
train
public static ForwardCurveInterpolation createForwardCurveFromMonteCarloLiborModel(String name, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{ int timeIndex = model.getTimeIndex(startTime); // Get all Libors at timeIndex which are not yet fixed (others null) and times for the timeDiscretizationFromArray of the curves ArrayList<RandomVariable> liborsAtTimeIndex = new ArrayList<>(); int firstLiborIndex = model.getLiborPeriodDiscretization().getTimeIndexNearestGreaterOrEqual(startTime); double firstLiborTime = model.getLiborPeriodDiscretization().getTime(firstLiborIndex); if(firstLiborTime>startTime) { liborsAtTimeIndex.add(model.getLIBOR(startTime, startTime, firstLiborTime)); } // Vector of times for the forward curve double[] times = new double[firstLiborTime==startTime ? (model.getNumberOfLibors()-firstLiborIndex) : (model.getNumberOfLibors()-firstLiborIndex+1)]; times[0]=0; int indexOffset = firstLiborTime==startTime ? 0 : 1; for(int i=firstLiborIndex;i<model.getNumberOfLibors();i++) { liborsAtTimeIndex.add(model.getLIBOR(timeIndex,i)); times[i-firstLiborIndex+indexOffset]=model.getLiborPeriodDiscretization().getTime(i)-startTime; } RandomVariable[] libors = liborsAtTimeIndex.toArray(new RandomVariable[liborsAtTimeIndex.size()]); return ForwardCurveInterpolation.createForwardCurveFromForwards(name, times, libors, model.getLiborPeriodDiscretization().getTimeStep(firstLiborIndex)); }
java
{ "resource": "" }
q3393
ForwardCurveInterpolation.addForward
train
private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) { double interpolationEntitiyTime; RandomVariable interpolationEntityForwardValue; switch(interpolationEntityForward) { case FORWARD: default: interpolationEntitiyTime = fixingTime; interpolationEntityForwardValue = forward; break; case FORWARD_TIMES_DISCOUNTFACTOR: interpolationEntitiyTime = fixingTime; interpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime))); break; case ZERO: { double paymentOffset = getPaymentOffset(fixingTime); interpolationEntitiyTime = fixingTime+paymentOffset; interpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset); break; } case DISCOUNTFACTOR: { double paymentOffset = getPaymentOffset(fixingTime); interpolationEntitiyTime = fixingTime+paymentOffset; interpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0)); break; } } super.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter); }
java
{ "resource": "" }
q3394
LinearInterpolatedTimeDiscreteProcess.add
train
public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException { Map<Double, RandomVariable> sum = new HashMap<>(); for(double time: timeDiscretization) { sum.put(time, realizations.get(time).add(process.getProcessValue(time, 0))); } return new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum); }
java
{ "resource": "" }
q3395
StochasticPathwiseLevenbergMarquardt.getCloneWithModifiedTargetValues
train
public StochasticPathwiseLevenbergMarquardt getCloneWithModifiedTargetValues(List<RandomVariable> newTargetVaues, List<RandomVariable> newWeights, boolean isUseBestParametersAsInitialParameters) throws CloneNotSupportedException { StochasticPathwiseLevenbergMarquardt clonedOptimizer = clone(); clonedOptimizer.targetValues = numberListToDoubleArray(newTargetVaues); clonedOptimizer.weights = numberListToDoubleArray(newWeights); if(isUseBestParametersAsInitialParameters && this.done()) { clonedOptimizer.initialParameters = this.getBestFitParameters(); } return clonedOptimizer; }
java
{ "resource": "" }
q3396
Option.getBasisFunctions
train
public RandomVariableInterface[] getBasisFunctions(double exerciseDate, LIBORModelMonteCarloSimulationInterface model) throws CalculationException { ArrayList<RandomVariableInterface> basisFunctions = new ArrayList<RandomVariableInterface>(); RandomVariableInterface basisFunction; // Constant basisFunction = model.getRandomVariableForConstant(1.0); basisFunctions.add(basisFunction); // LIBORs int liborPeriodIndex, liborPeriodIndexEnd; RandomVariableInterface rate; // 1 Period basisFunction = model.getRandomVariableForConstant(1.0); liborPeriodIndex = model.getLiborPeriodIndex(exerciseDate); if(liborPeriodIndex < 0) { liborPeriodIndex = -liborPeriodIndex-1; } liborPeriodIndexEnd = liborPeriodIndex+1; double periodLength1 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex); rate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd)); basisFunction = basisFunction.discount(rate, periodLength1); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength1); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); // n/2 Period basisFunction = model.getRandomVariableForConstant(1.0); liborPeriodIndex = model.getLiborPeriodIndex(exerciseDate); if(liborPeriodIndex < 0) { liborPeriodIndex = -liborPeriodIndex-1; } liborPeriodIndexEnd = (liborPeriodIndex + model.getNumberOfLibors())/2; double periodLength2 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex); if(periodLength2 != periodLength1) { rate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd)); basisFunction = basisFunction.discount(rate, periodLength2); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength2); // basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength2); // basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); } // n Period basisFunction = model.getRandomVariableForConstant(1.0); liborPeriodIndex = model.getLiborPeriodIndex(exerciseDate); if(liborPeriodIndex < 0) { liborPeriodIndex = -liborPeriodIndex-1; } liborPeriodIndexEnd = model.getNumberOfLibors(); double periodLength3 = model.getLiborPeriod(liborPeriodIndexEnd) - model.getLiborPeriod(liborPeriodIndex); if(periodLength3 != periodLength1 && periodLength3 != periodLength2) { rate = model.getLIBOR(exerciseDate, model.getLiborPeriod(liborPeriodIndex), model.getLiborPeriod(liborPeriodIndexEnd)); basisFunction = basisFunction.discount(rate, periodLength3); basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); basisFunction = basisFunction.discount(rate, periodLength3); // basisFunctions.add(basisFunction);//.div(Math.sqrt(basisFunction.mult(basisFunction).getAverage()))); } return basisFunctions.toArray(new RandomVariableInterface[0]); }
java
{ "resource": "" }
q3397
CalibratedCurves.createDiscountCurve
train
private DiscountCurve createDiscountCurve(String discountCurveName) { DiscountCurve discountCurve = model.getDiscountCurve(discountCurveName); if(discountCurve == null) { discountCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(discountCurveName, new double[] { 0.0 }, new double[] { 1.0 }); model = model.addCurves(discountCurve); } return discountCurve; }
java
{ "resource": "" }
q3398
Partition.d
train
public double d(double x){ int intervalNumber =getIntervalNumber(x); if (intervalNumber==0 || intervalNumber==points.length) { return x; } return getIntervalReferencePoint(intervalNumber-1); }
java
{ "resource": "" }
q3399
Swaption.getValue
train
public double getValue(ForwardCurveInterface forwardCurve, double swaprateVolatility) { double swaprate = swaprates[0]; for (double swaprate1 : swaprates) { if (swaprate1 != swaprate) { throw new RuntimeException("Uneven swaprates not allows for analytical pricing."); } } double[] swapTenor = new double[fixingDates.length+1]; System.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length); swapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1]; double forwardSwapRate = Swap.getForwardSwapRate(new TimeDiscretization(swapTenor), new TimeDiscretization(swapTenor), forwardCurve); double swapAnnuity = SwapAnnuity.getSwapAnnuity(new TimeDiscretization(swapTenor), forwardCurve); return AnalyticFormulas.blackModelSwaptionValue(forwardSwapRate, swaprateVolatility, exerciseDate, swaprate, swapAnnuity); }
java
{ "resource": "" }