text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express = require("express");
const bodyParser = require("body-parser");
const vsm = require("./vsmTypes");
const url = require("url");
class VsmApi {
    constructor(sites) {
        // TODO Which site structure should I use?
        this.site = sites.find((p) => p.version === vsm.SiteStructureVersion.Live);
        this.router = express.Router();
        this.router.use(bodyParser.json()); // for parsing application/json
        // TODO Protect these methods with auth key
        this.router.get("/linkrules", this.getLinkRules.bind(this));
        this.router.get("/filters", this.getFilters.bind(this));
        this.router.get("/modules", this.getModules.bind(this));
        this.router.get("/views", this.getViews.bind(this));
        this.router.get("/layouts", this.getLayouts.bind(this));
        this.router.get("/templates", this.getTemplates.bind(this));
        this.router.get("/menuitems", this.getMenuItems.bind(this));
        this.router.get("/data/routes", this.getDataRoutes.bind(this));
        this.router.post("/data/get", this.getData.bind(this));
        this.router.post("/data/getall", this.getDataAll.bind(this));
        this.router.post("/data/getraw", this.getDataRaw.bind(this));
        this.router.post("/data/getallraw", this.getDataRawAll.bind(this));
        this.router.post("/picklist/get", this.getPickList.bind(this));
        this.router.post("/debug/createUrl", this.postDebugCreateUrl.bind(this));
        this.router.get("/resources/hash", this.getResourcesHash.bind(this));
        this.router.get("/resources/hashes", this.getHashes.bind(this));
        this.router.get("/siteinfo", this.getSiteInfo.bind(this));
        this.router.get("/sitestructure", this.getSiteStructure.bind(this));
        this.router.get("/siteitem", this.getSiteItem.bind(this));
        this.router.get("/echo", this.getEcho.bind(this));
    }
    getData(req, res) {
        res.json({}); // DataExplorerResponse
    }
    getDataAll(req, res) {
        res.json({}); // DataExplorerResponse
    }
    getDataRaw(req, res) {
        res.json({});
    }
    getDataRawAll(req, res) {
        res.json({});
    }
    getPickList(req, res) {
        res.json([]);
    }
    getLinkRules(req, res) {
        res.json([]);
    }
    getFilters(req, res) {
        res.json([]);
    }
    getModules(req, res) {
        if (!this.site) {
            throw new Error("No site loaded");
        }
        res.json(this.site.getModules());
    }
    getViews(req, res) {
        const result = new Array();
        res.json(result);
    }
    getDataRoutes(req, res) {
        res.json([]);
    }
    postDebugCreateUrl(req, res) {
        const reqBody = req.body;
        const pageUrl = url.parse(reqBody.Url, true);
        pageUrl.query._debug = "y";
        res.json(url.format(pageUrl));
    }
    getResourcesHash(req, res) {
        res.json(null);
    }
    getHashes(req, res) {
        res.json([]);
    }
    getMenuItems(req, res) {
        res.json([]);
    }
    getTemplates(req, res) {
        if (!this.site) {
            throw new Error("No site loaded");
        }
        res.json(this.site.getTemplates());
    }
    getLayouts(req, res) {
        if (!this.site) {
            throw new Error("No site loaded");
        }
        res.json(this.site.getLayouts());
    }
    getSiteInfo(req, res) {
        // TODO Returns the correct info based on the host
        res.json({
            Culture: "en-us",
            Environment: "dev",
            HostName: "localhost",
            Platform: "default",
            SiteId: "en-us.default.dev",
            Time: new Date(Date.now()),
            NodeId: "localhost"
        });
    }
    getSiteStructure(req, res) {
        // TODO
        const data = {
            path: "~/",
            nodeType: "Directory",
            culture: null,
            platform: null,
            environment: null,
            isInternal: false,
            httpMethods: null,
            owners: [],
            nodes: [],
            status: 0,
            publishedRevision: null
        };
        res.json(data);
    }
    getSiteItem(req, res) {
        res.json(null);
    }
    getEcho(req, res) {
        // TODO
        res.json({ Status: "OK", MachineName: "localhost" }); // EchoResponseContract
    }
}
exports.VsmApi = VsmApi;
//# sourceMappingURL=VsmApi.js.map


text:
package com.pineone.icbms.sda.kb.mapper.service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.jena.datatypes.xsd.impl.XSDDateType;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.vocabulary.RDF;

import com.pineone.icbms.sda.comm.util.Utils;
import com.pineone.icbms.sda.kb.mapper.OneM2MMapper;

/**
 *   참석여부의 Mapper 클래스
 */
public class AttendanceServiceMapper implements OneM2MMapper {

	private Resource attendance;
	private Model model = ModelFactory.createDefaultModel();
	private String baseuri = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.uri");
	private Resource lecture;
	private Resource condition;
	private Resource user;
	private Literal createDate;

	public AttendanceServiceMapper(String lecture, String createDate, String condition, String user) {
		this.lecture = model.createResource(lecture);
		this.user = model.createResource(user);
		this.condition = model.createResource(baseuri + "/" + condition);
		this.createDate = model.createTypedLiteral(createDate, XSDDateType.XSDdateTime);
	}

	/* (non-Javadoc)
	 * @see com.pineone.icbms.sda.kb.mapper.OneM2MMapper#initResource()
	 */
	@Override
	public void initResource() {
		attendance = model.createResource(baseuri + "/Attendance_" + UUID.randomUUID());
	}

	/* (non-Javadoc)
	 * @see com.pineone.icbms.sda.kb.mapper.OneM2MMapper#from()
	 */
	@Override
	public List<Statement> from() {
		List<Statement> slist = new ArrayList<Statement>();
		initResource();
		slist.add(model.createStatement(this.attendance, RDF.type, model.createResource(baseuri + "/Attendance")));
		slist.add(model.createStatement(this.attendance, model.createProperty(baseuri+"/isAttendanceOf"), this.lecture));
		slist.add(model.createStatement(this.attendance, model.createProperty(baseuri+"/hasCreateDate"), this.createDate));
		slist.add(model.createStatement(this.attendance, model.createProperty(baseuri+"/hasCondition"), this.condition));
		slist.add(model.createStatement(this.attendance, model.createProperty("http://www.loa-cnr.it/ontologies/DUL.owl#hasMember"), this.user));
		return slist;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package fr.paris.lutece.portal.service.security;

/**
 * Basic Lutece User
 */
public class BasicLuteceUser extends LuteceUser
{
    private static final long serialVersionUID = 4077599434967808839L;

    /**
     * Constructor
     *
     * @param strUserName
     *            The User Name
     * @param authenticationService
     *            The PortalAuthentication object
     */
    public BasicLuteceUser( String strUserName, LuteceAuthentication authenticationService )
    {
        super( strUserName, authenticationService );
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width" />
    <title>Routeless Backbone Contacts</title>
    <link type="text/css" rel="stylesheet" href="https://srackham.github.io/stuarts-notes/main.css">
    <link type="text/css" rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.0/styles/default.min.css">

        srackham | notes

Posts

Tags

All

About

Search

Routeless Backbone Contacts

Sep 23, 2011

    · Backbone.js

    · coffeescript

You don’t need a URL router to write client-side applications.

Routeless Backbone.js Contacts is a totally client-side CRUD tutorial application written using CoffeeScript, Stylus, Backbone.js and jQuery which are a perfect match for writing concise, readable well structured web applications.

The source is on Github.

Note:
This release described in this post is at the 1.0 tag.

Uses DOM events exclusively for UI navigation.

The contacts data is persisted locally using browser Web Storage.

Templates are written using Underscore.js templates (included with Backbone.js).

Note:
A second version of this tutorial application [has been posted], it builds on the material covered in this post.

Screenshots

ListContactView

ShowContactView

EditContactView

Going routeless

It’s a mindset thing. If you come from a server-side web applications background your first instinct is to use a router and fragment identifiers to emulate browser page navigation – go down this route you soon find that trying to maintain a consistent back-button browser history is time consuming, messy and ultimately unnecessary.  Single page applications don’t need a back-button (or any browser chrome), especially if they are bundled as pseudo-native mobile apps with something like PhoneGap or packaged for the desktop, for example as Google Chrome Packaged Apps.

Routeless Backbone.js Contacts resides at a single unfragmented URL – user interface navigation is managed exclusively by DOM events. Button and link elements deal with the click events client-side (you are not POSTing form data to a server, so form elements and submit buttons are not necessary).  If the application were to persist data externally then then the data POSTS and GETS would be handled transparently by a Backbone database adapter.

Running the application

Once you have downloaded the source from Github open the index.html file in your browser. Press the Import Data button to load the example contacts database.

Important:
Unlike Google Chrome, neither Firefox 6 or IE9 like persisting Web Storage from file based URLs and you will need to open the application via a web server. I use Mongoose (a neat little single-executable cross-platform web server) for testing.  Once you’ve installed mongoose:

cd to the directory containing index.html

Then execute the mongoose command and open your web browser at localhost:8080.

The source

This post should be read side-by-side with the source, it’s very readable (although a basic understanding of CoffeeScript, HTML and jQuery is recommended).

index.html
     Application page HTML and view templates.
application.coffee
     Application, models and views.
data.js
     Canned data (100 fictitious contacts) loaded by the Import Data command.
main.styl
     Stylus CSS.
helpers.styl, gradients.styl
     CSS helper functions.

HTML5 markup is used throughout.  All the logic is confined to application.coffee (around 160 lines of code).  The beauty of CoffeeScript is that the code is concise and virtually self-documenting, for example, here’s the event handler in the ListContactView that responds to the Clear All button click:

clear: (e) ->
    return if not confirm 'About to delete all data.'
    contact.destroy() for contact in @collection.toArray()
    @render()

Application structure

The app object

There is a single global instance app of the App class which:

Initializes and namespaces global data (collections and views).

Contains a few generic methods to allow programmatic inter-view navigation – this allows views to call one another and not have to share any information about each other.

Starts the application (with app.start()).

Models and Collections

A single app.contacts collection of Contact models is persisted locally using the Backbone localStorage Adapter. A single store is instantiated and attached to the ContactModel, the same store is referenced by the ContactCollection.

Views

The CRUD user interface is implemented by three Backbone.js views – ListView, ShowView and EditView (the EditView is also used to create new contacts).

Each view handles the set of DOM events defined by the View’s events property.

The events property routes DOM events to a handler within the View.

When a matching DOM event occurs the View handler is called and passed a jQuery event object.

This example (from the ListContactView)  uses a custom data attribute (data-id) to pass the contact ID from the anchor element via a click event object.

DOM event registration:

events:
    'click a.show': 'show'

Link click handler:

show: (e) ->
    @model = @collection.get e.target.getAttribute('data-id')
    @render()

Template link markup:

<a class="show" data-id="<%= contact.id %>"><%= contact.getName() %></a>

It would have been nice to have used the HTML5 DOM dataset property to retrieve the data-id attribute (e.target.dataset.id) but it does not currently work in IE9, Safari or Android browsers.

Libraries

The app uses the following JavaScript libraries (in the lib directory):

Backbone.js

jQuery

Underscore.js

The Backbone localStorage Adapter persists models to the local disk using the browser Web Storage API.

Techniques

Load scripts at the end of the page body

Place script tags last in the page body, just before the closing body tag. This ensures the page elements elements have been parsed and can be referenced when the scripts execute and allows you to safely reference page elements from class property initializers. See this stackoverflow discussion.

Intra-application links do not need href’s

Dropping the href ensures there are no changes to the browser URL or history.

CSS and HTML Tips

Stylus is to CSS as CoffeeScript is to JavaScript, use it to keep your CSS DRY and to maintain your sanity.

Use Stylus imports to unclutter your main CSS.

CSS padding vs margins:

Margins define the element’s relationship to other elements (spacing) and are context specific i.e. an element’s margins will change depending on where it is used in the application.

Padding styles an elements appearance and isn’t a context sensitive as the element margins.

The width property does not include the margins, border or padding.

Use HTML5’s concise syntax, it may seem wrong after years of XML indoctrination but it’s not, it’s easier to read and your fingers will thank you. Examples:

Closing tag omission:

<tr><td>Foo<td>Bar                  YES
<tr><td>Foo</td><td>Bar</td></tr>   NO

Minimized attributes:

readonly                            YES
readonly="readonly"                 NO

Empty elements don’t need explicit termination:

<img src="me.png">                  YES
<img src="me.png" />                NO

Length and size:

Use em units to set size properties on elements that display text, it’ll make it much easier to resize your app.

To get exact placements you’ll need to use pixels, but this can probably be confined to non-text elements.

Use Stylus arithmetic expressions to maintain the size of interdependent page elements so that changing a single size will ensure the depend sizes are adjusted automatically (DRY again).

Be careful assigning id attributes in templates, do so only if the template will never appear more than once on a page. If in doubt assign class attributes instead of id attributes.

Tables are not bad, in fact they are very good for laying out application pages (which are quite different to document oriented websites).

Don’t put CSS style attributes in HTML template markup – this should be obvious.

Start with a clean slate, reset user-agent (browser) document oriented CSS defaults:

  * {
    font-size: 20px;
    font-family: sans-serif;
    margin: 0;
    padding: 0;
  }

References

E. Mathieu Sternberg’s The Backbone Store, version 2.0.

            « Previous

            Next »


text:
\section{Data Mining}
\label{sec:dataMining}

Data mining is the computational process of discovering patterns in large data sets (``big data'') involving methods at the intersection of artificial intelligence, machine learning, statistics, and database systems. The overall goal of the data mining process is to extract information from a data set and transform it into an understandable structure for further use.
\\RAVEN has support of several different data mining algorithms,
such as:
\begin{enumerate}
  \item \textit{Hierarchical methodologies}
  \item \textit{K-Means}
  \item \textit{Mean-Shift}, etc.
\end{enumerate}
In this section only few algorithms will be explained

\subsection{Clustering}
\label{clustering}
A loose definition of clustering is the process of organizing objects into groups whose members are, in some way, similar.
Therefore, a cluster is a collection of objects that are similar to each other and are dissimilar to the objects belonging to other clusters~\cite{SurveyClustering,MandelliClusteringRESS}.

The similarity criterion is distance. Two or more objects belong to the same cluster if they are ``close'' according to a specified distance. The approach of using distance metrics to clustering is called distance-based clustering and is used in this work.

The notion of distance implies that the data points lay in a metric space \cite{Mendelson75introduction}:

    \begin{mydef}[Metric Space]
    A metric space is a space X provided with a function \emph{d}:
    \begin{math}
    f: X\times X\rightarrow \mathbb{R}
    \end{math}
    satisfying the following properties \begin{math}\forall \vec{x},\vec{y} \in X \end{math} :

    \begin{itemize}
      \item \begin{math} d(\vec{x},\vec{y}) \geqslant 0 \end{math}
      \item \begin{math} d(\vec{x},\vec{y}) = d(\vec{y},\vec{x}) \end{math}
      \item \begin{math} d(\vec{x},\vec{y}) \leqslant d(\vec{x},\vec{z}) + d(\vec{z},\vec{y}) \end{math}
    \end{itemize}

    \end{mydef}

The function \begin{math} d(\vec{x},\vec{y}) \end{math} is usually called the distance function. In a 2-dimensional Euclidean space ($\mathbb{R}^{2}$), the distance between points can be calculated using the Pythagorean theorem which is the direct application of the Euclidean distance and is a special case of the most general Minkowski distance \begin{math}\ d_{2}(\vec{x},\vec{y}) = \sqrt{(x_{1}-y_{1})^{2}+(x_{2}-y_{2})^{2}} \end{math} between two points $\vec{x}=(x_{1},x_{2})$ and $\vec{y}=(y_{1},y_{2})$ in $\mathbb{R}^{2}$.

In the literature~\cite{Mendelson75introduction}, it is possible to find several types of distances other than the Euclidean and the Minkowski distance as shown in Table~\ref{table:tableDist}. The approach of using distance metrics is called distance-based clustering and will be used in this dissertation.

    \begin{table}[ht]
    \caption {\small Summary of the commonly used measures \cite{Mendelson75introduction}.}
    \centering
    \begin{tabular}{c c }
    \hline\hline
    Measure & Form \\ [0.5ex]
    \hline
    \hline
    Minkowski distance & \begin{math}\ d_{n}(\vec{x},\vec{y}) = (\displaystyle \sum_{k=1}^\delta |x_{k}-y_{k}|^{n})^{\frac{1}{n}} \end{math} \\
    Euclidean distance & \begin{math}\ d_{2}(\vec{x},\vec{y}) = (\displaystyle \sum_{k=1}^\delta |x_{k}-y_{k}|^{2})^{\frac{1}{2}} \end{math} \\
    Taxicab distance & \begin{math}\ d_{1}(\vec{x},\vec{y}) = \displaystyle \sum_{k=1}^\delta |x_{k}-y_{k}| \end{math} \\
    Supremum distance & \begin{math}\ d_{0}(\vec{x},\vec{y}) = \displaystyle max_{k} |x_{k}-y_{k}| \end{math} \\
    Mahalanobis distance & \begin{math}\ d_{M}(\vec{x},\vec{y}) = (\vec{x}-\vec{y})^{T} S^{-1} (\vec{x}-\vec{y}) \end{math} \\
    \hline
    \end{tabular}
    \label{table:tableDist}
    \end{table}

From a mathematical viewpoint, the concept of clustering~\cite{SurveyClustering} aims to find a partition $\mathbf{C}=\{C_{1},\ldots,C_{l},\ldots,{C_{L}}\}$
of the set of $I$ scenarios
    $\mathbf{X} = \{\vec{x_{1}},\ldots,\vec{x_{i}},\ldots,\vec{x_{I}}\}$
where each scenario $\vec{x_{i}}$ is represented as a $\delta$-dimensional vector.
Each $C_{l}$ $(l=1,\ldots,L)$ is called a cluster. The partition
    $ \mathbf{C} $ of $ \mathbf{X} $
is given as follows\footnote{In most clustering algorithms each scenario belongs to only one cluster. However this is not always the case. In fuzzy clustering methodologies~\cite{ZioMaio} a scenario may be allowed to belong to more than one cluster with a degree of membership
\begin{math} u_{i,j}\in [0,1] \end{math} which represents the member coefficient of the $j$ scenario for the $i^{th}$ cluster and satisfies the following properties:

$ \sum_{i=1}^{K}u_{i,j}=1,  \text{ and }  \sum_{j=1}^{N}u_{i,j}<N, \forall j $}:

    \begin{equation}\label{eq: ClassRequier}
        \begin{cases} \mathbf{C}_{l}\neq\varnothing, l=1,\ldots,L \\
                        \\
                     \bigcup_{l=1}^{L}\mathbf{C}_{l}= \mathbf{X} \\
        \end{cases}
    \end{equation}

\subsection{Hierarchical Methodologies}
\label{Hierarchical}

These methodologies organize the data set into a hierarchical structure according to a proximity matrix. Each element $d(i,j)$ of this matrix contains the distance between the the $i^{th}$ and the $j^{th}$ cluster center. The final results of this technique is a tree commonly called a dendrogram. This kind of representation has the advantages of providing a very informative description and visualization of the data structure even for high values of dimensionality.

The procedure to determine the dendrogram for a data set of $I$ points in an $\delta$-dimensional space is the following:

\begin{enumerate}
  \item Start the analysis with a set of $I$ clusters (i.e., each point is considered as a cluster).
  \item Determine the proximity matrix $M$ (dimension: $I\times I$): $M(i,j)= d(\vec{x_{i}},\vec{x_{j}})$ where $\vec{x_{i}}$ and $\vec{x_{j}}$ are the position of the $i^{th}$ and the $j^{th}$ cluster.
  \item For each point $p$ find the closest neighbor $q$  from the proximity matrix $M$
  \item Combine the points $p$ and $q$
  \item Repeat Steps 2, 3 and 4 until all the points of the data set are in the same cluster
\end{enumerate}

The advantage of this kind of algorithm is the nice visualization of the results that show the underlying structure of the data set. However, the computational complexity for most of the hierarchical algorithm is of the order of $\mathcal{O}(I^{2})$ (where \emph{I} is the number of points in the data set).

\subsection{\emph{K}-Means}
\label{KMeans}

\emph{K}-Means clustering algorithms belong to the more general family of Squared Error algorithms. The goal is to partition $I$ data points $\vec{x_{i}}$ $(i=1,\ldots,I)$ into \emph{K} clusters in which each data point maps to the cluster with the nearest mean. The stopping criterion is to find the global minimum of the error squared function $\chi$ defined as:

\begin{equation}
    \chi = \displaystyle \sum_{i=1}^K \displaystyle \sum_{x_{j}\in C_{i}} |\vec{x_{j}}-\vec{\mu_{i}}|^{2}
\end{equation}

where $\vec{\mu_{i}}$ is the centroid (i.e., the center) of the cluster $C_{i}$.

The procedure to determine the centroids $\vec{\mu_{i}}$ of \emph{K} clusters (${C_{1},\ldots,C_{K}}$) is the following:

\begin{enumerate}
  \item Start with a set of $K$ random centroids distributed in the state space
  \item Assign each pattern to the the closest centroid
  \item Determine the new $K$ centroids according to the point-centroid membership

    \begin{equation}
        \mu_{i} = \displaystyle \frac{1}{N_{i}} \sum_{\vec{x_{j}}\in C_{i}} \vec{x_{j}}
    \end{equation}

    where $N_{i}$ corresponds to the number of of data points in the $i^{th}$ cluster.

  \item Repeat Steps 2 and 3 until convergence is met (i.e., until a minima of the $\chi$ function is reached)
\end{enumerate}

\emph{K}-Means algorithm is one of the most popular and used methodologies also due to the fact that is very straightforward to implement and the computational time is directly proportional to the cardinality of data points (i.e., $\mathcal{O}(I)$ where \emph{I} is the number of data points). The main disadvantage is that the algorithm is sensitive to the choice of the initial partition and may converge to a local minimum of the error squared function~\cite{JainAlgor88}. Another disadvantage of this algorithm is that is only able to identify clusters having spherical or ellipsoidal geometry. Thus, \emph{K}-Means is not able to identify clusters of points having arbitrary shapes. Moreover, the number of cluster \emph{K} to be obtained is specified by the user prior the clustering process.

%\subsection{Fuzzy C-Means}
%\label{FuzzyCMeansn}
%
%Fuzzy \emph{C}-Means clustering is a clustering methodology that is based on fuzzy sets and, hence, it allows a data point to belong to more that one cluster~\cite{FuzzyBezdek,DunnFuzzy}. Similar to the \emph{K}-Means clustering, the objective is to find a partition of $C$ fuzzy centers to minimize the function $J$ defined as following:
%
%\begin{equation}
%    J = \displaystyle \sum_{i=1}^I \displaystyle \sum_{j=1}^C u_{ij}^{m}|\vec{x_{i}}-\vec{\mu_{j}}|^{2}
%\end{equation}
%
%where:
% \begin{itemize}
%   \item $u_{ij}^{m}\in[0,1]$ is the membership coefficient of the data point $\vec{x_{i}}$ for the $j^{th}$ cluster having centroid $\vec{\mu_{j}}$,
%   \item $m\in[0,\infty)$ is the fuzzification parameter (usually set to $m=2$), and,
%   \item $\mu_{j}$ is the centroid of the $j^{th}$ cluster center
% \end{itemize}
%
%The procedure to determine the centroids (or, equivalently, cluster centers)
%$ \vec{\mu_{j}}$ $(j=1,\ldots,C)$ of $C$ clusters is the following:
%
%\begin{enumerate}
%  \item Initialize the $U=[u_{ij}^{m}]$ matrix
%  \item Calculate the set of $C$ centroids  as following:
%
%          \begin{equation}
%            \mu_{j}=\frac{\sum_{i=1}^N u_{ij}^{m}x_{i}}{\sum_{i=1}^N u_{ij}^{m}}
%          \end{equation}
%
%  \item Update the matrix $U=[u_{ij}^{m}]$ as following:
%
%          \begin{equation}
%            u_{ij}^{m}=\frac{1}{\sum_{k=1}^C (\frac{|x_{i}-\mu_{j}|}{|x_{i}-\mu_{k}|})^{\frac{2}{m-1}}}
%          \end{equation}
%
%  \item Repeat Steps 2 and 3 until convergence, i.e. if \begin{math} |U^{(K+1)}-U^{(K)}|<\epsilon \end{math}
%\end{enumerate}
%
%Fuzzy \emph{C}-Means clustering is very similar to the \emph{K}-Means. As seen for the \emph{K}-Means, Fuzzy \emph{C}-Means can also converge to a local minima of the convergence criterion function~\cite{FuzzyBezdek}.
%Like \emph{K}-Means, it is not able to identify cluster of points having arbitrary shapes but only clusters having ellipsoidal or spherical geometry and the number of clusters \emph{C} to be obtained is specified by the user prior the clustering process.
%Fuzzy \emph{C}-Means algorithms can be useful when the boundaries among clusters are ambiguous and not well defined.

\subsection{Mean-Shift}
\label{Mean-Shift}

The Mean-Shift algorithm~\cite{EstimationGradient} is a non-parametric iterative procedure that can be used to assign each point to one cluster center through a set of local averaging operations~\cite{EstimationGradient}. The local averaging operations provide empirical cluster centers within the locality and define the vector which denotes the direction of increase for the underlying unknown density function.

The underlying idea is to treat each point $\vec{x_{i}}$ $(i=1,\ldots, I)$ of the dataset as an empirical probability distribution function using  kernel $K(\vec{x}): \mathbb{R}^{M\cdot K}\rightarrow \mathbb{R}$. This multivariate kernel density resides in a multidimensional space where regions with high data density (i.e., modes) correspond to local maxima of the density estimate $f_{I}(\vec{x})$~\cite{CacoullosEstimation}  defined by:
\begin{equation}
    f_{I}(\vec{x})=\frac{1}{Ih^{d}}\sum_{i=1}^{I} K\left(\frac{\vec{x}-\vec{x_{i}}}{h}\right),
    \label{eq:density:estimate}
\end{equation}
where $\vec{x}\in \mathbb{R}^{M\cdot K}$ and $h$ is often referred as the bandwidth associated with the kernel.

The kernel in Equation ~\ref{eq:density:estimate} serves as a weighting function~\cite{CacoullosEstimation} associated with each data point and is expressed as:
\begin{equation}
    K(\vec{x})=c_{k} k(\norm{\vec{x}}^{2})
\end{equation}
where $k(x):[0,\infty]\rightarrow \mathbb{R}$ is referred as the \emph{kernel profile} and $c_{k}$ is a normalization constant. The profile satisfies the following properties:
\begin{itemize}
  \item $k(x)$ is non negative
  \item $k(x)$ is non increasing (i.e., $k(a)\geq k(b)$ if $a<b$)
  \item $k(x)$ is piecewise continuous and $\int_0^\infty \! k(x) \, dx < \infty$
\end{itemize}

In order to estimate the data points with highest probability from an initial estimate (i.e., the modes of $f_{I}(\vec{x})$), consider the gradient of the density function $\nabla_{x} f_{I}(\vec{x})=0$ ~\cite{EstimationGradient} where
\begin{eqnarray}
\label{gradient}
    \nabla_{x} f_{I}(\vec{x}) & = & \frac{2 c_{k}}{I h^{d+2}} \sum_{i=1}^{I}(\vec{x}-\vec{x_{i}})k'\left(\norm{\frac{\vec{x}-\vec{x_{i}}}{h}}^{2}\right) \nonumber \\
    & = & \underbrace{\frac{2 c_{k}}{I h^{d+2}} \left(\sum_{i=1}^{I} g\left(\norm{\frac{\vec{x}-\vec{x_{i}}}{h}}^{2}\right)\right)}_{A}
    \underbrace{\left(\frac{\sum_{i=1}^{I}
    \vec{x} g\left(\norm{\frac{\vec{x}-\vec{x_{i}}}{h}}^{2}\right)}{\sum_{i=1}^{I} g\left(\norm{\frac{\vec{x}-\vec{x_{i}}}{h}}^{2}\right)}-\vec{x}\right)}_{B},
\end{eqnarray}
which points in the direction of the increase in kernel density estimate. The kernel $K(\vec{x})$ is also referred to as the shadow of $G(\vec{x})=c_{g} g(\norm{\vec{x}}^{2})$~\cite{Mode-seekingMedoidshifts} where $c_{g}$, similar to $c_{k}$, is a normalization constant and $g(x)$ is the derivative of $k(x)$ over $x$, i.e., $g(x)=k'(x)$. In the equation above, the first term denoted as $A$ is a scalar proportional to the density estimate computed with the kernel $G(\vec{x})$ and does not provide information regarding where the mode resides. Unlike $A$, the vector quantity $B$, which is the second term in the equation above, is difference between the weighted mean
\begin{equation}
	m(\vec{x})=\frac{\sum_{i=1}^{I}\vec{x} g(\norm{\frac{\vec{x}-\vec{x_{i}}}{h}}^{2})}{\sum_{i=1}^{I} g(\norm{\frac{\vec{x}-\vec{x_{i}}}{h}}^{2})}.
\end{equation}

and the initial estimate $\vec{x}$. This term points in the direction of local increase in density using kernel $G(\vec{x})$, hence provides a means to find the mode of the density. Note that all points used to compute a particular mode are considered to reside in the same cluster.

Since each each data point $\vec{x_{i}}$ (or scenario) is considered as an empirical probability distribution function, this consideration allows to include in the scenario clustering analysis also the possible uncertainty associated with each scenario.

\subsection{DBSCAN }
\label{DBSCAN }

The Density-Based Spatial Clustering of Applications with Noise (DBSCAN) algorithm views clusters as areas of high density of data points. The data points in the low-density areas are seen as noise and border points, which are actually separating the clusters. Clusters found by DBSCAN can be any shape because of this approach.
The main element of the DBSCAN algorithm is the concept of core samples, which are samples that are in areas of high density. Therefore, a cluster is a set of core samples, each close to each other (measured by some distance measure) and a set of non-core samples that are close to a core sample (but are not themselves core samples). There are two parameters to the algorithm: $min_samples$ and $eps$. Higher $min_samples$ or lower $eps$ indicate higher density necessary to form a cluster.
A cluster is a set of core samples, that can be built by recursively by taking a core sample, finding all of its neighbors that are core samples, finding all of their neighbors that are core samples, and so on. A cluster also has a set of non-core samples, which are samples that are neighbors of a core sample in the cluster but are not themselves core samples; these are on the borders of a cluster.
The DBSCAN algorithm finds core samples of high density and expands clusters from them. It is good for data, which contains clusters of similar density.

\subsection{Dimensionality Reduction}
\label{sec:6DimRed.section}

The dimensionality $\delta$ of each data point (i.e., each scenario) is equal to the product of the number of variables (i.e., $M$) chosen to represent each scenario multiplied by the number of times each variable has been sampled.
In order to reduce the computational time due to the high data dimensionality, the use of dimensionality reduction techniques was to reduce the number of variables $M$\footnote{Other possible options are to reduce the number of sample instants $K$ or to observe the local properties of the covariance matrix $S$.}.

The raw data generated by DET methodologies contain the temporal behavior of a vast set of variables (e.g., temperature, pressure). These variables are often heavily correlated and, consequently, the information contained in the set of $M$ variables comprising the full state space can be condensed to a set of $N$ variables where $N <M$. The objective of the dimensionality reduction process is to determine those $N$ variables by finding the correlations among the original $M$ variables\footnote{Note that those $N$ variables are not necessarily a subset of the original $M$ variables but, more likely, a combination of those $M$ variables.}.

Linear algorithms, such as PCA~\cite{JolliffePCA} or multidimensional scaling (MDS)~\cite{MDS}, have the advantage that they are easier to implement but they can only identify linear correlation among variables. On the other hand, methodologies such as Local Linear Embedding~\cite{lle} and ISOMAP~\cite{isomap} are more computationally intensive but they are able to identify non-linear correlations.

Dimensionality reduction is the process of finding a bijective mapping function $\mathfrak{F}$
\begin{equation}\label{eq:dimRed}
    \mathfrak{F}:\mathbb{R}^{D}\mapsto\mathbb{R}^{d} \mbox{ (where $d<D$)}
\end{equation}
which maps the data points from the $D$-dimensional space into a reduced $d$-dimensional space (i.e. embedding on a manifold) in such a way that the distances between each point and its neighbors are preserved. In our applications $D = M+1$, i.e. $M$ state variables plus time $t$.

\subsection{Dimensionality Reduction: Linear Algorithms}
\label{dimRed}
This section describes the two most important algorithms for dimensionality reduction:
\begin{enumerate}
  \item PCA (see Section~\ref{pca}), and,
  \item MDS (see Section~\ref{mds}).
\end{enumerate}

\subsection{Principal Component Analysis (PCA)}
\label{pca}

The main idea behind PCA~\cite{JolliffePCA} is to perform a linear mapping of the data set onto a lower dimensional space such that the variance of the data in the low-dimensional representation is maximized.

This is accomplished by determining the eigenvectors and their corresponding eigenvalues of the data covariance matrix\footnote{Given a data set in form of a vector $Z$, rows correspond to data dimensions ($D$) and columns correspond to data observations ($\Lambda$), the covariance matrix $S$ is determined as: $S=\frac{1}{\Lambda-1}Z'Z$.}
$S$.
The eigenvectors that correspond to the largest eigenvalues (i.e., the principal components) can be used as a set of basis functions. Thus, the original space is reduced to the space spanned by a few eigenvectors.

The algorithm is very straightforward to implement but, on the other hand, PCA is not able to identify non-linear correlations of more complex data sets.

\subsection{Multidimensional Scaling (MDS)}
\label{mds}

Multidimensional scaling~\cite{MDS} is a popular technique used to analyze the properties of data sets. The scope of this methodology is to find a set of dimensions that preserve distances between data points.

This is performed by:
\begin{enumerate}
  \item Creating dissimilarity matrix $D=[d_{ij}]$ where $d_{ij}$ is the distance between two points $x_i$ and $x_j$.
  \item Finding the hyper-plane that preserves the dissimilarity matrix $D$ (i.e., the \emph{nearness} of points)
\end{enumerate}

As in PCA analysis, the algorithm can be easily implemented but it is not able to identify non-linear correlations of more complex data sets.


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is auto-generated, do not edit! -jm -->
<CordovaSourceDictionary>
</CordovaSourceDictionary>


text:
namespace Fortran::parser {

struct Options {
  Options() {}

  using Predefinition = std::pair<std::string, std::optional<std::string>>;

  bool isFixedForm{false};
  int fixedFormColumns{72};
  common::LanguageFeatureControl features;
  std::vector<std::string> searchDirectories;
  std::vector<Predefinition> predefinitions;
  bool instrumentedParse{false};
  bool isModuleFile{false};
  bool needProvenanceRangeToCharBlockMappings{false};
};

class Parsing {
public:
  explicit Parsing(AllSources &);
  ~Parsing();

  bool consumedWholeFile() const { return consumedWholeFile_; }
  const char *finalRestingPlace() const { return finalRestingPlace_; }
  CookedSource &cooked() { return cooked_; }
  Messages &messages() { return messages_; }
  std::optional<Program> &parseTree() { return parseTree_; }

  const SourceFile *Prescan(const std::string &path, Options);
  void DumpCookedChars(llvm::raw_ostream &) const;
  void DumpProvenance(llvm::raw_ostream &) const;
  void DumpParsingLog(llvm::raw_ostream &) const;
  void Parse(llvm::raw_ostream &debugOutput);
  void ClearLog();

  void EmitMessage(llvm::raw_ostream &o, const char *at,
      const std::string &message, bool echoSourceLine = false) const {
    cooked_.allSources().EmitMessage(
        o, cooked_.GetProvenanceRange(CharBlock(at)), message, echoSourceLine);
  }

  bool ForTesting(std::string path, llvm::raw_ostream &);

private:
  Options options_;
  CookedSource cooked_;
  Messages messages_;
  bool consumedWholeFile_{false};
  const char *finalRestingPlace_{nullptr};
  std::optional<Program> parseTree_;
  ParsingLog log_;
};
} // namespace Fortran::parser
#endif // FORTRAN_PARSER_PARSING_H_


text:
package tools.xor.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
import tools.xor.AbstractBO;
import tools.xor.AbstractProperty;
import tools.xor.AbstractTypeMapper;
import tools.xor.AggregateAction;
import tools.xor.BasicType;
import tools.xor.BusinessEdge;
import tools.xor.BusinessObject;
import tools.xor.CallInfo;
import tools.xor.EntityKey;
import tools.xor.EntityType;
import tools.xor.ImmutableBO;
import tools.xor.ListType;
import tools.xor.MutableBO;
import tools.xor.NaturalEntityKey;
import tools.xor.ProcessingStage;
import tools.xor.Property;
import tools.xor.Settings;
import tools.xor.SurrogateEntityKey;
import tools.xor.Type;
import tools.xor.TypeMapper;
import tools.xor.providers.jdbc.CustomPersister;
import tools.xor.providers.jdbc.JDBCDataStore;
import tools.xor.service.DataModel;
import tools.xor.service.DataStore;
import tools.xor.service.Shape;
import tools.xor.util.graph.ObjectGraph;

/**
 * This class is used to create the appropriate instances of the copy, given the
 * class of the original object.
 *
 * @author Dilip Dalton
 */
public class ObjectCreator {
	private static final Logger logger = LogManager.getLogger(new Exception()
	.getStackTrace()[0].getClassName());

	// Map of the source instance and the target DataObject
	// This map also records the target instance and the target DataObject
	private Map<Object, BusinessObject>    instanceDataObjectMap = new Reference2ReferenceOpenHashMap<Object, BusinessObject>();
	private Map<EntityKey, BusinessObject> entitiesByKey = new Object2ReferenceOpenHashMap<EntityKey, BusinessObject>();

	// For those business objects that have a natural key, keep track of it
	// The natural key can change during XOR operation for a Business Object as the state changes
	// when moving data between the two models (External <-> Domain).
	// and this data structure is used to keep the entitiesByKey data structure
	// in sync.
	private Map<BusinessObject, List<EntityKey>> naturalKeyRegistrations = new Reference2ReferenceOpenHashMap<BusinessObject, List<EntityKey>>();

	private DataModel               dataModel;
	private Shape                   shape;
	private DataStore dataStore;
	private TypeMapper              typeMapper;
	private boolean                 share; // when registering if another object with the same id and type is found, it will be returned
	private CreationStrategy        creationStrategy; // JSON or POJO?
	private boolean                 readOnly; // The objects are read only
	private ObjectGraph             objectGraph; // represents the Object graph of the object we need to persist
	private BusinessObject          root; // represents the root object
	private Settings                settings; // the criteria under which this instance operates

	public ObjectCreator(Settings settings, DataStore po, TypeMapper typeMapper) {
		this.settings = settings;
		this.dataStore = po;
		this.typeMapper = typeMapper;
		this.creationStrategy = this.typeMapper.getCreationStrategy(this);

		this.shape = this.typeMapper.getShape();
		this.dataModel = this.typeMapper.getModel();
	}

	public Settings getSettings() {
		return this.settings;
	}

	public boolean isReadOnly() {
		return this.readOnly;
	}

	public void setReadOnly(boolean value) {
		this.readOnly = true;
	}

	public boolean doShare() {
		return share;
	}

	public void setShare(boolean share) {
		this.share = share;
	}

	public DataStore getDataStore() {
		return dataStore;
	}

	public void setDataStore(
			DataStore dataStore) {
		this.dataStore = dataStore;
	}

	public CreationStrategy getCreationStrategy() {
		return this.creationStrategy;
	}

	public Shape getShape() {
		return this.shape;
	}

	public DataModel getDataModel() {
		return dataModel;
	}

	public TypeMapper getTypeMapper() {
		return typeMapper;
	}

	public Type getType(Class<?> clazz) {
		clazz = ClassUtil.getUnEnhanced(clazz);
		return shape.getType(clazz);
	}

	/**
	 * Convert it to type based on the java class
	 * @param bo business object whose java class type we need to infer
	 * @return type
	 */
	public Type getDomainType(BusinessObject bo) {
		// We have the same type for JDBC
		if(getDataStore() instanceof JDBCDataStore) {
			return bo.getType();
		}

		Object instance = ClassUtil.getInstance(bo);
		Class<?> clazz = ClassUtil.getUnEnhanced(instance.getClass());

		return typeMapper.getDomainShape().getType(clazz);
	}

    public Type getType(String typeName, Type domainType) {
        // We have the same type for JDBC
        if (getDataStore() instanceof JDBCDataStore) {
            return domainType;
        }

        if (domainType != null && domainType instanceof EntityType) {
            return shape.getType(((EntityType) domainType).getEntityName());
        } else {
            return shape.getType(typeName);
        }
    }

    public Type getType(Class<?> inputClass, Type domainType) {
        // We have the same type for JDBC
        if (getDataStore() instanceof JDBCDataStore) {
            return domainType;
        }

        inputClass = ClassUtil.getUnEnhanced(inputClass);
        if (domainType != null && domainType instanceof EntityType) {
            return shape.getType(((EntityType) domainType).getEntityName());
        } else {
            return shape.getType(inputClass);
        }
    }

	public void addByNaturalKey(BusinessObject entity, String anchor) {
		if(naturalKeyRegistrations.containsKey(entity)) {
			for(EntityKey ek: naturalKeyRegistrations.get(entity)) {
				entitiesByKey.remove(ek);
			}
		}

		List<EntityKey> naturalKeys = entity.getNaturalKey(anchor);
		for(EntityKey naturalKey: naturalKeys) {
			entitiesByKey.put(naturalKey, entity);
		}
		naturalKeyRegistrations.put(entity, naturalKeys);
	}

	public void addBySurrogateKey(BusinessObject entity, String anchor) {
		EntityKey entityKey = entity.getSurrogateKey(anchor);
		if(entityKey != null) {
			entitiesByKey.put(entityKey, entity);
		}
	}

	public void removeByEntityKey(EntityKey key) {

		if(key instanceof NaturalEntityKey) {
			naturalKeyRegistrations.remove(key);
		}

		entitiesByKey.remove(key);
	}

	/**
	 * Retrieve the entity given an entity key
	 * @param key entity key
	 * @param entityType additional information to retrieve an entity successfully if it is
	 *                   part of an inheritance hierarchy
	 * @return BusinessObject indexed by the key
	 */
	public BusinessObject getByEntityKey(EntityKey key, Type entityType) {

		/* Currently this is not needed
		if(key instanceof SurrogateEntityKey) {
			BusinessObject result = null;
			do {
				result = entitiesByKey.get(key);
				if(entityType instanceof EntityType) {
					entityType = ((EntityType) entityType).getSuperType();
				} else {
					entityType = null;
				}
				// If this is a subtype try to locate it using it's parent type if possible
			} while (result == null && entityType != null);
			return result;
		} else {
			return entitiesByKey.get(key);
		}
		*/

		return entitiesByKey.get(key);
	}

	/**
	 * 	if anchor is set then we get ObjectResolver.Type#DISTINCT objects
	 *  else if path is null we get ObjectResolver.Type#SHARED objects
	 * @param idValue surrogate key value if present
	 * @param naturalKeyValues natural key values if the entity does not have a surrogate key
	 * @param type of the entity
	 * @param anchor where this type is anchored. Different type shapes can be present at different
	 *               anchors.
	 * @return businessObject instance
	 */
	public BusinessObject findEntity(Object idValue, Map<String, Object> naturalKeyValues, Type type, String anchor) {

		BusinessObject bo = null;

		if(naturalKeyValues.size() > 0) {
			bo = getByEntityKey(
				new NaturalEntityKey(
					naturalKeyValues,
					type.getName(),
					anchor), type);
		}

		if(bo != null) {
			return bo;
		}

		if(idValue != null && ((EntityType)type).getIdentifierProperty() != null) {
			bo = getByEntityKey(new SurrogateEntityKey(idValue,
				AbstractTypeMapper.getSurrogateKeyTypeName(type), anchor), type);
		}

		return bo;
	}

	public Set<BusinessObject> 	getDataObjects() {
		// Retrieve an Identity set
		Set<BusinessObject> result = Collections.newSetFromMap(new IdentityHashMap<BusinessObject, Boolean>());

		for(Object potentialDataObject: instanceDataObjectMap.values()) {
			if(BusinessObject.class.isAssignableFrom(potentialDataObject.getClass()) )
				result.add((BusinessObject) potentialDataObject);
		}

		return result;
	}

	/**
	 * Returns true if the given class is under a package that starts with
	 * "java.".
	 * @param c class
	 * @return boolean value
	 */
	protected boolean isJavaOrAppPackage(Class<?> c) {
		if (c == null)
			return false;
		Package p = c.getPackage();
		return p != null
				&& (p.getName().startsWith("java.") || p.getName().startsWith(
						"org.LWSDO."));
	}

	protected boolean immutable(Class<?> c) {
		if (c == null)
			return false;
		return c == String.class || c.isPrimitive() || c.isEnum()
				|| Number.class.isAssignableFrom(c)
				|| Boolean.class == c;
	}

	public BusinessObject getExistingDataObject(Object source) {
		if(source == null)
			return null;

		// The source is based on the instance object so extract if necessary
		if(source instanceof BusinessObject)
			source = ((BusinessObject)source).getInstance();

		return instanceDataObjectMap.get(source);
	}

	public Object createDataType(Object instance, Property property) throws Exception {

		if(property == null) {
			throw new RuntimeException("property is null, probably the object is a subtype instance and if so, the narrow flag needs to be set in settings");
		}

		Class<?> toClass = null;
		if(!property.isMany()) {
			toClass = (instance == null) ? null : instance.getClass();
		}

		Object result = creationStrategy.newInstance(instance, (BasicType) property.getType(), toClass);

		if(logger.isDebugEnabled()) {
			//logger.debug("ObjectCreator#createDataType instance: " + (instance==null?"null":instance.toString())
			logger.debug("ObjectCreator#createDataType instance: " + (instance==null?"null":instance.getClass().getName())
					+ ", property: " + property.getType().getName()
					+ ", propertyName: " + property.getName()
					+ ", result: " + (result==null?"null":result.toString()));
		}
		return result;
	}

	public BusinessObject createDataObject(Object targetInstance, Type targetType, BusinessObject container, Property containmentProperty) {
		return createDataObject(targetInstance, targetType, container, containmentProperty, null);
	}

	public BusinessObject createDataObject(Object targetInstance, Type targetType, BusinessObject container, Property containmentProperty, String anchor) {
		BusinessObject result = null;

		if(container != null && containmentProperty == null && (container.getContainmentProperty() == null || !container.getContainmentProperty().isMany()) )
			throw new RuntimeException("Cannot access the database without a containment property from the container [containmentProperty: "
					+ (containmentProperty == null ? "null": containmentProperty.getName()) + "]");

		// We always treat the collection object as not-shareable. So its container and containmentProperty is always populated.
		if(containmentProperty != null && !containmentProperty.isContainment() && !containmentProperty.isMany()) {
			container = null;
			containmentProperty = null;
		}

		if(targetInstance != null) {
			if(BusinessObject.class.isAssignableFrom(targetInstance.getClass()))
				throw new RuntimeException("targetInstance is a Data Object");

			result = getExistingDataObject(targetInstance);
			if(result != null && (result.getContainmentProperty() == null || !result.getContainmentProperty().isContainment()) ) {
				result.setContainer(container);
				result.setContainmentProperty(containmentProperty);
			}
		}

		if(result == null) {
			result = this.createDataObject(null, targetInstance, targetType, container, containmentProperty, anchor);
		}

		if(getSettings().getDetector() != null) {
			getSettings().getDetector().notifyCreate(null, result, targetInstance);
		}

		return result;
	}

	private void recordIO(Object sourceInstance, BusinessObject dataObject) {
		instanceDataObjectMap.put(sourceInstance, dataObject);
	}

	/**
	 * This method ensures that all derived and reference persistence instance point to the same reference data object
	 * @param sourceBO the provided source BusinessObject
	 * @param targetInstance the provided target instance or a persistence managed instance
	 * @param targetType the type of the instance
	 * @param container the parent BusinessObject
	 * @param containmentProperty the property referring to the target instance
	 * @param anchor the path in the state tree graph where this object is created
	 * @return the new BusinessObject
	 */
	private BusinessObject createDataObject(Object sourceBO, Object targetInstance, Type targetType, BusinessObject container, Property containmentProperty, String anchor) {

		Object sourceInstance = ClassUtil.getInstance(sourceBO);
		BusinessObject dataObject = instanceDataObjectMap.get(targetInstance);
		if(dataObject != null) {
			if(sourceInstance != null) {
				recordIO(sourceInstance, dataObject);
			}
			return dataObject;
		}

		if(readOnly) {
			dataObject = new ImmutableBO(targetType,
					container,
					containmentProperty,
					this);
		} else {
			// coerce type to the correct shape
			if(targetType instanceof EntityType && ((EntityType)targetType).isDomainType() ) {
				targetType = shape.getType(targetType.getName());
			}
			dataObject = new MutableBO(targetType,
					container,
					containmentProperty,
					this);
		}
		dataObject.setInstance(targetInstance);

		// NOTE: dataObject is registered only after its primitive typed properties have
		// been populated. See AbstractOperation#process
		if(targetInstance != null) {
			// Handle the case where the natural key points to entities
			// Needed for createWrapper to work properly
			if(targetType instanceof EntityType && ((EntityType)targetType).getNaturalKey() != null) {
				for(String key: ((EntityType)targetType).getNaturalKey()) {
					Property pKey = targetType.getProperty(key);
					if(pKey.getType() instanceof EntityType) {
						Object keyInstance = ((AbstractProperty)ClassUtil.getDelegate(pKey)).query(targetInstance);
						if(keyInstance != null) {
							String keyAnchor = anchor == null ? null : anchor + Settings.PATH_DELIMITER +pKey.getName();
							this.createDataObject(null, keyInstance, pKey.getType(), null, null, keyAnchor);
						}
					}
				}
			}

			dataObject = register(dataObject, sourceBO, false, anchor);
		}

		if(sourceInstance != null) {
			recordIO(sourceInstance, dataObject);
		}

		return dataObject;
	}

	// anchor is not relevant for GraphTraversal
	public void unregister(BusinessObject dataObject) {
		unregister(dataObject, null);
	}

	public void unregister(BusinessObject dataObject, String anchor) {
		instanceDataObjectMap.remove(dataObject.getInstance());
		dataObject.removeEntity(dataObject, null);
	}

	public void updateInstance(BusinessObject existingBO, Object oldInstance) {
		if(oldInstance != null) {
			instanceDataObjectMap.remove(oldInstance);
		}
		if(existingBO.getInstance() != null) {
			instanceDataObjectMap.put(existingBO.getInstance(), existingBO);
		}

		if(MutableBO.class.isAssignableFrom(existingBO.getClass()) && objectGraph != null) {
			objectGraph.replaceInstance(existingBO, existingBO.getInstance());
		}
	}

	private String getNaturalKeyString(EntityType entityType) {

		StringBuilder naturaKeyString = new StringBuilder();
		for(String key: entityType.getExpandedNaturalKey()) {
			if(naturaKeyString.length() == 0) {
				naturaKeyString.append(" {");
			} else {
				naturaKeyString.append(",");
			}
			naturaKeyString.append(key);
		}
		naturaKeyString.append("}");

		return new StringBuilder().append(entityType.getName()).append(naturaKeyString).toString();
	}

	private void evictTemporaryDomainObject(BusinessObject temporaryDomainObject) {
		if(temporaryDomainObject == null || temporaryDomainObject.getInstance() == null) {
			return;
		}

		if(temporaryDomainObject instanceof MutableBO) {
			((MutableBO)temporaryDomainObject).setEvicted(true);
		}

		// Make sure to evict the domain object from the persistence
		// layer as it is going to be swizzled
		// We don't want this swizzled out object to be saved for any reason
		Set objectsToClear = new HashSet();
		objectsToClear.add(temporaryDomainObject);
		getDataStore().clear(objectsToClear);
	}

	/**
	 * Register the user provided object in the object creator cache. Used if the object is deemed shareable.
	 * During registration the following issues are handled
	 * 1. Multiple objects with the same id (controlled by the share flag)
	 * 2. Multiple objects with the same id but of different types due to polymorphism. The
	 *    more specific instance is honored
	 *
	 * @param newDataObject to register
	 * @param sourceBO source BusinessObject
	 * @param naturalKeysPopulated flag to indicate if the natural key fields have already been populated in the newDataObject
	 * @param anchor state tree path that determines the shape we are interested in
	 * @return resolved BusinessObject
	 */
	public BusinessObject register (BusinessObject newDataObject, Object sourceBO, boolean naturalKeysPopulated, String anchor) {
		Object instance = newDataObject.getInstance();
		if (instance == null)
			throw new IllegalStateException("No persistent state found - possible data corruption");

		// External model objects, may create multiple copies of the same object for serialization purposes
		// So they should be de-duplicated and point to a single domain model object.
		boolean swizzle = false;
		if (naturalKeysPopulated &&
			sourceBO != null &&
			newDataObject.getType() instanceof EntityType &&
			sourceBO instanceof BusinessObject &&
			AggregateAction.isModificationAction(settings.getAction())) {
			if (!((BusinessObject)sourceBO).isReference()) {

				// Note: Swizzling should be done only after the natural keys have
				// been populated.
				// Also swizzling should occur only during the CREATE stage
				swizzle = true;
			}
		}

		// Embedded instances are not shareable, so we don't register them and
		// External model objects in a modification operation should not lose information by de-duplicating in the external model itself
		if (!newDataObject.getType().isDataType() && (
			((EntityType)newDataObject.getType()).isEmbedded() ||
				(!((EntityType)newDataObject.getType()).isDomainType()
					&& AggregateAction.isModificationAction(settings.getAction())))) {
			recordIO(newDataObject.getInstance(), newDataObject);
			return newDataObject;
		}

		// If an existing persistent object is already present, check if it is of a more general type, if so it has to be replaced
		// with the current object
		BusinessObject existing = newDataObject.getEntity(newDataObject, anchor);
		BusinessObject result = newDataObject;
		if (existing != newDataObject) {
			if (existing != null) {
				EntityType existingRootType = ((EntityType)existing.getType()).getRootEntityType();
				EntityType newRootType = ((EntityType)newDataObject.getType()).getRootEntityType();
				if (!swizzle) {
					if (existingRootType == newRootType) {
						// Embedded data objects without natural keys are not shareable
						if (share && !(existingRootType.isEmbedded()
							&& ((EntityType)newDataObject.getType()).getNaturalKey() == null)) {
							if (newDataObject.getInstance() != existing.getInstance()) {
								// Make sure we can re-fetch the BO by the other instance also
								recordIO(newDataObject.getInstance(), existing);
								if (newDataObject.isDomainType()) {
									evictTemporaryDomainObject(newDataObject);
								}
							}
							result = existing;
						}
						else {
							if (((EntityType)newDataObject.getType()).getNaturalKey() != null) {
								throw new IllegalStateException(
									"NaturalKey field(s) "
										+ getNaturalKeyString((EntityType)newDataObject.getType())
										+ " is either not populated or has duplicate values. Please check.");
							}
							else {
								throw new IllegalStateException(
									"There is more than 1 dataObject instance representing the same entity (same id and root type). Please check if XOR.id is populated. [type: "
										+ existingRootType.getEntityName() + ", id: "
										+ newDataObject.getIdentifierValue() + "]" + (
										existingRootType.isEmbedded() ?
											". Check your data as sharing of embedded objects is not allowed." :
											""));
							}
						}
					}
					else if (existingRootType.isSameOrSupertypeOf(newRootType)) {
						swizzle = true;
					}
					else {
						result = existing; // new data object is of a more general type, so we use the existing data object
					}
				}

				// We swizzle-out the exiting  instance
				// and swizzle-in the newDataObject instance
				if (swizzle) {

					// Evict the old instance from the persistence layer first
					// as it is going to be swizzled with the instance from the newDataObject
					evictTemporaryDomainObject(existing);

					// New data object is of a more specific type (This could be a proxy created by the persistent mechanism)
					// or the old object was just a reference association and the new data object is the real object
					Object oldInstance = existing.getInstance();
					existing.setInstance(instance);

					// preserve the link from the old instance as it refers to the same object,
					// the only difference being it now points to a more specific subtype, or the real object instead of a reference
					recordIO(oldInstance, existing);

					result = existing;
				}

				// Fix the source instance to the existing BO
				if (ClassUtil.getInstance(sourceBO) != null) {
					recordIO(ClassUtil.getInstance(sourceBO), result);
				}
			}

			// Do the actual registration
			recordIO(result.getInstance(), result);
		}

		addBySurrogateKey(result, anchor);

		// We delay natural key registration until they are assigned
		if(naturalKeysPopulated) {
			//result.register();
			addByNaturalKey(result, anchor);
		}

		// Mark the BusinessObject as reference or actual object
		if(result instanceof MutableBO && sourceBO != null) {
			if (swizzle) {
				((MutableBO)result).setReference(false);
			} else if(((AbstractBO)sourceBO).isReference()) {
				((MutableBO)result).setReference(true);
			} else {
				((MutableBO)result).setReference(false);
			}
		}

		return result;
	}

	public BusinessObject createTarget(CallInfo ci) {
		return createTarget(ci, null, null);
	}

	/**
	 * Create the target BusinessObject based on the TypeMapper direction target type
	 *
	 * @param ci CallInfo object
	 * @param targetInstance A reference to an already created target instance
	 * @param domainEntityType The desired type for the target if present
	 * @return new BusinessObject
	 */
	public BusinessObject createTarget(CallInfo ci, Object targetInstance, Type domainEntityType) {

		targetInstance = ClassUtil.getInstance(targetInstance);
		Object sourceInstance = ClassUtil.getInstance(ci.getInput());
		Object sourceBO = ci.getInput();
		Property sourceContainmentProperty = ci.getInputProperty();
		BusinessObject container = null;
		if(ci.getParent() != null && !ci.getParent().isBulkInput()) {
			container = (BusinessObject)ci.getParent().getOutput();
		}

		// Get the target BusinessObject mapped to the source instance
		BusinessObject result = getExistingDataObject(sourceInstance);
		if(result != null && (targetInstance != null && targetInstance != ClassUtil.getInstance(result)) )
			throw new IllegalStateException("existing target instance not the same as the passed in target instance");

		// Create the BusinessObject wrapper for the passed in target instance
		if(targetInstance != null) {
			// Check if an existing BusinessObject already exists for this target instance
			BusinessObject potentialResult = getExistingDataObject(targetInstance);
			if(potentialResult != null && result != null && potentialResult != result)
				throw new IllegalStateException("Source and target instance data objects are different");

			if(result == null && potentialResult != null) {
				// Let the source instance be associated with the target BusinessObject
				if(sourceInstance != null)
					recordIO(sourceInstance, potentialResult);
				result = potentialResult;
			}
		}

		boolean createdInstance = false;
		try {
			Class<?> targetInstanceClass = null;
			if(targetInstance == null) {
				//targetInstanceClass = sourceInstance != null ? ClassUtil.getUnEnhanced(sourceInstance.getClass()) : null;

				if(domainEntityType == null) {
                    if (sourceInstance != null) {
                        String mappedClassName = typeMapper.getMappedType(sourceInstance.getClass().getName(), ci);
                        targetInstanceClass = mappedClassName != null ? Class.forName(mappedClassName) : null;
                    } else {
                        targetInstanceClass = typeMapper.toExternal((Type)null);
                    }
				} else {
					if(typeMapper.isExternalSide()) {

						targetInstanceClass = typeMapper.toExternal(domainEntityType);
						//Class<?> externalClass = typeMapper.toExternal(domainEntityType.getInstanceClass());
						//instanceClass = das.getExternalType(typeMapper.getExternalTypeName(externalClass, domainEntityType)).getInstanceClass();
					} else {
						targetInstanceClass = domainEntityType.getInstanceClass();
					}
				}
			} else {
				targetInstanceClass = targetInstance.getClass();
			}

			Type targetType = null;
			if(sourceInstance != null && typeMapper.isDomain( ClassUtil.getUnEnhanced(sourceInstance.getClass()).getName())) {
				Type domainType = getDomainType((BusinessObject)ci.getInput());
				if(typeMapper.isOpen(targetInstanceClass)) {
					if(domainEntityType != null) {
						domainType = domainEntityType;
					}
				}
				targetType = getType(targetInstanceClass, domainType );
			} else {
				try {
					targetType = getType(targetInstanceClass, domainEntityType);
				}
				catch (NullPointerException e) {
					System.out.println("NullPointerException: " + targetInstanceClass);
				}
			}
			Property containmentProperty = (container == null || sourceContainmentProperty == null) ? null : container.getInstanceProperty(sourceContainmentProperty.getName());

			/*
			 * We need to fetch a persistent instance for the following:
			 * 1. AggregateAction is CREATE, CLONE or DELETE and the object being fetched is not part of the aggregate
			 * 2. Any UPDATE or MERGE action
			 */
			AggregateAction action = ci.getSettings().getAction();
			boolean isDependent = false;
			if(ci.getInput() != null)
				isDependent = ((BusinessObject)ci.getInput()).isDependent();
			boolean fetchPersistent =
				((action == AggregateAction.CREATE || action == AggregateAction.CLONE
					|| action == AggregateAction.DELETE) && !isDependent) ||
					(action == AggregateAction.MERGE || action == AggregateAction.UPDATE
						|| action == AggregateAction.LOAD);
			if( fetchPersistent && targetInstance == null) {

				if(result == null) {
					targetInstance = ci.getSettings().getAssociationStrategy().execute(ci, this);
					if(!ci.isDataType() && ci.getInputObjectCreator().getExistingDataObject(targetInstance) != null) {
						if(action != AggregateAction.LOAD && action != AggregateAction.CLONE) {
							logger.info("Directly modifying a persistence managed object.");
						}
					}

					if(targetInstance != null) {
						result = createDataObject(sourceBO, targetInstance, targetType, container, containmentProperty, null);
						result.setPersistent(true);
					}
				}
			}

			if(result == null) {

				if(targetInstance == null) {
					// Exception for Bulk processing
					if(targetType == null && domainEntityType instanceof ListType) {
						targetType = domainEntityType;
					}

					if(settings.isShouldCreate(targetType)) {
						targetInstance = createInstance(
							sourceInstance,
							targetInstanceClass,
							targetType,
							container,
							containmentProperty);

						createdInstance = true;

						if (targetInstance == null) {
							logger.error(
								"ObjectCreator#createTarget Unable to create targetInstance of class: "
									+ targetInstanceClass.getName()
									+ " and source instance: " + sourceInstance.getClass().getName()
									+ " and target type: " + targetType.getName()
									+ ". The instance has probably been deleted"
							);
						}
					}
				}

				if(targetInstance != null) {
					result = createDataObject(
						sourceBO,
						targetInstance,
						targetType,
						container,
						containmentProperty,
						null);
				}
			}

			// Give opportunity for reference objects to have any post processing done by the DAS
			if(targetInstance != null) {
				dataModel.postProcess(targetInstance, ci.getSettings().isAutoWire());
			}
		} catch (Exception e) {
			throw ClassUtil.wrapRun(e);
		}

		if(createdInstance && settings.getDetector() != null) {
			settings.getDetector().notifyCreate(sourceInstance, result, targetInstance);
		}

		return result;
	}

	protected Object createInstance(Object source, Class<?> targetClass, Type targetType, BusinessObject container, Property containmentProperty) throws Exception {
		Object instance = creationStrategy.newInstance(source, (BasicType) targetType, targetClass, container, containmentProperty);
		//setEmbeddedInstance(instance, targetType);

		if(settings.getDetector() != null) {
			settings.getDetector().notifyCreate(source, null, instance);
		}

		return instance;
	}

	public Object createInstance(Type targetType) throws Exception {
		Object instance = creationStrategy.newInstance(null, (BasicType) targetType, null);
		//setEmbeddedInstance(instance, targetType);

		if(settings.getDetector() != null) {
			settings.getDetector().notifyCreate(null, null, instance);
		}

		return instance;
	}

	public Object patchInstance(EntityType targetType) throws Exception {
		return creationStrategy.patchInstance(targetType);
	}

	public void clearVisited() {
		for(Object object: instanceDataObjectMap.values()) {
			BusinessObject node = (BusinessObject) object;
			node.setVisited(false);
		}
	}

	public ObjectGraph getObjectGraph() {
		return this.objectGraph;
	}

	public void setRoot(BusinessObject root) {
		this.root = root;
	}

	/**
	 * This method sets the root for MutableBO Business objects
	 * in the output ObjectCreator
	 * @param root of the object graph
	 */
	public void setObjectGraph(BusinessObject root) {
		this.root = root;
		if(this.objectGraph == null) {
			this.objectGraph = new ObjectGraph<MutableBO, BusinessEdge>(root);
		}
	}

	public BusinessObject getRoot() {
		return root;
	}

	public void persistGraph(Settings settings) {
		if(settings.getDataStore() instanceof JDBCDataStore) {
			CustomPersister cp = ((JDBCDataStore)settings.getDataStore()).getSessionContext();
			cp.persistGraph(this, settings);
		} else {
			objectGraph.persistGraph(this, settings);
		}
	}

	public void deleteGraph(Settings settings) {
		if(settings.getDataStore() instanceof JDBCDataStore) {
			CustomPersister cp = ((JDBCDataStore)settings.getDataStore()).getSessionContext();
			cp.deleteGraph(this, settings);
		} else {
			objectGraph.deleteGraph(this, settings);
		}
	}

	public static class CreateInstanceTracker implements Detector
	{
		private Class clazz;
		private String propertyName;
		private List<Object> skippedInstances;
		private List<BusinessObject> bos;
		private Map<Object, Object> allInstances;

		public CreateInstanceTracker(Class clazz, String propertyName) {
			this.clazz = clazz;
			this.propertyName = propertyName;
			this.skippedInstances = new ArrayList<>();
			this.bos = new ArrayList<>();
			this.allInstances = new IdentityHashMap<>();
		}

		@Override public void notifyCreate (Object source, BusinessObject createdBO, Object createdInstance)
		{
			if( createdInstance != null && clazz.isAssignableFrom(createdInstance.getClass())  ) {
				allInstances.put(createdInstance, null);
			}

			if(createdBO == null) {
				return;
			}

			if(clazz.isAssignableFrom(createdBO.getInstance().getClass())  ) {
				bos.add(createdBO);
				if(createdBO.getInstance() != createdInstance) {
					skippedInstances.add(createdInstance);
				}
			}
		}

		@Override public void performCall (CallInfo ci)
		{

		}

		@Override public void investigate (Object object)
		{

			List<String> keys = new ArrayList<>();
			System.out.println("No of skipped instances: " + skippedInstances.size());
			for(BusinessObject bo: bos) {
				keys.add(bo.get(propertyName).toString());
				if(allInstances.containsKey(bo.getInstance())) {
					allInstances.remove(bo.getInstance());
				}
			}
			System.out.println("No of extra instances: " + allInstances.size());

			Collections.sort(keys);

			for(String key: keys) {
				System.out.println("Key: " + key);
			}
		}
	}

	public static class DuplicateUniqueKeyByCall implements Detector {
		private Class clazz;
		private String propertyName;

		private Map<Object, List<Object>> duplicateInstances;
		private Map<Object, List<BusinessObject>> duplicateBusinessObjects;

		public DuplicateUniqueKeyByCall(Class clazz, String propertyName) {
			this.clazz = clazz;
			this.propertyName = propertyName;
			this.duplicateInstances = new HashMap<>();
			this.duplicateBusinessObjects = new HashMap<>();
		}

		@Override public void notifyCreate (Object source, BusinessObject createdBO, Object instance)
		{

		}

		/**
		 * Method should be invoked after the property has been set.
		 * @param ci details about the call
		 */
		@Override
		public void performCall(CallInfo ci) {

			if(ci.getStage() != ProcessingStage.UPDATE) {
				return;
			}

			if(ci.getParent() != null && ci.getParent().getOutput() instanceof BusinessObject) {
				if(ci.getInputProperty() != null && ci.getInputProperty().getName().equals(propertyName)) {
					BusinessObject outputBO = (BusinessObject)ci.getParent().getOutput();
					if(clazz.isAssignableFrom(outputBO.getType().getInstanceClass()) ) {
						Object keyValue = outputBO.get(propertyName);
						List<BusinessObject> bos = duplicateBusinessObjects.get(keyValue);
						if(bos == null) {
							bos = new ArrayList<>();
						}

						// Add only if the object is different from the others
						boolean existing = false;
						for(BusinessObject bo: bos) {
							if(bo == outputBO) {
								existing = true;
								break;
							}
						}
						if(!existing) {
							bos.add(outputBO);
						}

						// Check the actual instances to see if there are duplicates
						List<Object> instances = duplicateInstances.get(keyValue);
						if(instances == null) {
							instances = new ArrayList<>();
						}
						existing = false;
						for(Object instance: instances) {
							if(instance == outputBO.getInstance()) {
								existing = true;
								break;
							}
						}
						if(!existing) {
							instances.add(outputBO.getInstance());
						}
					}
				}
			}
		}

		@Override public void investigate (Object object)
		{
			Set<Object> dupInstanceKeys = new HashSet<>();
			Set<Object> dupBOKeys = new HashSet<>();

			// check for duplicate instances
			for(Map.Entry<Object, List<Object>> entry: duplicateInstances.entrySet()) {
				if(entry.getValue().size() > 1) {
					dupInstanceKeys.add(entry.getKey());
				}
			}

			for(Map.Entry<Object, List<BusinessObject>> entry: duplicateBusinessObjects.entrySet()) {
				if(entry.getValue().size() > 1) {
					dupBOKeys.add(entry.getKey());
				}
			}

			System.out.println("Keys of duplicate instances:");
			for(Object key: dupInstanceKeys) {
				System.out.println(key);
			}
			System.out.println("Keys of duplicate BusinessObjects:");
			for(Object key: dupBOKeys) {
				System.out.println(key);
			}
		}
	}

	public static class DuplicateUniqueKey implements Detector {

		private Class clazz;
		private String propertyName;
		private Map<Object, EntityKey> examined;
		private Map<Object, List<EntityKey>> duplicateKeys;
		private Map<Object, Set<BusinessObject>> duplicateObjects;

		public DuplicateUniqueKey(Class clazz, String propertyName) {
			this.clazz = clazz;
			this.propertyName = propertyName;
			this.examined = new HashMap<>();
			this.duplicateKeys = new HashMap<>();
			this.duplicateObjects = new HashMap<>();
		}

		@Override public void notifyCreate (Object source, BusinessObject createdBO, Object instance)
		{

		}

		@Override public void performCall (CallInfo ci)
		{
			// no functionality in this detector
		}

		@Override public void investigate (Object object)
		{
			if(! (object instanceof ObjectCreator)) {
				return;
			}

			ObjectCreator oc = (ObjectCreator) object;
			for(Map.Entry<EntityKey, BusinessObject> entry: oc.entitiesByKey.entrySet()) {
				if(clazz.isAssignableFrom(entry.getValue().getInstance().getClass()) ) {
					Object obj = entry.getValue().get(propertyName);
					EntityKey entityKey = entry.getKey();
					BusinessObject entity = entry.getValue();

					if(entity instanceof MutableBO && ((MutableBO)entity).isEvicted()) {
						continue;
					}

					if(examined.containsKey(obj)) {
						duplicateKeys.get(obj).add(entityKey);
						duplicateObjects.get(obj).add(entity);
					} else {
						examined.put(obj, entry.getKey());
						List<EntityKey> values = new ArrayList<EntityKey>();
						values.add(entityKey);
						duplicateKeys.put(obj, values);
						Set<BusinessObject> distinctObjects = new HashSet<>();
						distinctObjects.add(entity);
						duplicateObjects.put(obj, distinctObjects);
					}
				}
			}

			// Retain only those keys which has different objects for the same key
			for(Object key: duplicateKeys.keySet()) {
				if(duplicateObjects.containsKey(key) && duplicateObjects.get(key).size() == 1) {
					duplicateObjects.remove(key);
				}
			}

			if(duplicateObjects.size() > 0) {
				System.out.println("Duplicate objects found");
			}
		}
	}
}


text:
package javax.sip.header;

import javax.sip.InvalidArgumentException;

/**
 * A Contact header field value provides a URI whose meaning depends on
 * the type of request or response it is in. A Contact header field value
 * can contain a display name, a URI with URI parameters, and header
 * parameters.
 *

 * The Contact header field provides a SIP or SIPS URI that can be used
 * to contact that specific instance of the User Agent for subsequent requests.
 * The Contact header field MUST be present and contain exactly one SIP
 * or SIPS URI in any request that can result in the establishment of a
 * dialog.  For the methods defined in this specification, that includes
 * only the INVITE request.  For these requests, the scope of the
 * Contact is global.  That is, the Contact header field value contains
 * the URI at which the User Agent would like to receive requests, and this URI
 * MUST be valid even if used in subsequent requests outside of any
 * dialogs.
 *

 * If the Request-URI or top Route header field value contains a SIPS URI, the
 * Contact header field MUST contain a SIPS URI as well.
 *

 * Messages and Contact Headers
 *

 *
Requests: A contact header is mandatory for INVITE's and optional for
 * ACK, OPTIONS and REGISTER requests. This allows the callee to send future
 * Requests, such as BYE Requests, directly to the caller instead of through a
 * series of proxies.
 *
Informational Responses - A contact header is optional in a Informational
 * Response to an INVITE request. It has the same semantics in an Informational
 * Response as a Success Response.
 *
Success Responses - A contact header is mandatory in response to INVITE's
 * and optional in response to OPTIONS and REGISTER requests. An user agent
 * server sending a Success Response to an INIVTE must insert a ContactHeader
 * in the Response indicating the SIP address under which it is reachable most
 * directly for future SIP Requests.
 *
Redirection Responses - A contact header is optional in response to
 * INVITE's, OPTIONS, REGISTER and BYE requests. A proxy may also delete the
 * contact header.
 *
Ambiguous Header: - A contact header is optional in response to
 * INVITE, OPTIONS, REGISTER and BYE requests.
 *

 *
 * The ContactHeader defines the Contact parameters "q" and "expires".
 * The q-value value is used to prioritize addresses in a
 * list of contact addresses. The expires value suggests an
 * expiration interval that indicates how long the client would like a
 * registration to be valid for a specific address. These parameters are only
 * used when the Contact is present in a:
 *

 *
REGISTER request
 *
REGISTER response
 *
3xx response
 *

 *
 * For Example:

 *  Contact: "Mr. Watson" sip:watson@worcester.jcp.org;
 * q=0.7; expires=3600, "Mr. Watson" mailto:watson@jcp.org.com; q=0.1
 *
 * @see HeaderAddress
 * @see Parameters
 *
 * @author BEA Systems, NIST
 * @version 1.2
 */

public interface ContactHeader extends HeaderAddress, Parameters, Header {

    /**
     * Sets the value of the expires parameter as delta-seconds.
     * When a client sends a REGISTER request, it MAY suggest an expiration
     * interval that indicates how long the client would like the registration
     * to be valid for a specific address. There are two ways in which a client
     * can suggest an expiration interval for a binding:
     *

     *
through an Expires header field
     *
an "expires" Contact header parameter.
     *

     * The latter allows expiration intervals to be suggested on a per-binding
     * basis when more than one binding is given in a single REGISTER request,
     * whereas the former suggests an expiration interval for all Contact
     * header field values that do not contain the "expires" parameter. If
     * neither mechanism for expressing a suggested expiration time is present
     * in a REGISTER, the client is indicating its desire for the server to
     * choose.
     *

     * A User Agent requests the immediate removal of a binding by specifying an
     * expiration interval of "0" for that contact address in a REGISTER
     * request.  User Agents SHOULD support this mechanism so that bindings can be
     * removed before their expiration interval has passed. The
     * REGISTER-specific Contact header field value of "*" applies to all
     * registrations, but it MUST NOT be used unless the Expires header
     * field is present with a value of "0". The "*" value can be determined
     * if "this.getNameAddress().isWildcard() = = true".
     *
     * @param expires new relative value of the expires parameter.
     * 0 implies removal of Registration specified in Contact Header.
     * @throws InvalidArgumentException if supplied value is less than zero.
     */

    public void setExpires(int expires) throws InvalidArgumentException;

    /**
     * Returns the value of the expires parameter or -1 if no
     * expires parameter was specified or if the parameter value cannot be
     * parsed as an int.
     *
     * @return value of the expires parameter measured in
     * delta-seconds, O implies removal of Registration specified in Contact
     * Header.
     */

    public int getExpires();

    /**

     * Sets the qValue value of the Name Address. If more than

     * one Contact is sent in a REGISTER request, the registering UA intends

     * to associate all of the URIs in these Contact header field values with

     * the address-of-record present in the To field.  This list can be

     * prioritized with the "q" parameter in the Contact header field.  The "q"

     * parameter indicates a relative preference for the particular Contact

     * header field value compared to other bindings for this address-of-record.

     * A value of -1 indicates the qValue paramater

     * is not set.
     *
     * @param qValue - the new float value of the q-value parameter.
     * @throws InvalidArgumentException if the q-value parameter value is not
     * -1 or between 0 and 1.
     */
    public void setQValue(float qValue) throws InvalidArgumentException;

    /**

     * Returns the value of the q-value parameter of this

     * ContactHeader. The q-value parameter indicates the relative

     * preference amongst a set of locations. q-values are

     * decimal numbers from 0 to 1, with higher values indicating higher

     * preference.

     *

     * @return the q-value parameter of this ContactHeader, -1 if

     * the q-value is not set.

     */

    public float getQValue();

      /**
       * Sets a wildcard on this contact address that is "*" is assigned to the
       * contact header so that the header will have the format of Contact: *.
       *
       * @since v1.2
       */
    public void setWildCard();

       /**
        * Returns a boolean value that indicates if the contact header
        * has the format of Contact: *.
        * @return true if this is a wildcard address, false otherwise.
        * @since v1.2
        */
    public boolean isWildCard();

    /**
     * Name of ContactHeader
     */
    public final static String NAME = "Contact";

}


text:
(function() {
  // Initialize the Firebase SDK
  initializeApp({
    apiKey: "AIzaSyCR4ND2xwX3kU1IxTn0youF5OlI3x6MFZs",
    databaseURL: "https://geofire-gh-tests.firebaseio.com",
    projectId: "geofire-gh-tests"
  });

  // Generate a random Firebase location
  var firebaseRef = push(ref(getDatabase()));

  // Create a new GeoFire instance at the random Firebase location
  var geoFireInstance = new geofire.GeoFire(firebaseRef);
  var geoQuery;

  $("#addfish").on("submit", function() {
    var lat = parseFloat($("#addlat").val());
    var lon = parseFloat($("#addlon").val());
    var myID = "fish-" + firebaseRef.push().key;

    geoFireInstance.set(myID, [lat, lon]).then(function() {
      log(myID + ": setting position to [" + lat + "," + lon + "]");
    });

    return false;
  });

  $("#queryfish").on("submit", function() {
    var lat = parseFloat($("#querylat").val());
    var lon = parseFloat($("#querylon").val());
    var radius = parseFloat($("#queryradius").val());
    var operation;

    if (typeof geoQuery !== "undefined") {
      operation = "Updating";

      geoQuery.updateCriteria({
        center: [lat, lon],
        radius: radius
      });

    } else {
      operation = "Creating";

      geoQuery = geoFireInstance.query({
        center: [lat, lon],
        radius: radius
      });

      geoQuery.on("key_entered", function(key, location, distance) {
        log(key + " is located at [" + location + "] which is within the query (" + distance.toFixed(2) + " km from center)");
      });

      geoQuery.on("key_exited", function(key, location, distance) {
        console.log(key, location, distance);
        log(key + " is located at [" + location + "] which is no longer within the query (" + distance.toFixed(2) + " km from center)");
      });
    }

    log(operation + " the query: centered at [" + lat + "," + lon + "] with radius of " + radius + "km")

    return false;
  });

  /*************/
  /*  HELPERS  */
  /*************/
  /* Logs to the page instead of the console */
  function log(message) {
    var childDiv = document.createElement("div");
    var textNode = document.createTextNode(message);
    childDiv.appendChild(textNode);
    document.getElementById("log").appendChild(childDiv);
  }
})();


text:
'use strict';
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var MemberSchema = new Schema({
    name: String,
    email: {type: String, lowercase: true},
    birthday: Number,
    phone: Number,
    gender: String

})

var SportSchema = new Schema({
    name: String,
    year: Number,
    date: String,
    company_id: Schema.Types.ObjectId,
    enabled: {type: Boolean, default: true},
    captains: [MemberSchema],
    members: [MemberSchema]
});

module.exports = mongoose.model('Sport', SportSchema);


text:
int main (int argc, char **argv)
{
  if (argc < 2) {
    std::cout << "________________________________________________________________________________________________" << std::endl;
    std::cout << " -                                                                                - " << std::endl;
    std::cout << " -      Given an inverted index, computes visual word weights and saves them to disk.         - " << std::endl;
    std::cout << " -                       written 2015 by Torsten Sattler (sattlert@inf.ethz.ch)               - " << std::endl;
    std::cout << " -    copyright ETH Zurich, 2015-2016                                                         - " << std::endl;
    std::cout << " -                                                                                - " << std::endl;
    std::cout << " - usage: compute_index_weights index                                                         - " << std::endl;
    std::cout << " - Parameters:                                                                                - " << std::endl;
    std::cout << " -  index                                                                                - " << std::endl;
    std::cout << " -     The filename of an inverted index created with build_index. This program creates a     - " << std::endl;
    std::cout << " -     file index.weights storing all idf-weights and normalization constants.                - " << std::endl;
    std::cout << " -                                                                                - " << std::endl;
    std::cout << "________________________________________________________________________________________________" << std::endl;
    return -1;
  }

  geometric_burstiness::InvertedIndex<64> inverted_index;
  std::string index_file(argv[1]);
  if (!inverted_index.LoadInvertedIndex(index_file)) {
    std::cerr << "ERROR: Cannot load the inverted index from " << index_file
              << std::endl;
    return -1;
  }

  if (!inverted_index.ComputeWeightsAndNormalizationConstants()) {
    std::cerr << "ERROR: Failed to compute the weights and constants"
              << std::endl;
    return -1;
  }

  std::string outfile(index_file);
  outfile.append(".weights");
  if (!inverted_index.SaveWeightsAndConstants(outfile)) {
    std::cerr << "ERROR: Could not save the weights to " << outfile
              << std::endl;
    return -1;
  }

  return 0;
}


text:
package ru.pavkin.todoist.api.dispatch.circe

/**
  * Default asynchronous API client implementation.
  *
  * API effect is `Future[ Xor[DispatchAPI.Error, T] ]`
  *
  * Uses Dispatch HTTP client and Circe Json under the hood
  *
  * @see [[scala.concurrent.Future]]
  * @see [[cats.data.Xor]]
  * @see [[ru.pavkin.todoist.api.dispatch.impl.circe.DispatchAPI.Error]]
  */
object default extends CirceModelAPISuite


text:
<html>
<body>
Reports boolean expressions containing a boolean literal which can be further simplified.
</body>
</html>


text: Here are some icons, aren't they pretty?


text:
package org.apache.calcite.rel.rules;

import org.apache.calcite.plan.RelOptPredicateList;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelRule;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.RelCollations;
import org.apache.calcite.rel.RelDistribution;
import org.apache.calcite.rel.RelDistributions;
import org.apache.calcite.rel.RelFieldCollation;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Exchange;
import org.apache.calcite.rel.core.SortExchange;
import org.apache.calcite.rel.logical.LogicalExchange;
import org.apache.calcite.rel.logical.LogicalSortExchange;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rex.RexInputRef;

import org.immutables.value.Value;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * Planner rule that removes keys from
 * a {@link Exchange} if those keys are known to be constant.
 *
 *
For example,
 * SELECT key,value FROM (SELECT 1 AS key, value FROM src) r DISTRIBUTE
 * BY key can be reduced to
 * SELECT 1 AS key, value FROM src.
 *
 * @see CoreRules#EXCHANGE_REMOVE_CONSTANT_KEYS
 * @see CoreRules#SORT_EXCHANGE_REMOVE_CONSTANT_KEYS
 */
@Value.Enclosing
public class ExchangeRemoveConstantKeysRule
    extends RelRule<ExchangeRemoveConstantKeysRule.Config>
    implements SubstitutionRule {

  /** Creates an ExchangeRemoveConstantKeysRule. */
  protected ExchangeRemoveConstantKeysRule(Config config) {
    super(config);
  }

  /** Removes constant in distribution keys. */
  protected static List<Integer> simplifyDistributionKeys(RelDistribution distribution,
      Set<Integer> constants) {
    return distribution.getKeys().stream()
        .filter(key -> !constants.contains(key))
        .collect(Collectors.toList());
  }

  @Override public void onMatch(RelOptRuleCall call) {
    config.matchHandler().accept(this, call);
  }

  private static void matchExchange(ExchangeRemoveConstantKeysRule rule,
      RelOptRuleCall call) {
    final Exchange exchange = call.rel(0);
    final RelMetadataQuery mq = call.getMetadataQuery();
    final RelNode input = exchange.getInput();
    final RelOptPredicateList predicates = mq.getPulledUpPredicates(input);
    if (RelOptPredicateList.isEmpty(predicates)) {
      return;
    }

    final Set<Integer> constants = new HashSet<>();
    predicates.constantMap.keySet().forEach(key -> {
      if (key instanceof RexInputRef) {
        constants.add(((RexInputRef) key).getIndex());
      }
    });
    if (constants.isEmpty()) {
      return;
    }

    final List<Integer> distributionKeys = simplifyDistributionKeys(
        exchange.getDistribution(), constants);

    if (distributionKeys.size() != exchange.getDistribution().getKeys()
        .size()) {
      call.transformTo(call.builder()
          .push(exchange.getInput())
          .exchange(distributionKeys.isEmpty()
              ? RelDistributions.SINGLETON
              : RelDistributions.hash(distributionKeys))
          .build());
      call.getPlanner().prune(exchange);
    }
  }

  private static void matchSortExchange(ExchangeRemoveConstantKeysRule rule,
      RelOptRuleCall call) {
    final SortExchange sortExchange = call.rel(0);
    final RelMetadataQuery mq = call.getMetadataQuery();
    final RelNode input = sortExchange.getInput();
    final RelOptPredicateList predicates = mq.getPulledUpPredicates(input);
    if (RelOptPredicateList.isEmpty(predicates)) {
      return;
    }

    final Set<Integer> constants = new HashSet<>();
    predicates.constantMap.keySet().forEach(key -> {
      if (key instanceof RexInputRef) {
        constants.add(((RexInputRef) key).getIndex());
      }
    });

    if (constants.isEmpty()) {
      return;
    }

    List<Integer> distributionKeys = new ArrayList<>();
    boolean distributionSimplified = false;
    boolean hashDistribution = sortExchange.getDistribution().getType()
        == RelDistribution.Type.HASH_DISTRIBUTED;
    if (hashDistribution) {
      distributionKeys = simplifyDistributionKeys(
          sortExchange.getDistribution(), constants);
      distributionSimplified =
          distributionKeys.size() != sortExchange.getDistribution().getKeys()
              .size();
    }

    final List<RelFieldCollation> fieldCollations = sortExchange
        .getCollation().getFieldCollations().stream().filter(
            fc -> !constants.contains(fc.getFieldIndex()))
        .collect(Collectors.toList());

    boolean collationSimplified =
        fieldCollations.size() != sortExchange.getCollation()
            .getFieldCollations().size();
    if (distributionSimplified
        || collationSimplified) {
      RelDistribution distribution = distributionSimplified
          ? (distributionKeys.isEmpty()
          ? RelDistributions.SINGLETON
          : RelDistributions.hash(distributionKeys))
          : sortExchange.getDistribution();
      RelCollation collation = collationSimplified
          ? RelCollations.of(fieldCollations)
          : sortExchange.getCollation();

      call.transformTo(call.builder()
          .push(sortExchange.getInput())
          .sortExchange(distribution, collation)
          .build());
      call.getPlanner().prune(sortExchange);
    }
  }

  /** Rule configuration. */
  @Value.Immutable(singleton = false)
  public interface Config extends RelRule.Config {
    Config DEFAULT = ImmutableExchangeRemoveConstantKeysRule.Config
        .of(ExchangeRemoveConstantKeysRule::matchExchange)
        .withOperandFor(LogicalExchange.class,
            exchange -> exchange.getDistribution().getType()
                == RelDistribution.Type.HASH_DISTRIBUTED);

    Config SORT = ImmutableExchangeRemoveConstantKeysRule.Config
        .of(ExchangeRemoveConstantKeysRule::matchSortExchange)
        .withDescription("SortExchangeRemoveConstantKeysRule")
        .as(Config.class)
        .withOperandFor(LogicalSortExchange.class,
            sortExchange -> sortExchange.getDistribution().getType()
                == RelDistribution.Type.HASH_DISTRIBUTED
                || !sortExchange.getCollation().getFieldCollations()
                .isEmpty());

    @Override default ExchangeRemoveConstantKeysRule toRule() {
      return new ExchangeRemoveConstantKeysRule(this);
    }

    /** Forwards a call to {@link #onMatch(RelOptRuleCall)}. */
    @Value.Parameter
    MatchHandler<ExchangeRemoveConstantKeysRule> matchHandler();

    /** Sets {@link #matchHandler()}. */
    Config withMatchHandler(MatchHandler<ExchangeRemoveConstantKeysRule> matchHandler);

    /** Defines an operand tree for the given classes. */
    default <R extends Exchange> Config withOperandFor(Class<R> exchangeClass,
        Predicate<R> predicate) {
      return withOperandSupplier(b ->
          b.operand(exchangeClass).predicate(predicate)
              .anyInputs())
          .as(Config.class);
    }
  }
}


text:
ofxSynthDelayline::ofxSynthDelayline(){
	setSize(1.1);
	setFeedback(0.5);
	setMix(0.5);
}
void ofxSynthDelayline::process( float* input, float *output, int numFrames, int numInChannels, int numOutChannels )
{
	for (int i = 0; i < numFrames; i++){
		if (phase>=size) {
			phase=0;
		}
		memory[phase]=(memory[phase]*feedback)+(input[i*numInChannels]*feedback)*0.5;
		phase+=1;
		for (int j=0; j<numOutChannels; j++) {
			// puts the sound in memory on to all the output channels
			output[i*numOutChannels+j]=memory[phase+1]*mix+input[i*numInChannels]*(1.0-mix);
		}
	}
}
void ofxSynthDelayline::setSize(float _size){
	size = _size*sampleRate;
}
void ofxSynthDelayline::setFeedback(float _feedback){
	feedback = _feedback;
}
void ofxSynthDelayline::setMix(float _mix){
	mix = _mix;
}


text:
<link href="<?php echo base_url() ?>assets/css/back/style.css" rel="stylesheet">

              Form Ubah Item Pembayaran

             <form class="" action="<?php echo site_url('murid/actedit') ?>" method="post">

                     No Induk
                     <input type="hidden" name="id" value="<?php echo $data_edit['id'] ?>">
                     <input type="text" name="no_induk" value="<?php echo $data_edit['no_induk'] ?>" class="form-control border-input" placeholder="No Induk" required>

                     Nama
                     <input type="text" name="nama" value="<?php echo $data_edit['nama'] ?>" class="form-control border-input" required placeholder="Nama">

                       Program
                       <?php foreach ($data_program as $data): ?>

                         <?php if ($data->id == $data_edit['program']): ?>
                           <input type="radio" class="form-control" checked  name="program" required value="<?php echo $data->id ?>"> <?php echo $data->nama ?>
                         <?php else: ?>
                           <input type="radio" class="form-control" name="program" required value="<?php echo $data->id ?>"> <?php echo $data->nama ?>
                         <?php endif; ?>

                       <?php endforeach; ?>

                       Kelas
                       <?php foreach ($data_kelas as $data): ?>

                         <?php if ($data->id == $data_edit['kelas']): ?>
                           <input type="radio" class="form-control" checked  name="kelas" required value="<?php echo $data->id ?>"> <?php echo $data->nama_kelas ?>
                         <?php else: ?>
                           <input type="radio" class="form-control" name="kelas" required value="<?php echo $data->id ?>"> <?php echo $data->nama_kelas ?>
                         <?php endif; ?>

                       <?php endforeach; ?>

                 <button type="submit" class="btn btn-success">Simpan</button
             </form>