code stringlengths 2 1.05M |
|---|
'use strict';
const gulp = require('gulp');
const addSrc = require('gulp-add-src');
const concat = require('gulp-concat');
const insert = require('gulp-insert');
const remoteSrc = require('gulp-remote-src');
const replace = require('gulp-replace');
const uglify = require('gulp-uglify');
const BENCHMARKJS_VERSION = require('./package.json').devDependencies.benchmark;
const requestOptions = {
'gzip': true,
'strictSSL': true
};
gulp.task('js', function() {
// Fetch Platform.js, Benchmark.js, and its jsPerf UI dependencies.
remoteSrc([
'bestiejs/platform.js/1.3.1/platform.js',
`bestiejs/benchmark.js/${ BENCHMARKJS_VERSION }/benchmark.js`,
`bestiejs/benchmark.js/${ BENCHMARKJS_VERSION }/example/jsperf/ui.js`,
`bestiejs/benchmark.js/${ BENCHMARKJS_VERSION }/plugin/ui.browserscope.js`,
], {
'base': 'https://raw.githubusercontent.com/',
'requestOptions': requestOptions
}
)
// Use whatever version of lodash Benchmark.js is using.
.pipe(addSrc.prepend(require.resolve('lodash')))
.pipe(concat('all.js'))
// Set the Google Analytics ID.
.pipe(replace('gaId = \'\'', 'gaId = \'UA-6065217-40\''))
// jsPerf is browser-only. Ensure we’re detected as a browser environment,
// even if this is an AMD test, for example.
.pipe(replace(/freeDefine = (?:[^;]+)/, 'freeDefine = false'))
.pipe(replace(/freeExports = (?:[^;]+)/, 'freeExports = false'))
.pipe(replace(/freeModule = (?:[^;]+)/, 'freeModule = false'))
.pipe(replace(/freeRequire = (?:[^;]+)/, 'freeRequire = false'))
.pipe(replace(/(if\s*\()(typeof define|freeDefine)\b/, '$1false'))
// Set the CSS selector for the Browserscope results.
.pipe(replace('\'selector\': \'\'', '\'selector\': \'#bs-results\''))
// Avoid exposing `_` and `platform` as global variables.
.pipe(insert.wrap(
'(function(){var _,platform;',
'}.call(this))'
))
.pipe(replace('root.platform = parse()', 'platform = parse()'))
.pipe(replace('var _ = runInContext()', '_ = runInContext()'))
.pipe(replace('var _ = context && context._ || require(\'lodash\') || root._;', ''))
.pipe(replace('(freeWindow || freeSelf || {})._ = _', ''))
.pipe(replace('root._ = _', ''))
// Ensure that Benchmark.js uses the local copies of lodash and Platform.js.
.pipe(replace('var _ = context && context._ || req(\'lodash\') || root._;', ''))
.pipe(replace('\'platform\': context.platform', '\'platform\': platform'))
// Minify the result.
//.pipe(uglify())
.pipe(gulp.dest('./dist/'));
});
gulp.task('assets', function() {
// Update Platform.js, Benchmark.js, and its jsPerf UI dependencies.
remoteSrc([
'index.html',
'main.css'
], {
'base': `https://raw.githubusercontent.com/bestiejs/benchmark.js/${ BENCHMARKJS_VERSION }/example/jsperf/`,
'requestOptions': requestOptions
}
)
.pipe(replace('<script src="../../node_modules/lodash/lodash.js"></script>', ''))
.pipe(replace('<script src="../../node_modules/platform/platform.js"></script>', ''))
.pipe(replace('<script src="../../benchmark.js"></script>', ''))
.pipe(replace('<script src="ui.js"></script>', ''))
.pipe(replace(
'<script src="../../plugin/ui.browserscope.js"></script>',
'<script src="all.js"></script>'
))
.pipe(gulp.dest('./dist'));
});
gulp.task('default', ['js', 'assets']);
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPolicies, setNavigation } from '../actions';
import localization from '../helpers/localization';
import Command from '../components/commands/command';
import Content from '../components/templates/content';
import ContentHeader from '../components/templates/content_header';
import ContentBody from '../components/templates/content_body';
import PoliciesList from '../components/lists/policies_list';
class PoliciesIndex extends Component {
componentDidMount() {
this.props.fetchPolicies();
this.props.setNavigation('policies', 'policies', 'file');
}
render() {
return (
<Content>
<ContentHeader title={localization.policies} icon="th">
<Command to="/policies/new" title={localization.addPolicy} icon="plus" style="primary"/>
</ContentHeader>
<ContentBody>
<PoliciesList policies={this.props.policies} />
</ContentBody>
</Content>
);
}
}
function mapStateToProps(state) {
return {
policies: state.policies
}
}
export default connect(mapStateToProps, {fetchPolicies, setNavigation})(PoliciesIndex);
|
// ##### # #
// # # # #### ##### ## # # # ## ##### ####
// # # # # # # # # # # # # # # # #
// # #### # # # ##### # # # # # # # # # ####
// # # # # # # # ###### # # # ###### ##### #
// # # # # # # # # # # # # # # # # # #
// ##### ###### #### ##### # # ###### # # # # # ####
//global vars
var g_showText = true;
var g_drawingOptions = {
generateTriangleResultList: false,
drawUiOverlay: true,
drawKeypoints: false,
drawTriangles: true,
forceApplyTransformations: false,
drawImageOutline: true,
drawInteractiveCanvasUiLayer: true
};
//
// consts
//
const MAX_TRIANGLES_DRAW = 800;//max number of triangles to draw per layer
//FIXME: fix hardcoded values
const TARGET_TRIANGLE_SCALE = {
x: 160,
y: 160
};
const INTERACTIVE_CANVAS_ID = "queryImageCanvasImageContent";
const INTERACTIVE_CANVAS_OVERLAY_ID = "queryImageCanvasUiOverlay";
const INTERACTIVE_CANVAS_IMAGE_OUTLINE_ID = "queryImageCanvasImageOutline";
const INTERACTIVE_FRAGMENT_CANVAS_ID = "fragmentCanvas1";
const INTERACTIVE_HIGHLIGHTED_CANVAS_ID = "queryImageCanvasHighlightedTriangle";
const REFERENCE_CANVAS_ID = "databaseImageCanvasImageContent";
const REFERENCE_CANVAS_OVERLAY_ID = "databaseImageCanvasUiOverlay";
const REFERENCE_CANVAS_IMAGE_OUTLINE_ID = "databaseImageCanvasImageOutline";
const REFERENCE_FRAGMENT_CANVAS_ID = "fragmentCanvas2";
const REFERENCE_HIGHLIGHTED_CANVAS_ID = "databaseImageCanvasHighlightedTriangle";
var g_numberOfKeypoints = 52;
const MIN_CROPPING_POLYGON_AREA = 600;
const ORANGE_COLOUR = [255, 87, 34];
const BLUE_COLOUR = [33, 150, 243];
var setAlpha = false;
function newStep(minPntDist, maxPntDist, minTriArea, colour) {
return {
minPntDist: minPntDist,
maxPntDist: maxPntDist,
minTriArea: minTriArea,
colour: ORANGE_COLOUR
}
}
const g_steps = [
newStep(85, 90, 30, [255, 255, 255]),
newStep(90, 100, 30, [0, 0, 255]),
newStep(100, 150, 30, [255, 0, 0]),
newStep(150, 200, 30, [100, 250, 250]),
newStep(50, 450, 30, [100, 255, 100])
];
//
// globalState
//
function buildRect(x2, y2) {
return [
{x: 0, y: 0},
{x: x2, y: 0},
{x: x2, y: y2},
{x: 0, y: y2}
]
}
function buildRectangularCroppingPolyFromLayer(layer) {
return [
{x: 0, y: 0},
{x: layer.image.width, y: 0},
{x: layer.image.width, y: layer.image.height},
{x: 0, y: layer.image.height}
]
}
function newLayer(layerImage, keypoints, colour) {
return {
//TODO FIXME: FILL THIS IN
nonTransformedImageOutline: buildRect(layerImage.width, layerImage.height),
image: layerImage,
appliedTransformations: getIdentityMatrix(),
visible: true,
layerColour: [0, 0, 0], //used for canvas UI overlay elements
keypoints: keypoints,
colour: colour//used for UI elements
};
}
function newCanvasState() {
return {
//TODO: FIXME: FILL THIS IN
};
}
var _g_preloadImage = null;
var _g_linesImage1 = null;
var _g_linesImage2 = null;
var _g_linesImage3 = null;
var _g_linesImage4 = null;
var _g_linesImage5 = null;
var g_globalState = null;
function newGlobalState() {
return {
activeCanvas: null,
referenceCanvasState: null,
interactiveCanvasState: null,
isMouseDownAndClickedOnCanvas: null,
temporaryAppliedTransformations: null,
transformationMatBeforeTemporaryTransformations: null,
pageMouseDownPosition: null,
};
}
function reset() {
console.log("Reset called.");
//TODO: FIXME
}
var enum_TransformationOperation = {
TRANSLATE: 1,
UNIFORM_SCALE: 2,
NON_UNIFORM_SCALE: 3,
ROTATE: 4,
CROP: 5
};
//
// getters
//
function getInteractiveCanvas() {
return g_interactiveCanvas;
}
function getReferenceCanvas() {
return g_referenceCanvas;
}
function toggleDrawUIOverlayMode() {
g_shouldDrawUIOverlay = !g_shouldDrawUIOverlay;
draw();
}
function applyTransformationToImageOutline(imageOutline, appliedTransformations) {
return applyTransformationMatrixToAllKeypointsObjects(imageOutline, appliedTransformations);
}
function getIdentityTransformations() {
var ret = {
transformationCenterPoint: {
x: 0,
y: 0
},
uniformScale: 1,
directionalScaleMatrix: getIdentityMatrix(),
rotation: 0,
translate: {
x: 0,
y: 0
}
};
return ret;
}
function wipeTemporaryAppliedTransformations() {
g_globalState.temporaryAppliedTransformations = getIdentityTransformations();
}
function getActiveLayer(globalState) {
return globalState.activeCanvas.activeLayer;
}
function getReferenceImageTransformations() {
return g_referenceImageTransformation;
}
function getInteractiveImageTransformations() {
return g_interactiveImageTransformation;
}
function getKeypoints() {
return g_keypoints;
}
// ##### ####### ###### # # ####### ######
//# # # # # # # # # #
//# # # # # # # # #
// ##### ##### ###### # # ##### ######
// # # # # # # # # #
//# # # # # # # # # #
// ##### ####### # # # ####### # #
//server
function callSearch() {
var interactiveCanvasContext = document.getElementById('interactiveCanvas');
var image1 = interactiveCanvasContext.toDataURL('image/jpeg', 0.92).replace("image/jpeg", "image/octet-stream"); // here is the most important part because if you dont replace you will get a DOM 18 exception.
var referenceCanvasContext = document.getElementById('referenceCanvas');
var image2 = referenceCanvasContext.toDataURL('image/jpeg', 0.92).replace("image/jpeg", "image/octet-stream"); // here is the most important part because if you dont replace you will get a DOM 18 exception.
var regex = /^data:.+\/(.+);base64,(.*)$/;
var matches;
matches = image1.match(regex);
var data1 = matches[2];
matches = image2.match(regex);
var data2 = matches[2];
var info = {
'image1': {
'imageData': data1,
'keypoints': g_cachedCalculatedInteractiveCanvasKeypoints
},
'image2': {
'imageData': data2,
'keypoints': g_cachedCalculatedReferenceCanvasKeypoints
}
};
$("#searchResultsOutputDiv").html("loading...");
$.ajax({
url: 'http://104.197.137.79/runTestWithJsonData',
type: 'POST',
data: JSON.stringify(info),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: function (msg) {
console.log(msg);
$("#searchResultsOutputDiv").html("Found this many matches: " + msg);
},
error: function (msg) {
}
});
}
// ###### # # # ##### # #
// # # # # # # # # # #
// # # # # # # # # #
// ###### ####### # # ##### #######
// # # # ####### # # #
// # # # # # # # # #
// # # # # # ##### # #
//phash
// Credit goes to:
// https://raw.githubusercontent.com/naptha/phash.js/master/phash.js
// https://ironchef-team21.googlecode.com/git-history/75856e07bb89645d0e56820d6e79f8219a06bfb7/ironchef_team21/src/ImagePHash.java
function pHash(img) {
var size = 32,
smallerSize = 8;
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
//document.body.appendChild(canvas)
/* 1. Reduce size.
* Like Average Hash, pHash starts with a small image.
* However, the image is larger than 8x8; 32x32 is a good size.
* This is really done to simplify the DCT computation and not
* because it is needed to reduce the high frequencies.
*/
canvas.width = size;
canvas.height = size;
// ctx.drawImage(img, 0, 0, size, size);
ctx.drawImage(img, 0, -size, size, size * 3);
var im = ctx.getImageData(0, 0, size, size);
/* 2. Reduce color.
* The image is reduced to a grayscale just to further simplify
* the number of computations.
*/
var vals = new Float64Array(size * size);
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
var base = 4 * (size * i + j);
vals[size * i + j] = 0.299 * im.data[base] +
0.587 * im.data[base + 1] +
0.114 * im.data[base + 2];
}
}
/* 3. Compute the DCT.
* The DCT separates the image into a collection of frequencies
* and scalars. While JPEG uses an 8x8 DCT, this algorithm uses
* a 32x32 DCT.
*/
function applyDCT2(N, f) {
// initialize coefficients
var c = new Float64Array(N);
for (var i = 1; i < N; i++) c[i] = 1;
c[0] = 1 / Math.sqrt(2);
// output goes here
var F = new Float64Array(N * N);
// construct a lookup table, because it's O(n^4)
var entries = (2 * N) * (N - 1);
var COS = new Float64Array(entries);
for (var i = 0; i < entries; i++)
COS[i] = Math.cos(i / (2 * N) * Math.PI);
// the core loop inside a loop inside a loop...
for (var u = 0; u < N; u++) {
for (var v = 0; v < N; v++) {
var sum = 0;
for (var i = 0; i < N; i++) {
for (var j = 0; j < N; j++) {
sum += COS[(2 * i + 1) * u]
* COS[(2 * j + 1) * v]
* f[N * i + j];
}
}
sum *= ((c[u] * c[v]) / 4);
F[N * u + v] = sum;
}
}
return F
}
var dctVals = applyDCT2(size, vals);
// for(var x = 0; x < size; x++){
// for(var y = 0; y < size; y++){
// ctx.fillStyle = (dctVals[size * x + y] > 0) ? 'white' : 'black';
// ctx.fillRect(x, y, 1, 1)
// }
// }
/* 4. Reduce the DCT.
* This is the magic step. While the DCT is 32x32, just keep the
* top-left 8x8. Those represent the lowest frequencies in the
* picture.
*/
var vals = []
for (var x = 1; x <= smallerSize; x++) {
for (var y = 1; y <= smallerSize; y++) {
vals.push(dctVals[size * x + y])
}
}
/* 5. Compute the average value.
* Like the Average Hash, compute the mean DCT value (using only
* the 8x8 DCT low-frequency values and excluding the first term
* since the DC coefficient can be significantly different from
* the other values and will throw off the average).
*/
var median = vals.slice(0).sort(function (a, b) {
return a - b
})[Math.floor(vals.length / 2)];
/* 6. Further reduce the DCT.
* This is the magic step. Set the 64 hash bits to 0 or 1
* depending on whether each of the 64 DCT values is above or
* below the average value. The result doesn't tell us the
* actual low frequencies; it just tells us the very-rough
* relative scale of the frequencies to the mean. The result
* will not vary as long as the overall structure of the image
* remains the same; this can survive gamma and color histogram
* adjustments without a problem.
*/
return vals.map(function (e) {
return e > median ? '1' : '0';
}).join('');
}
function distance(a, b) {
var dist = 0;
for (var i = 0; i < a.length; i++)
if (a[i] != b[i]) dist++;
return dist;
}
// # #
// ## ## ## ##### # #
// # # # # # # # # #
// # # # # # # ######
// # # ###### # # #
// # # # # # # #
// # # # # # # #
//math
function calcPolygonArea(vertices) {
var total = 0;
for (var i = 0, l = vertices.length; i < l; i++) {
var addX = vertices[i].x;
var addY = vertices[i == vertices.length - 1 ? 0 : i + 1].y;
var subX = vertices[i == vertices.length - 1 ? 0 : i + 1].x;
var subY = vertices[i].y;
total += (addX * addY * 0.5);
total -= (subX * subY * 0.5);
}
return Math.abs(total);
}
function getArea(tri) {
var a = tri[0];
var b = tri[1];
var c = tri[2];
var one = (a.x - c.x) * (b.y - a.y);
var two = (a.x - b.x) * (c.y - a.y);
var area = Math.abs(one - two) * 0.5;
return area;
}
function getScaleMatrix(scaleX, scaleY) {
return [[scaleX, 0, 0], [0, scaleY, 0], [0, 0, 1]];
}
function getTargetTriangleRotated180() {
var targetTriangle = [
{x: TARGET_TRIANGLE_SCALE.x, y: TARGET_TRIANGLE_SCALE.y},
{x: .5 * TARGET_TRIANGLE_SCALE.x, y: 0},
{x: 0, y: TARGET_TRIANGLE_SCALE.y}
];
return targetTriangle;
}
function getTargetTriangle() {
var targetTriangle = [
{x: 0, y: 0},
{x: .5 * TARGET_TRIANGLE_SCALE.x, y: 1 * TARGET_TRIANGLE_SCALE.y},
{x: 1 * TARGET_TRIANGLE_SCALE.x, y: 0}
];
return targetTriangle;
}
function calcTransformationMatrixToEquilateralTriangle(inputTriangle) {
/*
* ######CODE BY ROSCA#######
*/
var targetTriangle = getTargetTriangle();
var pt1 = targetTriangle[1];
var pt2 = targetTriangle[2];
var targetTriangleMat = [
[pt1.x, pt2.x, 0.0],
[pt1.y, pt2.y, 0.0],
[0.0, 0.0, 1.0]
];
var pt0 = inputTriangle[0];
pt1 = inputTriangle[1];
pt2 = inputTriangle[2];
var inputTriangleMat = [
[pt1.x - pt0.x, pt2.x - pt0.x, 0.0],
[pt1.y - pt0.y, pt2.y - pt0.y, 0.0],
[0.0, 0.0, 1.0]
];
//move to 0,0
//move to 0,0
var tranlateMat = [
[1.0, 0.0, -pt0.x],
[0.0, 1.0, -pt0.y],
[0.0, 0.0, 1.0]
];
var result = getIdentityMatrix();
result = matrixMultiply(result, targetTriangleMat);
result = matrixMultiply(result, math.inv(inputTriangleMat));
result = matrixMultiply(result, tranlateMat);
return result
}
function getDirectionalScaleMatrix(scaleX, scaleY, direction) {
var ret = getIdentityMatrix();
ret = matrixMultiply(ret, getRotatoinMatrix(direction));
ret = matrixMultiply(ret, getScaleMatrix(scaleX, scaleY));
ret = matrixMultiply(ret, getRotatoinMatrix(-direction));
return ret;
}
function getRotatoinMatrix(inRotation) {
var toRads = inRotation * Math.PI / 180.0;
return [
[Math.cos(toRads), -Math.sin(toRads), 0],
[Math.sin(toRads), Math.cos(toRads), 0],
[0, 0, 1]
];
}
function getTranslateMatrix(x, y) {
return [
[1, 0, x],
[0, 1, y],
[0, 0, 1]
];
}
function getIdentityMatrix() {
return [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
];
}
//a = [1,0,0], b = [[1],[0],[0]]
//[1,0,0]*[[1],[0],[0]] = [1]
function matrixMultiply(a, b) {
var aNumRows = a.length, aNumCols = a[0].length,
bNumRows = b.length, bNumCols = b[0].length,
m = new Array(aNumRows); // initialize array of rows
for (var r = 0; r < aNumRows; ++r) {
m[r] = new Array(bNumCols); // initialize the current row
for (var c = 0; c < bNumCols; ++c) {
m[r][c] = 0; // initialize the current cell
for (var i = 0; i < aNumCols; ++i) {
m[r][c] += a[r][i] * b[i][c];
}
}
}
return m;
}
function convertSingleKeypointToMatrix(keypoint) {
return [[keypoint.x], [keypoint.y], [1]];
}
function convertKeypointsToMatrixKeypoints(keypoints) {
var ret = [];
for (var i = 0; i < keypoints.length; i++) {
var newKeypoint = convertSingleKeypointToMatrix(keypoints[i]);
ret.push(newKeypoint);
}
return ret;
}
function convertTransformationObjectToTransformationMatrix(transformations) {
var transformationCenterPoint = transformations.transformationCenterPoint;
var ret = getIdentityMatrix();
//Translate
ret = matrixMultiply(ret, getTranslateMatrix(-transformations.translate.x, -transformations.translate.y));
ret = matrixMultiply(ret, getTranslateMatrix(transformationCenterPoint.x, transformationCenterPoint.y));
ret = matrixMultiply(ret, getScaleMatrix(transformations.uniformScale, transformations.uniformScale));
//Rotate
ret = matrixMultiply(ret, getTranslateMatrix(-transformations.translate.x, -transformations.translate.y));
ret = matrixMultiply(ret, getRotatoinMatrix(-transformations.rotation));
ret = matrixMultiply(ret, getTranslateMatrix(transformations.translate.x, transformations.translate.y));
//Scale
ret = matrixMultiply(ret, transformations.directionalScaleMatrix);
ret = matrixMultiply(ret, getTranslateMatrix(-transformationCenterPoint.x, -transformationCenterPoint.y));
return ret;
}
function applyTransformationMatToSingleKeypoint(keypoint, transformationMat) {
return matrixMultiply(transformationMat, keypoint);
}
function applyTransformationMatrixToAllKeypoints(keypoints, transformationMat) {
var ret = [];
for (var i = 0; i < keypoints.length; i++) {
var transformedKeypoint = applyTransformationMatToSingleKeypoint(keypoints[i], transformationMat);
ret.push(transformedKeypoint);
}
return ret;
}
function applyTransformationMatrixToAllKeypointsObjects(keypoints, transformationMat) {
var keypointsToken1 = convertKeypointsToMatrixKeypoints(keypoints);
var keypointsToken2 = applyTransformationMatrixToAllKeypoints(keypointsToken1, transformationMat);
var keypointsToken3 = convertMatrixKeypointsToKeypointObjects(keypointsToken2);
return keypointsToken3;
}
function convertSingleMatrixKeypoinToKeypointObject(arrayKeypoint) {
return {
x: (arrayKeypoint[0][0] == undefined) ? arrayKeypoint[0] : arrayKeypoint[0][0],
y: (arrayKeypoint[1][0] == undefined) ? arrayKeypoint[1] : arrayKeypoint[1][0],
};
}
function convertMatrixKeypointsToKeypointObjects(keypoints) {
var ret = [];
for (var i = 0; i < keypoints.length; i++) {
ret.push(convertSingleMatrixKeypoinToKeypointObject(keypoints[i]))
}
return ret;
}
function computeTransformedKeypoints(keypoints, transformationMat) {
//turn the keypoints into arrays with an extra 1 at the end. {x: 2, y: 3} ---> [[2],[3],[1]]
var newKeypoints = convertKeypointsToMatrixKeypoints(keypoints);
//then mult each keypoint
var finalArrayKeypoints = applyTransformationMatrixToAllKeypoints(newKeypoints, transformationMat);
//convert back to keypoint objects
var finalKeypoints = convertMatrixKeypointsToKeypointObjects(finalArrayKeypoints);
return finalKeypoints;
}
function addTwoPoints(point1, point2) {
return {
x: point1.x + point2.x,
y: point1.y + point2.y
}
}
function minusTwoPoints(point1, point2) {
return {
x: point1.x - point2.x,
y: point1.y - point2.y
}
}
function generateRandomKeypoints(imageSize, numberOfKeypoints) {
var ret = [];
for (var i = 0; i < numberOfKeypoints; i++) {
var x = Math.floor((Math.random() * imageSize.width));
var y = Math.floor((Math.random() * imageSize.height));
var kp = {
x: x,
y: y
};
ret.push(kp)
}
return ret;
}
function applyTransformationMatToSingleTriangle(triangle, transformationMatrix) {
var transformedTriangle = [];
for (var i = 0; i < triangle.length; i++) {
var tempKeypoint1 = convertSingleKeypointToMatrix(triangle[i]);
var tempKeypoint2 = applyTransformationMatToSingleKeypoint(tempKeypoint1, transformationMatrix);
var tempKeypoint3 = convertSingleMatrixKeypoinToKeypointObject(tempKeypoint2);
transformedTriangle.push(tempKeypoint3);
}
return transformedTriangle;
}
function applyTransformationToTriangles(triangles, transformationMatrix) {
var ret = [];
for (var i = 0; i < triangles.length; i++) {
var currentTriangle = triangles[i];
var temp = applyTransformationMatToSingleTriangle(currentTriangle, transformationMatrix);
ret.push(temp);
}
return ret;
}
function getEuclideanDistance(point1, point2) {
var a = point1.x - point2.x;
var b = point1.y - point2.y;
return Math.sqrt(a * a + b * b);
}
function filterValidPoints(headPoint, tailcombs, maxPntDist, minPntDist) {
var ret = [];
for (var i = 0; i < tailcombs.length; i++) {
var currPt = tailcombs[i];
var dist = getEuclideanDistance(currPt, headPoint);
if (dist < maxPntDist && dist > minPntDist) {
ret.push([currPt]);
}
}
return ret;
}
function computeTriangles(inKeypoints, maxPntDist, minPntDist, minTriArea) {
var ret = [];
for (var i = 0; i < inKeypoints.length - 2; i++) {
var keypoint = inKeypoints[i];
var tail = inKeypoints.slice(i + 1);
var subsetOfValidPoints = filterValidPoints(keypoint, tail, maxPntDist, minPntDist);
var combs = k_combinations(subsetOfValidPoints, 2);
for (var j = 0; j < combs.length; j++) {
var currComb = combs[j];
var tempTriangle = [keypoint, currComb[0][0], currComb[1][0]];
if (getArea(tempTriangle) < minTriArea) {
//invalid triangle ignore
continue;
}
ret.push(tempTriangle);
}
}
return ret;
}
function k_combinations(set, k) {
var i, j, combs, head, tailcombs;
// There is no way to take e.g. sets of 5 elements from
// a set of 4.
if (k > set.length || k <= 0) {
return [];
}
// K-sized set has only one K-sized subset.
if (k == set.length) {
return [set];
}
// There is N 1-sized subsets in a N-sized set.
if (k == 1) {
combs = [];
for (i = 0; i < set.length; i++) {
combs.push([set[i]]);
}
return combs;
}
// Assert {1 < k < set.length}
// Algorithm description:
// To get k-combinations of a set, we want to join each element
// with all (k-1)-combinations of the other elements. The set of
// these k-sized sets would be the desired result. However, as we
// represent sets with lists, we need to take duplicates into
// account. To avoid producing duplicates and also unnecessary
// computing, we use the following approach: each element i
// divides the list into three: the preceding elements, the
// current element i, and the subsequent elements. For the first
// element, the list of preceding elements is empty. For element i,
// we compute the (k-1)-computations of the subsequent elements,
// join each with the element i, and store the joined to the set of
// computed k-combinations. We do not need to take the preceding
// elements into account, because they have already been the i:th
// element so they are already computed and stored. When the length
// of the subsequent list drops below (k-1), we cannot find any
// (k-1)-combs, hence the upper limit for the iteration:
combs = [];
for (i = 0; i < set.length - k + 1; i++) {
// head is a list that includes only our current element.
head = set.slice(i, i + 1);
// We take smaller combinations from the subsequent elements
tailcombs = k_combinations(set.slice(i + 1), k - 1);
// For each (k-1)-combination we join it with the current
// and store it to the set of k-combinations.
for (j = 0; j < tailcombs.length; j++) {
combs.push(head.concat(tailcombs[j]));
}
}
return combs;
}
// #####
// # # ##### ## # #
// # # # # # # # #
// # # # # # # # #
// # # ##### ###### # ## #
// # # # # # # ## ##
// ##### # # # # # #
//draw
function drawFragment(baseCanvas, fragmentCanvasContext, fragmentTriangle) {
fragmentCanvasContext.save();
paintCanvasWhite(fragmentCanvasContext);
//rotate 180 degrees around image center
fragmentCanvasContext.translate(fragmentCanvasContext.canvas.width / 2, fragmentCanvasContext.canvas.height / 2);
fragmentCanvasContext.rotate(180.0 * Math.PI / 180);
fragmentCanvasContext.translate(-fragmentCanvasContext.canvas.width / 2, -fragmentCanvasContext.canvas.height / 2);
var mat = calcTransformationMatrixToEquilateralTriangle(fragmentTriangle);
fragmentCanvasContext.transform(mat[0][0], mat[1][0], mat[0][1], mat[1][1], mat[0][2], mat[1][2]);
fragmentCanvasContext.drawImage(baseCanvas, 0, 0);
fragmentCanvasContext.restore();
fragmentCanvasContext.save();
cropCanvasImage(fragmentCanvasContext, getTargetTriangleRotated180());
fragmentCanvasContext.restore();
}
function highlightTriangle(layerIndex, triangleIndex) {
$(".triangleTRAll").removeClass("selectedTriangleTR");
$(".triangleTR" + layerIndex + "_" + triangleIndex).addClass("selectedTriangleTR");
var layerTriangleMap = g_globalState.outputListState.triangleMapArray[layerIndex];
var triangleStruct = layerTriangleMap.get(triangleIndex);
var interactiveHighlightedCanvasContext = g_globalState.interactiveCanvasState.highlightedTriangleLayerCanvasContext;
var referenceHighlightedCanvasContext = g_globalState.referenceCanvasState.highlightedTriangleLayerCanvasContext;
//draw the outline of the triangle on the original canvas
var enableFill = true;
clearCanvasByContext(interactiveHighlightedCanvasContext);
drawTriangleWithColour(interactiveHighlightedCanvasContext, triangleStruct.interactiveTriangle,
[255, 255, 255], [24, 61, 78], enableFill);
clearCanvasByContext(referenceHighlightedCanvasContext);
drawTriangleWithColour(referenceHighlightedCanvasContext, triangleStruct.referenceTriangle,
[255, 255, 255], [24, 61, 78], enableFill);
//fill the fragment canvases
var interactiveCanvas = g_globalState.interactiveCanvasState.imageLayerCanvas;
var interactiveFragmentCanvasContext = g_globalState.interactiveCanvasState.fragmentCanvasContext;
drawFragment(interactiveCanvas, interactiveFragmentCanvasContext, triangleStruct.interactiveTriangle);
var referenceCanvas = g_globalState.referenceCanvasState.imageLayerCanvas;
var referenceFragmentCanvasContext = g_globalState.referenceCanvasState.fragmentCanvasContext;
drawFragment(referenceCanvas, referenceFragmentCanvasContext, triangleStruct.referenceTriangle);
//Update pHash output
var pHash1 = pHash(interactiveFragmentCanvasContext.canvas);
var pHash2 = pHash(referenceFragmentCanvasContext.canvas);
var pHashDistance = distance(pHash1, pHash2);
$("#pHashDistanceOutputWrapper").html("" + pHashDistance + "");
}
function drawBackgroudImageWithTransformationMatrix(canvasContext, image, transformationMat) {
canvasContext.save();
var mat = transformationMat;
canvasContext.transform(mat[0][0], mat[1][0], mat[0][1], mat[1][1], mat[0][2], mat[1][2]);
canvasContext.drawImage(image, 0, 0);
canvasContext.restore();
}
function drawLineFromPointToMousePosition(ctx) {
// ctx.save();
// drawLine(mouseDownPoint, mouseCurrentPoint);
// ctx.restore();
}
function drawTriangleWithColour(ctx, tri, strokeColour, fillColour, enableFill) {
var alpha = 0.01;
if(setAlpha)
alpha = .01;
ctx.strokeStyle = 'rgba(' + strokeColour[0] + ', ' + strokeColour[1] + ' ,' + strokeColour[2] + ', ' + alpha + ')';
//ctx.fillStyle = 'rgba(255, 255, 255, 0.09)';
ctx.beginPath();
ctx.moveTo(tri[0].x, tri[0].y);
ctx.lineTo(tri[1].x, tri[1].y);
ctx.lineTo(tri[2].x, tri[2].y);
ctx.closePath();
ctx.stroke();
if (enableFill) {
ctx.fillStyle = 'rgba(' + fillColour[0] + ', ' + fillColour[1] + ' ,' + fillColour[2] + ', ' + .9 + ')';
ctx.fill();
}
}
function drawKeypoints(interactiveCanvasContext, keypoints, colourString) {
var backUpWidth = interactiveCanvasContext.lineWidth;
interactiveCanvasContext.lineWidth = 2;
if(colourString) {
interactiveCanvasContext.strokeStyle = colourString;
} else {
interactiveCanvasContext.strokeStyle = "red";
}
interactiveCanvasContext.beginPath();
for (var i = 0; i < keypoints.length; i++) {
var currentKeypoint = keypoints[i];
let ctx = interactiveCanvasContext;
ctx.beginPath();
ctx.arc(currentKeypoint.x,currentKeypoint.y,3,0,2*Math.PI);
ctx.fill();
ctx.stroke();
//interactiveCanvasContext.rect(currentKeypoint.x, currentKeypoint.y, 3, 3);
}
interactiveCanvasContext.closePath();
interactiveCanvasContext.stroke();
interactiveCanvasContext.lineWidth = backUpWidth;
}
function drawTriangle(ctx, tri, colour) {
drawTriangleWithColour(ctx, tri, colour, null/*fill colour*/, false/*enable fill*/);
}
function getColourForIndex(pointDistance) {
for (var i = 0; i < g_steps.length; i++) {
if (pointDistance > g_steps[i].minPntDist && pointDistance < g_steps[i].maxPntDist) {
return g_steps[i].colour;
}
}
console.log("Invalid colour/points distance")
return [0, 0, 0];
}
function drawTriangles(canvasContext, triangles, colour) {
canvasContext.beginPath();
for (var i = 0; i < triangles.length; i++) {
if (i >= MAX_TRIANGLES_DRAW) {
break;
}
// var colour = getColourForIndex(getEuclideanDistance(triangles[i][0], triangles[i][1]));
drawTriangle(canvasContext, triangles[i], colour);
}
canvasContext.stroke();
}
function drawClosingPolygon(ctx, inPoints, showFillEffect) {
if (inPoints.length == 0) {
return;
}
ctx.strokeStyle = 'rgba(0, 0, 0, 0.0)';
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, 512);
ctx.lineTo(512, 512);
ctx.lineTo(512, 0);
ctx.closePath();
ctx.moveTo(inPoints[0].x, inPoints[0].y);
for (var i = 1; i < inPoints.length; i++) {//i = 1 to skip first point
var currentPoint = inPoints[i];
ctx.lineTo(currentPoint.x, currentPoint.y);
}
ctx.closePath();
//fill
ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
if (showFillEffect) {
ctx.fillStyle = 'rgba(242, 242, 242, 0.3)';
ctx.strokeStyle = 'rgba(255, 0, 0, 0.9)';
}
ctx.fill('evenodd'); //for firefox 31+, IE 11+, chrome
//ctx.stroke();
};
function isPointInPolygon(point, vs) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var x = point.x, y = point.y;
var inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
var xi = vs[i].x, yi = vs[i].y;
var xj = vs[j].x, yj = vs[j].y;
var intersect = ((yi > y) != (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
};
function filterKeypointsOutsidePolygon(keypoints, coords) {
if (coords.length == 0) {
return keypoints;
}
var ret = [];
for (var i = 0; i < keypoints.length; i++) {
var keypoint = keypoints[i];
if (isPointInPolygon(keypoint, coords)) {
ret.push(keypoint);
}
}
return ret;
}
function getTransformedCroppingPointsMatrix(croppingPoints, transformationMatrix) {
var ret = [];
for (var i = 0; i < croppingPoints.length; i++) {
var point = croppingPoints[i];
var point2 = convertSingleKeypointToMatrix(point);
var transformedPoint = applyTransformationMatToSingleKeypoint(point2, transformationMatrix);
var point3 = convertSingleMatrixKeypoinToKeypointObject(transformedPoint);
ret.push(point3);
}
return ret;
}
function isAnyPointsOutsideCanvas(triangle, canvasDimensions) {
for (var i = 0; i < triangle.length; i++) {
var point = triangle[i];
if (
point.x > canvasDimensions.width ||
point.x < 0 ||
point.y > canvasDimensions.height ||
point.y < 0) {
//invalid triangle
return true;
}
}
return false;
}
function checkIfAllPointsInPolygon(triangle, croppingPointsPoly) {
for (var i = 0; i < triangle.length; i++) {
var point = triangle[i];
if (!isPointInPolygon(point, croppingPointsPoly)) {
return false;
}
}
return true;
}
function isValidKeypoints(currentKeypoint, validKeypoints) {
for (var i = 0; i < validKeypoints.length; i++) {
var validKeypoint = validKeypoints[i];
if (getEuclideanDistance(validKeypoint, currentKeypoint) < 1.0) {
return true;
}
}
return false;
}
function areAllKeypointsValid(triangle, validKeypoints) {
for (var j = 0; j < triangle.length; j++) {
var currentKeypoint = triangle[j];
if (isValidKeypoints(currentKeypoint, validKeypoints)) {
} else {
return false;
}
}
return true;
}
//Returns the filtered triangle along with the triangles previous index
function filterInvalidTriangles(triangles, validKeypoints, minPntDist, maxPntDist, minTriArea) {
var ret = [];
for (var i = 0; i < triangles.length; i++) {
var triangle = triangles[i];
if (!areAllKeypointsValid(triangle, validKeypoints)) {
continue;
}
//FIXME: THIS TRIANGLE FILERING STUFF IS JUNK!!! FIX IT
var d1 = getEuclideanDistance(triangle[0], triangle[1]);
var d2 = getEuclideanDistance(triangle[0], triangle[2]);
if (d1 > minPntDist
&& d1 < maxPntDist
&& d2 > minPntDist
&& d2 < maxPntDist
&& getArea(triangle) > minTriArea
) {
ret.push({index: i, triangle: triangle});
} else {
//Invalid triangle, ignore
}
}
return ret;
}
function getAllTrianglesFromIndexTriangleObjects(trianglesAndIndex) {
var ret = [];
for (var i = 0; i < trianglesAndIndex.length; i++) {
ret.push(trianglesAndIndex[i].triangle);
}
return ret;
}
function containsMatchingPoint(tri, currPt) {
for (var i = 0; i < tri.length; i++) {
var comparePt = tri[i];
if (comparePt.x == currPt.x && comparePt.y == currPt.y) {
return true;
}
}
return false;
}
function areAllPointsMatching(tri1, tri2) {
for (var i = 0; i < tri1.length; i++) {
var currPt = tri1[i];
if (containsMatchingPoint(tri2, currPt)) {
} else {
//if any of the points don't match it's not a matching triangle
return false;
}
}
return true;
}
function containsMatchingTriangleWithIndexes(addedReferenceTrianglesWithIndex, refTri) {
for (var i = 0; i < addedReferenceTrianglesWithIndex.length; i++) {
var currTri = addedReferenceTrianglesWithIndex[i].triangle;
if (areAllPointsMatching(refTri, currTri)) {
return true;
}
}
return false;
}
function containsMatchingTriangle(addedReferenceTriangles, refTri) {
for (var i = 0; i < addedReferenceTriangles.length; i++) {
var currTri = addedReferenceTriangles[i];
if (areAllPointsMatching(refTri, currTri)) {
return true;
}
}
return false;
}
function getTableEntry(key, layerIndex, area) {
//FIXME: i don't like these hardcoded strings
var outputStrClass = "triangleTRAll " + "triangleTR" + layerIndex + "_" + key.value;
var outputStr =
"<tr class=\"" + outputStrClass + "\" onmouseover=\"highlightTriangle(" + layerIndex + ", " + key.value + ")\">" +
"<td>" + key.value + "</td>" +
"<td>" + Math.round(area) + " </td>" +
"</tr>";
return outputStr;
}
function paintCanvasWhite(canvasContext) {
const canvas = canvasContext.canvas;
canvasContext.fillStyle = "#FFFFFF";
canvasContext.fillRect(0, 0, canvas.width, canvas.height); // clear canvas
}
function filterInvalidTrianglesForAllSteps(triangles, validKeypoints) {
var filteredReferenceImageTrianglesForAllSteps = [];
for (var i = 0; i < g_steps.length; i++) {
var currentStep = g_steps[i];
var tempFilteredReferenceImageTriangles = filterInvalidTriangles(triangles,
validKeypoints, currentStep.minPntDist, currentStep.maxPntDist, currentStep.minTriArea);
//add all the triangles while avoiding adding duplicates
for (var j = 0; j < tempFilteredReferenceImageTriangles.length; j++) {
var currentTriangleWithindex = tempFilteredReferenceImageTriangles[j];
if (containsMatchingTriangleWithIndexes(filteredReferenceImageTrianglesForAllSteps, currentTriangleWithindex.triangle)) {
//ignore, don't add duplicates
} else {
filteredReferenceImageTrianglesForAllSteps.push(currentTriangleWithindex);
}
}
}
return filteredReferenceImageTrianglesForAllSteps;
}
function drawPolygonPath(ctx, inPoints) {
ctx.moveTo(inPoints[0].x, inPoints[0].y);
for (var i = 1; i < inPoints.length; i++) {//i = 1 to skip first point
var currentPoint = inPoints[i];
ctx.lineTo(currentPoint.x, currentPoint.y);
}
ctx.closePath();
}
function cropCanvasImage(ctx, inPoints) {
if (inPoints.length == 0) {
return;
}
ctx.beginPath();
drawPolygonPath(ctx, inPoints);
ctx.globalCompositeOperation = 'destination-in';
ctx.fill('evenodd');
}
function getTemporaryCanvasContext(canvasSize) {
var tempCanvasElement = document.createElement('canvas');
tempCanvasElement.width = canvasSize.width;
tempCanvasElement.height = canvasSize.height;
var ctx = tempCanvasElement.getContext("2d");
return ctx;
}
function cropLayerImage(transformedImage, croppingPolygon) {
var ctx = getTemporaryCanvasContext(transformedImage);
ctx.drawImage(transformedImage, 0, 0);
cropCanvasImage(ctx, croppingPolygon);
return ctx.canvas;
}
function applyCroppingEffectToCanvas(ctx, inPoints) {
if (inPoints.length == 0) {
return;
}
ctx.beginPath();
drawPolygonPath(ctx, buildRect(ctx.canvas.width, ctx.canvas.height));
drawPolygonPath(ctx, inPoints);
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = 'rgba(255,255,255,0.3)';
ctx.fill('evenodd');
}
function applyCroppingEffectToImage(canvasSize, transformedImage, croppingPolygon) {
var ctx = getTemporaryCanvasContext(canvasSize);
ctx.drawImage(transformedImage, 0, 0);
applyCroppingEffectToCanvas(ctx, croppingPolygon);
return ctx.canvas;
}
function drawImageOutlineWithLayer(canvasContext, layer) {
var imageOutline = applyTransformationToImageOutline(layer.nonTransformedImageOutline, layer.appliedTransformations);
drawLayerImageOutline(canvasContext, imageOutline);
}
function clearCanvasByContext(context) {
var canvas = context.canvas;
context.clearRect(0, 0, canvas.width, canvas.height);
}
function drawImageOutlineInternal() {
var referenceImageOutlineContext = g_globalState.referenceCanvasState.imageOutlineLayerCanvasContext;
var referenceLayerUnderMouse = g_globalState.referenceCanvasState.imageOutlineHighlightLayer;
clearCanvasByContext(referenceImageOutlineContext);
if (referenceLayerUnderMouse != null && g_drawingOptions.drawImageOutline) {
drawImageOutlineWithLayer(referenceImageOutlineContext, referenceLayerUnderMouse);
}
var interactiveImageOutlineContext = g_globalState.interactiveCanvasState.imageOutlineLayerCanvasContext;
var interactiveLayerUnderMouse = g_globalState.interactiveCanvasState.imageOutlineHighlightLayer;
clearCanvasByContext(interactiveImageOutlineContext);
if (interactiveLayerUnderMouse != null && g_drawingOptions.drawImageOutline) {
drawImageOutlineWithLayer(interactiveImageOutlineContext, interactiveLayerUnderMouse);
}
window.requestAnimationFrame(drawImageOutlineInternal);
}
function isKeypointOccluded(keypoint, layers) {
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
var imageOutline = applyTransformationToImageOutline(layer.nonTransformedImageOutline, layer.appliedTransformations)
if (isPointInPolygon(keypoint, imageOutline)) {
return true;
}
}
return false;
}
function getNonOccludedKeypoints(keypoints, layers) {
var result = [];
for (var i = 0; i < keypoints.length; i++) {
var keypoint = keypoints[i];
if (isKeypointOccluded(keypoint, layers)) {
//ignore occluded keypoints
} else {
result.push(keypoint);
}
}
return result;
}
function drawUiLayer(canvasContext, keypoints, triangles, layerColour) {
if (!setAlpha){
drawKeypoints(canvasContext, keypoints);
}
drawTriangles(canvasContext, triangles, layerColour);
}
function drawLayerWithAppliedTransformations(canvasState, drawingLayer, dontCropImage) {
const imageCanvasContext = canvasState.imageLayerCanvasContext;
const uiCanvasContext = canvasState.uiLayerCanvasContext;
var drawingImage;
if (dontCropImage) {
drawingImage = drawingLayer.layer.image;
} else {
drawingImage = cropLayerImage(drawingLayer.layer.image, drawingLayer.layer.nonTransformedImageOutline);
}
var transformationsMat = drawingLayer.layer.appliedTransformations;
drawBackgroudImageWithTransformationMatrix(imageCanvasContext, drawingImage, transformationsMat);
if (canvasState == g_globalState.interactiveCanvasState) {
setAlpha = true;
} else {
setAlpha = false;
}
//drawUiLayer(uiCanvasContext, drawingLayer.transformedVisableKeypoints, drawingLayer.computedTriangles, drawingLayer.layer.colour);
}
function clearOutputListAndWipeCanvas() {
$("#triangleListBody").html("");
var c1 = g_globalState.interactiveCanvasState.highlightedTriangleLayerCanvasContext;
var c2 = g_globalState.referenceCanvasState.highlightedTriangleLayerCanvasContext;
clearCanvasByContext(c1);
clearCanvasByContext(c2);
}
function generateOutputList(triangleMapArray) {
var outputStr = "";
for (var i = 0; i < triangleMapArray.length; i++) {
var triangleMap = triangleMapArray[i];
var keys = triangleMap.keys();
for (var key = keys.next(); !key.done; key = keys.next()) { //iterate over keys
var tri = triangleMap.get(key.value).referenceTriangle;
var area = getArea(tri);
outputStr = outputStr + getTableEntry(key, i, area);
}
}
$("#triangleListBody").html(outputStr);
$(".list-group-item").hover(function () {
$(this).addClass("active");
},
function () {
$(this).removeClass("active");
});
g_globalState.outputListState.triangleMapArray = triangleMapArray;
}
function drawCroppingEffect(canvasContext, imageOutline) {
canvasContext.beginPath();
drawPolygonPath(canvasContext, buildRect(canvasContext.canvas.width, canvasContext.canvas.height));
drawPolygonPath(canvasContext, imageOutline);
canvasContext.globalCompositeOperation = 'source-over';
canvasContext.fillStyle = 'rgba(255, 255, 255, 0.5)';
canvasContext.fill('evenodd');
}
var drawingLayer = {
transformedVisableKeypoints: null,
}
function buildDrawingLayer(transformedVisableKeypoints, computedTriangles, layer) {
return {
layer: layer,
transformedVisableKeypoints: transformedVisableKeypoints,
computedTriangles: computedTriangles
}
}
function filterPointsOutsideOfCanvas(keypoints, canvasDimensions) {
var ret = [];
for (var i = 0; i < keypoints.length; i++) {
var keypoint = keypoints[i];
if (keypoint.x >= canvasDimensions.width
|| keypoint.x < 0
|| keypoint.y >= canvasDimensions.height
|| keypoint.y < 0) {
//ignore this keypoint
} else {
ret.push(keypoint)
}
}
return ret;
}
//FIXME: comment
function filterKeypoints(keypoints, transformedImageOutline, transformationsMat, layersOnTop, canvasDimensions) {
var keypointsToken1 = applyTransformationMatrixToAllKeypointsObjects(keypoints, transformationsMat);
var keypointsToken2 = filterKeypointsOutsidePolygon(keypointsToken1, transformedImageOutline);
var keypointsToken3 = getNonOccludedKeypoints(keypointsToken2, layersOnTop);
var keypointsToken4 = filterPointsOutsideOfCanvas(keypointsToken3, canvasDimensions);
return keypointsToken4;
}
//FIXME: comment this function!!
function buildInteractiveCanvasDrawingLayers(canvasDimensions, layers) {
var resultMap = new Map();
var result = [];
for (var i = 0; i < layers.length; i++) {
var currentLayer = layers[i];
var transformedImageOutline = applyTransformationToImageOutline(currentLayer.nonTransformedImageOutline, currentLayer.appliedTransformations);
var layersOnTop = layers.slice(0, i);
var filteredKeypoints = filterKeypoints(currentLayer.keypoints, transformedImageOutline, currentLayer.appliedTransformations, layersOnTop, canvasDimensions);
//compute the triangles FIXME: extract to method
var computedTrianglesForAllSteps = [];
for (var j = 0; j < g_steps.length; j++) {
var currentStep = g_steps[j];
var tempTriangles = computeTriangles(filteredKeypoints, currentStep.maxPntDist, currentStep.minPntDist, currentStep.minTriArea);
computedTrianglesForAllSteps = computedTrianglesForAllSteps.concat(tempTriangles);
if(computedTrianglesForAllSteps.length > MAX_TRIANGLES_DRAW){
break;
}
}
var computedTrianglesForAllSteps = filteredTrianglesByImageOutlineIntersection(layersOnTop, computedTrianglesForAllSteps);
const drawingLayer = buildDrawingLayer(filteredKeypoints, computedTrianglesForAllSteps, currentLayer);
resultMap.set(currentLayer, drawingLayer);
result.push(drawingLayer);
}
return [resultMap, result];
}
function _extractTriangles(filteredTrianglesWithIndex) {
var result = [];
for (var i = 0; i < filteredTrianglesWithIndex.length; i++) {
result.push(filteredTrianglesWithIndex[i].triangle);
}
return result;
}
function getCenterPointOfPoly(arr) {
var minX, maxX, minY, maxY;
for(var i=0; i< arr.length; i++){
minX = (arr[i].x < minX || minX == null) ? arr[i].x : minX;
maxX = (arr[i].x > maxX || maxX == null) ? arr[i].x : maxX;
minY = (arr[i].y < minY || minY == null) ? arr[i].y : minY;
maxY = (arr[i].y > maxY || maxY == null) ? arr[i].y : maxY;
}
return [(minX + maxX) /2, (minY + maxY) /2];
}
function arrayToPolygonObject(shapeArray) {
var arrayCenter = getCenterPointOfPoly(shapeArray);
var result = new Polygon({x: arrayCenter[0], y: arrayCenter[1]}, "#0000FF");
for (var i = 0; i < shapeArray.length; i++) {
result.addAbsolutePoint(shapeArray[i]);
}
return result;
}
function triangleIntersectsPolygon(triangle, imageOutline) {
var trianglePoly = arrayToPolygonObject(triangle);
var imageOutlinePoly = arrayToPolygonObject(imageOutline);
return trianglePoly.intersectsWith(imageOutlinePoly);
}
function triangleIntersectsLayers(triangle, layersOnTop) {
for (var i = 0; i < layersOnTop.length; i++) {
var currentLayer = layersOnTop[i];
var imageOutline = applyTransformationToImageOutline(currentLayer.nonTransformedImageOutline, currentLayer.appliedTransformations);
if (triangleIntersectsPolygon(triangle, imageOutline)){
return true;
}
}
return false;
}
function filteredTrianglesByImageOutlineIntersection(layersOnTop, filteredTrianglesWithIndex) {
var result = [];
for (var i = 0; i < filteredTrianglesWithIndex.length; i++) {
var currentTriangle = filteredTrianglesWithIndex[i];
if (triangleIntersectsLayers(currentTriangle, layersOnTop)){
//filter
} else {
result.push(filteredTrianglesWithIndex[i]);
}
}
return result;
}
function buildReferenceCanvasDrawingLayers(canvasDimensions, layers, drawingLayersByInteractiveImageLayer) {
var result = [];
var filteredTrianglesWithIndexInLayerArray = [];
for (var i = 0; i < layers.length; i++) {
var currentLayer = layers[i];
var associatedLayer = currentLayer.associatedLayer;
var transformationMat = math.inv(associatedLayer.appliedTransformations);
var interactiveImageDrawingLayer = drawingLayersByInteractiveImageLayer.get(associatedLayer);
var associatedLayerVisableKeypoints = applyTransformationMatrixToAllKeypointsObjects(interactiveImageDrawingLayer.transformedVisableKeypoints, transformationMat);
var nonTransformedTriangles = applyTransformationToTriangles(interactiveImageDrawingLayer.computedTriangles, transformationMat);
var transformedTriangles = applyTransformationToTriangles(nonTransformedTriangles, currentLayer.appliedTransformations);
var transformedImageOutline = applyTransformationToImageOutline(currentLayer.nonTransformedImageOutline, currentLayer.appliedTransformations);
var layersOnTop = layers.slice(0, i);
var filteredKeypoints = filterKeypoints(associatedLayerVisableKeypoints, transformedImageOutline, currentLayer.appliedTransformations, layersOnTop, canvasDimensions);
var filteredTrianglesWithIndex = filterInvalidTrianglesForAllSteps(transformedTriangles, filteredKeypoints);
var filteredTriangles = _extractTriangles(filteredTrianglesWithIndex);
result.push(buildDrawingLayer(filteredKeypoints, filteredTriangles, currentLayer));
filteredTrianglesWithIndexInLayerArray.push({
layer: currentLayer,
trianglesWithIndex: filteredTrianglesWithIndex
});
}
return [result, filteredTrianglesWithIndexInLayerArray];
}
function drawLayers(canvasState, drawingLayers) {
var imageCanvasContext = canvasState.imageLayerCanvasContext;
paintCanvasWhite(imageCanvasContext);
var uiCanvasContext = canvasState.uiLayerCanvasContext;
clearCanvasByContext(uiCanvasContext);
//check if a cropping effect needs to be applied
var isCrop = g_globalState.currentTranformationOperationState == enum_TransformationOperation.CROP;
var isCroppingEffectActive = g_globalState.isMouseDownAndClickedOnCanvas && isCrop;
for (var i = 0; i < drawingLayers.length; i++) {
var idx = (drawingLayers.length - 1) - i;
var drawingLayer = drawingLayers[idx];
var isActiveCanvas = g_globalState.activeCanvas == canvasState;
var isActiveLayer = canvasState.activeLayer == drawingLayer.layer;
var dontCropImage = isActiveLayer && isCroppingEffectActive && isActiveCanvas;
drawLayerWithAppliedTransformations(canvasState, drawingLayer, dontCropImage);
}
if (isCroppingEffectActive) {
var appliedTransformations = g_globalState.activeCanvas.activeLayer.appliedTransformations;
var imageOutlineToken1 = g_globalState.activeCanvas.activeLayer.nonTransformedImageOutline;
var transformedImageOutline = applyTransformationToImageOutline(imageOutlineToken1, appliedTransformations);
var canvasContext = g_globalState.activeCanvas.imageLayerCanvasContext;
drawCroppingEffect(canvasContext, transformedImageOutline);
}
}
//FIXME: this is really hacky
function buildInteractiveTriangleByReferenceTriangleMap(filteredTrianglesWithIndexInLayerArray, interactiveImageDrawingLayersByInteractiveImageLayer) {
var interactiveTriangleByReferenceTriangleMapInLayerArray = [];
for (var i = 0; i < filteredTrianglesWithIndexInLayerArray.length; i++) {
var interactiveTriangleByReferenceTriangleMap = new Map();
var currentLayer = filteredTrianglesWithIndexInLayerArray[i].layer;
var associatedDrawingLayer = interactiveImageDrawingLayersByInteractiveImageLayer.get(currentLayer.associatedLayer)
var trianglesWithindex = filteredTrianglesWithIndexInLayerArray[i].trianglesWithIndex;
for (var j = 0; j < trianglesWithindex.length; j++) {
var index = trianglesWithindex[j].index;
var referenceTriangle = trianglesWithindex[j].triangle;
var associatedTriangle = associatedDrawingLayer.computedTriangles[index];
interactiveTriangleByReferenceTriangleMap.set(index, {
referenceTriangle: referenceTriangle,
interactiveTriangle: associatedTriangle
});
}
interactiveTriangleByReferenceTriangleMapInLayerArray.push(interactiveTriangleByReferenceTriangleMap);
}
return interactiveTriangleByReferenceTriangleMapInLayerArray;
}
function draw() {
var interactiveCanvasLayers = g_globalState.interactiveCanvasState.layers;
var isInteractiveCanvasActive = g_globalState.activeCanvas == g_globalState.interactiveCanvasState;
var tempRet = buildInteractiveCanvasDrawingLayers(g_globalState.activeCanvas.imageLayerCanvas, interactiveCanvasLayers);
var interactiveImageDrawingLayersByInteractiveImageLayer = tempRet[0];
var interactiveImageDrawingLayers = tempRet[1];
drawLayers(g_globalState.interactiveCanvasState, interactiveImageDrawingLayers, isInteractiveCanvasActive);
var referenceCanvasLayers = g_globalState.referenceCanvasState.layers;
var isReferenceCanvasActive = g_globalState.activeCanvas == g_globalState.referenceCanvasState;
var canvasDimensions = g_globalState.referenceCanvasState.imageLayerCanvasContext.canvas;
var returnValueContainer = buildReferenceCanvasDrawingLayers(canvasDimensions, referenceCanvasLayers, interactiveImageDrawingLayersByInteractiveImageLayer);
var referenceImageDrawingLayers = returnValueContainer[0];
var filteredTrianglesWithIndexInLayerArray = returnValueContainer[1];
var triangleMapByReferenceTriangleIndex = buildInteractiveTriangleByReferenceTriangleMap(filteredTrianglesWithIndexInLayerArray, interactiveImageDrawingLayersByInteractiveImageLayer);
drawLayers(g_globalState.referenceCanvasState, referenceImageDrawingLayers, isReferenceCanvasActive);
return triangleMapByReferenceTriangleIndex;
}
// # # ###
// # # #### ###### ##### # # # ##### # # #####
// # # # # # # # ## # # # # # #
// # # #### ##### # # # # # # # # # # #
// # # # # ##### # # # # ##### # # #
// # # # # # # # # # ## # # # #
// ##### #### ###### # # ### # # # #### #
//user input
function changeCanvasSize(canvas, newWidth, newHeight) {
canvas.width = newWidth;
canvas.height = newHeight;
}
function changeCanvasSizeByState(canvasState, newWidth, newHeight) {
changeCanvasSize(canvasState.uiLayerCanvas, newWidth, newHeight);
changeCanvasSize(canvasState.imageLayerCanvas, newWidth, newHeight);
changeCanvasSize(canvasState.imageOutlineLayerCanvas, newWidth, newHeight);
changeCanvasSize(canvasState.highlightedTriangleLayerCanvas, newWidth, newHeight);
}
function changeReferenceCanvasSize(width, height) {
changeCanvasSizeByState(g_globalState.referenceCanvasState, width, height);
$(".referenceCanvasWrapper").width(width);
$(".referenceCanvasWrapper").height(height);
draw();
}
function changeInteractiveCanvasSize(width, height) {
changeCanvasSizeByState(g_globalState.interactiveCanvasState, width, height);
$(".interactiveCanvasWrapper").width(width);
$(".interactiveCanvasWrapper").height(height);
draw();
}
$(document).mousedown(function (e) {
//ignore
});
$(document).mousemove(function (e) {
if (g_globalState != null && g_globalState.isMouseDownAndClickedOnCanvas) {
g_globalState.referenceImageHighlightedTriangle = null;
g_globalState.activeCanvas.imageOutlineHighlightLayer = g_globalState.activeCanvas.activeLayer;
handleMouseMoveOnDocument(e);
draw();
clearOutputListAndWipeCanvas();
}
});
$(document).mouseup(function (e) {
if (g_globalState != null && g_globalState.isMouseDownAndClickedOnCanvas) {
handleMouseUp(e);
g_globalState.isMouseDownAndClickedOnCanvas = false;
//FIXME: finish this and extract to method
var triangleMapArray = draw();
generateOutputList(triangleMapArray);
}
});
$("#" + INTERACTIVE_CANVAS_OVERLAY_ID).mousedown(function (e) {
if (g_globalState == null) {
return;
}
g_globalState.activeCanvas = g_globalState.interactiveCanvasState;
e.preventDefault();
g_globalState.isMouseDownAndClickedOnCanvas = true;
handleMouseDownOnCanvas(e);
});
$("#" + INTERACTIVE_CANVAS_OVERLAY_ID).mousemove(function (e) {
if (g_globalState == null) {
return;
}
const layers = g_globalState.interactiveCanvasState.layers;
const canvasContext = g_globalState.interactiveCanvasState.imageOutlineLayerCanvasContext;
var canvasMousePosition = getCurrentCanvasMousePosition(e);
g_globalState.interactiveCanvasState.imageOutlineHighlightLayer = getActiveLayerWithCanvasPosition(canvasMousePosition, layers, null);
if (g_globalState == null || g_globalState.activeCanvas != g_globalState.interactiveCanvasState) {
return;
}
var canvasMousePosition = getCurrentCanvasMousePosition(e);
console.log(canvasMousePosition);
if (g_globalState.isMouseDownAndClickedOnCanvas) {
handleMouseMoveOnCanvas(e);
}
});
$("#" + INTERACTIVE_CANVAS_OVERLAY_ID).mouseup(function (e) {
if (g_globalState == null) {
return;
}
//ignore
});
$("#" + REFERENCE_CANVAS_OVERLAY_ID).mousedown(function (e) {
if (g_globalState == null) {
return;
}
g_globalState.activeCanvas = g_globalState.referenceCanvasState;
e.preventDefault();
g_globalState.isMouseDownAndClickedOnCanvas = true;
handleMouseDownOnCanvas(e);
});
$("#" + REFERENCE_CANVAS_OVERLAY_ID).mousemove(function (e) {
if (g_globalState == null) {
return;
}
const layers = g_globalState.referenceCanvasState.layers;
const canvasContext = g_globalState.referenceCanvasState.imageOutlineLayerCanvasContext;
var canvasMousePosition = getCurrentCanvasMousePosition(e);
g_globalState.referenceCanvasState.imageOutlineHighlightLayer = getActiveLayerWithCanvasPosition(canvasMousePosition, layers, null);
if (g_globalState == null || g_globalState.activeCanvas != g_globalState.referenceCanvasState) {
return;
}
if (g_globalState.isMouseDownAndClickedOnCanvas) {
handleMouseMoveOnCanvas(e);
}
});
$("#" + REFERENCE_CANVAS_OVERLAY_ID).mouseup(function (e) {
if (g_globalState == null) {
return;
}
//ignore
});
function getCurrentPageMousePosition(e) {
return {
x: e.pageX,
y: e.pageY
};
}
function getCurrentCanvasMousePosition(e) {
if (e.offsetX || e.offsetX === 0) {
return {
x: e.offsetX,
y: e.offsetY
};
} else if (e.layerX || e.offsetX === 0) {
return {
x: e.layerX,
y: e.layerY
};
} else {
console.log("Error: Invalid state");
}
}
function filterPointsOutsideImage(imageOutline, imageDimensions) {
var result = [];
for (var i = 0; i < imageOutline.length; i++) {
var point = imageOutline[i];
var x = point.x, y = point.y;
if (point.x < 0) {
x = 0;
}
if (point.x > imageDimensions.width) {
x = imageDimensions.width;
}
if (point.y < 0) {
y = 0;
}
if (point.y > imageDimensions.height) {
y = imageDimensions.height;
}
result.push({x: x, y: y});
}
return result;
}
function handleMouseUpCrop(mousePosition, activeLayer) {
var imageOutline = activeLayer.nonTransformedImageOutline;
var imageDimensions = {
width: activeLayer.image.width,
height: activeLayer.image.height
};
activeLayer.nonTransformedImageOutline = filterPointsOutsideImage(imageOutline, imageDimensions);
var area = calcPolygonArea(activeLayer.nonTransformedImageOutline);
if (area < MIN_CROPPING_POLYGON_AREA) {
activeLayer.nonTransformedImageOutline = buildRectangularCroppingPolyFromLayer(activeLayer);
activeLayer.croppingPolygonInverseMatrix = getIdentityMatrix();
}
}
function handleMouseUp(e) {
var pageMousePosition = getCurrentPageMousePosition(e);
var canvasMousePosition = getCurrentCanvasMousePosition(e);
var globalState = g_globalState;
switch (g_globalState.currentTranformationOperationState) {
case enum_TransformationOperation.TRANSLATE:
break;
case enum_TransformationOperation.NON_UNIFORM_SCALE:
break;
case enum_TransformationOperation.UNIFORM_SCALE:
break;
case enum_TransformationOperation.ROTATE:
break;
case enum_TransformationOperation.CROP:
var activeLayer = g_globalState.activeCanvas.activeLayer;
handleMouseUpCrop(canvasMousePosition, activeLayer);
break;
default:
console.log("ERROR: Invalid state.");
break;
}
wipeTemporaryAppliedTransformations();
}
function handleMouseMoveTranslate(pageMouseDownPosition, pageMousePosition, globalState) {
var translateDelta = minusTwoPoints(pageMouseDownPosition, pageMousePosition);
globalState.temporaryAppliedTransformations.translate = translateDelta;
}
function handleMouseMoveNonUniformScale(pageMouseDownPosition, pageMousePosition, globalState) {
var mouseDownPoint = pageMouseDownPosition;
var y = (pageMousePosition.y - mouseDownPoint.y);
var x = (pageMousePosition.x - mouseDownPoint.x);
var extraRotation = Math.atan2(y, x) * (180.0 / Math.PI) * -1;
if (extraRotation < 0) {
extraRotation = (360 + (extraRotation));
}
direction = extraRotation % 360;
scale = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
scale += 50;//skip all the fractions, 1 is the minimum scale
scale /= 50;
scaleMatrix = getDirectionalScaleMatrix(Math.sqrt(scale), 1 / Math.sqrt(scale), -direction);
globalState.temporaryAppliedTransformations.directionalScaleMatrix = scaleMatrix;
}
function handleMouseMoveUniformScale(pageMouseDownPosition, pageMousePosition, globalState) {
var mouseDownPoint = pageMouseDownPosition;
var y = (pageMousePosition.y - mouseDownPoint.y);
// var x = (pageMousePosition.x - mouseDownPoint.x);
scale = y;//(Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)));
if (y > 0) {
scale += 100;
scale = 1 / (scale / 100);
} else {
scale *= -1;//make y positive
scale += 100;
scale /= 100;
}
globalState.temporaryAppliedTransformations.uniformScale = scale;
}
function handleMouseMoveRotate(pageMouseDownPosition, pageMousePosition, globalState) {
var mouseDownPoint = pageMouseDownPosition;
var y = (pageMousePosition.y - mouseDownPoint.y);
var x = (pageMousePosition.x - mouseDownPoint.x);
var extraRotation = Math.atan2(y, x) * (180.0 / Math.PI) * -1;
if (extraRotation < 0) {
extraRotation = (360 + (extraRotation));
}
extraRotation = extraRotation % 360;
globalState.temporaryAppliedTransformations.rotation = extraRotation;
}
function handleMouseMoveCrop(mousePosition, activeLayer) {
var invMat = math.inv(activeLayer.appliedTransformations);
var keypointMat = convertSingleKeypointToMatrix(mousePosition);
var transformedPointMat = applyTransformationMatToSingleKeypoint(keypointMat, invMat);
var transformedPoint = convertSingleMatrixKeypoinToKeypointObject(transformedPointMat);
activeLayer.nonTransformedImageOutline.push(transformedPoint);
}
function applyTemporaryTransformationsToActiveLayer() {
var layer = getActiveLayer(g_globalState);
var temporaryAppliedTransformationsMat = convertTransformationObjectToTransformationMatrix(g_globalState.temporaryAppliedTransformations);
var savedLayerMat = g_globalState.transformationMatBeforeTemporaryTransformations;
layer.appliedTransformations = matrixMultiply(temporaryAppliedTransformationsMat, savedLayerMat);
}
function handleMouseMoveOnDocument(e) {
var pageMousePosition = getCurrentPageMousePosition(e);
var globalState = g_globalState;
switch (globalState.currentTranformationOperationState) {
case enum_TransformationOperation.TRANSLATE:
handleMouseMoveTranslate(globalState.pageMouseDownPosition, pageMousePosition, globalState);
break;
case enum_TransformationOperation.NON_UNIFORM_SCALE:
handleMouseMoveNonUniformScale(globalState.pageMouseDownPosition, pageMousePosition, globalState);
break;
case enum_TransformationOperation.UNIFORM_SCALE:
handleMouseMoveUniformScale(globalState.pageMouseDownPosition, pageMousePosition, globalState);
break;
case enum_TransformationOperation.ROTATE:
handleMouseMoveRotate(globalState.pageMouseDownPosition, pageMousePosition, globalState);
break;
case enum_TransformationOperation.CROP:
//ignore, handled in canvas on mouse move function
break;
default:
console.log("ERROR: Invalid state.");
break;
}
applyTemporaryTransformationsToActiveLayer();
}
function drawLayerImageOutline(ctx, imageOutlinePolygon) {
if (imageOutlinePolygon.length == 0) {
return;
}
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.beginPath();
ctx.moveTo(imageOutlinePolygon[0].x, imageOutlinePolygon[0].y);
for (var i = 1; i < imageOutlinePolygon.length; i++) {//i = 1 to skip first point
var currentPoint = imageOutlinePolygon[i];
ctx.lineTo(currentPoint.x, currentPoint.y);
}
ctx.closePath();
ctx.lineWidth = 2;
ctx.strokeStyle = '#2196F3';
ctx.stroke();
}
function handleMouseMoveOnCanvas(e) {
var canvasMousePosition = getCurrentCanvasMousePosition(e);
switch (g_globalState.currentTranformationOperationState) {
case enum_TransformationOperation.TRANSLATE:
//do nothing
break;
case enum_TransformationOperation.NON_UNIFORM_SCALE:
//do nothing
break;
case enum_TransformationOperation.UNIFORM_SCALE:
//do nothing
break;
case enum_TransformationOperation.ROTATE:
//do nothing
break;
case enum_TransformationOperation.CROP:
var activeLayer = g_globalState.activeCanvas.activeLayer;
handleMouseMoveCrop(canvasMousePosition, activeLayer);
break;
default:
console.log("ERROR: Invalid state.");
break;
}
}
function handleMouseDownCrop(activeLayer) {
//The nonTransformedImageOutline is never allowed to be an empty list
//so onMouseUp if the nonTransformedImageOutline is still empty then
//it is replaced with the outline of the image with no cropping
activeLayer.nonTransformedImageOutline = [];
}
function getActiveLayerWithCanvasPosition(canvasMousePosition, layers, noMatchReturnValue) {
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
var imageOutline = applyTransformationToImageOutline(layer.nonTransformedImageOutline, layer.appliedTransformations);
//take the cropping shape
if (isPointInPolygon(canvasMousePosition, imageOutline)) {
return layer;
}
}
return noMatchReturnValue;
}
function handleMouseDownOnCanvas(e) {
const pageMousePosition = getCurrentPageMousePosition(e);
const canvasMousePosition = getCurrentCanvasMousePosition(e);
g_globalState.pageMouseDownPosition = pageMousePosition;
g_globalState.temporaryAppliedTransformations.transformationCenterPoint = canvasMousePosition;
//FIXME: set the active canvas
const currentActiveLayer = g_globalState.activeCanvas.activeLayer;
const clickedActiveLayer = getActiveLayerWithCanvasPosition(canvasMousePosition, g_globalState.activeCanvas.layers, currentActiveLayer);
g_globalState.activeCanvas.activeLayer = clickedActiveLayer;
g_globalState.transformationMatBeforeTemporaryTransformations = clickedActiveLayer.appliedTransformations;
switch (g_globalState.currentTranformationOperationState) {
case enum_TransformationOperation.TRANSLATE:
//do nothing
break;
case enum_TransformationOperation.NON_UNIFORM_SCALE:
//do nothing
break;
case enum_TransformationOperation.UNIFORM_SCALE:
//do nothing
break;
case enum_TransformationOperation.ROTATE:
//do nothing
break;
case enum_TransformationOperation.CROP:
handleMouseDownCrop(clickedActiveLayer);
break;
default:
console.log("ERROR: Invalid state.");
break;
}
}
function applyTransformationEffects(state) {
if (state == enum_TransformationOperation.TRANSLATE) {
$(".twoCanvasWrapper").addClass("move");
} else {
$(".twoCanvasWrapper").removeClass("move");
}
}
function setCurrnetOperation(newState) {
g_globalState.currentTranformationOperationState = newState;
applyTransformationEffects(newState);
}
function buildCommonCanvasState(imageCanvasId, overlayCanvasId, imageOutlineCanvasId, fragmentCanvasId,
highlightedTriangleLayerId, preloadedImage) {
var returnedCanvasState = newCanvasState();
returnedCanvasState.uiLayerId = overlayCanvasId;
returnedCanvasState.uiLayerCanvas = document.getElementById(overlayCanvasId);
returnedCanvasState.uiLayerCanvasContext = document.getElementById(overlayCanvasId).getContext('2d');
returnedCanvasState.imageLayerId = imageCanvasId;
returnedCanvasState.imageLayerCanvas = document.getElementById(imageCanvasId);
returnedCanvasState.imageLayerCanvasContext = document.getElementById(imageCanvasId).getContext('2d');
returnedCanvasState.imageOutlineLayerId = imageOutlineCanvasId;
returnedCanvasState.imageOutlineLayerCanvas = document.getElementById(imageOutlineCanvasId);
returnedCanvasState.imageOutlineLayerCanvasContext = document.getElementById(imageOutlineCanvasId).getContext('2d');
returnedCanvasState.highlightedTriangleLayerId = highlightedTriangleLayerId;
returnedCanvasState.highlightedTriangleLayerCanvas = document.getElementById(highlightedTriangleLayerId);
returnedCanvasState.highlightedTriangleLayerCanvasContext = document.getElementById(highlightedTriangleLayerId).getContext('2d');
returnedCanvasState.fragmentCanvasId = fragmentCanvasId;
returnedCanvasState.fragmentCanvas = document.getElementById(fragmentCanvasId);
returnedCanvasState.fragmentCanvasContext = document.getElementById(fragmentCanvasId).getContext('2d');
returnedCanvasState.imageOutlineHighlightLayer = null;//The layer with a blue outline around the image
returnedCanvasState.layers = [];
//FIXME: reference image layers done have keypoints, they are computed from the associated interactive image layer
var keypoints = generateRandomKeypoints({
width: preloadedImage.width,
height: preloadedImage.height
}, g_numberOfKeypoints)
returnedCanvasState.layers.push(newLayer(preloadedImage, keypoints, BLUE_COLOUR));
returnedCanvasState.activeLayer = returnedCanvasState.layers[0];
return returnedCanvasState;
}
function buildReferenceCanvasState() {
return buildCommonCanvasState(REFERENCE_CANVAS_ID, REFERENCE_CANVAS_OVERLAY_ID,
REFERENCE_CANVAS_IMAGE_OUTLINE_ID, REFERENCE_FRAGMENT_CANVAS_ID, REFERENCE_HIGHLIGHTED_CANVAS_ID,
_g_preloadImage);
}
function buildInteractiveCanvasState() {
return buildCommonCanvasState(INTERACTIVE_CANVAS_ID, INTERACTIVE_CANVAS_OVERLAY_ID,
INTERACTIVE_CANVAS_IMAGE_OUTLINE_ID, INTERACTIVE_FRAGMENT_CANVAS_ID, INTERACTIVE_HIGHLIGHTED_CANVAS_ID,
_g_preloadImage);
}
function buildGlobalState() {
var resultingGlobalState = newGlobalState();//TODO: FIXME:
const referenceCanvasState = buildReferenceCanvasState();
const interactiveCanvasState = buildInteractiveCanvasState();
//FIXME: come up with a better way of handling associatedLayers
referenceCanvasState.layers[0].associatedLayer = interactiveCanvasState.layers[0];
interactiveCanvasState.layers[0].associatedLayer = referenceCanvasState.layers[0];
resultingGlobalState.activeCanvas = interactiveCanvasState;
resultingGlobalState.referenceCanvasState = referenceCanvasState;
resultingGlobalState.interactiveCanvasState = interactiveCanvasState;
resultingGlobalState.isMouseDownAndClickedOnCanvas = false;
resultingGlobalState.currentTranformationOperationState = enum_TransformationOperation.TRANSLATE;
resultingGlobalState.temporaryAppliedTransformations = getIdentityTransformations();
resultingGlobalState.pageMouseDownPosition = {x: 0, y: 0};
resultingGlobalState.outputListState = {
triangleMapArray: null
};
return resultingGlobalState;
}
function initAfterImageLoad() {
g_globalState = buildGlobalState();
setCurrnetOperation(enum_TransformationOperation.TRANSLATE);
draw();
window.requestAnimationFrame(drawImageOutlineInternal);
}
function loadImageAndInit(imageSrc) {
_g_linesImage1 = new Image();
_g_linesImage1.src = "images/lines1.png";
_g_linesImage2 = new Image();
_g_linesImage2.src = "images/lines2.png";
_g_linesImage3 = new Image();
_g_linesImage3.src = "images/lines3.png";
_g_linesImage4 = new Image();
_g_linesImage4.src = "images/lines4.png";
_g_linesImage5 = new Image();
_g_linesImage5.src = "images/lines5.png";
_g_preloadImage = new Image();
_g_preloadImage.src = imageSrc;
_g_preloadImage.onload = function () {
initAfterImageLoad();
};
}
//fixme: remove this
function _debug_addlayer(imageSrc) {
var image;
image = new Image();
image.src = imageSrc;
image.onload = function () {
var keypoints = generateRandomKeypoints({width: image.width, height: image.height}, g_numberOfKeypoints);
var layer1 = newLayer(image, keypoints, ORANGE_COLOUR);
var layer2 = newLayer(image, null, ORANGE_COLOUR);
layer1.associatedLayer = layer2;
layer2.associatedLayer = layer1;
g_globalState.interactiveCanvasState.layers.push(layer1);
g_globalState.referenceCanvasState.layers.push(layer2);
};
}
var start = 0;
function animateStep(timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start;
temporaryAppliedTransformations.rotation = progress / 100 % 360;
temporaryAppliedTransformations.uniformScale = progress / 100000 % 360;
console.log(progress % 360);
if (temporaryAppliedTransformations.uniformScale < 1) {
window.requestAnimationFrame(animateStep);
}
g_skipListGen = true;
g_forceApplyTransformations = true;
draw();
g_forceApplyTransformations = false;
g_skipListGen = false;
}
function animate() {
temporaryAppliedTransformations.transformationCenterPoint = {
x: 280 / 2,
y: 280 / 2
};
window.requestAnimationFrame(animateStep);
}
function init() {
loadImageAndInit('images/morty.png');
}
init();
var animationStartTime;
var end = false;
var animationStartMatrix;
var mult = 1;
var g_triangleKeypoints = [{x: 150, y: 20}, {x: 20, y: 200}, {x: 200, y: 200}];
function repeatTheLastFrame3(frame) {
console.log("final transform of frag");
var animationFrames = 15 * mult;
animationStart();
draw();
var percentageDone = frame / animationFrames;
let imageFragment1;
let imageWithWhiteTri1;
let shape = g_triangleKeypoints;
{
let layer1 = g_globalState.referenceCanvasState.layers[0];
transformedShape1 = applyTransformationMatrixToAllKeypointsObjects(shape, layer1.appliedTransformations);
let referenceCanvas = g_globalState.referenceCanvasState.imageLayerCanvas;
let referenceCanvasContext = g_globalState.referenceCanvasState.imageLayerCanvasContext;
imageFragment1 = referenceCanvas;
imageFragment1 = cropLayerImage(referenceCanvas, transformedShape1);
referenceCanvasContext.beginPath();
drawPolygonPath(referenceCanvasContext, transformedShape1);
referenceCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
referenceCanvasContext.fill();
imageWithWhiteTri1 = referenceCanvas
}
let imageFragment2;
let imageWithWhiteTri2;
let transformedShape2;
{
let layer2 = g_globalState.interactiveCanvasState.layers[0];
transformedShape2 = applyTransformationMatrixToAllKeypointsObjects(shape, layer2.appliedTransformations);
let interactiveCanvas = g_globalState.interactiveCanvasState.imageLayerCanvas;
let interactiveCanvasContext = g_globalState.interactiveCanvasState.imageLayerCanvasContext;
imageFragment2 = cropLayerImage(interactiveCanvas, transformedShape2);
interactiveCanvasContext.beginPath();
drawPolygonPath(interactiveCanvasContext, transformedShape2);
interactiveCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
interactiveCanvasContext.fill();
imageWithWhiteTri2 = interactiveCanvas
}
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
clearCanvasByContext(ctx);
paintCanvasWhite(ctx);
ctx.save();
{
// ctx.drawImage(imageWithWhiteTri2, 0, 0);
var nk = g_triangleKeypoints;
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
//drawTheTriangle(ctx, 100, nk);
let mat = calcTransformationMatrixToEquilateralTriangle(nk2);
mat = matrixMultiply(getTranslateMatrix(70, 30), mat);
per = percentageDone;
var transMat = [
[1+((mat[0][0]-1)), 0+(mat[0][1]-0), 0+(mat[0][2]-0)],
[0+(mat[1][0]-0), 1+(mat[1][1]-1), 0+(mat[1][2]-0)],
[0, 0, 1]
]
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk3, transMat);
var fillStr = 'rgba(255, 255, 255, ' + (1.0 - (percentageDone/2)) + ')';
ctx.strokeStyle = fillStr;
ctx.fillStyle = fillStr;
drawTheTriangle(ctx, 100, nk3, fillStr);
drawKeypoints(ctx, nk3, fillStr);
ctx.save();
ctx.transform(1 + ((mat[0][0] - 1)), 0 + (mat[1][0] - 0), 0 + (mat[0][1] - 0), 1 + (mat[1][1] - 1) , 0 + (mat[0][2] - 0), 0 + (mat[1][2] - 0));
// ctx.translate(0, 100);
ctx.drawImage(imageFragment2, 40, 10);
ctx.restore();
//drawTheTriangle(ctx, 100, nk3);
}
// ctx.drawImage(imageWithWhiteTri1, 0, 0);
ctx.restore();
ctx.save();
{
// ctx.drawImage(imageWithWhiteTri1, 380, 0);
var nk = g_triangleKeypoints;
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
let mat = calcTransformationMatrixToEquilateralTriangle(nk2);
mat = matrixMultiply(getTranslateMatrix(430, 100), mat);
per = percentageDone;
var transMat = [
[1+((mat[0][0]-1)), 0+(mat[0][1]-0), 0+(mat[0][2]-0)],
[0+(mat[1][0]-0), 1+(mat[1][1]-1), 0+(mat[1][2]-0)],
[0, 0, 1]
];
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
nk = applyTransformationMatrixToAllKeypointsObjects(nk, transMat);
var fillStr = 'rgba(255, 255, 255, ' + (1.0 - (percentageDone/2)) + ')';
ctx.strokeStyle = fillStr;
ctx.fillStyle = fillStr;
drawTheTriangle(ctx, 100, nk, fillStr);
drawKeypoints(ctx, nk, fillStr);
ctx.save();
ctx.transform(1+((mat[0][0]-1)), 0+(mat[1][0]-0), 0+(mat[0][1]-0), 1+(mat[1][1]-1), 0+(mat[0][2]-0), 0+(mat[1][2]-0));
// ctx.translate(0, 100);
ctx.drawImage(imageFragment1, 380, 10);
ctx.restore();
// drawTheTriangle(ctx, 100, nk);
}
ctx.restore();
if (g_showText) {
ctx.drawImage(_g_linesImage3, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function repeatTheLastFrame2(frame) {
console.log("final transform of frag");
var animationFrames = 60 * mult;
animationStart();
draw();
var percentageDone = frame / animationFrames;
let imageFragment1;
let imageWithWhiteTri1;
let shape = g_triangleKeypoints;
{
let layer1 = g_globalState.referenceCanvasState.layers[0];
transformedShape1 = applyTransformationMatrixToAllKeypointsObjects(shape, layer1.appliedTransformations);
let referenceCanvas = g_globalState.referenceCanvasState.imageLayerCanvas;
let referenceCanvasContext = g_globalState.referenceCanvasState.imageLayerCanvasContext;
imageFragment1 = referenceCanvas;
imageFragment1 = cropLayerImage(referenceCanvas, transformedShape1);
referenceCanvasContext.beginPath();
drawPolygonPath(referenceCanvasContext, transformedShape1);
referenceCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
referenceCanvasContext.fill();
imageWithWhiteTri1 = referenceCanvas
}
let imageFragment2;
let imageWithWhiteTri2;
let transformedShape2;
{
let layer2 = g_globalState.interactiveCanvasState.layers[0];
transformedShape2 = applyTransformationMatrixToAllKeypointsObjects(shape, layer2.appliedTransformations);
let interactiveCanvas = g_globalState.interactiveCanvasState.imageLayerCanvas;
let interactiveCanvasContext = g_globalState.interactiveCanvasState.imageLayerCanvasContext;
imageFragment2 = cropLayerImage(interactiveCanvas, transformedShape2);
interactiveCanvasContext.beginPath();
drawPolygonPath(interactiveCanvasContext, transformedShape2);
interactiveCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
interactiveCanvasContext.fill();
imageWithWhiteTri2 = interactiveCanvas
}
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
clearCanvasByContext(ctx);
paintCanvasWhite(ctx);
ctx.save();
{
// ctx.drawImage(imageWithWhiteTri2, 0, 0);
var nk = g_triangleKeypoints;
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
//drawTheTriangle(ctx, 100, nk);
let mat = calcTransformationMatrixToEquilateralTriangle(nk2);
mat = matrixMultiply(getTranslateMatrix(70, 30), mat);
per = percentageDone;
var transMat = [
[1+((mat[0][0]-1)), 0+(mat[0][1]-0), 0+(mat[0][2]-0)],
[0+(mat[1][0]-0), 1+(mat[1][1]-1), 0+(mat[1][2]-0)],
[0, 0, 1]
]
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk3, transMat);
var fillStr = 'rgba(255, 255, 255, ' + (1.0 - (percentageDone/2)) + ')';
ctx.strokeStyle = fillStr;
ctx.fillStyle = fillStr;
drawTheTriangle(ctx, 100, nk3, fillStr);
drawKeypoints(ctx, nk3, fillStr);
ctx.save();
ctx.transform(1 + ((mat[0][0] - 1)), 0 + (mat[1][0] - 0), 0 + (mat[0][1] - 0), 1 + (mat[1][1] - 1) , 0 + (mat[0][2] - 0), 0 + (mat[1][2] - 0));
// ctx.translate(0, 100);
ctx.drawImage(imageFragment2, 40, 10);
ctx.restore();
//drawTheTriangle(ctx, 100, nk3);
}
// ctx.drawImage(imageWithWhiteTri1, 0, 0);
ctx.restore();
ctx.save();
{
// ctx.drawImage(imageWithWhiteTri1, 380, 0);
var nk = g_triangleKeypoints;
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
let mat = calcTransformationMatrixToEquilateralTriangle(nk2);
mat = matrixMultiply(getTranslateMatrix(430, 100), mat);
per = percentageDone;
var transMat = [
[1+((mat[0][0]-1)), 0+(mat[0][1]-0), 0+(mat[0][2]-0)],
[0+(mat[1][0]-0), 1+(mat[1][1]-1), 0+(mat[1][2]-0)],
[0, 0, 1]
];
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
nk = applyTransformationMatrixToAllKeypointsObjects(nk, transMat);
var fillStr = 'rgba(255, 255, 255, ' + (1.0 - (percentageDone/2)) + ')';
ctx.strokeStyle = fillStr;
ctx.fillStyle = fillStr;
drawTheTriangle(ctx, 100, nk, fillStr);
drawKeypoints(ctx, nk, fillStr);
ctx.save();
ctx.transform(1+((mat[0][0]-1)), 0+(mat[1][0]-0), 0+(mat[0][1]-0), 1+(mat[1][1]-1), 0+(mat[0][2]-0), 0+(mat[1][2]-0));
// ctx.translate(0, 100);
ctx.drawImage(imageFragment1, 380, 10);
ctx.restore();
// drawTheTriangle(ctx, 100, nk);
}
ctx.restore();
if (g_showText) {
ctx.drawImage(_g_linesImage5, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function repeatTheLastFrame(frame) {
var animationFrames = 60 * mult;
animationStart();
draw();
var percentageDone = frame / animationFrames;
let imageFragment1;
let imageWithWhiteTri1;
let shape = g_triangleKeypoints;
{
let layer1 = g_globalState.referenceCanvasState.layers[0];
transformedShape1 = applyTransformationMatrixToAllKeypointsObjects(shape, layer1.appliedTransformations);
let referenceCanvas = g_globalState.referenceCanvasState.imageLayerCanvas;
let referenceCanvasContext = g_globalState.referenceCanvasState.imageLayerCanvasContext;
imageFragment1 = referenceCanvas;
imageFragment1 = cropLayerImage(referenceCanvas, transformedShape1);
referenceCanvasContext.beginPath();
drawPolygonPath(referenceCanvasContext, transformedShape1);
referenceCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
referenceCanvasContext.fill();
imageWithWhiteTri1 = referenceCanvas
}
let imageFragment2;
let imageWithWhiteTri2;
let transformedShape2;
{
let layer2 = g_globalState.interactiveCanvasState.layers[0];
transformedShape2 = applyTransformationMatrixToAllKeypointsObjects(shape, layer2.appliedTransformations);
let interactiveCanvas = g_globalState.interactiveCanvasState.imageLayerCanvas;
let interactiveCanvasContext = g_globalState.interactiveCanvasState.imageLayerCanvasContext;
imageFragment2 = cropLayerImage(interactiveCanvas, transformedShape2);
interactiveCanvasContext.beginPath();
drawPolygonPath(interactiveCanvasContext, transformedShape2);
interactiveCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
interactiveCanvasContext.fill();
imageWithWhiteTri2 = interactiveCanvas
}
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
clearCanvasByContext(ctx);
paintCanvasWhite(ctx);
ctx.save();
{
// ctx.drawImage(imageWithWhiteTri2, 0, 0);
var nk = g_triangleKeypoints;
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
//drawTheTriangle(ctx, 100, nk);
let mat = calcTransformationMatrixToEquilateralTriangle(nk2);
mat = matrixMultiply(getTranslateMatrix(70, 30), mat);
per = percentageDone;
var transMat = [
[1+((mat[0][0]-1)), 0+(mat[0][1]-0), 0+(mat[0][2]-0)],
[0+(mat[1][0]-0), 1+(mat[1][1]-1), 0+(mat[1][2]-0)],
[0, 0, 1]
]
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk3, transMat);
var fillStr = 'rgba(255, 255, 255, ' + (1.0 - (percentageDone/2)) + ')';
ctx.strokeStyle = fillStr;
ctx.fillStyle = fillStr;
drawTheTriangle(ctx, 100, nk3, fillStr);
drawKeypoints(ctx, nk3, fillStr);
ctx.save();
ctx.transform(1 + ((mat[0][0] - 1)), 0 + (mat[1][0] - 0), 0 + (mat[0][1] - 0), 1 + (mat[1][1] - 1) , 0 + (mat[0][2] - 0), 0 + (mat[1][2] - 0));
// ctx.translate(0, 100);
ctx.drawImage(imageFragment2, 40, 10);
ctx.restore();
//drawTheTriangle(ctx, 100, nk3);
}
// ctx.drawImage(imageWithWhiteTri1, 0, 0);
ctx.restore();
ctx.save();
{
// ctx.drawImage(imageWithWhiteTri1, 380, 0);
var nk = g_triangleKeypoints;
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
let mat = calcTransformationMatrixToEquilateralTriangle(nk2);
mat = matrixMultiply(getTranslateMatrix(430, 100), mat);
per = percentageDone;
var transMat = [
[1+((mat[0][0]-1)), 0+(mat[0][1]-0), 0+(mat[0][2]-0)],
[0+(mat[1][0]-0), 1+(mat[1][1]-1), 0+(mat[1][2]-0)],
[0, 0, 1]
];
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
nk = applyTransformationMatrixToAllKeypointsObjects(nk, transMat);
var fillStr = 'rgba(255, 255, 255, ' + (1.0 - (percentageDone/2)) + ')';
ctx.strokeStyle = fillStr;
ctx.fillStyle = fillStr;
drawTheTriangle(ctx, 100, nk, fillStr);
drawKeypoints(ctx, nk, fillStr);
ctx.save();
ctx.transform(1+((mat[0][0]-1)), 0+(mat[1][0]-0), 0+(mat[0][1]-0), 1+(mat[1][1]-1), 0+(mat[0][2]-0), 0+(mat[1][2]-0));
// ctx.translate(0, 100);
ctx.drawImage(imageFragment1, 380, 10);
ctx.restore();
// drawTheTriangle(ctx, 100, nk);
}
ctx.restore();
if (g_showText) {
ctx.drawImage(_g_linesImage4, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function fadeInKeypoints(frame) {
var animationFrames = 10*mult;//60*mult
var percentageDone = frame / animationFrames;
//now cut the fragment
animationStart();
// var percentageDone = frame/animationFrames;
// var endx = 80;
// var endy = 80;
// g_globalState.temporaryAppliedTransformations.translate = {
// x: -endx*percentageDone,
// y: -endy*percentageDone
// };
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
animationEnd(frame);
var nk = g_triangleKeypoints;
nonTransformedImage = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
ctx.globalAlpha = percentageDone;
var keypoints1 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints1 = applyTransformationMatrixToAllKeypointsObjects(keypoints1, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
var shape = g_globalState.interactiveCanvasState.layers[0].nonTransformedImageOutline;
shape = applyTransformationMatrixToAllKeypointsObjects(shape, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
keypoints1 = filterKeypointsOutsidePolygon(keypoints1, buildRect(280, 280));
keypoints_ = applyTransformationMatrixToAllKeypointsObjects(keypoints1, getTranslateMatrix(40, 10));
drawKeypoints(ctx, keypoints_, "blue");
var keypoints2 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints2 = applyTransformationMatrixToAllKeypointsObjects(keypoints2, getTranslateMatrix(380, 10));
drawKeypoints(ctx, keypoints2, "blue");
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk2, getTranslateMatrix(40, 10));
drawKeypoints(ctx, nk3, "blue");
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
drawKeypoints(ctx, nk2, "blue");
ctx.globalAlpha = 1;
ctx.globalAlpha = 1.0;
if (g_showText) {
ctx.drawImage(_g_linesImage1, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function repeatShowingPlainKeypoints2(frame) {
var animationFrames = 20*mult;//60*mult
var percentageDone = frame / animationFrames;
//now cut the fragment
animationStart();
// var percentageDone = frame/animationFrames;
// var endx = 80;
// var endy = 80;
// g_globalState.temporaryAppliedTransformations.translate = {
// x: -endx*percentageDone,
// y: -endy*percentageDone
// };
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
animationEnd(frame);
var nk = g_triangleKeypoints;
nonTransformedImage = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(310, 10));
ctx.globalAlpha = 1;
var keypoints1 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints1 = applyTransformationMatrixToAllKeypointsObjects(keypoints1, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
var shape = g_globalState.interactiveCanvasState.layers[0].nonTransformedImageOutline;
shape = applyTransformationMatrixToAllKeypointsObjects(shape, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
keypoints1 = filterKeypointsOutsidePolygon(keypoints1, buildRect(280, 280));
keypoints_ = applyTransformationMatrixToAllKeypointsObjects(keypoints1, getTranslateMatrix(40, 10));
drawKeypoints(ctx, keypoints_, "blue");
var keypoints2 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints2 = applyTransformationMatrixToAllKeypointsObjects(keypoints2, getTranslateMatrix(380, 10));
drawKeypoints(ctx, keypoints2, "blue");
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk2, getTranslateMatrix(40, 10));
drawKeypoints(ctx, nk3, "blue");
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
drawKeypoints(ctx, nk2, "blue");
ctx.globalAlpha = 1;
ctx.globalAlpha = 1.0;
if (g_showText) {
ctx.drawImage(_g_linesImage2, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function repeatShowingPlainKeypoints(frame) {
var animationFrames = 20*mult;//60*mult
var percentageDone = frame / animationFrames;
//now cut the fragment
animationStart();
// var percentageDone = frame/animationFrames;
// var endx = 80;
// var endy = 80;
// g_globalState.temporaryAppliedTransformations.translate = {
// x: -endx*percentageDone,
// y: -endy*percentageDone
// };
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
animationEnd(frame);
var nk = g_triangleKeypoints;
nonTransformedImage = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(310, 10));
ctx.globalAlpha = 1;
var keypoints1 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints1 = applyTransformationMatrixToAllKeypointsObjects(keypoints1, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
var shape = g_globalState.interactiveCanvasState.layers[0].nonTransformedImageOutline;
shape = applyTransformationMatrixToAllKeypointsObjects(shape, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
keypoints1 = filterKeypointsOutsidePolygon(keypoints1, buildRect(280, 280));
keypoints_ = applyTransformationMatrixToAllKeypointsObjects(keypoints1, getTranslateMatrix(40, 10));
drawKeypoints(ctx, keypoints_, "blue");
var keypoints2 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints2 = applyTransformationMatrixToAllKeypointsObjects(keypoints2, getTranslateMatrix(380, 10));
drawKeypoints(ctx, keypoints2, "blue");
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk2, getTranslateMatrix(40, 10));
drawKeypoints(ctx, nk3, "blue");
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
drawKeypoints(ctx, nk2, "blue");
ctx.globalAlpha = 1;
ctx.globalAlpha = 1.0;
if (g_showText) {
ctx.drawImage(_g_linesImage1, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function showJustRedKeypoints(frame) {
var animationFrames = 20*mult;//60*mult
var percentageDone = frame / animationFrames;
//now cut the fragment
animationStart();
// var percentageDone = frame/animationFrames;
// var endx = 80;
// var endy = 80;
// g_globalState.temporaryAppliedTransformations.translate = {
// x: -endx*percentageDone,
// y: -endy*percentageDone
// };
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
animationEnd(frame);
var nk = g_triangleKeypoints;
nonTransformedImage = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
ctx.globalAlpha = 0.0;
var keypoints1 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints1 = applyTransformationMatrixToAllKeypointsObjects(keypoints1, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
var shape = g_globalState.interactiveCanvasState.layers[0].nonTransformedImageOutline;
shape = applyTransformationMatrixToAllKeypointsObjects(shape, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
keypoints1 = filterKeypointsOutsidePolygon(keypoints1, buildRect(280, 280));
ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
drawKeypoints(ctx, keypoints1, "blue");
var keypoints2 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints2 = applyTransformationMatrixToAllKeypointsObjects(keypoints2, getTranslateMatrix(380, 10));
// ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
drawKeypoints(ctx, keypoints2, "blue");
ctx.fillStyle = 'rgba(255, 0, 0, 1.0)';
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
ctx.globalAlpha = 1.0;
drawKeypoints(ctx, nk3, "red");
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk2_ = applyTransformationMatrixToAllKeypointsObjects(nk2, getTranslateMatrix(40, 10));
drawKeypoints(ctx, nk2_, "red");
ctx.globalAlpha = 1.0;
ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
if (g_showText){
ctx.drawImage(_g_linesImage2, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function animation8(frame) {
var animationFrames = 10*mult;//60*mult
var percentageDone = frame / animationFrames;
//now cut the fragment
animationStart();
// var percentageDone = frame/animationFrames;
// var endx = 80;
// var endy = 80;
// g_globalState.temporaryAppliedTransformations.translate = {
// x: -endx*percentageDone,
// y: -endy*percentageDone
// };
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
animationEnd(frame);
var nk = g_triangleKeypoints;
nonTransformedImage = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
ctx.globalAlpha = 1.0 - percentageDone;
var keypoints1 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints1 = applyTransformationMatrixToAllKeypointsObjects(keypoints1, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
var shape = g_globalState.interactiveCanvasState.layers[0].nonTransformedImageOutline;
shape = applyTransformationMatrixToAllKeypointsObjects(shape, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
keypoints1 = filterKeypointsOutsidePolygon(keypoints1, buildRect(280, 280));
ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
keypoints_ = applyTransformationMatrixToAllKeypointsObjects(keypoints1, getTranslateMatrix(40, 10));
drawKeypoints(ctx, keypoints_, "blue");
var keypoints2 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints2 = applyTransformationMatrixToAllKeypointsObjects(keypoints2, getTranslateMatrix(380, 10));
// ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
drawKeypoints(ctx, keypoints2, "blue");
ctx.fillStyle = 'rgba(255, 0, 0, 1.0)';
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
ctx.globalAlpha = 1.0;
drawKeypoints(ctx, nk3, "red");
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk2_ = applyTransformationMatrixToAllKeypointsObjects(nk2, getTranslateMatrix(40, 10));
drawKeypoints(ctx, nk2_, "red");
ctx.globalAlpha = 1.0;
ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
if (g_showText){
ctx.drawImage(_g_linesImage2, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function showRedKeypointsAndOtherKeypoints(frame) {
var animationFrames = 30*mult;//60*mult
//now cut the fragment
animationStart();
var percentageDone = frame / animationFrames;
// var percentageDone = frame/animationFrames;
// var endx = 80;
// var endy = 80;
// g_globalState.temporaryAppliedTransformations.translate = {
// x: -endx*percentageDone,
// y: -endy*percentageDone
// };
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
animationEnd(frame);
var nk = g_triangleKeypoints;
nonTransformedImage = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
var keypoints1 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints1 = applyTransformationMatrixToAllKeypointsObjects(keypoints1, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
var shape = g_globalState.interactiveCanvasState.layers[0].nonTransformedImageOutline;
shape = applyTransformationMatrixToAllKeypointsObjects(shape, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
keypoints1 = filterKeypointsOutsidePolygon(keypoints1, buildRect(280, 280));
keypoints_ = applyTransformationMatrixToAllKeypointsObjects(keypoints1, getTranslateMatrix(40, 10));
drawKeypoints(ctx, keypoints_, "blue");
var keypoints2 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints2 = applyTransformationMatrixToAllKeypointsObjects(keypoints2, getTranslateMatrix(380, 10));
drawKeypoints(ctx, keypoints2, "blue");
var fillStr = 'rgba(255,'+ parseInt(255*(0)) +', ' + parseInt(255*(0)) +', 1.0)';
ctx.fillStyle = fillStr;
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
fillStr = 'rgba('+ parseInt(255*(1)) +',0,'+ parseInt(255*(0)) +', 1.0)';
drawKeypoints(ctx, nk2, fillStr);
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk2_ = applyTransformationMatrixToAllKeypointsObjects(nk2, getTranslateMatrix(40, 10));
drawKeypoints(ctx, nk2_, fillStr);
ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
if (g_showText){
ctx.drawImage(_g_linesImage2, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function animation6(frame) {
var animationFrames = 10*mult;//60*mult
//now cut the fragment
animationStart();
var percentageDone = frame / animationFrames;
// var percentageDone = frame/animationFrames;
// var endx = 80;
// var endy = 80;
// g_globalState.temporaryAppliedTransformations.translate = {
// x: -endx*percentageDone,
// y: -endy*percentageDone
// };
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
animationEnd(frame);
var nk = g_triangleKeypoints;
nonTransformedImage = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
var keypoints1 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints1 = applyTransformationMatrixToAllKeypointsObjects(keypoints1, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
var shape = g_globalState.interactiveCanvasState.layers[0].nonTransformedImageOutline;
shape = applyTransformationMatrixToAllKeypointsObjects(shape, g_globalState.interactiveCanvasState.layers[0].appliedTransformations);
keypoints1 = filterKeypointsOutsidePolygon(keypoints1, buildRect(280, 280));
keypoints_ = applyTransformationMatrixToAllKeypointsObjects(keypoints1, getTranslateMatrix(40, 10));
drawKeypoints(ctx, keypoints_, "blue");
var keypoints2 = g_globalState.interactiveCanvasState.layers[0].keypoints;
keypoints2 = applyTransformationMatrixToAllKeypointsObjects(keypoints2, getTranslateMatrix(380, 10));
drawKeypoints(ctx, keypoints2, "blue");
var fillStr = 'rgba(255,'+ parseInt(255*(1-percentageDone)) +', ' + parseInt(255*(1-percentageDone)) +', 1.0)';
ctx.fillStyle = fillStr;
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
fillStr = 'rgba('+ parseInt(255*(percentageDone)) +',0,'+ parseInt(255*(1-percentageDone)) +', 1.0)';
drawKeypoints(ctx, nk2, fillStr);
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk2_ = applyTransformationMatrixToAllKeypointsObjects(nk2, getTranslateMatrix(40, 10));
drawKeypoints(ctx, nk2_, fillStr);
ctx.fillStyle = 'rgba(255, 255, 255, 1.0)';
if (g_showText){
ctx.drawImage(_g_linesImage2, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
//repeat frame
function repeatFrameBeforeFinalTransform(frame) {
animationStart();
var animationFrames = 30 * mult;
draw();
var percentageDone = frame / animationFrames;
let imageFragment1;
let imageWithWhiteTri1;
let shape = g_triangleKeypoints;
{
let layer1 = g_globalState.referenceCanvasState.layers[0];
transformedShape1 = applyTransformationMatrixToAllKeypointsObjects(shape, layer1.appliedTransformations);
let referenceCanvas = g_globalState.referenceCanvasState.imageLayerCanvas;
let referenceCanvasContext = g_globalState.referenceCanvasState.imageLayerCanvasContext;
imageFragment1 = cropLayerImage(referenceCanvas, transformedShape1);
referenceCanvasContext.beginPath();
drawPolygonPath(referenceCanvasContext, transformedShape1);
referenceCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
referenceCanvasContext.fill();
imageWithWhiteTri1 = referenceCanvas
}
let imageFragment2;
let imageWithWhiteTri2;
let transformedShape2;
{
let layer2 = g_globalState.interactiveCanvasState.layers[0];
transformedShape2 = applyTransformationMatrixToAllKeypointsObjects(shape, layer2.appliedTransformations);
let interactiveCanvas = g_globalState.interactiveCanvasState.imageLayerCanvas;
let interactiveCanvasContext = g_globalState.interactiveCanvasState.imageLayerCanvasContext;
imageFragment2 = cropLayerImage(interactiveCanvas, transformedShape2);
interactiveCanvasContext.beginPath();
drawPolygonPath(interactiveCanvasContext, transformedShape2);
interactiveCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
interactiveCanvasContext.fill();
imageWithWhiteTri2 = interactiveCanvas
}
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
clearCanvasByContext(ctx);
paintCanvasWhite(ctx);
ctx.save();
{
ctx.globalAlpha = 0.0;
ctx.drawImage(imageWithWhiteTri2, 0, 0);
ctx.globalAlpha = 1.0;
var nk = g_triangleKeypoints;
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk_ = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(40, 10));
var fillStr = 'rgba(255, 0 ,0 , 1.0)';
ctx.strokeStyle = fillStr;
drawTheTriangle(ctx, 100, nk_);
ctx.fillStyle = fillStr;
drawKeypoints(ctx, nk_, fillStr);
ctx.drawImage(imageFragment2, 40, 10);
}
// ctx.drawImage(imageWithWhiteTri1, 0, 0);
ctx.restore();
ctx.save();
{
ctx.globalAlpha = 0.0;
ctx.drawImage(imageWithWhiteTri1, 380, 0);
ctx.globalAlpha = 1.0;
var nk = g_triangleKeypoints;
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
var fillStr = 'rgba(255, 0, 0, 1.0)';
ctx.strokeStyle = fillStr;
drawTheTriangle(ctx, 100, nk);
ctx.fillStyle = fillStr;
drawKeypoints(ctx, nk, fillStr);
let mat = calcTransformationMatrixToEquilateralTriangle(nk);
mat = matrixMultiply(getTranslateMatrix(280, 280), mat);
per = percentageDone;
//ctx.transform(1+((mat[0][0]-1)*per), 0+(mat[1][0]-0)*per, 0+(mat[0][1]-0)*per, 1+(mat[1][1]-1)*per, 0+(mat[0][2]-0)*per, 0+(mat[1][2]-0)*per);
// ctx.translate(0, 100);
ctx.drawImage(imageFragment1, 380, 10);
}
ctx.restore();
if (g_showText) {
ctx.drawImage(_g_linesImage3, 0, 310);
}
var fillStr = 'rgba(255, 255, 255, 1.0)';
ctx.fillStyle = fillStr;
sendImage()
return (frame >= animationFrames);
}
//fade out
function showTheLine2(frame) {
animationStart();
var animationFrames = 30 * mult;
draw();
var percentageDone = frame / animationFrames;
let imageFragment1;
let imageWithWhiteTri1;
let shape = g_triangleKeypoints;
{
let layer1 = g_globalState.referenceCanvasState.layers[0];
transformedShape1 = applyTransformationMatrixToAllKeypointsObjects(shape, layer1.appliedTransformations);
let referenceCanvas = g_globalState.referenceCanvasState.imageLayerCanvas;
let referenceCanvasContext = g_globalState.referenceCanvasState.imageLayerCanvasContext;
imageFragment1 = cropLayerImage(referenceCanvas, transformedShape1);
referenceCanvasContext.beginPath();
drawPolygonPath(referenceCanvasContext, transformedShape1);
referenceCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
referenceCanvasContext.fill();
imageWithWhiteTri1 = referenceCanvas
}
let imageFragment2;
let imageWithWhiteTri2;
let transformedShape2;
{
let layer2 = g_globalState.interactiveCanvasState.layers[0];
transformedShape2 = applyTransformationMatrixToAllKeypointsObjects(shape, layer2.appliedTransformations);
let interactiveCanvas = g_globalState.interactiveCanvasState.imageLayerCanvas;
let interactiveCanvasContext = g_globalState.interactiveCanvasState.imageLayerCanvasContext;
imageFragment2 = cropLayerImage(interactiveCanvas, transformedShape2);
interactiveCanvasContext.beginPath();
drawPolygonPath(interactiveCanvasContext, transformedShape2);
interactiveCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
interactiveCanvasContext.fill();
imageWithWhiteTri2 = interactiveCanvas
}
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
clearCanvasByContext(ctx);
paintCanvasWhite(ctx);
ctx.save();
{
ctx.globalAlpha = 1.0;
ctx.drawImage(imageWithWhiteTri2, 40, 10);
ctx.globalAlpha = 1.0;
var nk = g_triangleKeypoints;
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk_ = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(40, 10));
var fillStr = 'rgba(255, 0 ,0 , 1.0)';
ctx.strokeStyle = fillStr;
drawTheTriangle(ctx, 100, nk_);
ctx.fillStyle = fillStr;
drawKeypoints(ctx, nk_, fillStr);
let mat = calcTransformationMatrixToEquilateralTriangle(nk);
mat = matrixMultiply(getTranslateMatrix(0, 280), mat);
per = percentageDone;
//ctx.transform(1 + ((mat[0][0] - 1) * per), 0 + (mat[1][0] - 0) * per, 0 + (mat[0][1] - 0) * per, 1 + (mat[1][1] - 1) * per, 0 + (mat[0][2] - 0) * per, 0 + (mat[1][2] - 0) * per);
// ctx.translate(0, 100);
ctx.drawImage(imageFragment2, 40, 10);
}
// ctx.drawImage(imageWithWhiteTri1, 0, 0);
ctx.restore();
ctx.save();
{
ctx.globalAlpha = 1.0;
ctx.drawImage(imageWithWhiteTri1, 380, 10);
ctx.globalAlpha = 1.0;
var nk = g_triangleKeypoints;
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
var fillStr = 'rgba(255, 0, 0, 1.0)';
ctx.strokeStyle = fillStr;
drawTheTriangle(ctx, 100, nk);
ctx.fillStyle = fillStr;
drawKeypoints(ctx, nk, fillStr);
let mat = calcTransformationMatrixToEquilateralTriangle(nk);
mat = matrixMultiply(getTranslateMatrix(280, 280), mat);
per = percentageDone;
//ctx.transform(1+((mat[0][0]-1)*per), 0+(mat[1][0]-0)*per, 0+(mat[0][1]-0)*per, 1+(mat[1][1]-1)*per, 0+(mat[0][2]-0)*per, 0+(mat[1][2]-0)*per);
// ctx.translate(0, 100);
ctx.drawImage(imageFragment1, 380, 10);
}
ctx.restore();
if (g_showText) {
ctx.drawImage(_g_linesImage3, 0, 310);
}
var fillStr = 'rgba(255, 255, 255, 1.0)';
ctx.fillStyle = fillStr;
sendImage()
return (frame >= animationFrames);
}
//fade out
function showTheLine(frame) {
animationStart();
var animationFrames = 10 * mult;
draw();
var percentageDone = frame / animationFrames;
let imageFragment1;
let imageWithWhiteTri1;
let shape = g_triangleKeypoints;
{
let layer1 = g_globalState.referenceCanvasState.layers[0];
transformedShape1 = applyTransformationMatrixToAllKeypointsObjects(shape, layer1.appliedTransformations);
let referenceCanvas = g_globalState.referenceCanvasState.imageLayerCanvas;
let referenceCanvasContext = g_globalState.referenceCanvasState.imageLayerCanvasContext;
imageFragment1 = cropLayerImage(referenceCanvas, transformedShape1);
referenceCanvasContext.beginPath();
drawPolygonPath(referenceCanvasContext, transformedShape1);
referenceCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
referenceCanvasContext.fill();
imageWithWhiteTri1 = referenceCanvas
}
let imageFragment2;
let imageWithWhiteTri2;
let transformedShape2;
{
let layer2 = g_globalState.interactiveCanvasState.layers[0];
transformedShape2 = applyTransformationMatrixToAllKeypointsObjects(shape, layer2.appliedTransformations);
let interactiveCanvas = g_globalState.interactiveCanvasState.imageLayerCanvas;
let interactiveCanvasContext = g_globalState.interactiveCanvasState.imageLayerCanvasContext;
imageFragment2 = cropLayerImage(interactiveCanvas, transformedShape2);
interactiveCanvasContext.beginPath();
drawPolygonPath(interactiveCanvasContext, transformedShape2);
interactiveCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
interactiveCanvasContext.fill();
imageWithWhiteTri2 = interactiveCanvas
}
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
clearCanvasByContext(ctx);
paintCanvasWhite(ctx);
ctx.save();
{
ctx.globalAlpha = 1.0;
ctx.drawImage(imageWithWhiteTri2, 40, 10);
ctx.globalAlpha = 1.0;
var nk = g_triangleKeypoints;
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk_ = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(40, 10));
var fillStr = 'rgba(255, 0 ,0 , 1.0)';
ctx.strokeStyle = fillStr;
drawTheTriangle(ctx, 100, nk_);
ctx.fillStyle = fillStr;
drawKeypoints(ctx, nk_, fillStr);
let mat = calcTransformationMatrixToEquilateralTriangle(nk);
mat = matrixMultiply(getTranslateMatrix(0, 280), mat);
per = percentageDone;
//ctx.transform(1 + ((mat[0][0] - 1) * per), 0 + (mat[1][0] - 0) * per, 0 + (mat[0][1] - 0) * per, 1 + (mat[1][1] - 1) * per, 0 + (mat[0][2] - 0) * per, 0 + (mat[1][2] - 0) * per);
// ctx.translate(0, 100);
ctx.drawImage(imageFragment2, 40, 10);
}
// ctx.drawImage(imageWithWhiteTri1, 0, 0);
ctx.restore();
ctx.save();
{
ctx.globalAlpha = 1.0;
ctx.drawImage(imageWithWhiteTri1, 380, 10);
ctx.globalAlpha = 1.0;
var nk = g_triangleKeypoints;
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
var fillStr = 'rgba(255, 0, 0, 1.0)';
ctx.strokeStyle = fillStr;
drawTheTriangle(ctx, 100, nk);
ctx.fillStyle = fillStr;
drawKeypoints(ctx, nk, fillStr);
let mat = calcTransformationMatrixToEquilateralTriangle(nk);
mat = matrixMultiply(getTranslateMatrix(280, 280), mat);
per = percentageDone;
//ctx.transform(1+((mat[0][0]-1)*per), 0+(mat[1][0]-0)*per, 0+(mat[0][1]-0)*per, 1+(mat[1][1]-1)*per, 0+(mat[0][2]-0)*per, 0+(mat[1][2]-0)*per);
// ctx.translate(0, 100);
ctx.drawImage(imageFragment1, 380, 10);
}
ctx.restore();
if (g_showText) {
ctx.drawImage(_g_linesImage2, 0, 310);
}
var fillStr = 'rgba(255, 255, 255, 1.0)';
ctx.fillStyle = fillStr;
sendImage()
return (frame >= animationFrames);
}
//fade out
function animation5(frame) {
animationStart();
var animationFrames = 10 * mult;
draw();
var percentageDone = frame / animationFrames;
let imageFragment1;
let imageWithWhiteTri1;
let shape = g_triangleKeypoints;
{
let layer1 = g_globalState.referenceCanvasState.layers[0];
transformedShape1 = applyTransformationMatrixToAllKeypointsObjects(shape, layer1.appliedTransformations);
let referenceCanvas = g_globalState.referenceCanvasState.imageLayerCanvas;
let referenceCanvasContext = g_globalState.referenceCanvasState.imageLayerCanvasContext;
imageFragment1 = cropLayerImage(referenceCanvas, transformedShape1);
referenceCanvasContext.beginPath();
drawPolygonPath(referenceCanvasContext, transformedShape1);
referenceCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
referenceCanvasContext.fill();
imageWithWhiteTri1 = referenceCanvas
}
let imageFragment2;
let imageWithWhiteTri2;
let transformedShape2;
{
let layer2 = g_globalState.interactiveCanvasState.layers[0];
transformedShape2 = applyTransformationMatrixToAllKeypointsObjects(shape, layer2.appliedTransformations);
let interactiveCanvas = g_globalState.interactiveCanvasState.imageLayerCanvas;
let interactiveCanvasContext = g_globalState.interactiveCanvasState.imageLayerCanvasContext;
imageFragment2 = cropLayerImage(interactiveCanvas, transformedShape2);
interactiveCanvasContext.beginPath();
drawPolygonPath(interactiveCanvasContext, transformedShape2);
interactiveCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
interactiveCanvasContext.fill();
imageWithWhiteTri2 = interactiveCanvas
}
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
clearCanvasByContext(ctx);
paintCanvasWhite(ctx);
ctx.save();
{
ctx.globalAlpha = 1.0 - (1.0*percentageDone);
ctx.drawImage(imageWithWhiteTri2, 40, 10);
ctx.globalAlpha = 1.0;
var nk = g_triangleKeypoints;
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk_ = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(40, 10));
var fillStr = 'rgba(255, 0 ,0 , 1.0)';
ctx.strokeStyle = fillStr;
drawTheTriangle(ctx, 100, nk_);
ctx.fillStyle = fillStr;
drawKeypoints(ctx, nk_, fillStr);
let mat = calcTransformationMatrixToEquilateralTriangle(nk);
mat = matrixMultiply(getTranslateMatrix(0, 280), mat);
per = percentageDone;
//ctx.transform(1 + ((mat[0][0] - 1) * per), 0 + (mat[1][0] - 0) * per, 0 + (mat[0][1] - 0) * per, 1 + (mat[1][1] - 1) * per, 0 + (mat[0][2] - 0) * per, 0 + (mat[1][2] - 0) * per);
// ctx.translate(0, 100);
ctx.drawImage(imageFragment2, 40, 10);
}
// ctx.drawImage(imageWithWhiteTri1, 0, 0);
ctx.restore();
ctx.save();
{
ctx.globalAlpha = 1.0 - (1.0*percentageDone);
ctx.drawImage(imageWithWhiteTri1, 380, 10);
ctx.globalAlpha = 1.0;
var nk = g_triangleKeypoints;
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
var fillStr = 'rgba(255, 0, 0, 1.0)';
ctx.strokeStyle = fillStr;
drawTheTriangle(ctx, 100, nk);
ctx.fillStyle = fillStr;
drawKeypoints(ctx, nk, fillStr);
let mat = calcTransformationMatrixToEquilateralTriangle(nk);
mat = matrixMultiply(getTranslateMatrix(280, 280), mat);
per = percentageDone;
//ctx.transform(1+((mat[0][0]-1)*per), 0+(mat[1][0]-0)*per, 0+(mat[0][1]-0)*per, 1+(mat[1][1]-1)*per, 0+(mat[0][2]-0)*per, 0+(mat[1][2]-0)*per);
// ctx.translate(0, 100);
ctx.drawImage(imageFragment1, 380, 10);
}
ctx.restore();
if (g_showText) {
ctx.drawImage(_g_linesImage3, 0, 310);
}
var fillStr = 'rgba(255, 255, 255, 1.0)';
ctx.fillStyle = fillStr;
sendImage()
return (frame >= animationFrames);
}
function finalTransformOfFrag(frame) {
console.log("final transform of frag");
var animationFrames = 13 * mult;
animationStart();
draw();
var percentageDone = frame / animationFrames;
let imageFragment1;
let imageWithWhiteTri1;
let shape = g_triangleKeypoints;
{
let layer1 = g_globalState.referenceCanvasState.layers[0];
transformedShape1 = applyTransformationMatrixToAllKeypointsObjects(shape, layer1.appliedTransformations);
let referenceCanvas = g_globalState.referenceCanvasState.imageLayerCanvas;
let referenceCanvasContext = g_globalState.referenceCanvasState.imageLayerCanvasContext;
imageFragment1 = referenceCanvas;
imageFragment1 = cropLayerImage(referenceCanvas, transformedShape1);
referenceCanvasContext.beginPath();
drawPolygonPath(referenceCanvasContext, transformedShape1);
referenceCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
referenceCanvasContext.fill();
imageWithWhiteTri1 = referenceCanvas
}
let imageFragment2;
let imageWithWhiteTri2;
let transformedShape2;
{
let layer2 = g_globalState.interactiveCanvasState.layers[0];
transformedShape2 = applyTransformationMatrixToAllKeypointsObjects(shape, layer2.appliedTransformations);
let interactiveCanvas = g_globalState.interactiveCanvasState.imageLayerCanvas;
let interactiveCanvasContext = g_globalState.interactiveCanvasState.imageLayerCanvasContext;
imageFragment2 = cropLayerImage(interactiveCanvas, transformedShape2);
interactiveCanvasContext.beginPath();
drawPolygonPath(interactiveCanvasContext, transformedShape2);
interactiveCanvasContext.fillStyle = 'rgba(255, 255, 255, 1.0)';
interactiveCanvasContext.fill();
imageWithWhiteTri2 = interactiveCanvas
}
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
clearCanvasByContext(ctx);
paintCanvasWhite(ctx);
ctx.save();
{
// ctx.drawImage(imageWithWhiteTri2, 0, 0);
var nk = g_triangleKeypoints;
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
//drawTheTriangle(ctx, 100, nk);
let mat = calcTransformationMatrixToEquilateralTriangle(nk2);
mat = matrixMultiply(getTranslateMatrix(70, 30), mat);
per = percentageDone;
var transMat = [
[1+((mat[0][0]-1)*per), 0+(mat[0][1]-0)*per, 0+(mat[0][2]-0)*per],
[0+(mat[1][0]-0)*per, 1+(mat[1][1]-1)*per, 0+(mat[1][2]-0)*per],
[0, 0, 1]
]
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk3 = applyTransformationMatrixToAllKeypointsObjects(nk3, transMat);
var fillStr = 'rgba(255, 255, 255, ' + (1.0 - (percentageDone/2)) + ')';
ctx.strokeStyle = fillStr;
ctx.fillStyle = fillStr;
nk3_ = applyTransformationMatrixToAllKeypointsObjects(nk3, getTranslateMatrix(40, 10));
drawTheTriangle(ctx, 100, nk3_, fillStr);
drawKeypoints(ctx, nk3_, fillStr);
ctx.save();
ctx.transform(1 + ((mat[0][0] - 1) * per), 0 + (mat[1][0] - 0) * per, 0 + (mat[0][1] - 0) * per, 1 + (mat[1][1] - 1) * per, 0 + (mat[0][2] - 0) * per, 0 + (mat[1][2] - 0) * per);
// ctx.translate(0, 100);
ctx.drawImage(imageFragment2, 40, 10);
ctx.restore();
//drawTheTriangle(ctx, 100, nk3);
}
// ctx.drawImage(imageWithWhiteTri1, 0, 0);
ctx.restore();
ctx.save();
{
// ctx.drawImage(imageWithWhiteTri1, 380, 0);
var nk = g_triangleKeypoints;
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
let mat = calcTransformationMatrixToEquilateralTriangle(nk2);
mat = matrixMultiply(getTranslateMatrix(430, 100), mat);
per = percentageDone;
var transMat = [
[1+((mat[0][0]-1)*per), 0+(mat[0][1]-0)*per, 0+(mat[0][2]-0)*per],
[0+(mat[1][0]-0)*per, 1+(mat[1][1]-1)*per, 0+(mat[1][2]-0)*per],
[0, 0, 1]
];
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
nk = applyTransformationMatrixToAllKeypointsObjects(nk, transMat);
var fillStr = 'rgba(255, 255, 255, ' + (1.0 - (percentageDone/2)) + ')';
ctx.strokeStyle = fillStr;
ctx.fillStyle = fillStr;
drawTheTriangle(ctx, 100, nk, fillStr);
drawKeypoints(ctx, nk, fillStr);
ctx.save();
ctx.transform(1+((mat[0][0]-1)*per), 0+(mat[1][0]-0)*per, 0+(mat[0][1]-0)*per, 1+(mat[1][1]-1)*per, 0+(mat[0][2]-0)*per, 0+(mat[1][2]-0)*per);
// ctx.translate(0, 100);
ctx.drawImage(imageFragment1, 380, 10);
ctx.restore();
// drawTheTriangle(ctx, 100, nk);
}
ctx.restore();
if (g_showText) {
ctx.drawImage(_g_linesImage3, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function calcPerimeterOfTriangle(triangle) {
return getEuclideanDistance(triangle[0], triangle[1])
+ getEuclideanDistance(triangle[1], triangle[2])
+ getEuclideanDistance(triangle[2], triangle[0]);
}
function drawTheTriangle(ctx, percentageDone, triangle, strokeStyle) {
var nonTransformedImage = triangle;
var totalDist = calcPerimeterOfTriangle(nonTransformedImage);
var distDrawnSoFar = 0;
var prevPoint = nonTransformedImage[2];
ctx.beginPath();
ctx.strokeStyle = (strokeStyle)? strokeStyle : "red";
ctx.moveTo(nonTransformedImage[2].x, nonTransformedImage[2].y);
for (var i = 0; i < 3; i++) {
var currPoint = nonTransformedImage[i];
//should we draw this side?
var nextDist = getEuclideanDistance(prevPoint, currPoint);
if (distDrawnSoFar + nextDist <= totalDist * percentageDone) {
//draw the whole thing
ctx.lineTo(currPoint.x, currPoint.y);
} else {
//how much percentage isn't taken up
var distPer = ((totalDist*percentageDone)-distDrawnSoFar)/nextDist;
var remaining = distPer;
if (remaining < 0) {
//don't draw any of this line
} else {
ctx.lineTo(prevPoint.x + ((currPoint.x-prevPoint.x)*remaining), prevPoint.y + ((currPoint.y-prevPoint.y)*remaining));
}
}
distDrawnSoFar += nextDist;//not accurate but doesn't matter
prevPoint = currPoint;
}
ctx.stroke();
}
function drawTheLine(frame) {
var animationFrames = 35*mult;//60*mult
var percentageDone = frame/animationFrames;
//now cut the fragment
animationStart();
// var percentageDone = frame/animationFrames;
// var endx = 80;
// var endy = 80;
// g_globalState.temporaryAppliedTransformations.translate = {
// x: -endx*percentageDone,
// y: -endy*percentageDone
// };
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
animationEnd(frame);
var nk = g_triangleKeypoints;
nonTransformedImage = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
ctx.lineWidth = 3;
drawTheTriangle(ctx, percentageDone, nonTransformedImage);
//move the fragment!!!
nk2 = applyTransformationMatrixToAllKeypointsObjects(nk, getActiveLayer(g_globalState).appliedTransformations);
nk2_ = applyTransformationMatrixToAllKeypointsObjects(nk2, getTranslateMatrix(40, 10));
ctx.fillStyle = 'rgba(255, 0, 0, 1.0)';
nk = applyTransformationMatrixToAllKeypointsObjects(nk, getTranslateMatrix(380, 10));
drawKeypoints(ctx, nk2_, "red");
drawKeypoints(ctx, nk, "red");
ctx.beginPath();
drawTheTriangle(ctx, percentageDone, nk2_);
if (g_showText) {
ctx.drawImage(_g_linesImage2, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function repeatAfterFirstTransform2(frame) {
var animationFrames = 60;//120*mult;
animationStart();
animationEnd(frame);
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
//careful or this won't be sent!!!
//pick 3 center keypoints
ctx.beginPath();
let pt = {};
var nk = g_triangleKeypoints;
if (g_showText) {
ctx.drawImage(_g_linesImage1, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function repeatAfterFirstTransform(frame) {
var animationFrames = 20;//120*mult;
animationStart();
animationEnd(frame);
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
//careful or this won't be sent!!!
//pick 3 center keypoints
ctx.beginPath();
let pt = {};
var nk = g_triangleKeypoints;
if (g_showText) {
// ctx.drawImage(_g_linesImage1, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function transformTheWholeFirstImage(frame) {
var animationFrames = 20;//120*mult;
animationStart();
var percentageDone = frame/animationFrames;
var endRotation = 120;
g_globalState.temporaryAppliedTransformations.transformationCenterPoint = {x:140,y:140};
g_globalState.temporaryAppliedTransformations.rotation = percentageDone * endRotation;
var scale = (2*percentageDone)+1;
var scaleMatrix = getDirectionalScaleMatrix(Math.sqrt(scale), 1 / Math.sqrt(scale), 45);
g_globalState.temporaryAppliedTransformations.directionalScaleMatrix = scaleMatrix;
g_globalState.temporaryAppliedTransformations.uniformScale = 1-(.2*percentageDone);
animationEnd(frame);
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
//careful or this won't be sent!!!
//pick 3 center keypoints
ctx.beginPath();
let pt = {};
var nk = g_triangleKeypoints;
if (g_showText) {
// ctx.drawImage(_g_linesImage1, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
//do nothing for a few frames
function doNothingForTheFirstFewFrames(frame) {
var animationFrames = 20*mult;
animationStart();
var percentageDone = frame/animationFrames;
var endx = 0;
var endy = 0;
//draw a bunch of keypoints
//draw blue ones then red
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
animationEnd(frame);
//drawKeypoints(ctx, g_triangleKeypoints, "blue");
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
//careful or this won't be sent!!!
if (g_showText) {
// ctx.drawImage(_g_linesImage1, 0, 310);
}
sendImage()
return (frame >= animationFrames);
}
function animationStart() {
g_globalState.activeCanvas.activeLayer = g_globalState.interactiveCanvasState.layers[0];
g_globalState.transformationMatBeforeTemporaryTransformations = deepMatrixClone(animationStartMatrix);
wipeTemporaryAppliedTransformations();
}
function deepMatrixClone(inputMat) {
return[
inputMat[0].slice(0),
inputMat[1].slice(0),
inputMat[2].slice(0),
];
}
var g_frame = 1;
function theDrawPart(g_frame) {
// var canvas = document.createElement('canvas'),
// ctx = canvas.getContext('2d');
// canvas.width = 700;
// canvas.height = 600;
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
paintCanvasWhite(ctx);
var ctx1= document.getElementById('queryImageCanvasImageContent');
var ctx2= document.getElementById('queryImageCanvasUiOverlay');
var ctx3= document.getElementById('databaseImageCanvasImageContent');
var ctx4= document.getElementById('databaseImageCanvasUiOverlay');
ctx.drawImage(ctx1, 0, 0);
ctx.drawImage(ctx2, 0, 0);
ctx.drawImage(ctx3, 380, 0);
ctx.drawImage(ctx4, 380, 0);
}
function drawAllImagesToCanvasAndSend(g_frame) {
// var canvas = document.createElement('canvas'),
// ctx = canvas.getContext('2d');
// canvas.width = 700;
// canvas.height = 600;
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
paintCanvasWhite(ctx);
var ctx1= document.getElementById('queryImageCanvasImageContent');
var ctx2= document.getElementById('queryImageCanvasUiOverlay');
var ctx3= document.getElementById('databaseImageCanvasImageContent');
var ctx4= document.getElementById('databaseImageCanvasUiOverlay');
ctx.drawImage(ctx1, 40, 10);
ctx.drawImage(ctx2, 40, 10);
ctx.drawImage(ctx3, 380, 10);
ctx.drawImage(ctx4, 3, 10);
//
// var image1 = canvas.toDataURL('image/jpeg', 0.92).replace("image/jpeg", "image/octet-stream"); // here is the most important part because if you dont replace you will get a DOM 18 exception.
////
// var regex = /^data:.+\/(.+);base64,(.*)$/;
// var matches;
// matches = image1.match(regex);
// var data1 = matches[2];
//
// var info = {
// 'image1': {
// 'imageData': data1,
// 'frameNumber': g_frame
// }
// };
//
// $.ajax({
// url: 'http://127.0.0.1/runTestWithJsonData',
// type: 'POST',
// data: JSON.stringify(info),
// contentType: 'application/json; charset=utf-8',
// dataType: 'json',
// async: true,
// success: function (msg) {
// console.log(msg);
// },
// error: function (msg) {
// console.log(msg);
// }
// });
}
function sendImage() {
var canvas = document.getElementById('bigCanvas'),
ctx = canvas.getContext('2d');
var image1 = canvas.toDataURL('image/jpeg', 0.92).replace("image/jpeg", "image/octet-stream"); // here is the most important part because if you dont replace you will get a DOM 18 exception.
//
var regex = /^data:.+\/(.+);base64,(.*)$/;
var matches;
matches = image1.match(regex);
var data1 = matches[2];
var info = {
'image1': {
'imageData': data1,
'frameNumber': g_frame
}
};
$.ajax({
url: 'http://127.0.0.1/runTestWithJsonData',
type: 'POST',
data: JSON.stringify(info),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: function (msg) {
console.log(msg);
},
error: function (msg) {
console.log(msg);
}
});
}
function addToX(transformedShape2, number) {
for (var i = 0; i < transformedShape2.length; i++) {
transformedShape2[i].x += number;
}
}
function addToX2(transformedShape2, number) {
var ret = [];
for (var i = 0; i < transformedShape2.length; i++) {
var newPt = {
x: transformedShape2[i].x + number,
y: transformedShape2[i].y
};
ret.push(newPt);
}
return ret;
}
function animationEnd(frame) {
applyTemporaryTransformationsToActiveLayer();
wipeTemporaryAppliedTransformations();
drawAllImagesToCanvasAndSend(g_frame);
draw();
}
var currentAnimation = 0;
var prevAnimationsFrameCount = 0;
function doAnimations(frame) {
g_frame = frame;//HACK
var isDone = false;
switch(currentAnimation) {
case 0:
isDone = doNothingForTheFirstFewFrames(frame);
break;
case 1:
isDone = transformTheWholeFirstImage(frame-prevAnimationsFrameCount);
break;
case 2:
isDone = repeatAfterFirstTransform(frame-prevAnimationsFrameCount);
break;
case 3:
isDone = repeatAfterFirstTransform2(frame-prevAnimationsFrameCount);
break;
case 4:
//fade in keypoints
isDone = fadeInKeypoints(frame-prevAnimationsFrameCount);
break;
case 5:
//repeat frame showing keypoints
isDone = repeatShowingPlainKeypoints(frame-prevAnimationsFrameCount);
break;
case 6:
//repeat frame showing keypoints
isDone = repeatShowingPlainKeypoints2(frame-prevAnimationsFrameCount);
break;
case 7:
//fade in red keypoints
isDone = animation6(frame-prevAnimationsFrameCount);
break;
case 8:
//show the red keypoints and other keypoints
isDone = showRedKeypointsAndOtherKeypoints(frame-prevAnimationsFrameCount);
break;
case 9:
//fade out keypoints
isDone = animation8(frame-prevAnimationsFrameCount);
break;
case 10:
//show just the red keypoints for a bit
isDone = showJustRedKeypoints(frame-prevAnimationsFrameCount);
break;
case 11:
//draw the line
isDone = drawTheLine(frame-prevAnimationsFrameCount);
break;
case 12:
//fade out image
isDone = showTheLine(frame-prevAnimationsFrameCount);
break;
case 13:
//fade out image
isDone = showTheLine2(frame-prevAnimationsFrameCount);
break;
case 14:
//fade out image
isDone = animation5(frame-prevAnimationsFrameCount);
break;
case 15:
isDone = repeatFrameBeforeFinalTransform(frame-prevAnimationsFrameCount);
break;
case 16:
isDone = finalTransformOfFrag(frame-prevAnimationsFrameCount);
break;
case 17:
isDone = repeatTheLastFrame3(frame-prevAnimationsFrameCount);
break;
case 18:
isDone = repeatTheLastFrame(frame-prevAnimationsFrameCount);
break;
case 19:
isDone = repeatTheLastFrame2(frame-prevAnimationsFrameCount);
break;
// case 6:
// isDone = fadeInKeypoints(frame-prevAnimationsFrameCount);
// break;
default:
return true;
}
if(isDone){
g_globalState.forceTempAnimations = true;
g_globalState.activeCanvas.activeLayer = g_globalState.interactiveCanvasState.layers[0];
animationStartTime = new Date();
g_globalState.transformationMatBeforeTemporaryTransformations = g_globalState.activeCanvas.activeLayer.appliedTransformations;
animationStartMatrix = g_globalState.transformationMatBeforeTemporaryTransformations;
prevAnimationsFrameCount = frame;
currentAnimation++;
}
}
//returns true when finished
function computeFrames(frame){
if (doAnimations(frame)) {
return
}
let nextFrame = frame + 1;
window.requestAnimationFrame(function () {
computeFrames(nextFrame);
});
}
function startAnimation() {
reset();
g_drawingOptions.drawImageOutline = false;
g_drawingOptions.drawInteractiveCanvasUiLayer = true;//false;
g_globalState.activeCanvas = g_globalState.referenceCanvasState;
// g_globalState.activeCanvas.activeLayer = g_globalState.referenceCanvasState.layers[0];
// g_globalState.transformationMatBeforeTemporaryTransformations = g_globalState.activeCanvas.activeLayer.appliedTransformations;
//// g_globalState.temporaryAppliedTransformations.uniformScale = 0.846153847;
// g_globalState.temporaryAppliedTransformations.translate = {
// x: -440,
// y: 0
// };
//// g_globalState.temporaryAppliedTransformations.rotation = 90;
// applyTemporaryTransformationsToActiveLayer();
// wipeTemporaryAppliedTransformations();
g_globalState.activeCanvas.activeLayer = g_globalState.referenceCanvasState.layers[0];
g_globalState.transformationMatBeforeTemporaryTransformations = g_globalState.activeCanvas.activeLayer.appliedTransformations;
applyTemporaryTransformationsToActiveLayer();
wipeTemporaryAppliedTransformations();
draw();
animationStartTime = new Date();
g_globalState.transformationMatBeforeTemporaryTransformations = g_globalState.activeCanvas.activeLayer.appliedTransformations;
animationStartMatrix = g_globalState.transformationMatBeforeTemporaryTransformations;
computeFrames(1)
}
|
import { constants } from '../actions/apiQueries'
function apiQueryReducer (state, action) {
var key = null
var queries = null
switch (action.type) {
case constants.FETCH_API:
key = [action.path, action.params]
queries = Object.assign({}, state.queries)
queries[key] = { isFetching: true }
return Object.assign({}, state, { queries: queries })
case constants.RECEIVE_API:
key = [action.path, action.params]
queries = Object.assign({}, state.queries)
queries[key] = { isFetching: false, response: action.response }
return Object.assign({}, state, { queries: queries })
default:
return state
}
}
export default function apiQueries (state = { queries: [], cachedResources: {} }, action) {
switch (action.type) {
case constants.FETCH_API:
case constants.RECEIVE_API:
return Object.assign({}, state, apiQueryReducer(state, action))
default:
return state
}
}
|
import Mixin from '@ember/object/mixin';
import $ from 'jquery';
import DS from 'ember-data';
export let Model = Mixin.create({
name: DS.attr('string'),
getValidations: function () {
let parentValidations = this._super();
let thisValidations = {
};
return $.extend(true, {}, parentValidations, thisValidations);
},
init: function () {
this.set('validations', this.getValidations());
this._super(...arguments);
}
});
|
// # Ghost Configuration
// Setup your Ghost install for various environments
// Documentation can be found at http://support.ghost.org/config/
var path = require('path'),
config;
config = {
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
url: 'http://localhost',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://my-ghost-blog.com',
mail: {},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing MySQL
// Used by Travis - Automated testing run through GitHub
'testing-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing pg
// Used by Travis - Automated testing run through GitHub
'testing-pg': {
url: 'http://127.0.0.1:2369',
database: {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
}
};
// Export config
module.exports = config;
|
---
yuiCompress: !!bool true
---
(function($, window, document) {
/**
* Currently loaded page information.
*/
var curPage,
/**
* This function should be called in the jQuery click handler of a link
* element (`a`). It will try to use AJAX and history magic to keep page
* loading asynchronous. If it succeeds, it wil fire an event that may
* trigger some fancy animations, who knows.
*
* \param href The path to navigate to. Defaults to \c href attribute of
* \c this (so this function can be applied on \c a elements).
* \param itemId The ID of the page to navigate to. Defaults to
* \c data-id of \c this.
*/
navigate = function(href, itemId) {
if (historySupport) {
if (typeof(href) !== 'string') {
href = $(this).attr('href');
}
if (typeof(itemId) !== 'string') {
itemId = $(this).data('id');
}
$(window).trigger('denvelop-navigating', [curPage, itemId]);
$.ajax({
url: href + 'page.json',
success: updatePage,
dataType: 'json',
cache: false
});
}
// if there is no history support, do the default action (follow the
// link), otherwise we have handled it already above
return !historySupport;
},
/**
* If the browswer supports the history API. This is checked by seeing
* if functions we need are defined. We hope they are defined correctly.
*/
historySupport = (typeof(window.history.pushState) === 'function' &&
typeof(window.history.replaceState) === 'function'),
/**
* Add click handlers to links in the navigation menu to call the
* `navigate` function defined above.
*/
updateHeaderLinks = function(enable) {
if (typeof(enable) !== 'boolean') {
enable = true;
}
if (enable) {
$('#header a, .nav-link').on('click', navigate);
} else {
$('#header a, .nav-link').off();
}
},
/**
* Update page content from the given state. Possibly add the state to
* the history too.
*/
updatePage = function(page, addHistoryState) {
if (page.url === curPage.url) {
$(window).trigger('denvelop-navigated', [curPage, page]);
return;
}
if (typeof(addHistoryState) !== 'boolean') {
addHistoryState = historySupport;
}
// possibly push the new state on the history stack
if (addHistoryState) {
// not using page.url because the URL may need to be relative
window.history.pushState(page, page.title, this.url.split('page.json?')[0]);
}
// update document content and header, re-attach handlers in header
document.title = page.title;
updatePageContent(page);
updateHeaderLinks(false);
$('#header').children(':not(#logo)').remove();
$('#header').append($(page.header).filter(':not(#logo)'));
updateHeaderLinks();
$('html').attr('lang', page.lang);
// swap curPage and trigger custom event
$(window).trigger('denvelop-navigated', [curPage, page]);
curPage = page;
},
/**
* Update the page content using an animation.
*/
updatePageContent = function(page, oldPage) {
if (updatingPageContent) {
updatePageContentNext = page;
return;
}
if (typeof(oldPage) === 'undefined') {
oldPage = curPage;
}
updatingPageContent = true;
var content = $('#content'),
contentM = parseInt(content.css('margin-left')),
contentP = parseInt(content.css('padding-left')),
contentW = content.width(),
newContent = $('<div />', { html: page.html }),
contentWrap = $('<div />'),
contentWrapWrap = $('<div />'),
scrollLeft = (getPageIndex(oldPage) < getPageIndex(page));
contentWrap.css({
width: contentW * 2 + contentM * 4
});
contentWrapWrap.css({
width: contentW + contentM * 2,
overflow: 'hidden',
padding: contentP
});
if (content.css('display') === 'inline-block') {
contentWrapWrap.css('display', 'inline-block');
}
content.add(newContent).css({
display: 'inline-block',
verticalAlign: 'top',
width: contentW,
margin: contentM,
padding: contentP
});
content.wrap(contentWrapWrap);
content.wrap(contentWrap);
// do some animating
var mStart = (scrollLeft ? 0 : -contentW - contentM * 2),
mEnd = (scrollLeft ? -contentW - contentM * 2 : 0);
if (scrollLeft) {
content.after(newContent);
} else {
content.before(newContent);
}
content.parent().css('marginLeft', mStart).animate({
marginLeft: mEnd
}, function() {
// actually remove the old content now that it is off screen
content.parent().css('marginLeft', 0)
content.remove();
// make the newly shown content the actual #content
newContent.unwrap().unwrap()
.attr('id', 'content')
.removeAttr('style');
updatingPageContent = false;
// check if a request has come in in the meantime
if (updatePageContentNext !== null) {
var newPage = updatePageContentNext;
updatePageContentNext = null;
if (newPage.url !== page.url) {
updatePageContent(newPage, page);
}
}
});
},
/**
* If a content update animation is currently running.
*/
updatingPageContent = false,
/**
* Page to navigate to when the currently running content update
* animation is stopped.
*/
updatePageContentNext = null,
/**
* Given a page, return an absolute index that can be used to order pages.
*/
getPageIndex = function(page) {
var index = 0,
split = page.url.split('/'),
navItems = $('<div />').html(page.header).find('#nav > li');
index += navItems.size() *
(split.length > 1 && split[1] === 'en' ? 0 : 1);
index += navItems.index(navItems.filter(function(index) {
return ($('a, span', this).attr('data-url') === page.url);
}));
return index;
};
$(function() {
if (historySupport) {
var $window = $(window);
// save the current state
curPage = {
id: $('.nav-icon.active').attr('data-id'),
title: document.title,
url: window.location.pathname,
header: $('#header').html(),
html: $('#content').html()
};
window.history.replaceState(curPage, document.title, '');
// process all navigational links to use AJAX
updateHeaderLinks();
// listen for custom events
$window.on('denvelop-navigate', function(event, href, itemId) {
navigate(href, itemId);
});
// attach an event handler for when the user uses 'prev' and 'next'
$window.on('popstate', function(event) {
$window.trigger('denvelop-navigating', [curPage, event.originalEvent.state.id]);
updatePage(event.originalEvent.state, false);
});
}
});
}(jQuery, window, document));
|
/* eslint-disable
func-names,
prefer-arrow-callback,
*/
const maxRecursive = require('./maxRecursive');
it(`maxRecursive`, function() {
const len = 1e4;
const array = Array.from(Array(len), () => Math.random());
console.time(`\nmaxRecursive`);
const max = maxRecursive(array);
console.timeEnd(`\nmaxRecursive`);
expect(max).toBe(Math.max(...array));
});
|
'use strict'
const Router = require('../..').Server
const program = require('commander')
program
.version('0.0.1')
.option('-p, --port [Port]', 'The used port', 3000)
.parse(process.argv)
const port = program.port
const app = new Router()
app.newRoute()
.matchPath('/')
.toEndpoint('http://www.zalando-lounge.de')
.withFilter('requestHeader', 'Host', 'www.zalando-lounge.de')
.save()
app.newRoute()
.matchPath('/*path')
.toEndpoint('http://www.zalando-lounge.de')
.withFilter('requestHeader', 'Host', 'www.zalando-lounge.de')
.save()
app.listen(port)
console.log(`running on ${port}`) |
/**
* Created by JXP1195 on 7/2/2015.
*/
asyncTest(callbackTest);
console.log('not done');
function asyncTest(cbt){
setTimeout(function(){cbt('done')},1500);
}
function callbackTest(output){
console.log(output);
} |
angular
.module('controllers.news-detail.controller', [])
.controller('NewsDetailController', [
'$scope',
'$stateParams',
'News',
'$ionicNavBarDelegate',
'$window',
function($scope, $stateParams, News, $ionicNavBarDelegate, $window) {
$scope.article = News.get($stateParams.id);
$scope.onPublishedChange = function () {
if ($scope.article.published === true) {
$scope.article.date_published = new Date();
}
};
$scope.newsSaveClick = function () {
var data = $scope.article;
data.date_published = $window.moment(data.date_published).format('YYYY-MM-DD');
if (data.date_published === 'Invalid date') {
delete data.date_published;
}
News
.save(data)
.then(function () {
$ionicNavBarDelegate.back();
}, function () {
});
};
}
]);
|
$(document).ready(function () {
$('.button-collapse').sideNav();
});
Template.ApplicationLayout.events({
"click .menu-item": function (event, template) {
// FIXME change to $('.button-collapse').sideNav('hide'); (https://github.com/Dogfalo/materialize/issues/411)
$('#sidenav-overlay').trigger('click');
}
}); |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define("require exports ../../../core/tsSupport/assignHelper ../../../core/tsSupport/extendsHelper ../../../Color ./support/colors ./support/SymbologyBase ./support/utils".split(" "),function(m,k,q,t,f,u,v,n){function r(e,b,a){var c="mesh"!==e.geometryType&&e.worldScale?e.view:null,d=u[b];if(d){b=(e.theme||"default")+"/"+e.basemap+"/"+b;var h=[],g;for(g in d)"stops"!==g&&"name"!==g&&"tags"!==g&&h.push({numClasses:+g,colors:d[g]});switch(e.geometryType){case "point":case "multipoint":return e=a.noDataColor,
g=a.outline,a=a.size,{id:b,name:d.name,tags:d.tags.slice(),colorsForClassBreaks:l(h),noDataColor:new f(e),outline:{color:new f(g.color),width:g.width},size:c?n.toWorldScale(a,c):a,opacity:1};case "polyline":return e=a.noDataColor,a=a.width,{id:b,name:d.name,tags:d.tags.slice(),colorsForClassBreaks:l(h),noDataColor:new f(e),opacity:1,width:c?n.toWorldScale(a,c):a};case "polygon":return c=a.noDataColor,e=a.fillOpacity,a=a.outline,{id:b,name:d.name,tags:d.tags.slice(),colorsForClassBreaks:l(h),noDataColor:new f(c),
outline:{color:new f(a.color),width:a.width},opacity:e};case "mesh":return c=a.noDataColor,a=a.fillOpacity,{id:b,name:d.name,tags:d.tags.slice(),colorsForClassBreaks:l(h),noDataColor:new f(c),opacity:a}}}}function l(e){return e.map(function(b){return{numClasses:b.numClasses,colors:b.colors.map(function(a){return a.map(function(a){return new f(a)})})}})}m={color:[153,153,153,.25],width:"1px"};k="relationship-brewer-yellow-blue-black relationship-brewer-pink-blue-purple relationship-purple-green-blue relationship-blue-green-purple relationship-blue-orange-green relationship-mustard-blue-wine relationship-pink-blue-purple relationship-olive-blue-green relationship-yellow-cyan-blue relationship-blue-pink-purple relationship-purple-green-wine".split(" ");
var p="relationship-brewer-yellow-blue-black relationship-brewer-pink-blue-purple relationship-purple-green-blue relationship-blue-green-purple relationship-blue-orange-green relationship-mustard-blue-wine relationship-pink-blue-purple relationship-olive-blue-green relationship-yellow-cyan-blue relationship-blue-pink-purple relationship-purple-green-wine".split(" "),w={default:{name:"default",label:"Default",description:"Default theme for visualizing features based on relationship between two attributes.",
schemes:{point:{light:{common:{noDataColor:"#aaaaaa",outline:m,size:"8px"},primary:"relationship-blue-orange-brown",secondary:k},dark:{common:{noDataColor:"#aaaaaa",outline:{color:[26,26,26,.25],width:"1px"},size:"8px"},primary:"relationship-blue-orange-brown",secondary:p}},polyline:{light:{common:{noDataColor:"#aaaaaa",width:"2px"},primary:"relationship-blue-orange-brown",secondary:k},dark:{common:{noDataColor:"#aaaaaa",width:"2px"},primary:"relationship-blue-orange-brown",secondary:p}},polygon:{light:{common:{noDataColor:"#aaaaaa",
outline:m,fillOpacity:.8},primary:"relationship-blue-orange-brown",secondary:k},dark:{common:{noDataColor:"#aaaaaa",outline:{color:[153,153,153,.25],width:"1px"},fillOpacity:.8},primary:"relationship-blue-orange-brown",secondary:p}}}}};return new (function(e){function b(){return e.call(this,{themeDictionary:w})||this}t(b,e);b.prototype.getSchemes=function(a){var c=this.getRawSchemes({theme:"default",basemap:a.basemap,geometryType:a.geometryType,basemapTheme:a.basemapTheme});if(c){var d=c.schemesInfo,
h=c.basemapId,c=c.basemapTheme,g=q({},a,{basemap:h});return{primaryScheme:r(g,d.primary,d.common),secondarySchemes:d.secondary.map(function(a){return r(g,a,d.common)}).filter(Boolean),basemapId:h,basemapTheme:c}}};b.prototype.getSchemeByName=function(a){return this.filterSchemesByName(a)};b.prototype.getSchemesByTag=function(a){return this.filterSchemesByTag(a)};b.prototype.cloneScheme=function(a){if(a)return a=q({},a),a.colorsForClassBreaks=a.colorsForClassBreaks.map(function(a){return{numClasses:a.numClasses,
colors:a.colors.map(function(a){return a.map(function(a){return new f(a)})})}}),a.noDataColor&&(a.noDataColor=new f(a.noDataColor)),"outline"in a&&a.outline&&(a.outline={color:a.outline.color&&new f(a.outline.color),width:a.outline.width}),a};b.prototype.flatten2DArray=function(a,c){var d=[];c=(c||"HH").split("");var b=c[1];"L"===c[0]&&a.reverse();var g="H"===b;a.forEach(function(a){g&&a.reverse();d=d.concat(a)});return d};b.prototype.getColors=function(a,c,d){var b;a.colorsForClassBreaks.some(function(a){a.numClasses===
c&&(b=a.colors);return!!b});return(b=b.map(function(a){return a.map(function(a){return new f(a)})}))?this.flatten2DArray(b,d):null};b.prototype.flipColors=function(a,c){a=c?a:this.cloneScheme(a);a.colorsForClassBreaks.forEach(function(a){for(var c=a.colors.reverse(),d=[],b=function(a){var b=[];c.forEach(function(c){b.push(c[a])});d.push(b)},e=0;e<a.numClasses;e++)b(e);a.colors=d});return a};b.prototype.getMatchingSchemes=function(a){var c=this,d=a.theme||"default",b=a.geometryType,g=a.colors,e=a.numClasses;
if(a=this.themes.get(d)){var f=[];a.supportedBasemaps.forEach(function(a){if(a=c.getSchemes({theme:d,basemap:a,geometryType:b})){var h=c._compareColorsComprehensive(a.primaryScheme,g,e);h&&f.push(h);a.secondarySchemes.forEach(function(a){(h=c._compareColorsComprehensive(a,g,e))&&f.push(h)})}});return f}};b.prototype._compareColors=function(a,c,b,e){var d;(b=this.getColors(a,b,e))&&1===n.hasIdenticalColors(c,b)&&(d=a);return d};b.prototype._compareColorsByFocus=function(a,b,d,e){var c,f=1;do c=this._compareColors(a,
b,d,e),c||(a=this.flipColors(a),f++);while(!c&&4>=f);return c};b.prototype._compareColorsComprehensive=function(a,b,d){return this._compareColorsByFocus(a,b,d,"HH")||this._compareColorsByFocus(a,b,d,"HL")||this._compareColorsByFocus(a,b,d,"LH")||this._compareColorsByFocus(a,b,d,"LL")};return b}(v))}); |
angular.module('orderCloud')
.directive('ocQuantityInput', OCQuantityInput)
;
function OCQuantityInput(toastr, OrderCloudSDK, $rootScope) {
return {
scope: {
product: '=',
lineitem: '=',
label: '@',
order: '=',
onUpdate: '&'
},
templateUrl: 'common/templates/quantityInput.tpl.html',
replace: true,
link: function (scope) {
if (scope.product){
scope.item = scope.product;
scope.content = "product"
}
else if(scope.lineitem){
OrderCloudSDK.Me.GetProduct(scope.lineitem.ProductID)
.then(function(product) {
scope.item = scope.lineitem;
if (product.PriceSchedule && !product.PriceSchedule.RestrictedQuantity) {
scope.item.MinQty = product.PriceSchedule.MinQuantity;
scope.item.MaxQty = product.PriceSchedule.MaxQuantity;
} else {
scope.item.PriceBreaks = product.PriceSchedule.PriceBreaks;
}
scope.content = "lineitem";
scope.updateQuantity = function() {
if (scope.item.Quantity) {
OrderCloudSDK.LineItems.Patch('outgoing', scope.order.ID, scope.item.ID, {Quantity: scope.item.Quantity})
.then(function (data) {
if(data.ProductID === 'AACPunchoutProduct'){
data.Punchout = true;
}
data.Product = scope.lineitem.Product;
scope.item = data;
scope.lineitem = data;
if (typeof scope.onUpdate === "function") scope.onUpdate(scope.lineitem);
toastr.success('Quantity Updated');
$rootScope.$broadcast('OC:UpdateOrder', scope.order.ID, 'Calculating Order Total');
});
}
}
})
}
else {
toastr.error('Please input either a product or lineitem attribute in the directive','Error');
console.error('Please input either a product or lineitem attribute in the quantityInput directive ')
}
}
}
}
|
export const iosBarcode = {"viewBox":"0 0 512 512","children":[{"name":"g","attribs":{},"children":[{"name":"path","attribs":{"d":"M48,128v256h416V128H48z M128,320h-16V192h16V320z M192,352h-16V160h16V352z M263,336h-16V176h16V336z M336,352h-16V160h16\r\n\t\tV352z M400,320h-16V192h16V320z"},"children":[{"name":"path","attribs":{"d":"M48,128v256h416V128H48z M128,320h-16V192h16V320z M192,352h-16V160h16V352z M263,336h-16V176h16V336z M336,352h-16V160h16\r\n\t\tV352z M400,320h-16V192h16V320z"},"children":[]}]}]}]}; |
angular.module("ui.bootstrap", ["ui.bootstrap.tpls", "ui.bootstrap.modal"]);
angular.module("ui.bootstrap.tpls", ["template/modal/backdrop.html","template/modal/window.html"]);
angular.module('ui.bootstrap.modal', [])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* elements in the LIFO order
*/
.factory('$$stackedMap', function () {
return {
createNew: function () {
var stack = [];
return {
add: function (key, value) {
stack.push({
key: key,
value: value
});
},
get: function (key) {
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
return stack[i];
}
}
},
keys: function() {
var keys = [];
for (var i = 0; i < stack.length; i++) {
keys.push(stack[i].key);
}
return keys;
},
top: function () {
return stack[stack.length - 1];
},
remove: function (key) {
var idx = -1;
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
idx = i;
break;
}
}
return stack.splice(idx, 1)[0];
},
removeTop: function () {
return stack.splice(stack.length - 1, 1)[0];
},
length: function () {
return stack.length;
}
};
}
};
})
/**
* A helper directive for the $modal service. It creates a backdrop element.
*/
.directive('modalBackdrop', ['$modalStack', '$timeout', function ($modalStack, $timeout) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/modal/backdrop.html',
link: function (scope, element, attrs) {
//trigger CSS transitions
$timeout(function () {
scope.animate = true;
});
scope.close = function (evt) {
var modal = $modalStack.getTop();
if (modal && modal.value.backdrop && modal.value.backdrop != 'static') {
evt.preventDefault();
evt.stopPropagation();
$modalStack.dismiss(modal.key, 'backdrop click');
}
};
}
};
}])
.directive('modalWindow', ['$timeout', function ($timeout) {
return {
restrict: 'EA',
scope: {
index: '@'
},
replace: true,
transclude: true,
templateUrl: 'template/modal/window.html',
link: function (scope, element, attrs) {
scope.windowClass = attrs.windowClass || '';
//trigger CSS transitions
$timeout(function () {
scope.animate = true;
});
}
};
}])
.factory('$modalStack', ['$document', '$compile', '$rootScope', '$$stackedMap',
function ($document, $compile, $rootScope, $$stackedMap) {
var backdropjqLiteEl, backdropDomEl;
var backdropScope = $rootScope.$new(true);
var body = $document.find('body').eq(0);
var openedWindows = $$stackedMap.createNew();
var $modalStack = {};
function backdropIndex() {
var topBackdropIndex = -1;
var opened = openedWindows.keys();
for (var i = 0; i < opened.length; i++) {
if (openedWindows.get(opened[i]).value.backdrop) {
topBackdropIndex = i;
}
}
return topBackdropIndex;
}
$rootScope.$watch(backdropIndex, function(newBackdropIndex){
backdropScope.index = newBackdropIndex;
});
function removeModalWindow(modalInstance) {
var modalWindow = openedWindows.get(modalInstance).value;
//clean up the stack
openedWindows.remove(modalInstance);
//remove window DOM element
modalWindow.modalDomEl.remove();
//remove backdrop if no longer needed
if (backdropIndex() == -1) {
backdropDomEl.remove();
backdropDomEl = undefined;
}
//destroy scope
modalWindow.modalScope.$destroy();
}
$document.bind('keydown', function (evt) {
var modal;
if (evt.which === 27) {
modal = openedWindows.top();
if (modal && modal.value.keyboard) {
$rootScope.$apply(function () {
$modalStack.dismiss(modal.key);
});
}
}
});
$modalStack.open = function (modalInstance, modal) {
openedWindows.add(modalInstance, {
deferred: modal.deferred,
modalScope: modal.scope,
backdrop: modal.backdrop,
keyboard: modal.keyboard
});
var angularDomEl = angular.element('<div modal-window></div>');
angularDomEl.attr('window-class', modal.windowClass);
angularDomEl.attr('index', openedWindows.length() - 1);
angularDomEl.html(modal.content);
var modalDomEl = $compile(angularDomEl)(modal.scope);
openedWindows.top().value.modalDomEl = modalDomEl;
body.append(modalDomEl);
if (backdropIndex() >= 0 && !backdropDomEl) {
backdropjqLiteEl = angular.element('<div modal-backdrop></div>');
backdropDomEl = $compile(backdropjqLiteEl)(backdropScope);
body.append(backdropDomEl);
}
};
$modalStack.close = function (modalInstance, result) {
var modal = openedWindows.get(modalInstance);
if (modal) {
modal.value.deferred.resolve(result);
removeModalWindow(modalInstance);
}
};
$modalStack.dismiss = function (modalInstance, reason) {
var modalWindow = openedWindows.get(modalInstance).value;
if (modalWindow) {
modalWindow.deferred.reject(reason);
removeModalWindow(modalInstance);
}
};
$modalStack.getTop = function () {
return openedWindows.top();
};
return $modalStack;
}])
.provider('$modal', function () {
var $modalProvider = {
options: {
backdrop: true, //can be also false or 'static'
keyboard: true
},
$get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack',
function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) {
var $modal = {};
function getTemplatePromise(options) {
return options.template ? $q.when(options.template) :
$http.get(options.templateUrl, {cache: $templateCache}).then(function (result) {
return result.data;
});
}
function getResolvePromises(resolves) {
var promisesArr = [];
angular.forEach(resolves, function (value, key) {
if (angular.isFunction(value) || angular.isArray(value)) {
promisesArr.push($q.when($injector.invoke(value)));
}
});
return promisesArr;
}
$modal.open = function (modalOptions) {
var modalResultDeferred = $q.defer();
var modalOpenedDeferred = $q.defer();
//prepare an instance of a modal to be injected into controllers and returned to a caller
var modalInstance = {
result: modalResultDeferred.promise,
opened: modalOpenedDeferred.promise,
close: function (result) {
$modalStack.close(modalInstance, result);
},
dismiss: function (reason) {
$modalStack.dismiss(modalInstance, reason);
}
};
//merge and clean up options
modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
modalOptions.resolve = modalOptions.resolve || {};
//verify options
if (!modalOptions.template && !modalOptions.templateUrl) {
throw new Error('One of template or templateUrl options is required.');
}
var templateAndResolvePromise =
$q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
templateAndResolvePromise.then(function resolveSuccess(tplAndVars) {
var modalScope = (modalOptions.scope || $rootScope).$new();
modalScope.$close = modalInstance.close;
modalScope.$dismiss = modalInstance.dismiss;
var ctrlInstance, ctrlLocals = {};
var resolveIter = 1;
//controllers
if (modalOptions.controller) {
ctrlLocals.$scope = modalScope;
ctrlLocals.$modalInstance = modalInstance;
angular.forEach(modalOptions.resolve, function (value, key) {
ctrlLocals[key] = tplAndVars[resolveIter++];
});
ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
}
$modalStack.open(modalInstance, {
scope: modalScope,
deferred: modalResultDeferred,
content: tplAndVars[0],
backdrop: modalOptions.backdrop,
keyboard: modalOptions.keyboard,
windowClass: modalOptions.windowClass
});
}, function resolveError(reason) {
modalResultDeferred.reject(reason);
});
templateAndResolvePromise.then(function () {
modalOpenedDeferred.resolve(true);
}, function () {
modalOpenedDeferred.reject(false);
});
return modalInstance;
};
return $modal;
}]
};
return $modalProvider;
});
angular.module("template/modal/backdrop.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/modal/backdrop.html",
"<div class=\"modal-backdrop fade\" ng-class=\"{in: animate}\" ng-style=\"{'z-index': 1040 + index*10}\" ng-click=\"close($event)\"></div>");
}]);
angular.module("template/modal/window.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/modal/window.html",
"<div class=\"modal fade {{ windowClass }}\" ng-class=\"{in: animate}\" ng-style=\"{'z-index': 1050 + index*10}\" ng-transclude></div>");
}]);
|
angular
.module('openeApp.workflows')
.controller('StartParallelGroupReviewWorkflowController', StartParallelGroupReviewWorkflowController);
function StartParallelGroupReviewWorkflowController($controller, groupService, workflowDef) {
angular.extend(this, $controller('BaseStartCaseWorkflowController', {}));
var vm = this;
vm.workflowDef = workflowDef;
vm.BaseStartCaseWorkflowController_getWorkflowInfo = vm.getWorkflowInfo;
vm.getWorkflowInfo = getWorkflowInfo;
init();
function init(){
vm.init();
groupService.listGroupsByType('OE').then(function(result){
vm.recipients = result.data.map(function(item){
return {
name: item.displayName,
nodeRef: item.fullName
};
});
});
}
function getWorkflowInfo(){
var wi = vm.BaseStartCaseWorkflowController_getWorkflowInfo();
angular.merge(wi, {
assignToGroup: vm.selectedRecipient,
properties: {
wf_requiredApprovePercent: vm.requiredApprovalPercentage
}
});
return wi;
}
} |
module.exports = function (grunt) {
grunt.registerTask('serve', [
'concurrent:server',
'connect:server',
'karma:server',
'open',
'watch'
]);
grunt.registerTask('serve:dist', [
'connect:dist',
'open'
]);
};
|
export const initialState = {
user: null
}
export const getUser = (state = initialState) => state.user
|
var style = document.createElement('style');
var style_str = "@font-face {";
style_str = style_str + "font-family: \"Silkscreen\";";
style_str = style_str + "src: url(\"type/slkscr.ttf\");";
style_str = style_str + "}";
style.innerHTML = style_str;
document.documentElement.appendChild(style);
var docCookies={getItem:function(e){if(!e||!this.hasItem(e)){return null}return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"),"$1"))},setItem:function(e,t,n,r,i,s){if(!e||/^(?:expires|max\-age|path|domain|secure)$/i.test(e)){return}var o="";if(n){switch(n.constructor){case Number:o=n===Infinity?"; expires=Tue, 19 Jan 2038 03:14:07 GMT":"; max-age="+n;break;case String:o="; expires="+n;break;case Date:o="; expires="+n.toGMTString();break}}document.cookie=escape(e)+"="+escape(t)+o+(i?"; domain="+i:"")+(r?"; path="+r:"")+(s?"; secure":"")},removeItem:function(e,t){if(!e||!this.hasItem(e)){return}document.cookie=escape(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT"+(t?"; path="+t:"")},hasItem:function(e){return(new RegExp("(?:^|;\\s*)"+escape(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=")).test(document.cookie)}}
var user_jo = null;
var currentURL = "";
var currentId = "";
var currentHostname = "";
var t_jo = null;
var threadstatus = 0;
var msfe_according_to_backend = (new Date).getTime(); // set to local machine time to start... will be reset to backend time by first thread call.
var hn_login_step = 0;
var hn_existing_about = "";
var likedislikemode = "none";
var latest_ext_version = null;
var hn_topcolor = "ff6600";
var user_retrieval_loop_is_running = false;
var updatebutton = true;
(function() {
chrome.tabs.getSelected(null, function(tab) {
currentURL = tab.url;
currentId = tab.id;
currentHostname = getStandardizedHostname(currentURL);
var canvas = document.getElementById("button_canvas");
var context = canvas.getContext("2d");
context.fillStyle = "#ffffff";
context.font = "8px Silkscreen";
context.fillText("PRIMER",0,0);
drawHButton("gray", "white");
getUser(true); // user_jo should always be null when this is called
});
})();
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.method === "logout")
{
//alert("bg listener logout method");
docCookies.removeItem("screenname");
docCookies.removeItem("this_access_token");
sendResponse({message: "You are now logged out."});
}
else if(request.method == "getEndpoint") // don't need a getter for this as the receiver page can get this directly from cookie
{
sendResponse({endpoint: endpoint});
}
else if(request.method == "getCounts") // don't need a getter for this as the receiver page can get this directly from cookie
{
if(user_jo && typeof user_jo.notification_count !== "undefined" && user_jo.notification_count !== null && typeof user_jo.newsfeed_count !== "undefined" && user_jo.newsfeed_count !== null)
sendResponse({no: user_jo.notification_count, nf: user_jo.newsfeed_count});
else
sendResponse({no: 0, nf: 0});
}
else if(request.method == "sendRedirect") // don't need a getter for this as the receiver page can get this directly from cookie
{
chrome.tabs.update(sender.tab.id, {url: request.location});
}
else if(request.method == "closeTab") // don't need a getter for this as the receiver page can get this directly from cookie
{
chrome.tabs.remove(sender.tab.id);
}
else if(request.method == "setLastTabID") // don't need a getter for this as the receiver page can get this directly from cookie
{
docCookies.setItem("last_tab_id", request.last_tab_id);
}
else if(request.method === "getHNLoginStep") // don't need a getter for this as the receiver page can get this directly from cookie
{
sendResponse({hn_login_step: hn_login_step});
}
else if(request.method === "setHNLoginStep") // don't need a getter for this as the receiver page can get this directly from cookie
{
//alert("bg setting hn_login_step to " + request.hn_login_step);
hn_login_step = request.hn_login_step;
sendResponse({response_status: "success"});
}
else if(request.method === "getHNExistingAbout") // don't need a getter for this as the receiver page can get this directly from cookie
{
sendResponse({hn_existing_about: hn_existing_about});
}
else if(request.method === "setHNExistingAbout") // don't need a getter for this as the receiver page can get this directly from cookie
{
//alert("bg setting hn_existing_about to " + request.hn_existing_about);
hn_existing_about = request.hn_existing_about;
sendResponse({response_status: "success"});
}
else if(request.method === "isUserLoggedInToExtension") // don't need a getter for this as the receiver page can get this directly from cookie
{
var sn = docCookies.getItem("screenname");
if(sn === null || (sn !== request.detected_screenname))
sendResponse({logged_in: "no"});
else // user appears to be logged in already. Assume this sn and tat are valid until user tries to do something
sendResponse({logged_in: "yes"});
}
else if(request.method === "getHNAuthToken") // don't need a getter for this as the receiver page can get this directly from cookie
{
var tabid = 0;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
tabid = tabs[0].id;
$.ajax({
type: 'GET',
url: endpoint,
data: {
method: "getHNAuthToken",
screenname: request.detected_screenname
},
dataType: 'json',
timeout: 10000,
async: true,
success: function (data, status) {
if(data.response_status === "success")
{
chrome.tabs.sendMessage(tabid, {method: "gotHNAuthToken", token: data.token, manual_or_automatic: request.manual_or_automatic}, function(response) {});
}
else if(data.response_status === "error")
{
chrome.tabs.sendMessage(tabid, {method: "gotHNAuthToken", token: null}, function(response) {});
}
else
{
chrome.tabs.sendMessage(tabid, {method: "gotHNAuthToken", token: null}, function(response) {});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("getHNAuthToken ajax error");
chrome.tabs.sendMessage(tabid, {method: "gotHNAuthToken", token: null}, function(response) {});
}
});
});
}
else if(request.method === "tellBackendToCheckUser")
{
// set up ajax to backend and have it check the user's page
var tabid = 0;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
tabid = tabs[0].id;
$.ajax({
type: 'GET',
url: endpoint,
data: {
method: "verifyHNUser",
screenname: request.detected_screenname,
topcolor: request.topcolor
},
dataType: 'json',
timeout: 44000,
async: true,
success: function (data, status) {
if(data.response_status === "success")
{
if(data.verified === true)
{
docCookies.setItem("screenname", data.screenname, 31536e3);
docCookies.setItem("this_access_token", data.this_access_token, 31536e3);
getUser(false);
}
chrome.tabs.sendMessage(tabid, {method: "gotHNUserVerificationResponse", user_verified: data.verified}, function(response) {});
}
else if(data.response_status === "error")
{
console.log("verifyHNUser ajax success but r_s error");
alert("The Hackbook backend encountered an error communicating with the Hacker News API.\nThe API may be experiencing issues or it could simply be a temporary read error.\nGive it another try and it'll probably work.");
chrome.tabs.sendMessage(tabid, {method: "gotHNUserVerificationResponse", user_verified: false, alert_msg: data.message}, function(response) {});
}
else
{
console.log("verifyHNUser ajax success but r_s neither success nor error");
alert("verifyHNUser ajax success but r_s neither success nor error");
chrome.tabs.sendMessage(tabid, {method: "gotHNUserVerificationResponse", user_verified: false}, function(response) {});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("verifyHNUser ajax error");
alert("Timeout error.\nSometimes there is latency from the HN API.\nA second try usually works. Sorry.");
chrome.tabs.sendMessage(tabid, {method: "gotHNUserVerificationResponse", user_verified: false}, function(response) {});
}
});
});
}
else if(request.method === "getFollowing")
{
if(user_jo)
sendResponse({following: user_jo.following});
else
sendResponse({following: null});
}
else if(request.method === "followUser") // don't need a getter for this as the receiver page can get this directly from cookie
{
var target_screenname = request.target_screenname;
var screenname = docCookies.getItem("screenname");
var this_access_token = docCookies.getItem("this_access_token");
if(screenname !== null && this_access_token !== null && this_access_token.length == 32)// the shortest possible screenname length is x@b.co = 6.
{
if(screenname === target_screenname)
{
if(request.runtime_or_tabs === "runtime")
chrome.runtime.sendMessage({method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "that's you"}, function(response) {});
else
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "that's you"}, function(response) {});
});
}
}
else
{
$.ajax({
type: 'GET',
url: endpoint,
data: {
method: "followUser",
target_screenname: target_screenname,
screenname: screenname,
this_access_token: this_access_token
},
dataType: 'json',
timeout: 10000,
async: true,
success: function (data, status) {
if (data.response_status == "error")
{
if(request.runtime_or_tabs === "runtime")
chrome.runtime.sendMessage({method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "error"}, function(response) {});
else
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "error"}, function(response) {});
});
}
}
else //if (data.response_status === "success")
{
if(request.runtime_or_tabs === "runtime")
chrome.runtime.sendMessage({method: "userSuccessfullyFollowedSomeone", target_screenname:target_screenname}, function(response) {});
else
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {method: "userSuccessfullyFollowedSomeone", target_screenname:target_screenname}, function(response) {});
});
}
getUser(false); // refresh the user object with this new follow
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
if(request.runtime_or_tabs === "runtime")
chrome.runtime.sendMessage({method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "ajax error"}, function(response) {});
else
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "ajax error"}, function(response) {});
});
}
}
});
}
}
}
else if(request.method === "unfollowUser") // don't need a getter for this as the receiver page can get this directly from cookie
{
var target_screenname = request.target_screenname;
var screenname = docCookies.getItem("screenname");
var this_access_token = docCookies.getItem("this_access_token");
if(screenname !== null && this_access_token !== null && this_access_token.length == 32)// the shortest possible screenname length is x@b.co = 6.
{
if(screenname === target_screenname)
{
if(request.runtime_or_tabs === "runtime")
chrome.runtime.sendMessage({method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "that's you"}, function(response) {});
else
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "that's you"}, function(response) {});
});
}
}
else
{
$.ajax({
type: 'GET',
url: endpoint,
data: {
method: "unfollowUser",
target_screenname: target_screenname,
screenname: screenname,
this_access_token: this_access_token
},
dataType: 'json',
timeout: 10000,
async: true,
success: function (data, status) {
if (data.response_status == "error")
{
if(request.runtime_or_tabs === "runtime")
chrome.runtime.sendMessage({method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "error"}, function(response) {});
else
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "error"}, function(response) {});
});
}
}
else //if (data.response_status === "success")
{
if(request.runtime_or_tabs === "runtime")
chrome.runtime.sendMessage({method: "userSuccessfullyUnfollowedSomeone", target_screenname:target_screenname}, function(response) {});
else
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {method: "userSuccessfullyUnfollowedSomeone", target_screenname:target_screenname}, function(response) {});
});
}
getUser(false); // refresh the user object with this new unfollow
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
if(request.runtime_or_tabs === "runtime")
chrome.runtime.sendMessage({method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "ajax error"}, function(response) {});
else
{
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {method: "userFailedToFollowOrUnfollowSomeone", target_screenname:target_screenname, message: "ajax error"}, function(response) {});
});
}
}
});
}
}
}
else if(request.method === "getLikeDislikeMode") // don't need a getter for this as the receiver page can get this directly from cookie
{
sendResponse({likedislikemode: likedislikemode});
}
else if(request.method === "setLikeDislikeMode") // don't need a getter for this as the receiver page can get this directly from cookie
{
likedislikemode = request.likedislikemode
sendResponse({message: "success"});
}
else if(request.method === "getHideInlineFollow") // don't need a getter for this as the receiver page can get this directly from cookie
{
if(user_jo && typeof user_jo.hide_inline_follow !== "undefined" && user_jo.hide_inline_follow !== null)
sendResponse({hide_inline_follow: user_jo.hide_inline_follow});
else
sendResponse({hide_inline_follow: true});
}
else if(request.method === "getParentOfItem") // don't need a getter for this as the receiver page can get this directly from cookie
{
var tabid = 0;
var index = request.index;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
tabid = tabs[0].id;
$.ajax({
type: 'GET',
url: endpoint,
data: {
method: "getItem",
id: request.detected_child_id
},
dataType: 'json',
timeout: 10000,
async: true,
success: function (data, status) {
if(data.response_status === "success")
{
$.ajax({
type: 'GET',
url: endpoint,
data: {
method: "getItem",
id: data.item_jo.parent
},
dataType: 'json',
timeout: 10000,
async: true,
success: function (data, status) {
if(data.response_status === "success")
{
var time_ago_string = agoIt(data.item_jo.time*1000);
chrome.tabs.sendMessage(tabid, {method: "gotParentOfItem", item_jo: data.item_jo, index:index, time_ago_string:time_ago_string}, function(response) {});
}
else
{
// fail silently
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("getItem ajax error");
// chrome.tabs.sendMessage(tabid, {method: "gotHNAuthToken", token: null}, function(response) {});
}
});
}
else
{
// fail silently
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("getItem ajax error");
// chrome.tabs.sendMessage(tabid, {method: "gotHNAuthToken", token: null}, function(response) {});
}
});
});
}
});
//REAL FUNCTIONS, IN EXECUTION ORDER TOP2BOTTOM (sort of)
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, updatingtab) {
if (changeInfo.status === "loading") // also fires at "complete", which I'm ignoring here. Only need one (this one).
{
chrome.tabs.getSelected(null, function(tab) { // only follow through if the updating tab is the same as the selected tab, don't want background tabs reloading and wrecking stuff
if(user_retrieval_loop_is_running == false) // if the loop has died for any reason (or was never running in the first place), restart it
getUser(true);
if(updatingtab.url === tab.url) // the one that's updating is the one we're looking at. good. proceed
{
if(currentURL !== tab.url) // && tab.url.indexOf("chrome-extension://") !== 0) // only do this if the update is of a new url, no point in reloading the existing url again
{
currentURL = updatingtab.url;
currentId = tab.id;
currentHostname = getStandardizedHostname(currentURL);
doButtonGen();
}
}
else
{
//alert("updating other");
// some other tab is updating. ignore.
}
});
}
else if (changeInfo.status === "complete")
{
//alert("onupdated complete"); (do nothing for now)
}
});
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.getSelected(null, function(tab) {
if(user_retrieval_loop_is_running == false) // if the loop has died for any reason (or was never running in the first place), restart it
getUser(true);
else
getUser(false); // get user on every valid tab change. This updates notifications and logstat (do not getUser on random page updates (i.e. don't getUser(false) in the onUpdated block)
if(typeof tab.url !== "undefined" && tab.url !== null && tab.url !== "")
{
currentURL = tab.url;
currentId = tab.id;
currentHostname = getStandardizedHostname(currentURL);
doButtonGen();
}
});
});
/*
On (tab update or tab change)
{
getUser();
doButtonGen()
{
if(user has feed or notif counts)
{
drawNotificationNumber();
}
getThread(); // if global variable "updatebutton" is true, getThread can write animation and final result (blank or thread count). If false, it doesn't.
}
*/
function drawNotificationNumber()
{
if(user_jo)
{
if(user_jo.notification_mode === "notifications_only")
{
if(user_jo.notification_count === 0)
{
updatebutton = true; // if running, let getThread continue drawing
return false; // we didn't draw anything
}
else
{
updatebutton = false; // if running, stop getThread from drawing
drawHButton("#" + user_jo.hn_topcolor, "black", null, 0, user_jo.notification_count);
}
}
else
{
if(user_jo.newsfeed_count === 0 && user_jo.notification_count === 0)
{
updatebutton = true; // if running, let getThread continue drawing
return false; // we didn't draw anything
}
else
{
updatebutton = false; // if running, stop getThread from drawing
drawHButton("#" + user_jo.hn_topcolor, "black", null, user_jo.newsfeed_count, user_jo.notification_count);
}
}
return true; // we drew a notification number
}
}
function doButtonGen()
{
var url_at_function_call = currentURL; // need to save the currentURL bc if it has changed by the time threads come back, they are irrelevant at that point
t_jo = null;
var drew_notification_number = false;
if(user_jo)
drew_notification_number = drawNotificationNumber();
if(drew_notification_number) // if we drew a notification number, don't overwrite it
{
if(!isValidURLFormation(currentURL))
return;
else
getThread(url_at_function_call); // don't overwrite notification number
}
else
{
if(!isValidURLFormation(currentURL))
drawHButton("gray", "white");
else if(currentURL === "https://news.ycombinator.com" || currentURL === "https://news.ycombinator.com/" || currentURL === "https://news.ycombinator.com/news")
drawHButton("gray", "white");
else
getThread(url_at_function_call); // no notification number, overwrite
}
}
function getParameterByName(inc_url, name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(inc_url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function getThread(url_at_function_call)
{
// This function always calls getThread and getUserSelf (if credentials available) at the same time.
// Once it is finished getting the thread, it updates the button and goes to a ready state for thread viewing.
// The reason these are not called together is because the getThread call can be cached. The user call cannot.
// Adding the user call to the thread call would render getThread uncacheable.
t_jo = null;
var mode = "stealth";
if(typeof user_jo !== "undefined" && user_jo !== null && typeof user_jo.url_checking_mode !== null && user_jo.url_checking_mode !== null)
mode = user_jo.url_checking_mode;
if(mode === "stealth")
{
threadstatus = 1;
var hash = CryptoJS.SHA256(url_at_function_call);
var hn_story_id = null;
if(currentURL.indexOf("https://news.ycombinator.com/item") === 0) // this is an item page, include the hn_story_id in the AJAX call, so we can show the appropriate thread
hn_story_id = getParameterByName(currentURL, "id");
$.ajax({
type: 'GET',
url: endpoint,
data: {
method: "searchForHNItem3",
hashed_url: hash+"",
hn_story_id: hn_story_id,
mode: mode
},
dataType: 'json',
async: true,
success: function (data, status) {
if(data.response_status === "success")
{
msfe_according_to_backend = data.msfe;
if(data.objectID === "-1")
{
// no HN item, these two conditions end the animation and call finishThread();
threadstatus=0;
t_jo = {}; // this means stop animation and there's no item
}
else
{
//alert("Got objectID from Hackbook, querying firebase");
$.ajax({
type: 'GET',
url: "https://hacker-news.firebaseio.com/v0/item/" + data.objectID + ".json",
dataType: 'json',
async: true,
success: function (data, status) {
//alert("success getting object from firebase");
if(typeof data.kids !== "undefined")
{
data.children = data.kids;
delete data.kids;
}
t_jo = data;
threadstatus=0;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert("network error getting object from firebase");
if(currentURL === url_at_function_call)
{
threadstatus=0;
//alert("drawing red HN ajax");
drawHButton("gray", "red");
}
console.log(textStatus, errorThrown);
}
});
}
}
else if(data.response_status === "error")
{
console.log("searchForHNItem response_status=error");
//alert("drawing red searchForHNItem response_status error");
drawHButton("gray", "red");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert("searchForHNItem ajax error");
if(currentURL === url_at_function_call)
{
threadstatus=0;
drawHButton("gray", "red");
}
console.log(textStatus, errorThrown);
}
});
if(updatebutton) // only animate if we've not updated the button
{
var frame = 0;
var animation_loop = setInterval(function(){
// end case
if(frame === 96 && url_at_function_call === currentURL) // we've reached last frame and are still on the correct tab
threadstatus = 0;
if (url_at_function_call === currentURL && updatebutton) // this can change from updatebutton=true to updatebutton=false midway through animation, depending on what getUser() comes back with.
drawHButton("gray", "white", (frame%12));
else // we're not on the right tab anymore or we've drawn a notification number, end animation loop
clearInterval(animation_loop);
if (threadstatus === 0)
{
finishThread(url_at_function_call);
clearInterval(animation_loop);
}
frame++;
}, 100);
}
}
else
{
drawHButton("gray", "white");
}
}
function finishThread(url_at_function_call)
{
if (url_at_function_call === currentURL) // don't update if the currentURL has changed, the info is irrelevant in that case
{
// *** we can only get here if no notification number has been drawn. No need to check again.
if(typeof t_jo === "undefined" || t_jo === null)
{
//alert("drawing red finishThread t_jo undefined or null");
drawHButton("gray", "darkred");
}
else if(typeof t_jo !== "undefined" && t_jo !== null)
{
if(typeof t_jo.score !== "undefined" && t_jo.score !== null && typeof t_jo.children !== "undefined" && t_jo.children !== null && t_jo.children.length) // both defined and not null
drawTTUButton(t_jo.score+"", t_jo.children.length+"");
else if (typeof t_jo.score !== "undefined" && t_jo.score !== null && (typeof t_jo.children === "undefined" || t_jo.children === null)) // score defined, but children undefined or null
drawTTUButton(t_jo.score+"", "0");
else
drawHButton("gray", "white"); // t_jo defined and not null, but has neither a defined+nonnull .score nor a defined+nonnull .children
}
else
drawHButton("gray", "white");
}
else
{
// do nothing. Let whichever thread is in control now handle the button
}
}
//draws the button. if bottom=="NOTIFICATION", then top is displayed larger (and bottom is not displayed)
function drawTTUButton(top, bottom) {
// Get the canvas element.
var canvas = document.getElementById("button_canvas");
// Specify a 2d drawing context.
var context = canvas.getContext("2d");
var top_fg = "black"; // assume the top-color is light since HN's top wording is black and it's unlikely users would choose dark on dark for their topcolor
var bottom_fg = "white";
var top_bg = "#ff6600";
if(user_jo && typeof user_jo.hn_topcolor !== "undefined" && user_jo.hn_topcolor !== null)
top_bg = "#" + user_jo.hn_topcolor;
var bottom_bg = "black";
context.fillStyle = top_bg;
context.fillRect (0, 0, 19, 8);
if (bottom === "NOTIFICATION") // if this is a NOTIFICATION, fill the whole alert with topcolor
context.fillStyle = top_bg;
else
context.fillStyle = bottom_bg;
context.fillRect (0, 8, 19, 19);
var imageData = context.getImageData(0, 0, 19, 19);
var pix = imageData.data;
var r = 0; var g = 0; var b = 0; var a = 255;
for (var i = 0, n = pix.length; i < n; i += 4)
{
r = 0; g = 0; b = 0; a = 255;
if (i === 0 || i === 72 || i === 1140 || i === 1212 // four corner roundings
|| (i >= 1216 && i <= 1224) || (i >= 1240 && i <= 1288) // first row below bubble
|| (i >= 1292 && i <= 1304) || (i >= 1316 && i <= 1364) // second row below bubble
|| (i >= 1368 && i <= 1384) || (i >= 1392))
{
r = 255; g = 255; b = 255; a = 0;
pix[i ] = r; // red
pix[i+1] = g; // green
pix[i+2] = b; // blue
pix[i+3] = a; // i+3 is alpha (the fourth element)
}
}
context.putImageData(imageData, 0, 0);
if (bottom === "NOTIFICATION")
{
context.fillStyle = top_fg;
context.font = "16px Silkscreen";
if (top === "1" || top === 1)
context.fillText(top,5,13);
else
context.fillText(top,4,13);
}
else
{
context.fillStyle = top_fg;
context.font = "8px Silkscreen";
if (top.length === 1)
context.fillText(top,7,6);
else if (top.length === 2)
context.fillText(top,4,6);
else if (top.length >= 3)
{
if (top*1 > 999)
top = "999";
context.fillText(top,1,6);
}
context.fillStyle = bottom_fg;
context.font = "8px Silkscreen";
if (bottom.length === 1)
context.fillText(bottom,7,14);
else if (bottom.length === 2)
context.fillText(bottom,4,14);
else if (bottom.length >= 3)
{
if (bottom*1 > 999)
bottom = "999";
context.fillText(bottom,1,14);
}
}
imageData = context.getImageData(0, 0, 19, 19);
chrome.browserAction.setIcon({
imageData: imageData
});
}
function drawHButton(background_color, h_color, aframe, leftnumber, rightnumber)
{
var x_offset = 0;
var left = 0;
var right = 0;
if(typeof leftnumber === "undefined" && typeof rightnumber === "undefined")
{
left = 0; // signifying nothing to be shown.
right = 0;
}
else if((typeof leftnumber === "undefined" || leftnumber === null || leftnumber === 0) && typeof rightnumber !== "undefined" && rightnumber !== null && rightnumber > 0) // left is 0, right > 0
{
left = 0; // signifying nothing to be shown.
right = rightnumber;
x_offset = -3;
}
else if((typeof rightnumber === "undefined" || rightnumber === null || rightnumber === 0) && typeof leftnumber !== "undefined" && leftnumber !== null && leftnumber > 0) // right is 0, left > 0
{
left = leftnumber;
right = 0;
x_offset = 1;
}
else if(typeof leftnumber !== "undefined" && leftnumber !== null && leftnumber > 0 && typeof rightnumber !== "undefined" && rightnumber !== null && rightnumber > 0) // both are > 0
{
left = leftnumber;
right = rightnumber;
x_offset = 1;
}
else
{
// something bizarre. This clause may even be dead code. In any case, do nothing.
}
// Get the canvas element.
var canvas = document.getElementById("button_canvas");
// Specify a 2d drawing context.
var context = canvas.getContext("2d");
// var bg_r = "0x7e";
// var bg_g = "0x7e";
// var bg_b = "0x7e";
context.fillStyle = background_color;
if(devel === true)
context.fillStyle = "pink";
context.fillRect (0, 0, 19, 19);
context.fillStyle = "gray";
context.fillRect (0, 0, 19, 1);
context.fillRect (18, 0, 1, 19);
context.fillRect (0, 18, 19, 1);
context.fillRect (0, 0, 1, 19);
context.fillStyle = h_color;
context.fillRect (7+x_offset, 4, 3, 15); // H left
context.fillRect (8+x_offset, 3, 2, 1); // H left tilt top
context.fillRect (13+x_offset, 10, 3, 9); // H right
context.fillRect (11+x_offset, 8, 3, 1); // H crossbar top row 1
context.fillRect (10+x_offset, 9, 5, 2); // H crossbar bottom rows 2/3
if(aframe !== null)
context.fillRect ((aframe*2+-1), (aframe*-.6+7), 2, 2);
if(leftnumber > 0)
{
if(leftnumber > 9)
leftnumber = 9;
context.fillStyle = "black";
context.font = "8px Silkscreen";
if(leftnumber === 1)
context.fillText(leftnumber+"",2,7);
else
context.fillText(leftnumber+"",1,7);
}
if(rightnumber > 0)
{
if(rightnumber > 9)
rightnumber = 9;
context.fillStyle = "black";
context.font = "8px Silkscreen";
if(rightnumber === 1)
context.fillText(rightnumber+"",13,7);
else
context.fillText(rightnumber+"",12,7);
}
var imageData = context.getImageData(0, 0, 19, 19);
var pix = imageData.data;
var r = 0; var g = 0; var b = 0; var a = 255;
for (var i = 0, n = pix.length; i < n; i += 4)
{
r = 0; g = 0; b = 0; a = 255;
if (i === 0 || i === 72 || i === 1368 || i === 1440)//
{
r = 255; g = 255; b = 255; a = 0;
pix[i ] = r; // red
pix[i+1] = g; // green
pix[i+2] = b; // blue
pix[i+3] = a; // i+3 is alpha (the fourth element)
}
}
chrome.browserAction.setIcon({
imageData: imageData
});
}
function getUser(loop)
{
if(typeof loop === "undefined" || loop === null)
loop = false;
else if(loop === true)
user_retrieval_loop_is_running = true; // set this BEFORE the call to getUserSelf so we don't get double loops going.
var screenname = docCookies.getItem("screenname");
var this_access_token = docCookies.getItem("this_access_token");
var ext_version = chrome.runtime.getManifest().version;
if(screenname !== null && this_access_token !== null && this_access_token.length == 32)// the shortest possible screenname length is x@b.co = 6.
{
$.ajax({
type: 'GET',
url: endpoint,
data: {
method: "getUserSelf",
screenname: screenname,
this_access_token: this_access_token,
ext_version: ext_version
},
dataType: 'json',
async: true,
timeout: 7000,
success: function (data, status) {
if (data.response_status === "error")
{
if(data.error_code && data.error_code === "0000")
{
//alert("getUser error 0000");
docCookies.removeItem("screenname");
docCookies.removeItem("this_access_token");
user_jo = null;
}
}
else if (data.response_status === "success")
{
msfe_according_to_backend = data.msfe;
if(data.user_jo)
{
user_jo = data.user_jo;
latest_ext_version = data.latest_ext_version;
if(typeof data.user_jo.hn_topcolor !== "undefined" && data.user_jo.hn_topcolor !== null)
hn_topcolor = data.user_jo.hn_topcolor;
drawNotificationNumber();
}
}
else
{
//alert("getUser problem. response_status neither success nor error");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
})
// note: as written, this then() only happens on success. To do on fail, too: .then(function(){ // success stuff}, function() { // fail stuff });
// since a tab change will restart the loop, I don't think there's any need to provide a then() for failure.
.then(function() {
if(loop)
{
setTimeout(function(){getUser(true)}, 30000);
}
});
}
else if(screenname !== null || this_access_token !== null) // if either of these is not null and we've gotten here,
{ // something is rotten in denmark re: cookie credentials, delete them
docCookies.removeItem("screenname");
docCookies.removeItem("this_access_token");
user_jo = null;
}
else
{
user_jo = null; // proceed with user_jo = null
}
}
function agoIt(inc_ts_in_ms)
{
if(typeof msfe_according_to_backend === "undefined" || msfe_according_to_backend === null) // should never happen as bg sets msfe_according_to_backend to d.getTime() on load
{
var d = new Date();
msfe_according_to_backend = d.getTime();
}
var millis_ago = msfe_according_to_backend - inc_ts_in_ms;
if(millis_ago < 0)
millis_ago = 0;
var minutes_ago = millis_ago/60000;
var time_ago = 0;
var time_ago_units = "";
if(minutes_ago < 60)
{
time_ago = minutes_ago;
time_ago_units = "mins";
}
else if ((minutes_ago > 60) && (minutes_ago < 1440))
{
time_ago = minutes_ago / 60;
time_ago_units = "hrs";
}
else
{
time_ago = minutes_ago / 1440;
time_ago_units = "days";
}
return (time_ago.toFixed(0) + " " + time_ago_units + " ago");
}
// FIRSTRUN
chrome.runtime.onInstalled.addListener(function(details){
if(details.reason == "install"){
chrome.tabs.create({url: chrome.extension.getURL("firstrun.html")});
}else if(details.reason == "update"){
// var thisVersion = chrome.runtime.getManifest().version;
// alert("Updated from " + details.previousVersion + " to " + thisVersion + "!");
}
});
|
legend = [];
function addLegend(id, text) {
if(typeof legend[id] === "undefined") {
legend[id] = [];
}
legend[id][text] = text;
}
$("body").on("click", ".BPASLViewerLink", function(event){
event.stopPropagation();
var e = $(this);
var wList = e.attr("data-list"),
wRow = e.attr("data-row"),
wView = e.attr("data-view"),
wUrl = e.attr("data-url"),
wRandom = e.attr("data-random"),
wDetail = e.attr("data-detail"),
wTitle = e.attr("data-title"),
wId = e.attr("data-id");
var source = $("#" + wId + "_Event");
SLViewer(wList, wRow, wView, wUrl,
wRandom, "", wDetail,
wTitle, wId);
});
|
'use strict';
crop.factory('cropAreaCircle', ['cropArea', function(CropArea) {
var CropAreaCircle = function() {
CropArea.apply(this, arguments);
this._boxResizeBaseSize = 20;
this._boxResizeNormalRatio = 0.9;
this._boxResizeHoverRatio = 1.2;
this._iconMoveNormalRatio = 0.9;
this._iconMoveHoverRatio = 1.2;
this._boxResizeNormalSize = this._boxResizeBaseSize * this._boxResizeNormalRatio;
this._boxResizeHoverSize = this._boxResizeBaseSize * this._boxResizeHoverRatio;
this._posDragStartX = 0;
this._posDragStartY = 0;
this._posResizeStartX = 0;
this._posResizeStartY = 0;
this._posResizeStartSize = 0;
this._boxResizeIsHover = false;
this._areaIsHover = false;
this._boxResizeIsDragging = false;
this._areaIsDragging = false;
};
CropAreaCircle.prototype = new CropArea();
CropAreaCircle.prototype.getType = function() {
return 'circle';
};
CropAreaCircle.prototype._calcCirclePerimeterCoords = function(angleDegrees) {
var hSize = this._size.w / 2;
var angleRadians = angleDegrees * (Math.PI / 180),
circlePerimeterX = this.getCenterPoint().x + hSize * Math.cos(angleRadians),
circlePerimeterY = this.getCenterPoint().y + hSize * Math.sin(angleRadians);
return [circlePerimeterX, circlePerimeterY];
};
CropAreaCircle.prototype._calcResizeIconCenterCoords = function() {
return this._calcCirclePerimeterCoords(-45);
};
CropAreaCircle.prototype._isCoordWithinArea = function(coord) {
return Math.sqrt((coord[0] - this.getCenterPoint().x) * (coord[0] - this.getCenterPoint().x) + (coord[1] - this.getCenterPoint().y) * (coord[1] - this.getCenterPoint().y)) < this._size.w / 2;
};
CropAreaCircle.prototype._isCoordWithinBoxResize = function(coord) {
var resizeIconCenterCoords = this._calcResizeIconCenterCoords();
var hSize = this._boxResizeHoverSize / 2;
return (coord[0] > resizeIconCenterCoords[0] - hSize && coord[0] < resizeIconCenterCoords[0] + hSize &&
coord[1] > resizeIconCenterCoords[1] - hSize && coord[1] < resizeIconCenterCoords[1] + hSize);
};
CropAreaCircle.prototype._drawArea = function(ctx, centerCoords, size) {
ctx.arc(centerCoords.x, centerCoords.y, size.w / 2, 0, 2 * Math.PI);
};
CropAreaCircle.prototype.draw = function() {
CropArea.prototype.draw.apply(this, arguments);
// draw move icon
var center = this.getCenterPoint();
this._cropCanvas.drawIconMove([center.x, center.y], this._areaIsHover ? this._iconMoveHoverRatio : this._iconMoveNormalRatio);
// draw resize cubes
this._cropCanvas.drawIconResizeBoxNESW(this._calcResizeIconCenterCoords(), this._boxResizeBaseSize, this._boxResizeIsHover ? this._boxResizeHoverRatio : this._boxResizeNormalRatio);
};
CropAreaCircle.prototype.processMouseMove = function(mouseCurX, mouseCurY) {
var cursor = 'default';
var res = false;
this._boxResizeIsHover = false;
this._areaIsHover = false;
if (this._areaIsDragging) {
this.setCenterPointOnMove({
x: mouseCurX - this._posDragStartX,
y: mouseCurY - this._posDragStartY
});
this._areaIsHover = true;
cursor = 'move';
res = true;
this._events.trigger('area-move');
} else if (this._boxResizeIsDragging) {
cursor = 'nesw-resize';
var iFR, iFX, iFY;
iFX = mouseCurX - this._posResizeStartX;
iFY = this._posResizeStartY - mouseCurY;
if (iFX > iFY) {
iFR = this._posResizeStartSize.w + iFY * 2;
} else {
iFR = this._posResizeStartSize.w + iFX * 2;
}
var center = this.getCenterPoint(),
newNO = {},
newSE = {};
newNO.x = this.getCenterPoint().x - iFR * 0.5;
newSE.x = this.getCenterPoint().x + iFR * 0.5;
newNO.y = this.getCenterPoint().y - iFR * 0.5;
newSE.y = this.getCenterPoint().y + iFR * 0.5;
this.CircleOnMove(newNO, newSE);
this._boxResizeIsHover = true;
res = true;
this._events.trigger('area-resize');
} else if (this._isCoordWithinBoxResize([mouseCurX, mouseCurY])) {
cursor = 'nesw-resize';
this._areaIsHover = false;
this._boxResizeIsHover = true;
res = true;
} else if (this._isCoordWithinArea([mouseCurX, mouseCurY])) {
cursor = 'move';
this._areaIsHover = true;
res = true;
}
//this._dontDragOutside();
angular.element(this._ctx.canvas).css({
'cursor': cursor
});
return res;
};
CropAreaCircle.prototype.processMouseDown = function(mouseDownX, mouseDownY) {
if (this._isCoordWithinBoxResize([mouseDownX, mouseDownY])) {
this._areaIsDragging = false;
this._areaIsHover = false;
this._boxResizeIsDragging = true;
this._boxResizeIsHover = true;
this._posResizeStartX = mouseDownX;
this._posResizeStartY = mouseDownY;
this._posResizeStartSize = this._size;
this._events.trigger('area-resize-start');
} else if (this._isCoordWithinArea([mouseDownX, mouseDownY])) {
this._areaIsDragging = true;
this._areaIsHover = true;
this._boxResizeIsDragging = false;
this._boxResizeIsHover = false;
var center = this.getCenterPoint();
this._posDragStartX = mouseDownX - center.x;
this._posDragStartY = mouseDownY - center.y;
this._events.trigger('area-move-start');
}
};
CropAreaCircle.prototype.processMouseUp = function( /*mouseUpX, mouseUpY*/ ) {
if (this._areaIsDragging) {
this._areaIsDragging = false;
this._events.trigger('area-move-end');
}
if (this._boxResizeIsDragging) {
this._boxResizeIsDragging = false;
this._events.trigger('area-resize-end');
}
this._areaIsHover = false;
this._boxResizeIsHover = false;
this._posDragStartX = 0;
this._posDragStartY = 0;
};
return CropAreaCircle;
}]); |
import { assert, deprecate, isTesting } from '@ember/debug';
import { onErrorTarget } from 'ember-error-handling';
import { beginPropertyChanges, endPropertyChanges } from 'ember-metal';
import Backburner from 'backburner';
import { RUN_SYNC } from '@ember/deprecated-features';
let currentRunLoop = null;
export function getCurrentRunLoop() {
return currentRunLoop;
}
function onBegin(current) {
currentRunLoop = current;
}
function onEnd(current, next) {
currentRunLoop = next;
}
export const _rsvpErrorQueue = `${Math.random()}${Date.now()}`.replace('.', '');
/**
Array of named queues. This array determines the order in which queues
are flushed at the end of the RunLoop. You can define your own queues by
simply adding the queue name to this array. Normally you should not need
to inspect or modify this property.
@property queues
@type Array
@default ['actions', 'destroy']
@private
*/
export const queues = [
'actions',
// used in router transitions to prevent unnecessary loading state entry
// if all context promises resolve on the 'actions' queue first
'routerTransitions',
'render',
'afterRender',
'destroy',
// used to re-throw unhandled RSVP rejection errors specifically in this
// position to avoid breaking anything rendered in the other sections
_rsvpErrorQueue,
];
let backburnerOptions = {
defaultQueue: 'actions',
onBegin,
onEnd,
onErrorTarget,
onErrorMethod: 'onerror',
};
if (RUN_SYNC) {
queues.unshift('sync');
backburnerOptions.sync = {
before: beginPropertyChanges,
after: endPropertyChanges,
};
}
export const backburner = new Backburner(queues, backburnerOptions);
/**
@module @ember/runloop
*/
// ..........................................................
// run - this is ideally the only public API the dev sees
//
/**
Runs the passed target and method inside of a RunLoop, ensuring any
deferred actions including bindings and views updates are flushed at the
end.
Normally you should not need to invoke this method yourself. However if
you are implementing raw event handlers when interfacing with other
libraries or plugins, you should probably wrap all of your code inside this
call.
```javascript
import { run } from '@ember/runloop';
run(function() {
// code to be executed within a RunLoop
});
```
@method run
@for @ember/runloop
@static
@param {Object} [target] target of method to call
@param {Function|String} method Method to invoke.
May be a function or a string. If you pass a string
then it will be looked up on the passed target.
@param {Object} [args*] Any additional arguments you wish to pass to the method.
@return {Object} return value from invoking the passed function.
@public
*/
export function run() {
return backburner.run(...arguments);
}
// used for the Ember.run global only
export const _globalsRun = run.bind(null);
/**
If no run-loop is present, it creates a new one. If a run loop is
present it will queue itself to run on the existing run-loops action
queue.
Please note: This is not for normal usage, and should be used sparingly.
If invoked when not within a run loop:
```javascript
import { join } from '@ember/runloop';
join(function() {
// creates a new run-loop
});
```
Alternatively, if called within an existing run loop:
```javascript
import { run, join } from '@ember/runloop';
run(function() {
// creates a new run-loop
join(function() {
// joins with the existing run-loop, and queues for invocation on
// the existing run-loops action queue.
});
});
```
@method join
@static
@for @ember/runloop
@param {Object} [target] target of method to call
@param {Function|String} method Method to invoke.
May be a function or a string. If you pass a string
then it will be looked up on the passed target.
@param {Object} [args*] Any additional arguments you wish to pass to the method.
@return {Object} Return value from invoking the passed function. Please note,
when called within an existing loop, no return value is possible.
@public
*/
export function join() {
return backburner.join(...arguments);
}
/**
Allows you to specify which context to call the specified function in while
adding the execution of that function to the Ember run loop. This ability
makes this method a great way to asynchronously integrate third-party libraries
into your Ember application.
`bind` takes two main arguments, the desired context and the function to
invoke in that context. Any additional arguments will be supplied as arguments
to the function that is passed in.
Let's use the creation of a TinyMCE component as an example. Currently,
TinyMCE provides a setup configuration option we can use to do some processing
after the TinyMCE instance is initialized but before it is actually rendered.
We can use that setup option to do some additional setup for our component.
The component itself could look something like the following:
```app/components/rich-text-editor.js
import Component from '@ember/component';
import { on } from '@ember/object/evented';
import { bind } from '@ember/runloop';
export default Component.extend({
initializeTinyMCE: on('didInsertElement', function() {
tinymce.init({
selector: '#' + this.$().prop('id'),
setup: bind(this, this.setupEditor)
});
}),
didInsertElement() {
tinymce.init({
selector: '#' + this.$().prop('id'),
setup: bind(this, this.setupEditor)
});
}
setupEditor(editor) {
this.set('editor', editor);
editor.on('change', function() {
console.log('content changed!');
});
}
});
```
In this example, we use `bind` to bind the setupEditor method to the
context of the RichTextEditor component and to have the invocation of that
method be safely handled and executed by the Ember run loop.
@method bind
@static
@for @ember/runloop
@param {Object} [target] target of method to call
@param {Function|String} method Method to invoke.
May be a function or a string. If you pass a string
then it will be looked up on the passed target.
@param {Object} [args*] Any additional arguments you wish to pass to the method.
@return {Function} returns a new function that will always have a particular context
@since 1.4.0
@public
*/
export const bind = (...curried) => (...args) => join(...curried.concat(args));
/**
Begins a new RunLoop. Any deferred actions invoked after the begin will
be buffered until you invoke a matching call to `end()`. This is
a lower-level way to use a RunLoop instead of using `run()`.
```javascript
import { begin, end } from '@ember/runloop';
begin();
// code to be executed within a RunLoop
end();
```
@method begin
@static
@for @ember/runloop
@return {void}
@public
*/
export function begin() {
backburner.begin();
}
/**
Ends a RunLoop. This must be called sometime after you call
`begin()` to flush any deferred actions. This is a lower-level way
to use a RunLoop instead of using `run()`.
```javascript
import { begin, end } from '@ember/runloop';
begin();
// code to be executed within a RunLoop
end();
```
@method end
@static
@for @ember/runloop
@return {void}
@public
*/
export function end() {
backburner.end();
}
/**
Adds the passed target/method and any optional arguments to the named
queue to be executed at the end of the RunLoop. If you have not already
started a RunLoop when calling this method one will be started for you
automatically.
At the end of a RunLoop, any methods scheduled in this way will be invoked.
Methods will be invoked in an order matching the named queues defined in
the `queues` property.
```javascript
import { schedule } from '@ember/runloop';
schedule('actions', this, function() {
// this will be executed in the 'actions' queue, after bindings have synced.
console.log('scheduled on actions queue');
});
// Note the functions will be run in order based on the run queues order.
// Output would be:
// scheduled on sync queue
// scheduled on actions queue
```
@method schedule
@static
@for @ember/runloop
@param {String} queue The name of the queue to schedule against. Default queues is 'actions'
@param {Object} [target] target object to use as the context when invoking a method.
@param {String|Function} method The method to invoke. If you pass a string it
will be resolved on the target object at the time the scheduled item is
invoked allowing you to change the target function.
@param {Object} [arguments*] Optional arguments to be passed to the queued method.
@return {*} Timer information for use in canceling, see `cancel`.
@public
*/
export function schedule(queue /*, target, method */) {
assert(
`You have turned on testing mode, which disabled the run-loop's autorun. ` +
`You will need to wrap any code with asynchronous side-effects in a run`,
currentRunLoop || !isTesting()
);
deprecate(`Scheduling into the '${queue}' run loop queue is deprecated.`, queue !== 'sync', {
id: 'ember-metal.run.sync',
until: '3.5.0',
});
return backburner.schedule(...arguments);
}
// Used by global test teardown
export function hasScheduledTimers() {
return backburner.hasTimers();
}
// Used by global test teardown
export function cancelTimers() {
backburner.cancelTimers();
}
/**
Invokes the passed target/method and optional arguments after a specified
period of time. The last parameter of this method must always be a number
of milliseconds.
You should use this method whenever you need to run some action after a
period of time instead of using `setTimeout()`. This method will ensure that
items that expire during the same script execution cycle all execute
together, which is often more efficient than using a real setTimeout.
```javascript
import { later } from '@ember/runloop';
later(myContext, function() {
// code here will execute within a RunLoop in about 500ms with this == myContext
}, 500);
```
@method later
@static
@for @ember/runloop
@param {Object} [target] target of method to invoke
@param {Function|String} method The method to invoke.
If you pass a string it will be resolved on the
target at the time the method is invoked.
@param {Object} [args*] Optional arguments to pass to the timeout.
@param {Number} wait Number of milliseconds to wait.
@return {*} Timer information for use in canceling, see `cancel`.
@public
*/
export function later(/*target, method*/) {
return backburner.later(...arguments);
}
/**
Schedule a function to run one time during the current RunLoop. This is equivalent
to calling `scheduleOnce` with the "actions" queue.
@method once
@static
@for @ember/runloop
@param {Object} [target] The target of the method to invoke.
@param {Function|String} method The method to invoke.
If you pass a string it will be resolved on the
target at the time the method is invoked.
@param {Object} [args*] Optional arguments to pass to the timeout.
@return {Object} Timer information for use in canceling, see `cancel`.
@public
*/
export function once(...args) {
assert(
`You have turned on testing mode, which disabled the run-loop's autorun. ` +
`You will need to wrap any code with asynchronous side-effects in a run`,
currentRunLoop || !isTesting()
);
args.unshift('actions');
return backburner.scheduleOnce(...args);
}
/**
Schedules a function to run one time in a given queue of the current RunLoop.
Calling this method with the same queue/target/method combination will have
no effect (past the initial call).
Note that although you can pass optional arguments these will not be
considered when looking for duplicates. New arguments will replace previous
calls.
```javascript
import { run, scheduleOnce } from '@ember/runloop';
function sayHi() {
console.log('hi');
}
run(function() {
scheduleOnce('afterRender', myContext, sayHi);
scheduleOnce('afterRender', myContext, sayHi);
// sayHi will only be executed once, in the afterRender queue of the RunLoop
});
```
Also note that for `scheduleOnce` to prevent additional calls, you need to
pass the same function instance. The following case works as expected:
```javascript
function log() {
console.log('Logging only once');
}
function scheduleIt() {
scheduleOnce('actions', myContext, log);
}
scheduleIt();
scheduleIt();
```
But this other case will schedule the function multiple times:
```javascript
import { scheduleOnce } from '@ember/runloop';
function scheduleIt() {
scheduleOnce('actions', myContext, function() {
console.log('Closure');
});
}
scheduleIt();
scheduleIt();
// "Closure" will print twice, even though we're using `scheduleOnce`,
// because the function we pass to it won't match the
// previously scheduled operation.
```
Available queues, and their order, can be found at `queues`
@method scheduleOnce
@static
@for @ember/runloop
@param {String} [queue] The name of the queue to schedule against. Default queues is 'actions'.
@param {Object} [target] The target of the method to invoke.
@param {Function|String} method The method to invoke.
If you pass a string it will be resolved on the
target at the time the method is invoked.
@param {Object} [args*] Optional arguments to pass to the timeout.
@return {Object} Timer information for use in canceling, see `cancel`.
@public
*/
export function scheduleOnce(queue /*, target, method*/) {
assert(
`You have turned on testing mode, which disabled the run-loop's autorun. ` +
`You will need to wrap any code with asynchronous side-effects in a run`,
currentRunLoop || !isTesting()
);
deprecate(`Scheduling into the '${queue}' run loop queue is deprecated.`, queue !== 'sync', {
id: 'ember-metal.run.sync',
until: '3.5.0',
});
return backburner.scheduleOnce(...arguments);
}
/**
Schedules an item to run from within a separate run loop, after
control has been returned to the system. This is equivalent to calling
`later` with a wait time of 1ms.
```javascript
import { next } from '@ember/runloop';
next(myContext, function() {
// code to be executed in the next run loop,
// which will be scheduled after the current one
});
```
Multiple operations scheduled with `next` will coalesce
into the same later run loop, along with any other operations
scheduled by `later` that expire right around the same
time that `next` operations will fire.
Note that there are often alternatives to using `next`.
For instance, if you'd like to schedule an operation to happen
after all DOM element operations have completed within the current
run loop, you can make use of the `afterRender` run loop queue (added
by the `ember-views` package, along with the preceding `render` queue
where all the DOM element operations happen).
Example:
```app/components/my-component.js
import Component from '@ember/component';
import { scheduleOnce } from '@ember/runloop';
export Component.extend({
didInsertElement() {
this._super(...arguments);
scheduleOnce('afterRender', this, 'processChildElements');
},
processChildElements() {
// ... do something with component's child component
// elements after they've finished rendering, which
// can't be done within this component's
// `didInsertElement` hook because that gets run
// before the child elements have been added to the DOM.
}
});
```
One benefit of the above approach compared to using `next` is
that you will be able to perform DOM/CSS operations before unprocessed
elements are rendered to the screen, which may prevent flickering or
other artifacts caused by delaying processing until after rendering.
The other major benefit to the above approach is that `next`
introduces an element of non-determinism, which can make things much
harder to test, due to its reliance on `setTimeout`; it's much harder
to guarantee the order of scheduled operations when they are scheduled
outside of the current run loop, i.e. with `next`.
@method next
@static
@for @ember/runloop
@param {Object} [target] target of method to invoke
@param {Function|String} method The method to invoke.
If you pass a string it will be resolved on the
target at the time the method is invoked.
@param {Object} [args*] Optional arguments to pass to the timeout.
@return {Object} Timer information for use in canceling, see `cancel`.
@public
*/
export function next(...args) {
args.push(1);
return backburner.later(...args);
}
/**
Cancels a scheduled item. Must be a value returned by `later()`,
`once()`, `scheduleOnce()`, `next()`, `debounce()`, or
`throttle()`.
```javascript
import {
next,
cancel,
later,
scheduleOnce,
once,
throttle,
debounce
} from '@ember/runloop';
let runNext = next(myContext, function() {
// will not be executed
});
cancel(runNext);
let runLater = later(myContext, function() {
// will not be executed
}, 500);
cancel(runLater);
let runScheduleOnce = scheduleOnce('afterRender', myContext, function() {
// will not be executed
});
cancel(runScheduleOnce);
let runOnce = once(myContext, function() {
// will not be executed
});
cancel(runOnce);
let throttle = throttle(myContext, function() {
// will not be executed
}, 1, false);
cancel(throttle);
let debounce = debounce(myContext, function() {
// will not be executed
}, 1);
cancel(debounce);
let debounceImmediate = debounce(myContext, function() {
// will be executed since we passed in true (immediate)
}, 100, true);
// the 100ms delay until this method can be called again will be canceled
cancel(debounceImmediate);
```
@method cancel
@static
@for @ember/runloop
@param {Object} timer Timer object to cancel
@return {Boolean} true if canceled or false/undefined if it wasn't found
@public
*/
export function cancel(timer) {
return backburner.cancel(timer);
}
/**
Delay calling the target method until the debounce period has elapsed
with no additional debounce calls. If `debounce` is called again before
the specified time has elapsed, the timer is reset and the entire period
must pass again before the target method is called.
This method should be used when an event may be called multiple times
but the action should only be called once when the event is done firing.
A common example is for scroll events where you only want updates to
happen once scrolling has ceased.
```javascript
import { debounce } from '@ember/runloop';
function whoRan() {
console.log(this.name + ' ran.');
}
let myContext = { name: 'debounce' };
debounce(myContext, whoRan, 150);
// less than 150ms passes
debounce(myContext, whoRan, 150);
// 150ms passes
// whoRan is invoked with context myContext
// console logs 'debounce ran.' one time.
```
Immediate allows you to run the function immediately, but debounce
other calls for this function until the wait time has elapsed. If
`debounce` is called again before the specified time has elapsed,
the timer is reset and the entire period must pass again before
the method can be called again.
```javascript
import { debounce } from '@ember/runloop';
function whoRan() {
console.log(this.name + ' ran.');
}
let myContext = { name: 'debounce' };
debounce(myContext, whoRan, 150, true);
// console logs 'debounce ran.' one time immediately.
// 100ms passes
debounce(myContext, whoRan, 150, true);
// 150ms passes and nothing else is logged to the console and
// the debouncee is no longer being watched
debounce(myContext, whoRan, 150, true);
// console logs 'debounce ran.' one time immediately.
// 150ms passes and nothing else is logged to the console and
// the debouncee is no longer being watched
```
@method debounce
@static
@for @ember/runloop
@param {Object} [target] target of method to invoke
@param {Function|String} method The method to invoke.
May be a function or a string. If you pass a string
then it will be looked up on the passed target.
@param {Object} [args*] Optional arguments to pass to the timeout.
@param {Number} wait Number of milliseconds to wait.
@param {Boolean} immediate Trigger the function on the leading instead
of the trailing edge of the wait interval. Defaults to false.
@return {Array} Timer information for use in canceling, see `cancel`.
@public
*/
export function debounce() {
return backburner.debounce(...arguments);
}
/**
Ensure that the target method is never called more frequently than
the specified spacing period. The target method is called immediately.
```javascript
import { throttle } from '@ember/runloop';
function whoRan() {
console.log(this.name + ' ran.');
}
let myContext = { name: 'throttle' };
throttle(myContext, whoRan, 150);
// whoRan is invoked with context myContext
// console logs 'throttle ran.'
// 50ms passes
throttle(myContext, whoRan, 150);
// 50ms passes
throttle(myContext, whoRan, 150);
// 150ms passes
throttle(myContext, whoRan, 150);
// whoRan is invoked with context myContext
// console logs 'throttle ran.'
```
@method throttle
@static
@for @ember/runloop
@param {Object} [target] target of method to invoke
@param {Function|String} method The method to invoke.
May be a function or a string. If you pass a string
then it will be looked up on the passed target.
@param {Object} [args*] Optional arguments to pass to the timeout.
@param {Number} spacing Number of milliseconds to space out requests.
@param {Boolean} immediate Trigger the function on the leading instead
of the trailing edge of the wait interval. Defaults to true.
@return {Array} Timer information for use in canceling, see `cancel`.
@public
*/
export function throttle() {
return backburner.throttle(...arguments);
}
|
'use strict';
/*!
* ss2react
* https://github.com/SnakeskinTpl/ss2react
*
* Released under the MIT license
* https://github.com/SnakeskinTpl/ss2react/blob/master/LICENSE
*/
const
snakeskin = require('snakeskin'),
babel = require('babel-core');
function setParams(p) {
p = Object.assign({}, p, {
doctype: 'transitional',
literalBounds: ['{', '}'],
attrLiteralBounds: ['{', '}']
});
p.adapterOptions = Object.assign({babelrc: false}, p.adapterOptions, {
plugins: [
require('babel-plugin-syntax-jsx'),
require('babel-plugin-transform-react-jsx'),
require('babel-plugin-transform-react-display-name')
].concat(p.plugins || [])
});
return p;
}
function template(id, fn, txt, p) {
txt = `${id} = ${fn + (/\breturn\s+\(?\s*[{<](?!\/)/.test(txt) ? '' : 'return ') + txt}};`;
p = Object.assign({}, p);
delete p.header;
delete p.footer;
return babel.transform(txt, p).code;
}
exports.adapter = function (txt, opt_params, opt_info) {
return snakeskin.adapter(txt, {
template,
setParams,
importNative: 'import React from "react";',
importCJS: 'typeof React === "undefined" ? require("react") : React',
importAMD: '"react"',
importGlobal: 'React',
local: 'React'
}, opt_params, opt_info);
};
|
'use strict';
angular.module("snippetShare")
.controller("BoardsEditController", function ($scope, Board, User, $routeParams, $location, categories) {
//request GET the current board from server
Board.find($routeParams.userid, $routeParams.bid)
.success(function (data) {
console.log("get board "+ $routeParams.bid+ " success");
console.log(data);
$scope.board = data;
});
$scope.Board = Board;
$scope.User = User;
$scope.categories = categories;
$scope.isSubmitting = false;
$scope.updateBoard = function (board) {
$scope.isSubmitting = true;
console.log(board);
Board.update($routeParams.userid, $routeParams.bid, board)
.success(function(data, status, headers, config) {
console.log("in update board success");
console.log(data);
console.log(status);
})
.error(function(data, status, headers, config) {
console.log("in board error");
console.log(data);
console.log(status);
}).finally(function () {
$scope.isSubmitting = false;
$location.path("/users/"+$routeParams.userid+"/boards/" + $routeParams.bid);
});
};
});
|
const _ = require(`lodash`)
const normalize = require(`./normalize`)
const fetchData = require(`./fetch`)
const conflictFieldPrefix = `contentful`
// restrictedNodeFields from here https://www.gatsbyjs.org/docs/node-interface/
const restrictedNodeFields = [`id`, `children`, `parent`, `fields`, `internal`]
exports.setFieldsOnGraphQLNodeType = require(`./extend-node-type`).extendNodeType
/***
* Localization algorithm
*
* 1. Make list of all resolvable IDs worrying just about the default ids not
* localized ids
* 2. Make mapping between ids, again not worrying about localization.
* 3. When creating entries and assets, make the most localized version
* possible for each localized node i.e. get the localized field if it exists
* or the fallback field or the default field.
*/
exports.sourceNodes = async (
{ boundActionCreators, getNodes, hasNodeChanged, store },
{ spaceId, accessToken, host }
) => {
const {
createNode,
deleteNodes,
touchNode,
setPluginStatus,
} = boundActionCreators
host = host || `cdn.contentful.com`
// Get sync token if it exists.
let syncToken
if (
store.getState().status.plugins &&
store.getState().status.plugins[`gatsby-source-contentful`]
) {
syncToken = store.getState().status.plugins[`gatsby-source-contentful`]
.status.syncToken
}
const {
currentSyncData,
contentTypeItems,
defaultLocale,
locales,
} = await fetchData({
syncToken,
spaceId,
accessToken,
host,
})
const entryList = normalize.buildEntryList({
currentSyncData,
contentTypeItems,
})
// Remove deleted entries & assets.
// TODO figure out if entries referencing now deleted entries/assets
// are "updated" so will get the now deleted reference removed.
deleteNodes(currentSyncData.deletedEntries.map(e => e.sys.id))
deleteNodes(currentSyncData.deletedAssets.map(e => e.sys.id))
const existingNodes = getNodes().filter(
n => n.internal.owner === `gatsby-source-contentful`
)
existingNodes.forEach(n => touchNode(n.id))
const assets = currentSyncData.assets
console.log(`Updated entries `, currentSyncData.entries.length)
console.log(`Deleted entries `, currentSyncData.deletedEntries.length)
console.log(`Updated assets `, currentSyncData.assets.length)
console.log(`Deleted assets `, currentSyncData.deletedAssets.length)
console.timeEnd(`Fetch Contentful data`)
// Update syncToken
const nextSyncToken = currentSyncData.nextSyncToken
// Store our sync state for the next sync.
// TODO: we do not store the token if we are using preview, since only initial sync is possible there
// This might change though
// TODO: Also we should think about not overriding tokens between host
if (host !== `preview.contentful.com`) {
setPluginStatus({
status: {
syncToken: nextSyncToken,
},
})
}
// Create map of resolvable ids so we can check links against them while creating
// links.
const resolvable = normalize.buildResolvableSet({
existingNodes,
entryList,
assets,
defaultLocale,
locales,
})
// Build foreign reference map before starting to insert any nodes
const foreignReferenceMap = normalize.buildForeignReferenceMap({
contentTypeItems,
entryList,
resolvable,
defaultLocale,
locales,
})
const newOrUpdatedEntries = []
entryList.forEach(entries => {
entries.forEach(entry => {
newOrUpdatedEntries.push(entry.sys.id)
})
})
// Update existing entry nodes that weren't updated but that need reverse
// links added.
Object.keys(foreignReferenceMap)
existingNodes
.filter(n => _.includes(newOrUpdatedEntries, n.id))
.forEach(n => {
if (foreignReferenceMap[n.id]) {
foreignReferenceMap[n.id].forEach(foreignReference => {
// Add reverse links
if (n[foreignReference.name]) {
n[foreignReference.name].push(foreignReference.id)
// It might already be there so we'll uniquify after pushing.
n[foreignReference.name] = _.uniq(n[foreignReference.name])
} else {
// If is one foreign reference, there can always be many.
// Best to be safe and put it in an array to start with.
n[foreignReference.name] = [foreignReference.id]
}
})
}
})
contentTypeItems.forEach((contentTypeItem, i) => {
normalize.createContentTypeNodes({
contentTypeItem,
restrictedNodeFields,
conflictFieldPrefix,
entries: entryList[i],
createNode,
resolvable,
foreignReferenceMap,
defaultLocale,
locales,
})
})
assets.forEach(assetItem => {
normalize.createAssetNodes({
assetItem,
createNode,
defaultLocale,
locales,
})
})
return
}
|
(function() {
requirejs.config({
paths: {
// google analytics
"Analytics": "google_analytics_universal",
// "Analytics": "google_analytics_classic",
"Popover": "popover",
"ContentTabs": "content_tabs",
"AccordionContent": "accordion_content",
"DropdownMenu": "dropdown_menu",
"CookieDough": "cookie_dough",
'ColorShift': 'color_shift',
// jQuery
"jquery": '../components/jquery/dist/jquery.min',
// demo
"demo": '../../demo/js/demo'
}
});
require(['demo', 'Analytics'], function(Demo, Analytics) {
Demo.init();
return Analytics.track();
});
}).call(this);
|
var User = function(id, name) {
var id = id,
name = name;
return {
id: id,
name: name
}
};
exports.User = User;
|
var should = require('should');
var helper = require('../support/spec_helper');
var ORM = require('../.');
describe("hasMany extra properties", function() {
var db = null;
var Person = null;
var Pet = null;
var setup = function (opts) {
opts = opts || {};
return function (done) {
db.settings.set('instance.cache', false);
Person = db.define('person', {
name : String,
}, opts);
Pet = db.define('pet', {
name : String
});
Person.hasMany('pets', Pet, {
since : Date
});
return helper.dropSync([ Person, Pet ], done);
};
};
before(function(done) {
helper.connect(function (connection) {
db = connection;
done();
});
});
describe("if passed to addAccessor", function () {
before(setup());
it("should be added to association", function (done) {
Person.create([{
name : "John"
}], function (err, people) {
Pet.create([{
name : "Deco"
}, {
name : "Mutt"
}], function (err, pets) {
people[0].addPets(pets, { since : new Date() }, function (err) {
should.equal(err, null);
Person.find({ name: "John" }, { autoFetch : true }).first(function (err, John) {
should.equal(err, null);
John.should.have.property("pets");
should(Array.isArray(pets));
John.pets.length.should.equal(2);
John.pets[0].should.have.property("name");
John.pets[0].should.have.property("extra");
John.pets[0].extra.should.be.a("object");
John.pets[0].extra.should.have.property("since");
should(John.pets[0].extra.since instanceof Date);
return done();
});
});
});
});
});
});
});
|
$(function() {
var linksURL = '../scripts/graph.js/links/json';
var hosts = {};
var links = {};
var nodes;
var edges;
var network;
function addLink(link,from,to) {
links[link] = link;
edges.add({
id:link,
from:from,
to:to
});
}
function removeLink(link) {
delete links[link];
edges.remove({id:link});
}
function addHost(host,group) {
hosts[host] = host;
nodes.add({
id: host,
label: host,
group:group
});
}
function removeHost(host) {
delete hosts[host];
nodes.remove({id:host});
}
function updateLinks(data) {
var new_hosts = {};
var new_links = {};
for(var link in data) {
var info = data[link];
new_hosts[info.start] = info.start;
new_hosts[info.end] = info.end;
new_links[link] = link;
if(!hosts[info.start]) addHost(info.start,info.grpstart);
if(!hosts[info.end]) addHost(info.end,info.grpend);
if(!links[link]) addLink(link,info.start,info.end);
}
for(var link in links) {
if(!new_links[link]) removeLink(link);
}
for(var host in hosts) {
if(!new_hosts[host]) removeHost(host);
}
}
var timeout_poll;
function pollLinks() {
$.ajax({
url:linksURL,
dataType:'json',
success: function(data) {
updateLinks(data);
timeout_poll = setTimeout(pollLinks, 2000);
},
error: function(result,status,errorThrown) {
timeout_poll = setTimeout(pollLinks, 2000);
},
timeout: 60000
});
};
nodes = new vis.DataSet([]);
edges = new vis.DataSet([]);
var container = document.getElementById('mynetwork');
var data = {
nodes: nodes,
edges: edges
};
var options = {
physics:{
solver:'repulsion'
},
groups: {
external: {color:{background:'#FF6666'}},
private: {color:{background:'#33CC33'}},
multicast: {color:{background:'#FFFF00'}}
}
};
network = new vis.Network(container, data, options);
pollLinks();
});
|
/**
* lscache library
* Copyright (c) 2011, Pamela Fox
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jshint undef:true, browser:true */
/**
* Creates a namespace for the lscache functions.
*/
var lscache = function() {
// Prefix for all lscache keys
var CACHE_PREFIX = 'lscache-';
// Suffix for the key name on the expiration items in localStorage
var CACHE_SUFFIX = '-cacheexpiration';
// expiration date radix (set to Base-36 for most space savings)
var EXPIRY_RADIX = 10;
// time resolution in minutes
var EXPIRY_UNITS = 60 * 1000;
// ECMAScript max Date (epoch + 1e8 days)
var MAX_DATE = Math.floor(8.64e15/EXPIRY_UNITS);
var cachedStorage;
var cachedJSON;
var cacheBucket = '';
// Determines if localStorage is supported in the browser;
// result is cached for better performance instead of being run each time.
// Feature detection is based on how Modernizr does it;
// it's not straightforward due to FF4 issues.
// It's not run at parse-time as it takes 200ms in Android.
function supportsStorage() {
var key = '__lscachetest__';
var value = key;
if (cachedStorage !== undefined) {
return cachedStorage;
}
try {
setItem(key, value);
removeItem(key);
cachedStorage = true;
} catch (exc) {
cachedStorage = false;
}
return cachedStorage;
}
// Determines if native JSON (de-)serialization is supported in the browser.
function supportsJSON() {
/*jshint eqnull:true */
if (cachedJSON === undefined) {
cachedJSON = (window.JSON != null);
}
return cachedJSON;
}
/**
* Returns the full string for the localStorage expiration item.
* @param {String} key
* @return {string}
*/
function expirationKey(key) {
return key + CACHE_SUFFIX;
}
/**
* Returns the number of minutes since the epoch.
* @return {number}
*/
function currentTime() {
return Math.floor((new Date().getTime())/EXPIRY_UNITS);
}
/**
* Wrapper functions for localStorage methods
*/
function getItem(key) {
return localStorage.getItem(CACHE_PREFIX + cacheBucket + key);
}
function setItem(key, value) {
// Fix for iPad issue - sometimes throws QUOTA_EXCEEDED_ERR on setItem.
localStorage.removeItem(CACHE_PREFIX + cacheBucket + key);
try {
localStorage.setItem(CACHE_PREFIX + cacheBucket + key, value);
} catch (e) {
return;
}
}
function removeItem(key) {
localStorage.removeItem(CACHE_PREFIX + cacheBucket + key);
}
return {
/**
* Stores the value in localStorage. Expires after specified number of minutes.
* @param {string} key
* @param {Object|string} value
* @param {number} time
*/
set: function(key, value, time) {
if (!supportsStorage()) return;
// If we don't get a string value, try to stringify
// In future, localStorage may properly support storing non-strings
// and this can be removed.
if (typeof value !== 'string') {
if (!supportsJSON()) return;
try {
value = JSON.stringify(value);
} catch (e) {
// Sometimes we can't stringify due to circular refs
// in complex objects, so we won't bother storing then.
return;
}
}
try {
setItem(key, value);
} catch (e) {
if (e.name === 'QUOTA_EXCEEDED_ERR' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
// If we exceeded the quota, then we will sort
// by the expire time, and then remove the N oldest
var storedKeys = [];
var storedKey;
for (var i = 0; i < localStorage.length; i++) {
storedKey = localStorage.key(i);
if (storedKey.indexOf(CACHE_PREFIX + cacheBucket) === 0 && storedKey.indexOf(CACHE_SUFFIX) < 0) {
var mainKey = storedKey.substr((CACHE_PREFIX + cacheBucket).length);
var exprKey = expirationKey(mainKey);
var expiration = getItem(exprKey);
if (expiration) {
expiration = parseInt(expiration, EXPIRY_RADIX);
} else {
// TODO: Store date added for non-expiring items for smarter removal
expiration = MAX_DATE;
}
storedKeys.push({
key: mainKey,
size: (getItem(mainKey)||'').length,
expiration: expiration
});
}
}
// Sorts the keys with oldest expiration time last
storedKeys.sort(function(a, b) { return (b.expiration-a.expiration); });
var targetSize = (value||'').length;
while (storedKeys.length && targetSize > 0) {
storedKey = storedKeys.pop();
removeItem(storedKey.key);
removeItem(expirationKey(storedKey.key));
targetSize -= storedKey.size;
}
try {
setItem(key, value);
} catch (e) {
// value may be larger than total quota
return;
}
} else {
// If it was some other error, just give up.
return;
}
}
// If a time is specified, store expiration info in localStorage
if (time) {
setItem(expirationKey(key), (currentTime() + time).toString(EXPIRY_RADIX));
} else {
// In case they previously set a time, remove that info from localStorage.
removeItem(expirationKey(key));
}
},
/**
* Retrieves specified value from localStorage, if not expired.
* @param {string} key
* @return {string|Object}
*/
get: function(key) {
if (!supportsStorage()) return null;
// Return the de-serialized item if not expired
var exprKey = expirationKey(key);
var expr = getItem(exprKey);
if (expr) {
var expirationTime = parseInt(expr, EXPIRY_RADIX);
// Check if we should actually kick item out of storage
if (currentTime() >= expirationTime) {
removeItem(key);
removeItem(exprKey);
return null;
}
}
// Tries to de-serialize stored value if its an object, and returns the normal value otherwise.
var value = getItem(key);
if (!value || !supportsJSON()) {
return value;
}
try {
// We can't tell if its JSON or a string, so we try to parse
return JSON.parse(value);
} catch (e) {
// If we can't parse, it's probably because it isn't an object
return value;
}
},
/**
* Removes a value from localStorage.
* Equivalent to 'delete' in memcache, but that's a keyword in JS.
* @param {string} key
*/
remove: function(key) {
if (!supportsStorage()) return null;
removeItem(key);
removeItem(expirationKey(key));
},
/**
* Returns whether local storage is supported.
* Currently exposed for testing purposes.
* @return {boolean}
*/
supported: function() {
return supportsStorage();
},
/**
* Flushes all lscache items and expiry markers without affecting rest of localStorage
*/
flush: function() {
if (!supportsStorage()) return;
// Loop in reverse as removing items will change indices of tail
for (var i = localStorage.length-1; i >= 0 ; --i) {
var key = localStorage.key(i);
if (key.indexOf(CACHE_PREFIX + cacheBucket) === 0) {
localStorage.removeItem(key);
}
}
},
/**
* Appends CACHE_PREFIX so lscache will partition data in to different buckets.
* @param {string} bucket
*/
setBucket: function(bucket) {
cacheBucket = bucket;
},
/**
* Resets the string being appended to CACHE_PREFIX so lscache will use the default storage behavior.
*/
resetBucket: function() {
cacheBucket = '';
}
};
}(); |
require('board');
var util = require('utilities');
SetGame = function(options) {
this.options = options;
this.options.mode = this.options.mode || 'easy';
var opts = SetGame.MODES[this.options.mode];
this.board = new Board(opts);
}
// key used in message passing so that we can filter out messages addressed only to us
SetGame.MSG_KEY = "SetGame";
SetGame.MODES = {
'easy': {
rows: 3,
cols: 3,
attributes: ['color', 'shape', 'number']
},
'hard': {
rows: 4,
cols: 3,
attributes: ['color', 'shape', 'number', 'texture']
},
}
SetGame.prototype = {
getSolutions: function() {
return this.board.
getSolutions().map(function(indices) {
return indices.map(function(idx) { return idx + 1 });
});
},
}
SetGame.ClientHandler = function(user, game) {
this.user = user;
this.game = game;
this.onConnect();
user.client.on('message', util.bind(this, this.onMessage));
}
SetGame.ClientHandler.prototype = {
onConnect: function() {
this.payload("initBoard", this.game.board);
},
onMessage: function(obj) {
if (obj.key != SetGame.MSG_KEY) return;
if (obj.method) {
if (typeof(this[obj.method]) == "function")
this[obj.method].call(this, obj.data);
else
console.error("Don't know how to handle", obj.key, obj.method);
}
},
verify: function(indices) {
var board = this.game.board, user = this.user;
var result = board.verify(indices);
if (result) {
user.score++;
user.announce("got a set!");
if (board.deck.length < indices.length) {
// If we run out of cards, reset the board
board.reset();
} else {
// Otherwise, replace the set cards with new ones from the deck
indices.forEach(function(idx){
board.cards[idx] = board.deck.shift();
});
if (board.numSolutions() < 1) board.reset();
}
}
this.payload("verifyResult", {
result: result,
board: board,
score: this.user.score
});
this.broadcast("initBoard", board);
this.user.broadcastLeaderboard();
},
cmd_userSelect: function(cellIdx) {
this.broadcast("userSelect", cellIdx);
},
payload: function(method, data) {
this.user.payload(SetGame.MSG_KEY, method, data);
},
broadcast: function(method, data) {
this.user.broadcast(SetGame.MSG_KEY, method, data);
},
} |
declare module '@react-navigation/material-top-tabs' {
//---------------------------------------------------------------------------
// SECTION 1: IDENTICAL TYPE DEFINITIONS
// This section is identical across all React Navigation libdefs and contains
// shared definitions. We wish we could make it DRY and import from a shared
// definition, but that isn't yet possible.
//---------------------------------------------------------------------------
/**
* We start with some definitions that we have copy-pasted from React Native
* source files.
*/
// This is a bastardization of the true StyleObj type located in
// react-native/Libraries/StyleSheet/StyleSheetTypes. We unfortunately can't
// import that here, and it's too lengthy (and consequently too brittle) to
// copy-paste here either.
declare type StyleObj =
| null
| void
| number
| false
| ''
| $ReadOnlyArray<StyleObj>
| { [name: string]: any, ... };
declare type ViewStyleProp = StyleObj;
declare type TextStyleProp = StyleObj;
declare type AnimatedViewStyleProp = StyleObj;
declare type AnimatedTextStyleProp = StyleObj;
// Vaguely copied from
// react-native/Libraries/Animated/src/animations/Animation.js
declare type EndResult = { finished: boolean, ... };
declare type EndCallback = (result: EndResult) => void;
declare interface Animation {
start(
fromValue: number,
onUpdate: (value: number) => void,
onEnd: ?EndCallback,
previousAnimation: ?Animation,
animatedValue: AnimatedValue,
): void;
stop(): void;
}
declare type AnimationConfig = {
isInteraction?: boolean,
useNativeDriver: boolean,
onComplete?: ?EndCallback,
iterations?: number,
...
};
// Vaguely copied from
// react-native/Libraries/Animated/src/nodes/AnimatedTracking.js
declare interface AnimatedTracking {
constructor(
value: AnimatedValue,
parent: any,
animationClass: any,
animationConfig: Object,
callback?: ?EndCallback,
): void;
update(): void;
}
// Vaguely copied from
// react-native/Libraries/Animated/src/nodes/AnimatedValue.js
declare type ValueListenerCallback = (state: { value: number, ... }) => void;
declare interface AnimatedValue {
constructor(value: number): void;
setValue(value: number): void;
setOffset(offset: number): void;
flattenOffset(): void;
extractOffset(): void;
addListener(callback: ValueListenerCallback): string;
removeListener(id: string): void;
removeAllListeners(): void;
stopAnimation(callback?: ?(value: number) => void): void;
resetAnimation(callback?: ?(value: number) => void): void;
interpolate(config: InterpolationConfigType): AnimatedInterpolation;
animate(animation: Animation, callback: ?EndCallback): void;
stopTracking(): void;
track(tracking: AnimatedTracking): void;
}
// Copied from
// react-native/Libraries/Animated/src/animations/TimingAnimation.js
declare type TimingAnimationConfigSingle = AnimationConfig & {
toValue: number | AnimatedValue,
easing?: (value: number) => number,
duration?: number,
delay?: number,
...
};
// Copied from
// react-native/Libraries/Animated/src/animations/SpringAnimation.js
declare type SpringAnimationConfigSingle = AnimationConfig & {
toValue: number | AnimatedValue,
overshootClamping?: boolean,
restDisplacementThreshold?: number,
restSpeedThreshold?: number,
velocity?: number,
bounciness?: number,
speed?: number,
tension?: number,
friction?: number,
stiffness?: number,
damping?: number,
mass?: number,
delay?: number,
...
};
// Copied from react-native/Libraries/Types/CoreEventTypes.js
declare type SyntheticEvent<T> = $ReadOnly<{|
bubbles: ?boolean,
cancelable: ?boolean,
currentTarget: number,
defaultPrevented: ?boolean,
dispatchConfig: $ReadOnly<{|
registrationName: string,
|}>,
eventPhase: ?number,
preventDefault: () => void,
isDefaultPrevented: () => boolean,
stopPropagation: () => void,
isPropagationStopped: () => boolean,
isTrusted: ?boolean,
nativeEvent: T,
persist: () => void,
target: ?number,
timeStamp: number,
type: ?string,
|}>;
declare type Layout = $ReadOnly<{|
x: number,
y: number,
width: number,
height: number,
|}>;
declare type LayoutEvent = SyntheticEvent<
$ReadOnly<{|
layout: Layout,
|}>,
>;
declare type BlurEvent = SyntheticEvent<
$ReadOnly<{|
target: number,
|}>,
>;
declare type FocusEvent = SyntheticEvent<
$ReadOnly<{|
target: number,
|}>,
>;
declare type ResponderSyntheticEvent<T> = $ReadOnly<{|
...SyntheticEvent<T>,
touchHistory: $ReadOnly<{|
indexOfSingleActiveTouch: number,
mostRecentTimeStamp: number,
numberActiveTouches: number,
touchBank: $ReadOnlyArray<
$ReadOnly<{|
touchActive: boolean,
startPageX: number,
startPageY: number,
startTimeStamp: number,
currentPageX: number,
currentPageY: number,
currentTimeStamp: number,
previousPageX: number,
previousPageY: number,
previousTimeStamp: number,
|}>,
>,
|}>,
|}>;
declare type PressEvent = ResponderSyntheticEvent<
$ReadOnly<{|
changedTouches: $ReadOnlyArray<$PropertyType<PressEvent, 'nativeEvent'>>,
force: number,
identifier: number,
locationX: number,
locationY: number,
pageX: number,
pageY: number,
target: ?number,
timestamp: number,
touches: $ReadOnlyArray<$PropertyType<PressEvent, 'nativeEvent'>>,
|}>,
>;
// Vaguely copied from
// react-native/Libraries/Animated/src/nodes/AnimatedInterpolation.js
declare type ExtrapolateType = 'extend' | 'identity' | 'clamp';
declare type InterpolationConfigType = {
inputRange: Array<number>,
outputRange: Array<number> | Array<string>,
easing?: (input: number) => number,
extrapolate?: ExtrapolateType,
extrapolateLeft?: ExtrapolateType,
extrapolateRight?: ExtrapolateType,
...
};
declare interface AnimatedInterpolation {
interpolate(config: InterpolationConfigType): AnimatedInterpolation;
}
// Copied from react-native/Libraries/Components/View/ViewAccessibility.js
declare type AccessibilityRole =
| 'none'
| 'button'
| 'link'
| 'search'
| 'image'
| 'keyboardkey'
| 'text'
| 'adjustable'
| 'imagebutton'
| 'header'
| 'summary'
| 'alert'
| 'checkbox'
| 'combobox'
| 'menu'
| 'menubar'
| 'menuitem'
| 'progressbar'
| 'radio'
| 'radiogroup'
| 'scrollbar'
| 'spinbutton'
| 'switch'
| 'tab'
| 'tablist'
| 'timer'
| 'toolbar';
declare type AccessibilityActionInfo = $ReadOnly<{
name: string,
label?: string,
...
}>;
declare type AccessibilityActionEvent = SyntheticEvent<
$ReadOnly<{actionName: string, ...}>,
>;
declare type AccessibilityState = {
disabled?: boolean,
selected?: boolean,
checked?: ?boolean | 'mixed',
busy?: boolean,
expanded?: boolean,
...
};
declare type AccessibilityValue = $ReadOnly<{|
min?: number,
max?: number,
now?: number,
text?: string,
|}>;
// Copied from
// react-native/Libraries/Components/Touchable/TouchableWithoutFeedback.js
declare type Stringish = string;
declare type EdgeInsetsProp = $ReadOnly<$Shape<EdgeInsets>>;
declare type TouchableWithoutFeedbackProps = $ReadOnly<{|
accessibilityActions?: ?$ReadOnlyArray<AccessibilityActionInfo>,
accessibilityElementsHidden?: ?boolean,
accessibilityHint?: ?Stringish,
accessibilityIgnoresInvertColors?: ?boolean,
accessibilityLabel?: ?Stringish,
accessibilityLiveRegion?: ?('none' | 'polite' | 'assertive'),
accessibilityRole?: ?AccessibilityRole,
accessibilityState?: ?AccessibilityState,
accessibilityValue?: ?AccessibilityValue,
accessibilityViewIsModal?: ?boolean,
accessible?: ?boolean,
children?: ?React$Node,
delayLongPress?: ?number,
delayPressIn?: ?number,
delayPressOut?: ?number,
disabled?: ?boolean,
focusable?: ?boolean,
hitSlop?: ?EdgeInsetsProp,
importantForAccessibility?: ?('auto' | 'yes' | 'no' | 'no-hide-descendants'),
nativeID?: ?string,
onAccessibilityAction?: ?(event: AccessibilityActionEvent) => mixed,
onBlur?: ?(event: BlurEvent) => mixed,
onFocus?: ?(event: FocusEvent) => mixed,
onLayout?: ?(event: LayoutEvent) => mixed,
onLongPress?: ?(event: PressEvent) => mixed,
onPress?: ?(event: PressEvent) => mixed,
onPressIn?: ?(event: PressEvent) => mixed,
onPressOut?: ?(event: PressEvent) => mixed,
pressRetentionOffset?: ?EdgeInsetsProp,
rejectResponderTermination?: ?boolean,
testID?: ?string,
touchSoundDisabled?: ?boolean,
|}>;
// Copied from react-native/Libraries/Image/ImageSource.js
declare type ImageURISource = $ReadOnly<{
uri?: ?string,
bundle?: ?string,
method?: ?string,
headers?: ?Object,
body?: ?string,
cache?: ?('default' | 'reload' | 'force-cache' | 'only-if-cached'),
width?: ?number,
height?: ?number,
scale?: ?number,
...
}>;
/**
* The following is copied from react-native-gesture-handler's libdef
*/
declare type $EventHandlers<ExtraProps: {...}> = {|
onGestureEvent?: ($Event<ExtraProps>) => mixed,
onHandlerStateChange?: ($Event<ExtraProps>) => mixed,
onBegan?: ($Event<ExtraProps>) => mixed,
onFailed?: ($Event<ExtraProps>) => mixed,
onCancelled?: ($Event<ExtraProps>) => mixed,
onActivated?: ($Event<ExtraProps>) => mixed,
onEnded?: ($Event<ExtraProps>) => mixed,
|};
declare type HitSlop =
| number
| {|
left?: number,
top?: number,
right?: number,
bottom?: number,
vertical?: number,
horizontal?: number,
width?: number,
height?: number,
|}
| {|
width: number,
left: number,
|}
| {|
width: number,
right: number,
|}
| {|
height: number,
top: number,
|}
| {|
height: number,
bottom: number,
|};
declare type $GestureHandlerProps<
AdditionalProps: {...},
ExtraEventsProps: {...}
> = $ReadOnly<{|
...$Exact<AdditionalProps>,
...$EventHandlers<ExtraEventsProps>,
id?: string,
enabled?: boolean,
waitFor?: React$Ref<any> | Array<React$Ref<any>>,
simultaneousHandlers?: React$Ref<any> | Array<React$Ref<any>>,
shouldCancelWhenOutside?: boolean,
minPointers?: number,
hitSlop?: HitSlop,
children?: React$Node,
|}>;
declare type PanGestureHandlerProps = $GestureHandlerProps<
{
activeOffsetY?: number | [number, number],
activeOffsetX?: number | [number, number],
failOffsetY?: number | [number, number],
failOffsetX?: number | [number, number],
minDist?: number,
minVelocity?: number,
minVelocityX?: number,
minVelocityY?: number,
minPointers?: number,
maxPointers?: number,
avgTouches?: boolean,
...
},
{
x: number,
y: number,
absoluteX: number,
absoluteY: number,
translationX: number,
translationY: number,
velocityX: number,
velocityY: number,
...
}
>;
/**
* MAGIC
*/
declare type $If<Test: boolean, Then, Else = empty> = $Call<
((true, Then, Else) => Then) & ((false, Then, Else) => Else),
Test,
Then,
Else,
>;
declare type $IsA<X, Y> = $Call<
(Y => true) & (mixed => false),
X,
>;
declare type $IsUndefined<X> = $IsA<X, void>;
declare type $Partial<T> = $Rest<T, {...}>;
/**
* Actions, state, etc.
*/
declare export type ScreenParams = { +[key: string]: mixed, ... };
declare export type BackAction = {|
+type: 'GO_BACK',
+source?: string,
+target?: string,
|};
declare export type NavigateAction = {|
+type: 'NAVIGATE',
+payload:
| {| +key: string, +params?: ScreenParams |}
| {| +name: string, +key?: string, +params?: ScreenParams |},
+source?: string,
+target?: string,
|};
declare export type ResetAction = {|
+type: 'RESET',
+payload: StaleNavigationState,
+source?: string,
+target?: string,
|};
declare export type SetParamsAction = {|
+type: 'SET_PARAMS',
+payload: {| +params?: ScreenParams |},
+source?: string,
+target?: string,
|};
declare export type CommonAction =
| BackAction
| NavigateAction
| ResetAction
| SetParamsAction;
declare type NavigateActionCreator = {|
(routeName: string, params?: ScreenParams): NavigateAction,
(
| {| +key: string, +params?: ScreenParams |}
| {| +name: string, +key?: string, +params?: ScreenParams |},
): NavigateAction,
|};
declare export type CommonActionsType = {|
+navigate: NavigateActionCreator,
+goBack: () => BackAction,
+reset: (state: PossiblyStaleNavigationState) => ResetAction,
+setParams: (params: ScreenParams) => SetParamsAction,
|};
declare export type GenericNavigationAction = {|
+type: string,
+payload?: { +[key: string]: mixed, ... },
+source?: string,
+target?: string,
|};
declare export type LeafRoute<RouteName: string = string> = {|
+key: string,
+name: RouteName,
+params?: ScreenParams,
|};
declare export type StateRoute<RouteName: string = string> = {|
...LeafRoute<RouteName>,
+state: NavigationState | StaleNavigationState,
|};
declare export type Route<RouteName: string = string> =
| LeafRoute<RouteName>
| StateRoute<RouteName>;
declare export type NavigationState = {|
+key: string,
+index: number,
+routeNames: $ReadOnlyArray<string>,
+history?: $ReadOnlyArray<mixed>,
+routes: $ReadOnlyArray<Route<>>,
+type: string,
+stale: false,
|};
declare export type StaleLeafRoute<RouteName: string = string> = {|
+key?: string,
+name: RouteName,
+params?: ScreenParams,
|};
declare export type StaleStateRoute<RouteName: string = string> = {|
...StaleLeafRoute<RouteName>,
+state: StaleNavigationState,
|};
declare export type StaleRoute<RouteName: string = string> =
| StaleLeafRoute<RouteName>
| StaleStateRoute<RouteName>;
declare export type StaleNavigationState = {|
// It's possible to pass React Nav a StaleNavigationState with an undefined
// index, but React Nav will always return one with the index set. This is
// the same as for the type property below, but in the case of index we tend
// to rely on it being set more...
+index: number,
+history?: $ReadOnlyArray<mixed>,
+routes: $ReadOnlyArray<StaleRoute<>>,
+type?: string,
+stale?: true,
|};
declare export type PossiblyStaleNavigationState =
| NavigationState
| StaleNavigationState;
declare export type PossiblyStaleRoute<RouteName: string = string> =
| Route<RouteName>
| StaleRoute<RouteName>;
/**
* Routers
*/
declare type ActionCreators<
State: NavigationState,
Action: GenericNavigationAction,
> = {
+[key: string]: (...args: any) => (Action | State => Action),
...
};
declare export type DefaultRouterOptions = {
+initialRouteName?: string,
...
};
declare export type RouterFactory<
State: NavigationState,
Action: GenericNavigationAction,
RouterOptions: DefaultRouterOptions,
> = (options: RouterOptions) => Router<State, Action>;
declare export type ParamListBase = { +[key: string]: ?ScreenParams, ... };
declare export type RouterConfigOptions = {|
+routeNames: $ReadOnlyArray<string>,
+routeParamList: ParamListBase,
|};
declare export type Router<
State: NavigationState,
Action: GenericNavigationAction,
> = {|
+type: $PropertyType<State, 'type'>,
+getInitialState: (options: RouterConfigOptions) => State,
+getRehydratedState: (
partialState: PossibleStaleNavigationState,
options: RouterConfigOptions,
) => State,
+getStateForRouteNamesChange: (
state: State,
options: RouterConfigOptions,
) => State,
+getStateForRouteFocus: (state: State, key: string) => State,
+getStateForAction: (
state: State,
action: Action,
options: RouterConfigOptions,
) => ?PossiblyStaleNavigationState;
+shouldActionChangeFocus: (action: GenericNavigationAction) => boolean,
+actionCreators?: ActionCreators<State, Action>,
|};
/**
* Stack actions and router
*/
declare export type StackNavigationState = {|
...NavigationState,
+type: 'stack',
|};
declare export type ReplaceAction = {|
+type: 'REPLACE',
+payload: {| +name: string, +key?: ?string, +params?: ScreenParams |},
+source?: string,
+target?: string,
|};
declare export type PushAction = {|
+type: 'PUSH',
+payload: {| +name: string, +key?: ?string, +params?: ScreenParams |},
+source?: string,
+target?: string,
|};
declare export type PopAction = {|
+type: 'POP',
+payload: {| +count: number |},
+source?: string,
+target?: string,
|};
declare export type PopToTopAction = {|
+type: 'POP_TO_TOP',
+source?: string,
+target?: string,
|};
declare export type StackAction =
| CommonAction
| ReplaceAction
| PushAction
| PopAction
| PopToTopAction;
declare export type StackActionsType = {|
+replace: (routeName: string, params?: ScreenParams) => ReplaceAction,
+push: (routeName: string, params?: ScreenParams) => PushAction,
+pop: (count?: number) => PopAction,
+popToTop: () => PopToTopAction,
|};
declare export type StackRouterOptions = $Exact<DefaultRouterOptions>;
/**
* Tab actions and router
*/
declare export type TabNavigationState = {|
...NavigationState,
+type: 'tab',
+history: $ReadOnlyArray<{| type: 'route', key: string |}>,
|};
declare export type JumpToAction = {|
+type: 'JUMP_TO',
+payload: {| +name: string, +params?: ScreenParams |},
+source?: string,
+target?: string,
|};
declare export type TabAction =
| CommonAction
| JumpToAction;
declare export type TabActionsType = {|
+jumpTo: string => JumpToAction,
|};
declare export type TabRouterOptions = {|
...$Exact<DefaultRouterOptions>,
+backBehavior?: 'initialRoute' | 'order' | 'history' | 'none',
|};
/**
* Drawer actions and router
*/
declare type DrawerHistoryEntry =
| {| +type: 'route', +key: string |}
| {| +type: 'drawer' |};
declare export type DrawerNavigationState = {|
...NavigationState,
+type: 'drawer',
+history: $ReadOnlyArray<DrawerHistoryEntry>,
|};
declare export type OpenDrawerAction = {|
+type: 'OPEN_DRAWER',
+source?: string,
+target?: string,
|};
declare export type CloseDrawerAction = {|
+type: 'CLOSE_DRAWER',
+source?: string,
+target?: string,
|};
declare export type ToggleDrawerAction = {|
+type: 'TOGGLE_DRAWER',
+source?: string,
+target?: string,
|};
declare export type DrawerAction =
| TabAction
| OpenDrawerAction
| CloseDrawerAction
| ToggleDrawerAction;
declare export type DrawerActionsType = {|
...TabActionsType,
+openDrawer: () => OpenDrawerAction,
+closeDrawer: () => CloseDrawerAction,
+toggleDrawer: () => ToggleDrawerAction,
|};
declare export type DrawerRouterOptions = {|
...TabRouterOptions,
+openByDefault?: boolean,
|};
/**
* Events
*/
declare export type EventMapBase = {
+[name: string]: {|
+data?: mixed,
+canPreventDefault?: boolean,
|},
...
};
declare type EventPreventDefaultProperties<Test: boolean> = $If<
Test,
{| +defaultPrevented: boolean, +preventDefault: () => void |},
{| |},
>;
declare type EventDataProperties<Data> = $If<
$IsUndefined<Data>,
{| |},
{| +data: Data |},
>;
declare type EventArg<
EventName: string,
CanPreventDefault: ?boolean = false,
Data = void,
> = {|
...EventPreventDefaultProperties<CanPreventDefault>,
...EventDataProperties<Data>,
+type: EventName,
+target?: string,
|};
declare type GlobalEventMap<State: PossiblyStaleNavigationState> = {|
+state: {| +data: {| +state: State |}, +canPreventDefault: false |},
|};
declare type EventMapCore<State: PossiblyStaleNavigationState> = {|
...GlobalEventMap<State>,
+focus: {| +data: void, +canPreventDefault: false |},
+blur: {| +data: void, +canPreventDefault: false |},
|};
declare type EventListenerCallback<
EventName: string,
State: PossiblyStaleNavigationState = NavigationState,
EventMap: EventMapBase = EventMapCore<State>,
> = (e: EventArg<
EventName,
$PropertyType<
$ElementType<
{| ...EventMap, ...EventMapCore<State> |},
EventName,
>,
'canPreventDefault',
>,
$PropertyType<
$ElementType<
{| ...EventMap, ...EventMapCore<State> |},
EventName,
>,
'data',
>,
>) => mixed;
/**
* Navigation prop
*/
declare export type SimpleNavigate<ParamList> =
<DestinationRouteName: $Keys<ParamList>>(
routeName: DestinationRouteName,
params: $ElementType<ParamList, DestinationRouteName>,
) => void;
declare export type Navigate<ParamList> =
& SimpleNavigate<ParamList>
& <DestinationRouteName: $Keys<ParamList>>(
route:
| {|
key: string,
params?: $ElementType<ParamList, DestinationRouteName>,
|}
| {|
name: DestinationRouteName,
key?: string,
params?: $ElementType<ParamList, DestinationRouteName>,
|},
) => void;
declare type NavigationHelpers<
ParamList: ParamListBase,
State: PossiblyStaleNavigationState = PossiblyStaleNavigationState,
EventMap: EventMapBase = EventMapCore<State>,
> = {
+navigate: Navigate<ParamList>,
+dispatch: (
action:
| GenericNavigationAction
| (State => GenericNavigationAction),
) => void,
+reset: PossiblyStaleNavigationState => void,
+goBack: () => void,
+isFocused: () => boolean,
+canGoBack: () => boolean,
+dangerouslyGetParent: <Parent: NavigationProp<ParamListBase>>() => ?Parent,
+dangerouslyGetState: () => NavigationState,
+addListener: <EventName: $Keys<
{| ...EventMap, ...EventMapCore<State> |},
>>(
name: EventName,
callback: EventListenerCallback<EventName, State, EventMap>,
) => () => void,
+removeListener: <EventName: $Keys<
{| ...EventMap, ...EventMapCore<State> |},
>>(
name: EventName,
callback: EventListenerCallback<EventName, State, EventMap>,
) => void,
...
};
declare export type NavigationProp<
ParamList: ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
State: PossiblyStaleNavigationState = PossiblyStaleNavigationState,
ScreenOptions: {...} = {...},
EventMap: EventMapBase = EventMapCore<State>,
> = {
...$Exact<NavigationHelpers<
ParamList,
State,
EventMap,
>>,
+setOptions: (options: $Shape<ScreenOptions>) => void,
+setParams: (
params: $If<
$IsUndefined<$ElementType<ParamList, RouteName>>,
empty,
$Shape<$NonMaybeType<$ElementType<ParamList, RouteName>>>,
>,
) => void,
...
};
/**
* CreateNavigator
*/
declare export type RouteProp<
ParamList: ParamListBase,
RouteName: $Keys<ParamList>,
> = {|
...LeafRoute<RouteName>,
+params: $ElementType<ParamList, RouteName>,
|};
declare export type ScreenListeners<
EventMap: EventMapBase = EventMapCore<State>,
State: NavigationState = NavigationState,
> = $ObjMapi<
{| [name: $Keys<EventMap>]: empty |},
<K: $Keys<EventMap>>(K, empty) => EventListenerCallback<K, State, EventMap>,
>;
declare type BaseScreenProps<
ParamList: ParamListBase,
NavProp,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
State: NavigationState = NavigationState,
ScreenOptions: {...} = {...},
EventMap: EventMapBase = EventMapCore<State>,
> = {|
+name: RouteName,
+options?:
| ScreenOptions
| ({|
route: RouteProp<ParamList, RouteName>,
navigation: NavProp,
|}) => ScreenOptions,
+listeners?:
| ScreenListeners<EventMap, State>
| ({|
route: RouteProp<ParamList, RouteName>,
navigation: NavProp,
|}) => ScreenListeners<EventMap, State>,
+initialParams?: $Shape<$ElementType<ParamList, RouteName>>,
|};
declare export type ScreenProps<
ParamList: ParamListBase,
NavProp,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
State: NavigationState = NavigationState,
ScreenOptions: {...} = {...},
EventMap: EventMapBase = EventMapCore<State>,
> =
| {|
...BaseScreenProps<
ParamList,
NavProp,
RouteName,
State,
ScreenOptions,
EventMap,
>,
+component: React$ComponentType<{|
route: RouteProp<ParamList, RouteName>,
navigation: NavProp,
|}>,
|}
| {|
...BaseScreenProps<
ParamList,
NavProp,
RouteName,
State,
ScreenOptions,
EventMap,
>,
+children: ({|
route: RouteProp<ParamList, RouteName>,
navigation: NavProp,
|}) => React$Node,
|};
declare export type ScreenComponent<
GlobalParamList: ParamListBase,
ParamList: ParamListBase,
State: NavigationState = NavigationState,
ScreenOptions: {...} = {...},
EventMap: EventMapBase = EventMapCore<State>,
> = <
RouteName: $Keys<ParamList>,
NavProp: NavigationProp<
GlobalParamList,
RouteName,
State,
ScreenOptions,
EventMap,
>,
>(props: ScreenProps<
ParamList,
NavProp,
RouteName,
State,
ScreenOptions,
EventMap,
>) => React$Node;
declare type ScreenOptionsProp<ScreenOptions: {...}, NavProp> = {|
+screenOptions?:
| ScreenOptions
| ({| route: LeafRoute<>, navigation: NavProp |}) => ScreenOptions,
|};
declare export type ExtraNavigatorPropsBase = {
...$Exact<DefaultRouterOptions>,
+children?: React$Node,
...
};
declare export type NavigatorPropsBase<ScreenOptions: {...}, NavProp> = {
...$Exact<ExtraNavigatorPropsBase>,
...ScreenOptionsProp<ScreenOptions, NavProp>,
...
};
declare export type CreateNavigator<
State: NavigationState,
ScreenOptions: {...},
EventMap: EventMapBase,
ExtraNavigatorProps: ExtraNavigatorPropsBase,
> = <
GlobalParamList: ParamListBase,
ParamList: ParamListBase,
NavProp: NavigationHelpers<
GlobalParamList,
State,
EventMap,
>,
>() => {|
+Screen: ScreenComponent<
GlobalParamList,
ParamList,
State,
ScreenOptions,
EventMap,
>,
+Navigator: React$ComponentType<{|
...$Exact<ExtraNavigatorProps>,
...ScreenOptionsProp<ScreenOptions, NavProp>,
|}>,
|};
declare export type CreateNavigatorFactory = <
State: NavigationState,
ScreenOptions: {...},
EventMap: EventMapBase,
NavProp: NavigationHelpers<
ParamListBase,
State,
EventMap,
>,
ExtraNavigatorProps: ExtraNavigatorPropsBase,
>(
navigator: React$ComponentType<{|
...$Exact<ExtraNavigatorPropsBase>,
...ScreenOptionsProp<ScreenOptions, NavProp>,
|}>,
) => CreateNavigator<State, ScreenOptions, EventMap, ExtraNavigatorProps>;
/**
* useNavigationBuilder
*/
declare export type Descriptor<
NavProp,
ScreenOptions: {...} = {...},
> = {|
+render: () => React$Node,
+options: $ReadOnly<ScreenOptions>,
+navigation: NavProp,
|};
declare export type UseNavigationBuilder = <
State: NavigationState,
Action: GenericNavigationAction,
ScreenOptions: {...},
RouterOptions: DefaultRouterOptions,
NavProp,
>(
routerFactory: RouterFactory<State, Action, RouterOptions>,
options: {|
...$Exact<RouterOptions>,
...ScreenOptionsProp<ScreenOptions, NavProp>,
+children?: React$Node,
|},
) => {|
+state: State,
+descriptors: {| +[key: string]: Descriptor<NavProp, ScreenOptions> |},
+navigation: NavProp,
|};
/**
* EdgeInsets
*/
declare type EdgeInsets = {|
+top: number,
+right: number,
+bottom: number,
+left: number,
|};
/**
* TransitionPreset
*/
declare export type TransitionSpec =
| {|
animation: 'spring',
config: $Diff<
SpringAnimationConfigSingle,
{ toValue: number | AnimatedValue, ... },
>,
|}
| {|
animation: 'timing',
config: $Diff<
TimingAnimationConfigSingle,
{ toValue: number | AnimatedValue, ... },
>,
|};
declare export type StackCardInterpolationProps = {|
+current: {|
+progress: AnimatedInterpolation,
|},
+next?: {|
+progress: AnimatedInterpolation,
|},
+index: number,
+closing: AnimatedInterpolation,
+swiping: AnimatedInterpolation,
+inverted: AnimatedInterpolation,
+layouts: {|
+screen: {| +width: number, +height: number |},
|},
+insets: EdgeInsets,
|};
declare export type StackCardInterpolatedStyle = {|
containerStyle?: AnimatedViewStyleProp,
cardStyle?: AnimatedViewStyleProp,
overlayStyle?: AnimatedViewStyleProp,
shadowStyle?: AnimatedViewStyleProp,
|};
declare export type StackCardStyleInterpolator = (
props: StackCardInterpolationProps,
) => StackCardInterpolatedStyle;
declare export type StackHeaderInterpolationProps = {|
+current: {|
+progress: AnimatedInterpolation,
|},
+next?: {|
+progress: AnimatedInterpolation,
|},
+layouts: {|
+header: {| +width: number, +height: number |},
+screen: {| +width: number, +height: number |},
+title?: {| +width: number, +height: number |},
+leftLabel?: {| +width: number, +height: number |},
|},
|};
declare export type StackHeaderInterpolatedStyle = {|
leftLabelStyle?: AnimatedViewStyleProp,
leftButtonStyle?: AnimatedViewStyleProp,
rightButtonStyle?: AnimatedViewStyleProp,
titleStyle?: AnimatedViewStyleProp,
backgroundStyle?: AnimatedViewStyleProp,
|};
declare export type StackHeaderStyleInterpolator = (
props: StackHeaderInterpolationProps,
) => StackHeaderInterpolatedStyle;
declare type GestureDirection =
| 'horizontal'
| 'horizontal-inverted'
| 'vertical'
| 'vertical-inverted';
declare export type TransitionPreset = {|
+gestureDirection: GestureDirection,
+transitionSpec: {|
+open: TransitionSpec,
+close: TransitionSpec,
|},
+cardStyleInterpolator: StackCardStyleInterpolator,
+headerStyleInterpolator: StackHeaderStyleInterpolator,
|};
/**
* Stack options
*/
declare export type StackDescriptor = Descriptor<
StackNavigationProp<>,
StackOptions,
>;
declare type Scene<T> = {|
+route: T,
+descriptor: StackDescriptor,
+progress: {|
+current: AnimatedInterpolation,
+next?: AnimatedInterpolation,
+previous?: AnimatedInterpolation,
|},
|};
declare export type StackHeaderProps = {|
+mode: 'float' | 'screen',
+layout: {| +width: number, +height: number |},
+insets: EdgeInsets,
+scene: Scene<Route<>>,
+previous?: Scene<Route<>>,
+navigation: StackNavigationProp<ParamListBase>,
+styleInterpolator: StackHeaderStyleInterpolator,
|};
declare export type StackHeaderLeftButtonProps = $Shape<{|
+onPress: (() => void),
+pressColorAndroid: string;
+backImage: (props: {| tintColor: string |}) => React$Node,
+tintColor: string,
+label: string,
+truncatedLabel: string,
+labelVisible: boolean,
+labelStyle: AnimatedTextStyleProp,
+allowFontScaling: boolean,
+onLabelLayout: LayoutEvent => void,
+screenLayout: {| +width: number, +height: number |},
+titleLayout: {| +width: number, +height: number |},
+canGoBack: boolean,
|}>;
declare type StackHeaderTitleInputBase = {
+onLayout: LayoutEvent => void,
+children: string,
+allowFontScaling: ?boolean,
+tintColor: ?string,
+style: ?AnimatedTextStyleProp,
...
};
declare export type StackHeaderTitleInputProps =
$Exact<StackHeaderTitleInputBase>;
declare export type StackOptions = $Shape<{|
+title: string,
+header: StackHeaderProps => React$Node,
+headerShown: boolean,
+cardShadowEnabled: boolean,
+cardOverlayEnabled: boolean,
+cardOverlay: {| style: ViewStyleProp |} => React$Node,
+cardStyle: ViewStyleProp,
+animationEnabled: boolean,
+animationTypeForReplace: 'push' | 'pop',
+gestureEnabled: boolean,
+gestureResponseDistance: {| vertical?: number, horizontal?: number |},
+gestureVelocityImpact: number,
+safeAreaInsets: $Shape<EdgeInsets>,
// Transition
...TransitionPreset,
// Header
+headerTitle: string | (StackHeaderTitleInputProps => React$Node),
+headerTitleAlign: 'left' | 'center',
+headerTitleStyle: AnimatedTextStyleProp,
+headerTitleContainerStyle: ViewStyleProp,
+headerTintColor: string,
+headerTitleAllowFontScaling: boolean,
+headerBackAllowFontScaling: boolean,
+headerBackTitle: string | null,
+headerBackTitleStyle: TextStyleProp,
+headerBackTitleVisible: boolean,
+headerTruncatedBackTitle: string,
+headerLeft: StackHeaderLeftButtonProps => React$Node,
+headerLeftContainerStyle: ViewStyleProp,
+headerRight: {| tintColor?: string |} => React$Node,
+headerRightContainerStyle: ViewStyleProp,
+headerBackImage: $PropertyType<StackHeaderLeftButtonProps, 'backImage'>,
+headerPressColorAndroid: string,
+headerBackground: ({| style: ViewStyleProp |}) => React$Node,
+headerStyle: ViewStyleProp,
+headerTransparent: boolean,
+headerStatusBarHeight: number,
|}>;
/**
* Stack navigation prop
*/
declare export type StackNavigationEventMap = {|
...EventMapCore<StackNavigationState>,
+transitionStart: {|
+data: {| +closing: boolean |},
+canPreventDefault: false,
|},
+transitionEnd: {|
+data: {| +closing: boolean |},
+canPreventDefault: false,
|},
|};
declare type InexactStackNavigationProp<
ParamList: ParamListBase = ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
Options: {...} = StackOptions,
EventMap: EventMapBase = StackNavigationEventMap,
> = {
...$Exact<NavigationProp<
ParamList,
RouteName,
StackNavigationState,
Options,
EventMap,
>>,
+replace: SimpleNavigate<ParamList>,
+push: SimpleNavigate<ParamList>,
+pop: (count?: number) => void,
+popToTop: () => void,
...
};
declare export type StackNavigationProp<
ParamList: ParamListBase = ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
Options: {...} = StackOptions,
EventMap: EventMapBase = StackNavigationEventMap,
> = $Exact<InexactStackNavigationProp<
ParamList,
RouteName,
Options,
EventMap,
>>;
/**
* Miscellaneous stack exports
*/
declare type StackNavigationConfig = {|
+mode?: 'card' | 'modal',
+headerMode?: 'float' | 'screen' | 'none',
+keyboardHandlingEnabled?: boolean,
|};
declare export type ExtraStackNavigatorProps = {|
...$Exact<ExtraNavigatorPropsBase>,
...StackRouterOptions,
...StackNavigationConfig,
|};
declare export type StackNavigatorProps<
NavProp: InexactStackNavigationProp<> = StackNavigationProp<>,
> = {|
...ExtraStackNavigatorProps,
...ScreenOptionsProp<StackOptions, NavProp>,
|};
/**
* Bottom tab options
*/
declare export type BottomTabBarButtonProps = {|
...$Diff<
TouchableWithoutFeedbackProps,
{| onPress?: ?(event: PressEvent) => mixed |},
>,
+to?: string,
+children: React$Node,
+onPress?: (MouseEvent | PressEvent) => void,
|};
declare export type BottomTabOptions = $Shape<{|
+title: string,
+tabBarLabel:
| string
| ({| focused: boolean, color: string |}) => React$Node,
+tabBarIcon: ({|
focused: boolean,
color: string,
size: number,
|}) => React$Node,
+tabBarAccessibilityLabel: string,
+tabBarTestID: string,
+tabBarVisible: boolean,
+tabBarButton: BottomTabBarButtonProps => React$Node,
+unmountOnBlur: boolean,
|}>;
/**
* Bottom tab navigation prop
*/
declare export type BottomTabNavigationEventMap = {|
...EventMapCore<TabNavigationState>,
+tabPress: {| +data: void, +canPreventDefault: true |},
+tabLongPress: {| +data: void, +canPreventDefault: false |},
|};
declare type InexactTabNavigationProp<
ParamList: ParamListBase,
RouteName: $Keys<ParamList>,
Options: {...},
EventMap: EventMapBase,
> = {
...$Exact<NavigationProp<
ParamList,
RouteName,
TabNavigationState,
Options,
EventMap,
>>,
+jumpTo: SimpleNavigate<ParamList>,
...
};
declare export type InexactBottomTabNavigationProp<
ParamList: ParamListBase = ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
Options: {...} = BottomTabOptions,
EventMap: EventMapBase = BottomTabNavigationEventMap,
> = InexactTabNavigationProp<
ParamList,
RouteName,
Options,
EventMap,
>;
declare export type BottomTabNavigationProp<
ParamList: ParamListBase = ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
Options: {...} = BottomTabOptions,
EventMap: EventMapBase = BottomTabNavigationEventMap,
> = $Exact<InexactBottomTabNavigationProp<
ParamList,
RouteName,
Options,
EventMap,
>>;
/**
* Miscellaneous bottom tab exports
*/
declare export type BottomTabDescriptor = Descriptor<
BottomTabNavigationProp<>,
BottomTabOptions,
>;
declare export type BottomTabBarOptions = $Shape<{|
+keyboardHidesTabBar: boolean,
+activeTintColor: string,
+inactiveTintColor: string,
+activeBackgroundColor: string,
+inactiveBackgroundColor: string,
+allowFontScaling: boolean,
+showLabel: boolean,
+showIcon: boolean,
+labelStyle: TextStyleProp,
+iconStyle: TextStyleProp,
+tabStyle: ViewStyleProp,
+labelPosition: 'beside-icon' | 'below-icon',
+adaptive: boolean,
+safeAreaInsets: $Shape<EdgeInsets>,
+style: ViewStyleProp,
|}>;
declare type BottomTabNavigationBuilderResult = {|
+state: TabNavigationState,
+navigation: BottomTabNavigationProp<>,
+descriptors: {| +[key: string]: BottomTabDescriptor |},
|};
declare export type BottomTabBarProps = {|
...BottomTabBarOptions,
...BottomTabNavigationBuilderResult,
|}
declare type BottomTabNavigationConfig = {|
+lazy?: boolean,
+tabBar?: BottomTabBarProps => React$Node,
+tabBarOptions?: BottomTabBarOptions,
|};
declare export type ExtraBottomTabNavigatorProps = {|
...$Exact<ExtraNavigatorPropsBase>,
...TabRouterOptions,
...BottomTabNavigationConfig,
|};
declare export type BottomTabNavigatorProps<
NavProp: InexactBottomTabNavigationProp<> = BottomTabNavigationProp<>,
> = {|
...ExtraBottomTabNavigatorProps,
...ScreenOptionsProp<BottomTabOptions, NavProp>,
|};
/**
* Material bottom tab options
*/
declare export type MaterialBottomTabOptions = $Shape<{|
+title: string,
+tabBarColor: string,
+tabBarLabel: string,
+tabBarIcon:
| string
| ({| +focused: boolean, +color: string |}) => React$Node,
+tabBarBadge: boolean | number | string,
+tabBarAccessibilityLabel: string,
+tabBarTestID: string,
|}>;
/**
* Material bottom tab navigation prop
*/
declare export type MaterialBottomTabNavigationEventMap = {|
...EventMapCore<TabNavigationState>,
+tabPress: {| +data: void, +canPreventDefault: true |},
|};
declare export type InexactMaterialBottomTabNavigationProp<
ParamList: ParamListBase = ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
Options: {...} = MaterialBottomTabOptions,
EventMap: EventMapBase = MaterialBottomTabNavigationEventMap,
> = InexactTabNavigationProp<
ParamList,
RouteName,
Options,
EventMap,
>;
declare export type MaterialBottomTabNavigationProp<
ParamList: ParamListBase = ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
Options: {...} = MaterialBottomTabOptions,
EventMap: EventMapBase = MaterialBottomTabNavigationEventMap,
> = $Exact<InexactMaterialBottomTabNavigationProp<
ParamList,
RouteName,
Options,
EventMap,
>>;
/**
* Miscellaneous material bottom tab exports
*/
declare export type PaperFont = {|
+fontFamily: string,
+fontWeight?:
| 'normal'
| 'bold'
| '100'
| '200'
| '300'
| '400'
| '500'
| '600'
| '700'
| '800'
| '900',
|};
declare export type PaperFonts = {|
+regular: Font,
+medium: Font,
+light: Font,
+thin: Font,
|};
declare export type PaperTheme = {|
+dark: boolean,
+mode?: 'adaptive' | 'exact',
+roundness: number,
+colors: {|
+primary: string,
+background: string,
+surface: string,
+accent: string,
+error: string,
+text: string,
+onSurface: string,
+onBackground: string,
+disabled: string,
+placeholder: string,
+backdrop: string,
+notification: string,
|},
+fonts: PaperFonts,
+animation: {|
+scale: number,
|},
|};
declare export type PaperRoute = {|
+key: string,
+title?: string,
+icon?: any,
+badge?: string | number | boolean,
+color?: string,
+accessibilityLabel?: string,
+testID?: string,
|};
declare export type PaperTouchableProps = {|
...TouchableWithoutFeedbackProps,
+key: string,
+route: PaperRoute,
+children: React$Node,
+borderless?: boolean,
+centered?: boolean,
+rippleColor?: string,
|};
declare export type MaterialBottomTabNavigationConfig = {|
+shifting?: boolean,
+labeled?: boolean,
+renderTouchable?: PaperTouchableProps => React$Node,
+activeColor?: string,
+inactiveColor?: string,
+sceneAnimationEnabled?: boolean,
+keyboardHidesNavigationBar?: boolean,
+barStyle?: ViewStyleProp,
+style?: ViewStyleProp,
+theme?: PaperTheme,
|};
declare export type ExtraMaterialBottomTabNavigatorProps = {|
...$Exact<ExtraNavigatorPropsBase>,
...TabRouterOptions,
...MaterialBottomTabNavigationConfig,
|};
declare export type MaterialBottomTabNavigatorProps<
NavProp: InexactMaterialBottomTabNavigationProp<> =
MaterialBottomTabNavigationProp<>,
> = {|
...ExtraMaterialBottomTabNavigatorProps,
...ScreenOptionsProp<MaterialBottomTabOptions, NavProp>,
|};
/**
* Material top tab options
*/
declare export type MaterialTopTabOptions = $Shape<{|
+title: string,
+tabBarLabel:
| string
| ({| +focused: boolean, +color: string |}) => React$Node,
+tabBarIcon: ({| +focused: boolean, +color: string |}) => React$Node,
+tabBarAccessibilityLabel: string,
+tabBarTestID: string,
|}>;
/**
* Material top tab navigation prop
*/
declare export type MaterialTopTabNavigationEventMap = {|
...EventMapCore<TabNavigationState>,
+tabPress: {| +data: void, +canPreventDefault: true |},
+tabLongPress: {| +data: void, +canPreventDefault: false |},
+swipeStart: {| +data: void, +canPreventDefault: false |},
+swipeEnd: {| +data: void, +canPreventDefault: false |},
|};
declare export type InexactMaterialTopTabNavigationProp<
ParamList: ParamListBase = ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
Options: {...} = MaterialTopTabOptions,
EventMap: EventMapBase = MaterialTopTabNavigationEventMap,
> = InexactTabNavigationProp<
ParamList,
RouteName,
Options,
EventMap,
>;
declare export type MaterialTopTabNavigationProp<
ParamList: ParamListBase = ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
Options: {...} = MaterialTopTabOptions,
EventMap: EventMapBase = MaterialTopTabNavigationEventMap,
> = $Exact<InexactMaterialTopTabNavigationProp<
ParamList,
RouteName,
Options,
EventMap,
>>;
/**
* Miscellaneous material top tab exports
*/
declare type MaterialTopTabPagerCommonProps = {|
+keyboardDismissMode: 'none' | 'on-drag' | 'auto',
+swipeEnabled: boolean,
+swipeVelocityImpact?: number,
+springVelocityScale?: number,
+springConfig: $Shape<{|
+damping: number,
+mass: number,
+stiffness: number,
+restSpeedThreshold: number,
+restDisplacementThreshold: number,
|}>,
+timingConfig: $Shape<{|
+duration: number,
|}>,
|};
declare export type MaterialTopTabPagerProps = {|
...MaterialTopTabPagerCommonProps,
+onSwipeStart?: () => void,
+onSwipeEnd?: () => void,
+onIndexChange: (index: number) => void,
+navigationState: TabNavigationState,
+layout: {| +width: number, +height: number |},
+removeClippedSubviews: boolean,
+children: ({|
+addListener: (type: 'enter', listener: number => void) => void,
+removeListener: (type: 'enter', listener: number => void) => void,
+position: any, // Reanimated.Node<number>
+render: React$Node => React$Node,
+jumpTo: string => void,
|}) => React$Node,
+gestureHandlerProps: PanGestureHandlerProps,
|};
declare export type MaterialTopTabBarIndicatorProps = {|
+navigationState: TabNavigationState,
+width: string,
+style?: ViewStyleProp,
+getTabWidth: number => number,
|};
declare export type MaterialTopTabBarOptions = $Shape<{|
+scrollEnabled: boolean,
+bounces: boolean,
+pressColor: string,
+pressOpacity: number,
+getAccessible: ({| +route: Route<> |}) => boolean,
+renderBadge: ({| +route: Route<> |}) => React$Node,
+renderIndicator: MaterialTopTabBarIndicatorProps => React$Node,
+tabStyle: ViewStyleProp,
+indicatorStyle: ViewStyleProp,
+indicatorContainerStyle: ViewStyleProp,
+labelStyle: TextStyleProp,
+contentContainerStyle: ViewStyleProp,
+style: ViewStyleProp,
+activeTintColor: string,
+inactiveTintColor: string,
+iconStyle: ViewStyleProp,
+labelStyle: TextStyleProp,
+showLabel: boolean,
+showIcon: boolean,
+allowFontScaling: boolean,
|}>;
declare export type MaterialTopTabDescriptor = Descriptor<
MaterialBottomTabNavigationProp<>,
MaterialBottomTabOptions,
>;
declare type MaterialTopTabNavigationBuilderResult = {|
+state: TabNavigationState,
+navigation: MaterialTopTabNavigationProp<>,
+descriptors: {| +[key: string]: MaterialTopTabDescriptor |},
|};
declare export type MaterialTopTabBarProps = {|
...MaterialTopTabBarOptions,
...MaterialTopTabNavigationBuilderResult,
+layout: {| +width: number, +height: number |},
+position: any, // Reanimated.Node<number>
+jumpTo: string => void,
|};
declare export type MaterialTopTabNavigationConfig = {|
...$Partial<MaterialTopTabPagerCommonProps>,
+position?: any, // Reanimated.Value<number>
+tabBarPosition?: 'top' | 'bottom',
+initialLayout?: $Shape<{| +width: number, +height: number |}>,
+lazy?: boolean,
+lazyPreloadDistance?: number,
+removeClippedSubviews?: boolean,
+sceneContainerStyle?: ViewStyleProp,
+style?: ViewStyleProp,
+gestureHandlerProps?: PanGestureHandlerProps,
+pager?: MaterialTopTabPagerProps => React$Node,
+lazyPlaceholder?: ({| +route: Route<> |}) => React$Node,
+tabBar?: MaterialTopTabBarProps => React$Node,
+tabBarOptions?: MaterialTopTabBarOptions,
|};
declare export type ExtraMaterialTopTabNavigatorProps = {|
...$Exact<ExtraNavigatorPropsBase>,
...TabRouterOptions,
...MaterialTopTabNavigationConfig,
|};
declare export type MaterialTopTabNavigatorProps<
NavProp: InexactMaterialTopTabNavigationProp<> =
MaterialTopTabNavigationProp<>,
> = {|
...ExtraMaterialTopTabNavigatorProps,
...ScreenOptionsProp<MaterialTopTabOptions, NavProp>,
|};
/**
* Drawer options
*/
declare export type DrawerOptions = $Shape<{|
title: string,
drawerLabel:
| string
| ({| +color: string, +focused: boolean |}) => React$Node,
drawerIcon: ({|
+color: string,
+size: number,
+focused: boolean,
|}) => React$Node,
gestureEnabled: boolean,
swipeEnabled: boolean,
unmountOnBlur: boolean,
|}>;
/**
* Drawer navigation prop
*/
declare export type DrawerNavigationEventMap = {|
...EventMapCore<DrawerNavigationState>,
+drawerOpen: {| +data: void, +canPreventDefault: false |},
+drawerClose: {| +data: void, +canPreventDefault: false |},
|};
declare export type InexactDrawerNavigationProp<
ParamList: ParamListBase = ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
Options: {...} = DrawerOptions,
EventMap: EventMapBase = DrawerNavigationEventMap,
> = {
...$Exact<NavigationProp<
ParamList,
RouteName,
DrawerNavigationState,
Options,
EventMap,
>>,
+jumpTo: SimpleNavigate<ParamList>,
+openDrawer: () => void,
+closeDrawer: () => void,
+toggleDrawer: () => void,
...
};
declare export type DrawerNavigationProp<
ParamList: ParamListBase = ParamListBase,
RouteName: $Keys<ParamList> = $Keys<ParamList>,
Options: {...} = DrawerOptions,
EventMap: EventMapBase = DrawerNavigationEventMap,
> = $Exact<InexactDrawerNavigationProp<
ParamList,
RouteName,
Options,
EventMap,
>>;
/**
* Miscellaneous drawer exports
*/
declare export type DrawerDescriptor = Descriptor<
DrawerNavigationProp<>,
DrawerOptions,
>;
declare export type DrawerItemListBaseOptions = $Shape<{|
+activeTintColor: string,
+activeBackgroundColor: string,
+inactiveTintColor: string,
+inactiveBackgroundColor: string,
+itemStyle: ViewStyleProp,
+labelStyle: TextStyleProp,
|}>;
declare export type DrawerContentOptions = $Shape<{|
...DrawerItemListBaseOptions,
+contentContainerStyle: ViewStyleProp,
+style: ViewStyleProp,
|}>;
declare type DrawerNavigationBuilderResult = {|
+state: DrawerNavigationState,
+navigation: DrawerNavigationProp<>,
+descriptors: {| +[key: string]: DrawerDescriptor |},
|};
declare export type DrawerContentProps = {|
...DrawerContentOptions,
...DrawerNavigationBuilderResult,
+progress: any, // Reanimated.Node<number>
|};
declare export type DrawerNavigationConfig = {|
+drawerPosition?: 'left' | 'right',
+drawerType?: 'front' | 'back' | 'slide' | 'permanent',
+edgeWidth?: number,
+hideStatusBar?: boolean,
+keyboardDismissMode?: 'on-drag' | 'none',
+minSwipeDistance?: number,
+overlayColor?: string,
+statusBarAnimation?: 'slide' | 'none' | 'fade',
+gestureHandlerProps?: PanGestureHandlerProps,
+lazy?: boolean,
+drawerContent?: DrawerContentProps => React$Node,
+drawerContentOptions?: DrawerContentOptions,
+sceneContainerStyle?: ViewStyleProp,
+drawerStyle?: ViewStyleProp,
|};
declare export type ExtraDrawerNavigatorProps = {|
...$Exact<ExtraNavigatorPropsBase>,
...DrawerRouterOptions,
...DrawerNavigationConfig,
|};
declare export type DrawerNavigatorProps<
NavProp: InexactDrawerNavigationProp<> = DrawerNavigationProp<>,
> = {|
...ExtraDrawerNavigatorProps,
...ScreenOptionsProp<DrawerOptions, NavProp>,
|};
/**
* BaseNavigationContainer
*/
declare export type BaseNavigationContainerProps = {|
+children: React$Node,
+initialState?: PossiblyStaleNavigationState,
+onStateChange?: (state: ?PossiblyStaleNavigationState) => void,
+independent?: boolean,
|};
declare export type ContainerEventMap = {|
...GlobalEventMap<PossiblyStaleNavigationState>,
+options: {|
+data: {| +options: { +[key: string]: mixed, ... } |},
+canPreventDefault: false,
|},
+__unsafe_action__: {|
+data: {|
+action: GenericNavigationAction,
+noop: boolean,
|},
+canPreventDefault: false,
|},
|};
declare export type BaseNavigationContainerInterface = {|
...$Exact<NavigationHelpers<
ParamListBase,
PossiblyStaleNavigationState,
ContainerEventMap,
>>,
+setParams: (params: ScreenParams) => void,
+resetRoot: (state?: ?PossiblyStaleNavigationState) => void,
+getRootState: () => PossiblyStaleNavigationState,
|};
/**
* State utils
*/
declare export type GetStateFromPath = (
path: string,
options?: LinkingConfig,
) => PossiblyStaleNavigationState;
declare export type GetPathFromState = (
state?: ?PossiblyStaleNavigationState,
options?: LinkingConfig,
) => string;
declare export type GetFocusedRouteNameFromRoute =
PossiblyStaleRoute<string> => ?string;
/**
* Linking
*/
declare export type ScreenLinkingConfig = {|
+path?: string,
+exact?: boolean,
+parse?: {| +[param: string]: string => mixed |},
+stringify?: {| +[param: string]: mixed => string |},
+screens?: ScreenLinkingConfigMap,
+initialRouteName?: string,
|};
declare export type ScreenLinkingConfigMap = {|
+[routeName: string]: string | ScreenLinkingConfig,
|};
declare export type LinkingConfig = {|
+initialRouteName?: string,
+screens: ScreenLinkingConfigMap,
|};
declare export type LinkingOptions = {|
+enabled?: boolean,
+prefixes: $ReadOnlyArray<string>,
+config?: LinkingConfig,
+getStateFromPath?: GetStateFromPath,
+getPathFromState?: GetPathFromState,
|};
/**
* NavigationContainer
*/
declare export type Theme = {|
+dark: boolean,
+colors: {|
+primary: string,
+background: string,
+card: string,
+text: string,
+border: string,
|},
|};
declare export type NavigationContainerType = React$AbstractComponent<
{|
...BaseNavigationContainerProps,
+theme?: Theme,
+linking?: LinkingOptions,
+fallback?: React$Node,
+onReady?: () => mixed,
|},
BaseNavigationContainerInterface,
>;
//---------------------------------------------------------------------------
// SECTION 2: EXPORTED MODULE
// This section defines the module exports and contains exported types that
// are not present in any other React Navigation libdef.
//---------------------------------------------------------------------------
/**
* createMaterialTopTabNavigator
*/
declare export var createMaterialTopTabNavigator: CreateNavigator<
TabNavigationState,
MaterialTopTabOptions,
MaterialTopTabNavigationEventMap,
ExtraMaterialTopTabNavigatorProps,
>;
/**
* MaterialTopTabView
*/
declare export type MaterialTopTabViewProps = {|
...MaterialTopTabNavigationConfig,
...MaterialTopTabNavigationBuilderResult,
|};
declare export var MaterialTopTabView: React$ComponentType<
MaterialTopTabViewProps,
>;
/**
* MaterialTopTabBar
*/
declare export var MaterialTopTabBar: React$ComponentType<
MaterialTopTabBarProps,
>;
}
|
(function() {
function resolveTranslationValue(value, dimension) {
var v = /^(-?\d+)px$/.exec(value);
if (v) {
return parseInt(v[1]);
}
v = /^(-?\d+)%$/.exec(value);
if (v) {
return dimension * parseInt(v[1]) / 100;
}
return 0;
}
function resolveCssTranslate(element) {
var x = 0, y = 0;
var transform = element.style.transform ||
element.style.webkitTransform ||
element.style.mozTransform ||
element.style.msTransform ||
element.style.oTransform;
if (!!transform) {
var regex = /translate\(\s*(\-?[\d\w%]+)\s*,\s*(\-?[\d\w%]+)\s*\)/g;
var translations = transform.match(regex);
if (translations) {
for (var i = 0; i < translations.length; ++i) {
var groups = regex.exec(translations[i]);
var translationX = groups[1],
translationY = groups[2];
x += resolveTranslationValue(translationX, element.offsetWidth);
y += resolveTranslationValue(translationY, element.offsetHeight);
}
}
}
return {
xOffset: x,
yOffset: y
};
}
function getFrameInScreen(element) {
var xPosition = 0;
var yPosition = 0;
var width = element.offsetWidth;
var height = element.offsetHeight;
while (element) {
var transform = resolveCssTranslate(element);
xPosition += element.offsetLeft -
element.scrollLeft +
transform.xOffset +
element.clientLeft;
yPosition += element.offsetTop -
element.scrollTop +
transform.yOffset +
element.clientTop;
element = element.offsetParent;
}
return {x: xPosition, y: yPosition, width: width, height: height};
}
function getScreenSize() {
return {
width: window.innerWidth,
height: window.innerHeight
};
}
function clip(position, max) {
if (position < 0) {
return 0;
} else if (position > max) {
return max;
} else {
return position;
}
}
/**
* @param {HTMLElement} element
* @param {{left: Number, right: Number, top: Number, bottom: Number}} insets
* portion of the screen to exclude from area considered visible
* @returns {Number} [0..1] - portion of the element currently visible on screen
*/
window.com.sivintech.elmentVisibleRatio = function(element, insets) {
var frame = getFrameInScreen(element);
var screenSize = getScreenSize();
var position = {
left: frame.x,
right: frame.x + frame.width,
top: frame.y,
bottom: frame.y + frame.height
};
position.left -= insets.left;
position.right -= insets.left;
position.top -= insets.top;
position.bottom -= insets.top;
screenSize.width = screenSize.width - insets.left - insets.right;
screenSize.height = screenSize.height - insets.top - insets.bottom;
var visibleWidth = clip(position.right, screenSize.width) -
clip(position.left, screenSize.width),
visibleHeight = clip(position.bottom, screenSize.height) -
clip(position.top, screenSize.height),
visibleRatioH = visibleWidth / frame.width,
visibleRatioV = visibleHeight / frame.height;
return visibleRatioH * visibleRatioV;
};
})();
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import { Link } from 'react-router';
import { List } from 'semantic-ui-react';
import { fetchRoster } from './../actions/action_index';
class Roster extends Component {
componentWillMount(){
this.props.fetchRoster();
}
renderList() {
if(!this.props.profiles.roster.length) {
return <div>Loading Roster...</div>;
}
return this.props.profiles.roster.map((profile) => {
if (!profile.active) {return null} // don't show profile unless active
return (
<div key={profile.profileid} className="profile-individual">
<div className='profile-information'>
<h3> <span className="profile-name">{profile.nickname ? profile.nickname : profile.firstname} {profile.lastname.charAt(0).toUpperCase()}</span></h3> <br />
<p className='profile-information-details'> Address: {profile.address}, {profile.city} {profile.state} </p>
<p className='profile-information-details'> Phone: {profile.homephone}, Cell: {profile.cellphone ? profile.cellphone : 'none'}</p>
<p className='profile-information-details'> Email: {profile.email}</p>
</div>
<div className='profile-image'>
<img src={profile.imageurl || './images/blank_profile.jpg'}></img>
</div>
</div>
)
})
}
render() {
return(
<div className="roster-list">
{this.renderList()}
</div>
)
}
}
const mapStateToProps = function({ profiles }) {
return { profiles }
};
const mapDispatchToProps = function (dispatch) {
return bindActionCreators({ fetchRoster }, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(Roster);
|
export default {
LEFT_BUTTON: 0
}; |
app.controller('ProjectCtrl', function($scope, $state, $stateParams, Project) {
$scope.state = $state.current.name;
Project.get({name: $stateParams.name}, function(project) {
$scope.project = project;
});
$scope.navigateTo = function(state) {
$state.transitionTo(state, {name: $stateParams.name}, {reload: true});
};
$scope.synchronize = function() {
$scope.project.$synchronize();
}
$scope.mapCommits = function() {
$scope.project.$mapCommits();
}
});
|
define([
'app/App',
'dojo/has',
'dojo/request/xhr',
'dojo/_base/Color',
'esri/config',
'esri/symbols/SimpleMarkerSymbol',
'dojo/domReady!'
], function (
App,
has,
xhr,
Color,
esriConfig,
SimpleMarkerSymbol
) {
esriConfig.defaults.io.corsEnabledServers.push('gis.trustlands.utah.gov');
esriConfig.defaults.io.corsEnabledServers.push('api.mapserv.utah.gov');
esriConfig.defaults.io.corsEnabledServers.push('discover.agrc.utah.gov');
var SITEADDRES = 'SITEADDRES';
var SITENAME = 'SITENAME';
var FAC_NAME = 'FAC_NAME';
var LOCNAME = 'LOCNAME';
var Title_EventName = 'Title_EventName';
var FAC_ADDRES = 'FAC_ADDRES';
var LOCSTR = 'LOCSTR';
var Address_Location = 'Address_Location';
var DERRID = 'DERRID';
window.AGRCGLOBAL = {
// app: app.App
// global reference to App
app: null,
// version: String
// The version number.
version: '2.7.3',
// apiKey: String
// Key for api.mapserv.utah.gov services
// Passed in as a parameter to the app
apiKey: null,
// urls: Object
urls: {
mapservice: 'https://mapserv.utah.gov/arcgis/rest/services/DEQSpills/MapService/MapServer',
landOwnership: 'https://gis.trustlands.utah.gov/server/rest/services/Ownership/UT_SITLA_Ownership_LandOwnership_WM/MapServer/0',
referenceLayers: 'https://mapserv.utah.gov/arcgis/rest/services/DEQSpills/ReferenceLayers/MapServer'
},
// labelsMinScale: Number
// The minimum scale beyond which the labels will not be shown
labelsMinScale: 50000,
zoomLevel: 12,
queries: [
['BOUNDARIES.ZipCodes', ['ZIP5', 'NAME'], ['ZIP', 'ZIPCITY']],
['BOUNDARIES.Municipalities', ['NAME'], ['CITY']],
['BOUNDARIES.Counties', ['NAME'], ['COUNTY']],
['CADASTRE.PLSSSections_GCDB',
['LABEL', 'SNUM', 'BASEMERIDIAN'],
['TOWNSHIP/RANGE', 'SECTION', 'BASEMERIDIAN']
],
['CADASTRE.LandOwnership', ['AGENCY'], ['OWNER_AGENCY']]
],
projections: {
utm: '+proj=utm +zone=12 +ellps=GRS80 +datum=NAD83 +units=m +no_defs'
},
deqLayerFields: [
DERRID,
'SITEDESC',
'ST_KEY',
SITENAME,
SITEADDRES,
FAC_NAME,
LOCNAME,
Title_EventName,
FAC_ADDRES,
LOCSTR,
Address_Location
],
fields: {
SITENAME: SITENAME,
SITEADDRES: SITEADDRES
},
// all others layers are SITENAME
nonStandardSiteNameLU: {
7: FAC_NAME,
8: FAC_NAME,
9: LOCNAME,
11: Title_EventName
},
// all other layers are SITEADDRES
nonStandardSiteAddressLU: {
7: FAC_ADDRES,
8: FAC_ADDRES,
9: LOCSTR,
11: Address_Location
},
labelsLU: {
sitename: 'SITENAME',
siteid: DERRID,
siteaddress: 'SITEADDRES'
},
symbol: new SimpleMarkerSymbol()
.setStyle(SimpleMarkerSymbol.STYLE_CIRCLE)
.setColor(new Color([255, 255, 0])),
zipCityHelpText: 'For city or zip code only searches, see "Map Search..." above',
outsideUtahMsg: 'No data is returned for points outside of the state of Utah!',
topics: {
labelLayer: 'deq-spills/labelLayer'
}
};
if (window.location.hostname === 'localhost' && window.AGRC_testQuadWord) {
// allow deq dev to define quad word for their testing on localhost...
window.AGRCGLOBAL.quadWord = window.AGRC_testQuadWord;
} else {
if (has('agrc-build') === 'prod') {
window.AGRCGLOBAL.quadWord = 'result-table-secure-antenna';
} else if (has('agrc-build') === 'stage') {
// *.dev.utah.gov & *.deq.utah.gov (their dev servers)
window.AGRCGLOBAL.quadWord = 'orca-brown-door-concert';
} else if (!window.dojoConfig || !window.dojoConfig.isJasmineTestRunner) {
xhr(require.baseUrl + 'secrets.json', {
handleAs: 'json',
sync: true
}).then(function (secrets) {
window.AGRCGLOBAL.quadWord = secrets.quadWord;
}, function () {
throw 'Error getting secrets!';
});
}
}
window.AGRCMap = App;
});
|
'use strict';
const routes = [
{
method: 'GET',
path: '/threejs/',
config: {
cache: false,
handler(request, reply){
reply.view('./threejs/app/templates/index.pug',
{});
},
tags: ['web'],
validate: {}
}
}
];
module.exports = routes;
|
//Problem: https://www.hackerrank.com/challenges/electronics-shop
//JavaScript
/*
Initial Thoughts:
We can sort and compare all pairs. If a pair is > max and <= s
then we set it as the new max. Then we eturn max after
checking all pairs.
Time Complexity: O(n * m) //Iterate over both arrays
Space Complexity: O(1) //No additional memory used
*/
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function getMoneySpent(keyboards, drives, s){
drives.sort((a, b) => a - b);
keyboards.sort((a, b) => a - b);
let max = -1;
for (let d of drives) {
for (let k of keyboards) {
if (d + k <= s) {
max = (d + k > max) ? d + k : max;
}
}
}
return max;
}
function main() {
var s_temp = readLine().split(' ');
var s = parseInt(s_temp[0]);
var n = parseInt(s_temp[1]);
var m = parseInt(s_temp[2]);
keyboards = readLine().split(' ');
keyboards = keyboards.map(Number);
drives = readLine().split(' ');
drives = drives.map(Number);
// The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items
var moneySpent = getMoneySpent(keyboards, drives, s);
process.stdout.write(""+moneySpent+"\n");
}
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("circle", {
cx: "4.5",
cy: "9.5",
r: "1.5"
}), h("path", {
d: "M22.17 9.17c0-3.91-3.19-7.06-7.11-7-3.83.06-6.99 3.37-6.88 7.19.09 3.38 2.58 6.16 5.83 6.7V20H6v-3h.5c.28 0 .5-.22.5-.5V13c0-.55-.45-1-1-1H3c-.55 0-1 .45-1 1v3.5c0 .28.22.5.5.5H3v4c0 .55.45 1 1 1h14c.55 0 1-.45 1-1s-.45-1-1-1h-2v-3.88c3.47-.41 6.17-3.36 6.17-6.95z"
})), 'NaturePeopleRounded'); |
var path = require('path');
var exec = require('child_process').exec;
var fs = require('fs');
exec('npm run-script generateparser', function(err, stdout,stderr) {
console.log( stdout, stderr);
if( err ) console.log( "!Error", err );
else {
exec('npm run-script buildclient', function(err, stdout,stderr) {
console.log( stdout, stderr);
if( err ) console.log( "!Error", err );
});
fs.createReadStream('./node_modules/moment/min/moment.min.js').pipe(fs.createWriteStream('./public/javascripts/chartled/deps/moment.min.js'));
fs.createReadStream('./node_modules/moment-timezone/min/moment-timezone.min.js').pipe(fs.createWriteStream('./public/javascripts/chartled/deps/moment-timezone.min.js'));
}
});
|
(function() {
var content = $('#content');
var video = $('#webcam')[0];
var resize = function() {
var w = $(this).width();
var h = $(this).height() - 110;
var ratio = video.width / video.height;
if (content.width() > w) {
content.width(w);
content.height(w / ratio);
}
else {
content.height(h);
content.width(h * ratio);
}
content.css('left', (w - content.width()) / 2 );
content.css('top', ((h - content.height()) / 2) + 55 );
};
$(window).resize(resize);
$(window).ready(function() {
resize();
$('#watchVideo').click(function() {
$(".browsers").fadeOut();
$(".browsersWithVideo").delay(300).fadeIn();
$("#video-demo").delay(300).fadeIn();
$("#video-demo")[0].play();
$('.backFromVideo').fadeIn();
event.stopPropagation();
return false;
});
$('.backFromVideo a').click(function() {
$(".browsersWithVideo").fadeOut();
$('.backFromVideo').fadeOut();
$(".browsers").fadeIn();
$("#video-demo")[0].pause();
$('#video-demo').fadeOut();
event.stopPropagation();
return false;
});
});
function hasGetUserMedia() {
// Note: Opera builds are unprefixed.
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
if (hasGetUserMedia()) {
$('.introduction').fadeIn();
$('.allow').fadeIn();
} else {
$('.browsers').fadeIn();
return;
}
var webcamError = function(e) {
alert('Webcam error!', e);
};
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({video: true}).then(function(stream) {
video.srcObject = stream;
initialize();
}, webcamError);
} else if (navigator.getUserMedia) {
navigator.getUserMedia({video: true}, function(stream) {
video.srcObject = stream;
initialize();
}, webcamError);
} else if (navigator.webkitGetUserMedia) {
navigator.webkitGetUserMedia({video:true}, function(stream) {
video.srcObject = window.webkitURL.createObjectURL(stream);
initialize();
}, webcamError);
} else {
//video.src = 'somevideo.webm'; // fallback.
}
var AudioContext = (
window.AudioContext ||
window.webkitAudioContext ||
null
);
var timeOut, lastImageData;
var canvasSource = $("#canvas-source")[0];
var canvasBlended = $("#canvas-blended")[0];
var contextSource = canvasSource.getContext('2d');
var contextBlended = canvasBlended.getContext('2d');
var soundContext;
var bufferLoader;
var notes = [];
// mirror video
contextSource.translate(canvasSource.width, 0);
contextSource.scale(-1, 1);
var c = 5;
function initialize() {
if (!AudioContext) {
alert("AudioContext not supported!");
}
else {
$('.introduction').fadeOut();
$('.allow').fadeOut();
$('.loading').delay(300).fadeIn();
setTimeout(loadSounds, 1000);
}
}
function loadSounds() {
soundContext = new AudioContext();
bufferLoader = new BufferLoader(soundContext,
[
'sounds/note1.mp3',
'sounds/note2.mp3',
'sounds/note3.mp3',
'sounds/note4.mp3',
'sounds/note5.mp3',
'sounds/note6.mp3',
'sounds/note7.mp3',
'sounds/note8.mp3'
],
finishedLoading
);
bufferLoader.load();
}
function finishedLoading(bufferList) {
for (var i=0; i<8; i++) {
var source = soundContext.createBufferSource();
source.buffer = bufferList[i];
source.connect(soundContext.destination);
var note = {
note: source,
ready: true,
visual: $("#note" + i)
};
notes.push(note);
}
start();
}
function playSound(obj) {
if (!obj.ready) return;
var source = soundContext.createBufferSource();
source.buffer = obj.note.buffer;
source.connect(soundContext.destination);
source.start(0);
obj.ready = false;
// throttle the note
setTimeout(setNoteReady, 400, obj);
}
function setNoteReady(obj) {
obj.ready = true;
}
function start() {
//$("#footer .instructions").show();
$('.loading').fadeOut();
$('body').addClass('black-background');
$(".instructions").delay(600).fadeIn();
$(canvasSource).delay(600).fadeIn();
$(canvasBlended).delay(600).fadeIn();
$("#xylo").delay(600).fadeIn();
$(".motion-cam").delay(600).fadeIn();
update();
}
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
function update() {
drawVideo();
blend();
checkAreas();
requestAnimFrame(update);
// timeOut = setTimeout(update, 1000/60);
}
function drawVideo() {
contextSource.drawImage(video, 0, 0, video.width, video.height);
}
function blend() {
var width = canvasSource.width;
var height = canvasSource.height;
// get webcam image data
var sourceData = contextSource.getImageData(0, 0, width, height);
// create an image if the previous image doesn’t exist
if (!lastImageData) lastImageData = contextSource.getImageData(0, 0, width, height);
// create a ImageData instance to receive the blended result
var blendedData = contextSource.createImageData(width, height);
// blend the 2 images
differenceAccuracy(blendedData.data, sourceData.data, lastImageData.data);
// draw the result in a canvas
contextBlended.putImageData(blendedData, 0, 0);
// store the current webcam image
lastImageData = sourceData;
}
function fastAbs(value) {
// funky bitwise, equal Math.abs
return (value ^ (value >> 31)) - (value >> 31);
}
function threshold(value) {
return (value > 0x15) ? 0xFF : 0;
}
function difference(target, data1, data2) {
// blend mode difference
if (data1.length != data2.length) return null;
var i = 0;
while (i < (data1.length * 0.25)) {
target[4*i] = data1[4*i] == 0 ? 0 : fastAbs(data1[4*i] - data2[4*i]);
target[4*i+1] = data1[4*i+1] == 0 ? 0 : fastAbs(data1[4*i+1] - data2[4*i+1]);
target[4*i+2] = data1[4*i+2] == 0 ? 0 : fastAbs(data1[4*i+2] - data2[4*i+2]);
target[4*i+3] = 0xFF;
++i;
}
}
function differenceAccuracy(target, data1, data2) {
if (data1.length != data2.length) return null;
var i = 0;
while (i < (data1.length * 0.25)) {
var average1 = (data1[4*i] + data1[4*i+1] + data1[4*i+2]) / 3;
var average2 = (data2[4*i] + data2[4*i+1] + data2[4*i+2]) / 3;
var diff = threshold(fastAbs(average1 - average2));
target[4*i] = diff;
target[4*i+1] = diff;
target[4*i+2] = diff;
target[4*i+3] = 0xFF;
++i;
}
}
function checkAreas() {
// loop over the note areas
for (var r=0; r<8; ++r) {
var blendedData = contextBlended.getImageData(1/8*r*video.width, 0, video.width/8, 100);
var i = 0;
var average = 0;
// loop over the pixels
while (i < (blendedData.data.length * 0.25)) {
// make an average between the color channel
average += (blendedData.data[i*4] + blendedData.data[i*4+1] + blendedData.data[i*4+2]) / 3;
++i;
}
// calculate an average between of the color values of the note area
average = Math.round(average / (blendedData.data.length * 0.25));
if (average > 10) {
// over a small limit, consider that a movement is detected
// play a note and show a visual feedback to the user
playSound(notes[r]);
// notes[r].visual.show();
// notes[r].visual.fadeOut();
if(!notes[r].visual.is(':animated')) {
notes[r].visual.css({opacity:1});
notes[r].visual.animate({opacity:0}, 700);
}
}
}
}
})();
|
var count = (function log(Decimal) {
var start = +new Date(),
log,
error,
passed = 0,
total = 0;
if (typeof window === 'undefined') {
log = console.log;
error = console.error;
} else {
log = function (str) { document.body.innerHTML += str.replace('\n', '<br>') };
error = function (str) { document.body.innerHTML += '<div style="color: red">' +
str.replace('\n', '<br>') + '</div>' };
}
if (!Decimal && typeof require === 'function') Decimal = require('../decimal');
function assert(expected, actual) {
total++;
//if ( total % 100 == 0 ) log(total);
if (expected !== actual) {
error('\n Test number: ' + total + ' failed');
error(' Expected: ' + expected);
error(' Actual: ' + actual);
//process.exit();
} else {
passed++;
//log('\n Expected and actual: ' + actual);
}
}
function T(n, base, result, pr, rm) {
Decimal.precision = pr;
Decimal.rounding = rm;
assert(result, new Decimal(n).log(base).toFixed());
}
log('\n Testing log...');
Decimal.config({
precision: 40,
rounding: 4,
toExpNeg: -9e15,
toExpPos: 9e15,
minE: -9e15,
maxE: 9e15,
errors: true
});
/*
Example of a log that will fail.
It results in 2.6 due to having 15 or more zeros from the first rounding digit.
*/
//T('4503599627370502', '1048576', '2.7', 2, 2); // 2.60000000000000009610279511444746656225...
T('0', '10', '-Infinity', 40, 4);
T('-0', '10', '-Infinity', 40, 4);
T('1', '10', '0', 40, 4);
T('-1', '10', 'NaN', 40, 4);
T('Infinity', '10', 'Infinity', 40, 4);
T('Infinity', '0', 'NaN', 40, 4);
T('-Infinity', 'Infinity', 'NaN', 40, 4);
T('NaN', '10', 'NaN', 40, 4);
T('1', '0', 'NaN', 40, 4); // Math.log(1) / Math.log(0) == -0
T('10', '0', 'NaN', 40, 4); // Math.log(10) / Math.log(0) == -0
T('10', '-0', 'NaN', 40, 4); // Math.log(10) / Math.log(-0) == -0
T('10', '1', 'NaN', 40, 4); // Math.log(10) / Math.log(1) == Infinity
T('10', '-1', 'NaN', 40, 4);
T('10', 'Infinity', 'NaN', 40, 4); // Math.log(10) / Math.log(Infinity) == 0
T('10', '-Infinity', 'NaN', 40, 4);
T('10', 'NaN', 'NaN', 40, 4);
T('-1', '-1', 'NaN', 40, 4);
T('0', '0', 'NaN', 40, 4);
T('7625597484987', '59049', '2.7', 2, 5);
T('839756321.64088511', '28', '6.16667503', 9, 0);
T('94143178827', '3486784401', '1.15', 3, 0);
T('243', '9', '3', 1, 4);
T('512', '16', '2.25', 7, 0);
T('512', '16', '2.25', 7, 2);
T('512', '16', '2.2', 2, 5);
T('512', '16', '2.2', 2, 6);
T('16', '2', '4', 7, 0);
T('16', '2', '4', 7, 2);
T('243', '3', '5', 7, 1);
T('243', '9', '2.5', 7, 1);
T('243', '3', '5', 7, 3);
T('243', '9', '2.5', 7, 3);
T('32', '4', '2.5', 7, 0);
T('32', '4', '2.5', 7, 2);
T('4', '2', '2', 1, 2);
T('8', '2', '3', 2, 0);
T('16', '2', '4', 2, 0);
T('32', '2', '5', 3, 0);
T('64', '2', '6', 3, 0);
T('64', '2', '6', 2, 0);
T('64', '2', '6', 1, 2);
T('128', '2', '7', 1, 0);
T('256', '2', '8', 1, 2);
T('1024', '2', '10', 2, 0);
T('1024', '2', '10', 10, 0);
T('16384', '2', '14', 2, 0);
T('16384', '2', '14', 10, 0);
T('243', '3', '5', 7, 4);
T('243', '9', '2.5', 7, 4);
T('243', '3', '5', 7, 4);
T('243', '9', '2.5', 7, 4);
T('16', '2', '4', 7, 4);
T('32', '4', '2.5', 7, 4);
T('16', '2', '4', 7, 4);
T('32', '4', '2.5', 7, 4);
T('1.2589254117', 10, '0.1', 1, 2);
T('1.023292992', 10, '0.01', 1, 2);
T('1.258925411794167210423954106395800606', 10, '0.1', 1, 4);
T('1.25892541179416721', 10, '0.1', 1, 0);
T('1.258925411', 10, '0.1', 1, 5);
T('1.258925411794167210423954', 10, '0.1', 1, 4);
/*
6.166675020000903537297764507632802193308677149
28^6.16667502 = 839756321.6383567959704282429971526703012698
28^6.16667503 = 839756349.6207552863005150010387178739013142
*/
T('839756321.64088511', '28', '6.16667503', 9, 0);
T('576306512.96177', '985212731.27158', '0.9742', 4, 2);
T('97.65625', '6.25', '2.5', 3, 0);
T('223677472.0384754303304727631735', '26', '5.900904252190486450814', 22, 5);
T('2063000845.3020737243910803079', '35', '6.0324410183892767982149330415', 29, 0);
T('302381977.956021650184952836276441035025875682714942', '2623', '2.4805663226398755020289647999', 29, 6);
T('456870693.58', '238920772.66', '1.0336035877093034523', 21, 4);
T('16', '2', '4', 10, 4);
T('32', '4', '2.5', 10, 1);
T('316.2277660168379331998893544432645719585553021316022642247511089459022980600999502961482777894980004', '10', '2.49999999999999999999', 21, 1);
// Base 10 therefore the following tests pass despite 15 or more zeros or nines as the rounding digits.
// 4.0000000000000000000173...
T('10000.0000000000000004', 10, '4.01', 3, 2);
// 4.00000000000000000173...
T('10000.00000000000004', 10, '4.01', 3, 2);
// 2.000000000000000000000004342944...
T('100.000000000000000000001', 10, '2.1', 2, 0);
// 2.00000000000000004342944...
T('100.00000000000001', 10, '2.1', 2, 0);
// 4.9999999999999999999960913...
T('99999.9999999999999991', 10, '4.999', 4, 1);
// 0.09360000000000000000000000020197...
T('124050.923004222533485495840', 10, '5.093601', 7, 2);
// 0.09999999999999999999999999999972381...
// 10^0.1 = 1.258925411794167210423954106395800606093617409466...
T('1.258925411794167210423954106395', 10, '0.09999', 4, 1);
// 8.959609629999999999999999999999431251938064
T('911191437.48166728043529900000', 10, '8.959609629999999999999999', 25, 3);
// 2.4038746000000000000000000000000268051243...
T('253.4396732554691740503010363220', 10, '2.403874600001', 13, 2);
// 3.391702100000000000000000000000000025534271040...
T('2464.348361986885121671329250344224', 10, '3.3917021', 18, 1);
T('2464.348361986885121671329250344224', 10, '3.39170210000000001', 18, 0);
// 4.0000000000000000173...
T('10000.0000000000004', 10, '4.01', 3, 2);
// 4.00000000000000173...
T('10000.00000000004', 10, '4.01', 3, 2);
// 2.0000000000000004342944...
T('100.0000000000001', 10, '2.1', 2, 0);
// 4.99999999999999999960913...
T('99999.99999999999991', 10, '4.999', 4, 1);
// 4.9999999999999999960913...
T('99999.9999999999991', 10, '4.999', 4, 1);
// 4.99999999999960913...
T('99999.99999991', 10, '4.999', 4, 1);
T('6.626757835589191227753975149737456562020794782', 10, '0.8213011002743699999999999999999999999999999', 43, 1);
T('4.20732041199815040736678139715312481859825562145776045079', 10, '0.6240055873352599999999999999999999999999999999999999', 52, 3);
T('64513410281785809574142282220919135969.8537876292904158501590880', 10, '37.80964999999999999999', 22, 1);
T('33.51145738694771448172942314968136067036971739113975569076629', 10, '1.5251933153717162999999999999999999999999999999999999999', 56, 3);
T('10232.9299228075413096627', 10, '4.009999999999999', 16, 1);
T('1.258925411794167210423954106395', 10, '0.099999999999999999999999999999723814', 35, 0);
T('1.29891281037500', 10, '0.11357', 5, 1);
T('16.399137225681149762104868844', 10, '1.21482099999999999999999', 24, 3);
T('0.01', 10, '-2', 17, 3);
T('0.0000000001', 10, '-10', 4, 2);
T('0.00001', 10, '-5', 35, 3);
T('0.00000001', 10, '-8', 24, 2);
T('0.0000100000000000010000005060000000000800030000000400908', 10, '-4.99', 3, 1);
T('94143178827', '3486784401', '1.15', 3, 0);
T('15625', '3125', '1.2', 2, 3);
T('3', '3486784401', '0.05', 1, 8);
T('268435456', '1048576', '1.4', 2, 3);
T('25', '9765625', '0.2', 1, 7);
T('524288', '256', '2.375', 4, 8);
T('177147', '81', '2.75', 3, 5);
T('531441', '59049', '1.2', 2, 8);
T('387420489', '59049', '1.8', 2, 6);
T('16384', '65536', '0.875', 3, 6);
T('31381059609', '59049', '2.2', 2, 5);
T('8589934592', '65536', '2.0625', 5, 3);
T('33554432', '256', '3.125', 4, 3);
T('4503599627370496', '65536', '3.25', 3, 3);
T('68630377364883', '59049', '2.9', 2, 3);
T('68630377364883', '847288609443', '1.16', 3, 5);
T('16', '1125899906842624', '0.08', 1, 2);
T('3814697265625', '390625', '2.25', 3, 8);
T('8', '4294967296', '0.09375', 4, 1);
T('22876792454961', '59049', '2.8', 2, 2);
T('32', '33554432', '0.2', 1, 2);
T('16', '1125899906842624', '0.08', 1, 2);
T('16777216', '1024', '2.4', 2, 2);
T('31381059609', '3486784401', '1.1', 2, 4);
T('131072', '16', '4.25', 3, 7);
T('17179869184', '65536', '2.125', 4, 2);
T('131072', '32', '3.4', 2, 5);
T('31381059609', '6561', '2.75', 3, 4);
T('1162261467', '81', '4.75', 3, 2);
T('5', '152587890625', '0.0625', 3, 8);
T('2048', '32', '2.2', 2, 5);
T('15625', '390625', '0.75', 2, 0);
T('3125', '390625', '0.625', 3, 8);
T('17592186044416', '65536', '2.75', 3, 4);
T('4194304', '1048576', '1.1', 2, 2);
T('125', '390625', '0.375', 3, 5);
T('134217728', '256', '3.375', 4, 2);
T('762939453125', '625', '4.25', 3, 7);
T('8', '4294967296', '0.09375', 4, 0);
T('4', '1125899906842624', '0.04', 1, 5);
T('2384185791015625', '390625', '2.75', 3, 7);
T('4', '1024', '0.2', 1, 2);
T('268435456', '1048576', '1.4', 2, 8);
T('17592186044416', '4294967296', '1.375', 4, 0);
T('32', '4294967296', '0.15625', 5, 7);
T('256', '32', '1.6', 2, 2);
T('531441', '59049', '1.2', 2, 3);
T('67108864', '1048576', '1.3', 2, 2);
T('3814697265625', '3125', '3.6', 2, 5);
T('4096', '1024', '1.2', 2, 6);
T('78125', '625', '1.75', 3, 3);
T('1162261467', '81', '4.75', 3, 1);
T('4782969', '6561', '1.75', 3, 0);
T('4', '1024', '0.2', 1, 1);
T('59049', '6561', '1.25', 3, 2);
T('1024', '1099511627776', '0.25', 2, 2);
T('134217728', '1048576', '1.35', 3, 4);
T('65536', '32', '3.2', 2, 5);
T('19073486328125', '9765625', '1.9', 2, 2);
T('19073486328125', '3125', '3.8', 2, 5);
T('34359738368', '65536', '2.1875', 5, 4);
T('387420489', '59049', '1.8', 2, 1);
T('1125899906842624', '1099511627776', '1.25', 3, 3);
T('4', '1024', '0.2', 1, 8);
T('3125', '95367431640625', '0.25', 2, 4);
T('9', '6561', '0.25', 2, 0);
T('456870693.58', '238920772.66', '1.0336035877093034523', 21, 4);
T('575547956.8582', '824684975.3545', '0.98248076', 8, 4);
T('82275648.874341603', '959190115.624130088', '0.88124641544168894893181429200832363', 35, 4);
T('74257343.4', '743703514.4', '0.88720377341908842250463392057841865999040289364224', 50, 4);
T('617556576.22', '1390349767.37', '0.96145220002205342499', 20, 4);
T('385659206.402956', '306197094.245356', '1.0118079926535367225661814147003237994862', 41, 4);
T('1739848017', '139741504', '1.134455757605027173760473871049514546484', 40, 4);
T('684413372.332', '749444030.62', '0.99556', 5, 4);
T('1276559129.76358811', '1814329747.19301894', '0.983510102095361604388', 21, 4);
T('470873324.56', '770017206.95', '0.975963952980122531477453931545461086248352', 42, 4);
T('142843622.855', '188030025.676', '0.985573716314165', 15, 4);
T('208762187.506204', '15673510.715596', '1.1563', 5, 4);
T('1066260899.1963', '954219284.761', '1.005369396783858165862954752482856604', 37, 4);
T('98615189.15', '75483684.05', '1.0147363402964731399253', 23, 4);
T('134306349.93018997', '262971762.95484809', '0.965342550919082621945239', 24, 4);
T('964681161.089224', '1910911588.814815', '0.9680153968863558918522522557796148', 34, 4);
T('9303669', '272208139', '0.8262', 4, 4);
T('388804210', '196979048', '1.035603565223696855965', 22, 4);
T('699589959.2322617', '574032511.7854473', '1.0098079347111332288609', 23, 4);
T('100575245.36', '172874206.82', '0.971443699412905370317336892965778', 33, 4);
T('188632711.8541175', '1056627336.0975408', '0.9170754305183363941127042', 25, 4);
T('267522787.94', '528716571.79', '0.966083390988836341228896', 24, 4);
T('145509306.43395', '472783713.04935', '0.941003844701466585568051857', 28, 4);
T('991525965.6381098', '609527830.0476525', '1.024053580832128', 16, 4);
T('1023653880.6218838', '953120602.1428507', '1.00345303146', 13, 4);
T('55755796.19', '1330531177.01', '0.84899920538009273', 17, 4);
T('334096229.1342503', '563056758.6770503', '0.97409528', 8, 4);
T('9635164', '231514430', '0.834932623823994616103829175346875687708', 39, 4);
T('131654133.157309973', '115412751.259558256', '1.007092396906741330059871530698890891053443', 43, 4);
T('28107031.16903', '323908252.33297', '0.87525800295707725472', 20, 4);
T('942124652.44', '686394876.98', '1.01556421460608796561', 21, 4);
T('134207809', '170927649', '0.9872419619471883239821215', 26, 4);
T('198609255.296', '765215848.971', '0.9340613778607868792216981337564', 31, 4);
T('664631640.1191', '376279805.8674', '1.0288111231512597915756117213', 29, 4);
T('647566101.164328642', '407052201.855466296', '1.023419534517733289078130759686', 31, 4);
T('242605467.6', '3268140.5', '1.287152826698319781357494634688', 31, 4);
T('5396771.02937553', '1411282.60639346', '1.0947246452397777430415523165413422902424568', 45, 4);
T('6228580.16566', '453960426.11951', '0.7848417390817178840972620893811037531107708294', 46, 4);
T('878490932.5', '189566553.9', '1.080453580440657158456', 22, 4);
T('1500680766.6371536', '1494780181.6442677', '1.0001864920020959610926036', 27, 4);
T('173605161', '989556046', '0.91597101071520992883356353020920075841', 38, 4);
T('570910553.14918', '616094822.16082', '0.996236539891160511560385433132728465017198', 42, 4);
T('37195924.394254207', '127531072.030845613', '0.9339814946288269', 16, 4);
T('22164450.211923', '243265988.586396', '0.87593437485408990967662593016805664894656', 41, 4);
T('175111472.895051078', '561767815.122048785', '0.94214081222679273276622917511607118811', 38, 4);
T('92702966.55', '562074647.894', '0.910546423686847055179464329092669', 33, 4);
T('260084613', '160581316', '1.0255212564415', 14, 4);
T('213030852.3', '47040534.8', '1.08549659522166864397502645463300419005653', 42, 4);
T('1327668611.05913', '848611793.9525', '1.02177029434766261729', 21, 4);
T('66944433.91', '37665148.37', '1.03296947987902231513689373', 27, 4);
T('333313135.0827385', '147427566.3086553', '1.043370303', 10, 4);
T('756767858.792642', '513855352.06323', '1.019', 4, 4);
T('551590228.4822', '253966714.4708', '1.04007718126961747868602448117617608919458655503', 48, 4);
T('1882211388.983751503', '1593467634.878447375', '1.007859427551369756176720215269895309219252795831', 49, 4);
T('496604846.993369651', '1250937096.045637042', '0.955895995137179786819967061075092', 33, 4);
T('460938387.41106403', '892723899.76771112', '0.97', 2, 4);
T('1208583543.0755', '1801535412.788', '0.981269142418459120915', 21, 4);
T('71809284.33940128', '1599263904.61399344', '0.853568966592640560288310566832707', 34, 4);
T('165181894', '197693262', '0.9905943222681096997828', 22, 4);
T('172342892.2755695', '1013895675.5730544', '0.91454580627089536191594420786355067402436333108', 47, 4);
T('76327930.1691', '605058531.8951', '0.8976161867656397914685427265032120246028151', 44, 4);
T('157359823.532684', '53839744.709721', '1.060248953923960673498498182556874', 35, 4);
T('278952919.13814458', '409957472.74412763', '0.980585978464508766054991193215240504363', 39, 4);
T('1258423560.1', '1619810525.2', '0.98809514066162', 14, 4);
T('798939732.686433', '1672296635.208782', '0.96521864919758039929', 20, 4);
T('334706290.845', '330433505.915', '1.000654976135280091123085197917', 31, 4);
T('921610727.8', '1683508825.7', '0.971638655200833693263145748073', 30, 4);
T('91469509.55', '84500848.95', '1.0043416023016102807100081454879', 32, 4);
T('1238654120.34', '419789841.51', '1.0545', 5, 4);
T('779032702.616761', '656872953.495305', '1.00840084663', 12, 4);
// base 2
T('26880.2432276408875624', 2, '14.7142585720457255', 19, 3);
T('18216.8140929585641372', 2, '14.152983050314836771855701', 26, 1);
T('28062.73494235358182', 2, '14.776367997755111083362495', 26, 0);
T('7408.82842447993', 2, '12.8550297084583087071', 21, 1);
T('395.067', 2, '8.62595353', 9, 3);
T('27442.6587462411378', 2, '14.74414', 7, 0);
T('29259.23925137426', 2, '14.83660463902', 13, 1);
T('31809.09321', 2, '14.95715162', 10, 3);
T('21088.306138691278', 2, '14.3641556', 9, 4);
T('21417.99322', 2, '14.386535691235055367', 20, 4);
T('30749.008158228314845157', 2, '14.9', 3, 3);
T('11701.5', 2, '13.51440585840535244680127', 25, 0);
T('31737.6741', 2, '14.954', 5, 2);
T('1688.88816886', 2, '10.7218580867075137099751634', 27, 3);
T('31553.4', 2, '14.945507849063278420302384', 26, 1);
T('28215.19', 2, '14.7841844442', 12, 3);
T('6080.97', 2, '12.57008575', 10, 1);
T('575.881932366571406', 2, '9.16962924962079798', 18, 1);
T('4573.55560689675', 2, '12.1591004766309775332', 21, 1);
T('24202.85989198517539', 2, '15', 2, 4);
T('18334.9', 2, '14.16230477704721387108079127958', 31, 4);
T('20179.623017', 2, '14.4', 3, 0);
T('8607.97004888426002071', 2, '13.07145734276093159769689946319', 31, 1);
T('27231.463745', 2, '14.732986911725376996874804951679', 32, 3);
T('24325.08', 2, '14.57015693', 10, 0);
T('826.3541073', 2, '9.69', 3, 3);
T('6877.51851488', 2, '12.7476724030697', 15, 3);
T('13510.031', 2, '13.7217433646123774736072103937', 30, 4);
T('559.1647711259', 2, '9.12712965971023632', 18, 1);
T('1262.018796786493279', 2, '10.30151768', 10, 3);
T('31897.9889', 2, '14.9611778475691091525075', 24, 1);
T('24187.818942357666924548', 2, '14.561', 5, 3);
T('7233.846688339241', 2, '12.820547306996872048936910678432', 32, 3);
T('10162.3041', 2, '13.31093992111', 13, 4);
T('9091.859714971663525', 2, '13.1503597085807068872335', 24, 1);
T('16205.492', 2, '13.984195201', 11, 3);
T('17578.3501161869916711', 2, '14.101512046680555', 18, 3);
T('5661.58', 2, '12.466989012642603919950322048', 29, 1);
T('6674.6', 2, '12.704465665236394967162', 23, 3);
T('5063.035517', 2, '12.305786889', 11, 1);
T('10067.374870965783416', 2, '13.297399920454024702032', 23, 3);
T('22864.071031662628282003', 2, '14.480794683114196339697931635', 29, 0);
T('15588.7831039333836277142', 2, '13.9282207', 9, 0);
T('17513.7015', 2, '14.09619640742934', 16, 2);
T('6136.604218568458', 2, '12.58322482425266756363155737198', 31, 0);
T('26016.619885247', 2, '14.667145916871983257557509389', 29, 2);
T('3486.883295195387', 2, '11.76772236306965954', 20, 1);
T('29853.4019880856169328', 2, '14.9', 3, 4);
T('32174.410652492293356508', 2, '14.97362610199656', 16, 0);
T('10790.71404', 2, '13.3975027131319239178743446', 27, 4);
T('3869.9702839155983', 2, '11.918106773147484057', 20, 3);
T('14572.9804731649161632826', 2, '13.831008347831373539', 20, 1);
T('3530.1698', 2, '11.7855218629818768241', 21, 3);
T('24098.35633479612268105', 2, '14.55664712', 10, 3);
T('9625.5360719', 2, '13.23', 4, 3);
T('21545.8', 2, '14.395', 5, 3);
T('19975.55193', 2, '14.28594774531463052', 19, 3);
T('11981.45533497274', 2, '13.548515', 8, 3);
T('2944.587874', 2, '11.52386', 7, 0);
T('17730.0672623', 2, '14.11391038892776450560262608325', 31, 3);
T('27232.2', 2, '14.7330259172334297642766', 24, 0);
T('16141.46080336', 2, '13.9784835280781625406', 21, 3);
T('22862.35', 2, '14.48068608402465290616804821871', 31, 3);
T('19701.97134401560579604', 2, '14.26605237', 12, 2);
T('1582.14854859', 2, '10.62766934', 10, 1);
T('11629.28476612279', 2, '13.505474749', 11, 3);
T('12024.272', 2, '13.553', 5, 1);
T('30287.02241583997417078439', 2, '14.88641213011400845046', 22, 3);
T('10681.405529866718069', 2, '13.38281387840546429058', 22, 4);
T('17028.3', 2, '14.055647', 8, 2);
T('31450.5123172489', 2, '14.940795897815678146773997', 26, 2);
T('10267.630410391621', 2, '13.325815651', 11, 2);
T('30041.03308734805248601613', 2, '14.874646806395182486207', 24, 2);
T('9098.63993126244373708', 2, '13.1514351913945', 15, 4);
T('30885.4583445139003016', 2, '14', 2, 3);
T('1771.1692', 2, '10.79048632416067', 16, 0);
T('31464.3', 2, '14.9414282265508731233', 21, 0);
T('22935.2', 2, '14.485275867643', 14, 0);
T('8314.31328', 2, '13.02138139382', 14, 3);
T('16288.48033937', 2, '13.991564391078708126', 20, 4);
T('16341.375474', 2, '13.9962418015', 12, 3);
T('29335.7329578096819103831', 2, '14.840371417967011524840917', 26, 4);
T('22186.7391341699826076', 2, '14.437411', 8, 0);
T('4148.563221253323604', 2, '12.01839605666979644655634094031', 31, 2);
T('30958.95586132340163', 2, '14.9180691947303244998231', 24, 4);
T('27227.216131376', 2, '14.73276186', 11, 4);
T('2893.149172764447', 2, '11.498', 5, 4);
T('11428.90884008455568467895', 2, '13.4804', 8, 4);
T('6665.09', 2, '12.702408641', 12, 1);
T('23660.7112925', 2, '14.5302058244333', 16, 1);
T('15779.58', 2, '13.94577118566247809264782829', 28, 2);
T('24758.13481636580123', 2, '14.595615011042757456588', 23, 2);
T('21545.2581', 2, '14.4', 3, 0);
T('8445.30210341451', 2, '13.0439333163687263747352981', 27, 1);
T('19723.89194345160270028329', 2, '14.2676566337760362079360509651', 30, 3);
T('8131.76680164600944819', 2, '12.98936', 7, 0);
T('10409.9459240778764723', 2, '13.35', 4, 4);
T('23008.0741775', 2, '14.48985261166230230904434431', 28, 0);
T('27113.61586019', 2, '14.7268', 6, 0);
T('18807.87914187401201', 2, '14.199', 6, 1);
T('14724.76659275464725898566', 2, '13.8459', 6, 1);
T('32358.7', 2, '14.981', 5, 1);
T('8736.77', 2, '13.092884295936739139012765', 26, 0);
log('\n ' + passed + ' of ' + total + ' tests passed in ' + (+new Date() - start) + ' ms \n');
return [passed, total];
})(this.Decimal);
if (typeof module !== 'undefined' && module.exports) module.exports = count;
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.1-master-f6dedff
*/
!function(e,t,o){"use strict";function n(e){function t(e,t){this.$scope=e,this.$element=t}return{restrict:"E",controller:["$scope","$element",t],link:function(t,o){o.addClass("_md"),e(o),t.$broadcast("$mdContentLoaded",o),l(o[0])}}}function l(e){t.element(e).on("$md.pressdown",function(t){"t"===t.pointer.type&&(t.$materialScrollFixed||(t.$materialScrollFixed=!0,0===e.scrollTop?e.scrollTop=1:e.scrollHeight===e.scrollTop+e.offsetHeight&&(e.scrollTop-=1)))})}n.$inject=["$mdTheming"],t.module("material.components.content",["material.core"]).directive("mdContent",n)}(window,window.angular); |
'use strict';
var os = require('os');
var Helper = require('../../helper');
describe('bpmn-moddle - read', function() {
var moddle = Helper.createModdle();
function read(xml, root, opts, callback) {
return moddle.fromXML(xml, root, opts, callback);
}
function fromFile(file, root, opts, callback) {
var contents = Helper.readFile(file);
return read(contents, root, opts, callback);
}
describe('should import types', function() {
describe('bpmn', function() {
it('SubProcess#flowElements', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/sub-process-flow-nodes.part.bpmn', 'bpmn:SubProcess', function(err, result) {
var expected = {
$type: 'bpmn:SubProcess',
id: 'SubProcess_1',
name: 'Sub Process 1',
flowElements: [
{ $type: 'bpmn:StartEvent', id: 'StartEvent_1', name: 'Start Event 1' },
{ $type: 'bpmn:Task', id: 'Task_1', name: 'Task' },
{ $type: 'bpmn:SequenceFlow', id: 'SequenceFlow_1', name: '' }
]
};
// then
expect(result).to.jsonEqual(expected);
done(err);
});
});
it('SubProcess#flowElements (nested references)', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/sub-process.part.bpmn', 'bpmn:SubProcess', function(err, result) {
var expected = {
$type: 'bpmn:SubProcess',
id: 'SubProcess_1',
name: 'Sub Process 1',
flowElements: [
{ $type: 'bpmn:StartEvent', id: 'StartEvent_1', name: 'Start Event 1' },
{ $type: 'bpmn:Task', id: 'Task_1', name: 'Task' },
{ $type: 'bpmn:SequenceFlow', id: 'SequenceFlow_1', name: '' }
]
};
// then
expect(result).to.jsonEqual(expected);
done(err);
});
});
it('SubProcess#incoming', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/subprocess-flow-nodes-outgoing.part.bpmn', 'bpmn:Process', function(err, result) {
var expectedSequenceFlow = {
$type: 'bpmn:SequenceFlow',
id: 'SequenceFlow_1'
};
var expectedSubProcess = {
$type: 'bpmn:SubProcess',
id: 'SubProcess_1',
name: 'Sub Process 1',
flowElements: [
{ $type: 'bpmn:Task', id: 'Task_1', name: 'Task' }
]
};
var expected = {
$type: 'bpmn:Process',
flowElements: [
expectedSubProcess,
expectedSequenceFlow
]
};
// then
expect(result).to.jsonEqual(expected);
var subProcess = result.flowElements[0];
var sequenceFlow = result.flowElements[1];
// expect correctly resolved references
expect(subProcess.incoming).to.jsonEqual([ expectedSequenceFlow ]);
expect(subProcess.outgoing).to.jsonEqual([ expectedSequenceFlow ]);
expect(sequenceFlow.sourceRef).to.jsonEqual(expectedSubProcess);
expect(sequenceFlow.targetRef).to.jsonEqual(expectedSubProcess);
done(err);
});
});
it('Documentation', function(done) {
// when
fromFile('test/fixtures/bpmn/documentation.bpmn', function(err, result) {
// then
expect(result).to.jsonEqual({
$type: 'bpmn:Definitions',
id: 'documentation',
targetNamespace: 'http://bpmn.io/schema/bpmn',
rootElements: [
{
$type: 'bpmn:Process',
id: 'Process_1',
documentation: [
{ $type : 'bpmn:Documentation', text : 'THIS IS A PROCESS' }
],
flowElements: [
{
$type : 'bpmn:SubProcess',
id: 'SubProcess_1',
name : 'Sub Process 1',
documentation : [
{
$type : 'bpmn:Documentation',
text : os.EOL + ' <h1>THIS IS HTML</h1>' + os.EOL + ' '
}
]
}
]
}
]
});
done(err);
});
});
it('Escalation + Error', function(done) {
// when
fromFile('test/fixtures/bpmn/escalation-error.bpmn', function(err, result) {
// then
expect(result).to.jsonEqual({
$type: 'bpmn:Definitions',
id: 'test',
targetNamespace: 'http://bpmn.io/schema/bpmn',
rootElements: [
{ $type : 'bpmn:Escalation', id : 'escalation' },
{ $type : 'bpmn:Error', id : 'error' }
]
});
done(err);
});
});
it('ExtensionElements', function(done) {
// when
fromFile('test/fixtures/bpmn/extension-elements.bpmn', function(err, result) {
expect(result).to.jsonEqual({
$type: 'bpmn:Definitions',
id: 'test',
targetNamespace: 'http://bpmn.io/schema/bpmn',
extensionElements: {
$type : 'bpmn:ExtensionElements',
values : [
{ $type: 'vendor:info', key: 'bgcolor', value: '#ffffff' },
{ $type: 'vendor:info', key: 'role', value: '[]' }
]
}
});
done(err);
});
});
it('ScriptTask', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/scriptTask-script.part.bpmn', 'bpmn:ScriptTask', function(err, result) {
// then
expect(result).to.jsonEqual({
$type: 'bpmn:ScriptTask',
id : 'ScriptTask_4',
scriptFormat: 'Javascript',
script: 'context.set("FOO", "BAR");'
});
done(err);
});
});
it('CallActivity#calledElement', function(done) {
// when
fromFile('test/fixtures/bpmn/callActivity-calledElement.part.bpmn', 'bpmn:CallActivity', function(err, result) {
// then
expect(result).to.jsonEqual({
$type: 'bpmn:CallActivity',
id: 'CallActivity_1',
calledElement: 'otherProcess'
});
done(err);
});
});
it('ItemDefinition#structureRef', function(done) {
// when
fromFile('test/fixtures/bpmn/itemDefinition-structureRef.part.bpmn', 'bpmn:ItemDefinition', function(err, result) {
// then
expect(result).to.jsonEqual({
$type: 'bpmn:ItemDefinition',
id: 'itemDefinition',
structureRef: 'foo:Service'
});
done(err);
});
});
it('Operation#implementationRef', function(done) {
// when
fromFile('test/fixtures/bpmn/operation-implementationRef.part.bpmn', 'bpmn:Operation', function(err, result) {
// then
expect(result).to.jsonEqual({
$type: 'bpmn:Operation',
id: 'operation',
implementationRef: 'foo:operation'
});
done(err);
});
});
it('Interface#implementationRef', function(done) {
// when
fromFile('test/fixtures/bpmn/interface-implementationRef.part.bpmn', 'bpmn:Interface', function(err, result) {
// then
expect(result).to.jsonEqual({
$type: 'bpmn:Interface',
id: 'interface',
implementationRef: 'foo:interface'
});
done(err);
});
});
it('Lane#childLaneSet', function(done) {
// when
fromFile('test/fixtures/bpmn/lane-childLaneSets.part.bpmn', 'bpmn:Lane', function(err, result) {
// then
expect(result).to.jsonEqual({
$type: 'bpmn:Lane',
id: 'Lane_1',
name: 'Lane',
childLaneSet: {
$type: 'bpmn:LaneSet',
id: 'LaneSet_2',
lanes: [
{
$type: 'bpmn:Lane',
id: 'Lane_2',
name: 'Nested Lane'
}
]
}
});
done(err);
});
});
it('SequenceFlow#conditionExpression', function(done) {
// when
fromFile('test/fixtures/bpmn/sequenceFlow-conditionExpression.part.bpmn', 'bpmn:SequenceFlow', function(err, result) {
if (err) {
return done(err);
}
// then
expect(result).to.jsonEqual({
$type: 'bpmn:SequenceFlow',
id: 'SequenceFlow_1',
conditionExpression: {
$type: 'bpmn:FormalExpression',
body: '${foo > bar}'
}
});
done(err);
});
});
it('Category', function(done) {
// when
fromFile('test/fixtures/bpmn/category.bpmn', function(err, result) {
if (err) {
return done(err);
}
var category = result.rootElements[0];
// then
expect(category).to.jsonEqual({
$type: "bpmn:Category",
id: "sid-ccc7e63e-916e-4bd0-a9f0-98cbff749195",
categoryValue: [
{
$type: "bpmn:CategoryValue",
id: "sid-afd7e63e-916e-4bd0-a9f0-98cbff749193",
value: "group with label"
}
]
});
done(err);
});
});
it('MultiInstanceLoopCharacteristics#completionCondition', function(done) {
// when
fromFile('test/fixtures/bpmn/multiInstanceLoopCharacteristics-completionCondition.part.bpmn', 'bpmn:MultiInstanceLoopCharacteristics', function(err, result) {
if (err) {
return done(err);
}
// then
expect(result).to.jsonEqual({
$type: 'bpmn:MultiInstanceLoopCharacteristics',
completionCondition: {
$type: 'bpmn:FormalExpression',
body: '${foo > bar}'
}
});
done(err);
});
});
});
describe('bpmndi', function() {
it('Extensions', function(done) {
// when
fromFile('test/fixtures/bpmn/di/bpmnDiagram-extension.part.bpmn', 'bpmndi:BPMNDiagram', function(err, result) {
if (err) {
return done(err);
}
var expected = {
$type: 'bpmndi:BPMNDiagram',
id: 'BPMNDiagram_1',
plane: {
$type: 'bpmndi:BPMNPlane',
id: 'BPMNPlane_1',
extension: {
$type: 'di:Extension',
values: [
{
$type: 'vendor:baz',
baz: 'BAZ'
}
]
},
planeElement: [
{
$type: 'bpmndi:BPMNShape',
id: 'BPMNShape_1',
extension: {
$type: 'di:Extension',
values: [
{
$type: 'vendor:bar',
$body: 'BAR'
}
]
}
},
{
$type: 'bpmndi:BPMNEdge',
id: 'BPMNEdge_1',
extension: {
$type: 'di:Extension'
}
}
]
}
};
// then
expect(result).to.jsonEqual(expected);
done(err);
});
});
it('BPMNShape#bounds (non-ns-attributes)', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/di/bpmnShape.part.bpmn', 'bpmndi:BPMNShape', function(err, result) {
var expected = {
$type: 'bpmndi:BPMNShape',
id: 'BPMNShape_1',
isExpanded: true,
bounds: { $type: 'dc:Bounds', height: 300.0, width: 300.0, x: 300.0, y: 80.0 }
};
// then
expect(result).to.jsonEqual(expected);
done(err);
});
});
it('BPMNEdge#waypoint', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/di/bpmnEdge-waypoint.part.bpmn', 'bpmndi:BPMNEdge', function(err, result) {
// then
expect(result).to.jsonEqual({
$type: 'bpmndi:BPMNEdge',
id : 'sid-2365FF07-4092-4B79-976A-AD192FE4E4E9_gui',
waypoint: [
{ $type: 'dc:Point', x: 4905.0, y: 1545.0 },
{ $type: 'dc:Point', x: 4950.0, y: 1545.0 }
]
});
done(err);
});
});
it('BPMNEdge#waypoint (explicit xsi:type)', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/di/bpmnEdge.part.bpmn', 'bpmndi:BPMNEdge', function(err, result) {
var expected = {
$type: 'bpmndi:BPMNEdge',
id: 'BPMNEdge_1',
waypoint: [
{ $type: 'dc:Point', x: 388.0, y: 260.0 },
{ $type: 'dc:Point', x: 420.0, y: 260.0 }
]
};
// then
expect(result).to.jsonEqual(expected);
done(err);
});
});
it('BPMNDiagram (nested elements)', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/di/bpmnDiagram.part.bpmn', 'bpmndi:BPMNDiagram', function(err, result) {
var expected = {
$type: 'bpmndi:BPMNDiagram',
id: 'bpmndiagram',
plane: {
$type: 'bpmndi:BPMNPlane',
id: 'BPMNPlane_1',
planeElement: [
{
$type: 'bpmndi:BPMNShape',
id: 'BPMNShape_1',
isExpanded: true,
bounds: { $type: 'dc:Bounds', height: 300.0, width: 300.0, x: 300.0, y: 80.0 }
},
{
$type: 'bpmndi:BPMNEdge',
id: 'BPMNEdge_1',
waypoint: [
{ $type: 'dc:Point', x: 388.0, y: 260.0 },
{ $type: 'dc:Point', x: 420.0, y: 260.0 }
]
}
]
}
};
// then
expect(result).to.jsonEqual(expected);
done(err);
});
});
});
});
describe('should import references', function() {
it('via attributes', function(done) {
// given
var xml = '<bpmn:sequenceFlow xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/bpmnModel" sourceRef="FOO_BAR" />';
// when
read(xml, 'bpmn:SequenceFlow', function(err, result, context) {
var expectedReference = {
element: {
$type: 'bpmn:SequenceFlow'
},
property: 'bpmn:sourceRef',
id: 'FOO_BAR'
};
var references = context.references;
// then
expect(references).to.jsonEqual([ expectedReference ]);
done(err);
});
});
it('via elements', function(done) {
// given
var xml =
'<bpmn:serviceTask xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/bpmnModel">' +
'<bpmn:outgoing>OUT_1</bpmn:outgoing>' +
'<bpmn:outgoing>OUT_2</bpmn:outgoing>' +
'</bpmn:serviceTask>';
// when
read(xml, 'bpmn:ServiceTask', function(err, result, context) {
var reference1 = {
property: 'bpmn:outgoing',
id: 'OUT_1',
element: { $type: 'bpmn:ServiceTask' }
};
var reference2 = {
property: 'bpmn:outgoing',
id: 'OUT_2',
element: { $type: 'bpmn:ServiceTask' }
};
var references = context.references;
// then
expect(references).to.jsonEqual([ reference1, reference2 ]);
done(err);
});
});
});
describe('should import extensions', function() {
it('as attributes', function(done) {
// given
var xml = '<bpmn:sequenceFlow xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/bpmnModel" ' +
'xmlns:foo="http://foobar" foo:bar="BAR" />';
// when
read(xml, 'bpmn:SequenceFlow', function(err, result, context) {
// then
expect(result.$attrs['foo:bar']).to.eql("BAR");
done(err);
});
});
it('as elements', function(done) {
// when
fromFile('test/fixtures/bpmn/extension-elements.bpmn', function(err, result) {
expect(result).to.jsonEqual({
$type: 'bpmn:Definitions',
id: 'test',
targetNamespace: 'http://bpmn.io/schema/bpmn',
extensionElements: {
$type : 'bpmn:ExtensionElements',
values : [
{ $type: 'vendor:info', key: 'bgcolor', value: '#ffffff' },
{ $type: 'vendor:info', key: 'role', value: '[]' }
]
}
});
done(err);
});
});
});
describe('should read xml documents', function() {
it('empty definitions', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/empty-definitions.bpmn', function(err, result) {
var expected = {
$type: 'bpmn:Definitions',
id: 'empty-definitions',
targetNamespace: 'http://bpmn.io/schema/bpmn'
};
// then
expect(result).to.jsonEqual(expected);
done(err);
});
});
it('empty definitions (default ns)', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/empty-definitions-default-ns.bpmn', function(err, result) {
var expected = {
$type: 'bpmn:Definitions',
id: 'empty-definitions',
targetNamespace: 'http://bpmn.io/schema/bpmn'
};
// then
expect(result).to.jsonEqual(expected);
done(err);
});
});
it('simple process', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/simple.bpmn', function(err, result) {
// then
expect(result.id).to.equal('simple');
done(err);
});
});
it('simple process (default ns)', function(done) {
// given
// when
fromFile('test/fixtures/bpmn/simple-default-ns.bpmn', function(err, result) {
expect(result.id).to.equal('simple');
done(err);
});
});
});
describe('should handle errors', function() {
it('when importing non-xml text', function(done) {
// when
fromFile('test/fixtures/bpmn/error/no-xml.txt', function(err, result) {
expect(err).not.to.eql(null);
done();
});
});
it('when importing binary', function(done) {
// when
fromFile('test/fixtures/bpmn/error/binary.png', function(err, result) {
expect(err).not.to.eql(null);
done();
});
});
it('when importing invalid bpmn', function(done) {
// when
fromFile('test/fixtures/bpmn/error/undeclared-ns-child.bpmn', function(err, result, context) {
var warnings = context.warnings;
expect(err).not.to.exist;
expect(warnings.length).to.eql(1);
done();
});
});
it('when importing invalid categoryValue / reference', function(done) {
// when
fromFile('test/fixtures/bpmn/error/categoryValue.bpmn', function(err, result, context) {
var warnings = context.warnings;
// then
expect(err).not.to.exist;
// wrong <categoryValue> + unresolvable reference
expect(warnings.length).to.eql(2);
var invalidElementWarning = warnings[0];
var unresolvableReferenceWarning = warnings[1];
expect(invalidElementWarning.message).to.eql(
'unparsable content <categoryValue> detected\n\t' +
'line: 2\n\t' +
'column: 89\n\t' +
'nested error: unrecognized element <bpmn:categoryValue>');
expect(unresolvableReferenceWarning.message).to.eql(
'unresolved reference <sid-afd7e63e-916e-4bd0-a9f0-98cbff749193>');
done();
});
});
it('when importing valid bpmn / unrecognized element', function(done) {
// when
fromFile('test/fixtures/bpmn/error/unrecognized-child.bpmn', function(err, result, context) {
var warnings = context.warnings;
expect(err).not.to.exist;
expect(warnings.length).to.eql(1);
done();
});
});
});
}); |
/*
* Network Access Status v2.1.0
*Copyright 2017
*Authors: Venkatesh Chinthakindi.
*All Rights Reserved.
*use ,reproduction, distribution, and modification of this code is subject to the terms and conditions of the MIT license
*
*/
debugger;
var networkAccessStatus=(function(){
return{
check: function() {
var newEvent;
var w;
var status = null;
if (typeof (Worker) !== "undefined") {
if (typeof (w) == "undefined") {
var blob=new Blob([
`var startNetworkCheck=(function(){
var interval=3000;
return{
checkNetwork:function(){
try{
setInterval(()=>{startNetworkCheck.callback()},interval);
}
catch(error){
console.log('inner file console catch'+error)
}
},
callback:function(){
guid = (startNetworkCheck.S4() + startNetworkCheck.S4() + "-" +
startNetworkCheck.S4() + "-4" +
startNetworkCheck.S4().substr(0,3) + "-" + startNetworkCheck.S4()
+ "-" + startNetworkCheck.S4() +
startNetworkCheck.S4() + startNetworkCheck.S4()).toLowerCase();
self.postMessage("https://www.google.co.in/images/branding/product/ico/googleg_lodp.ico?ID="+guid);
},
S4:function(){
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
}
})((startNetworkCheck||{}))
startNetworkCheck.checkNetwork();`])
var blobURL = window.URL.createObjectURL(blob);
w = new Worker(blobURL);
}
var img=new Image();
w.onmessage = function(event) {
img.src=event.data;
img.onload = function() {
if(status!=true)
{
status=true;
newEvent = new CustomEvent('networkStatusChanged', { detail:true});
window.dispatchEvent(newEvent);
}
};
img.onerror = function() {
if(status!=false)
{
status=false;
newEvent = new CustomEvent('networkStatusChanged', { detail: false });
window.dispatchEvent(newEvent);
}
};
};
};
}
}
})((networkAccessStatus||{}));
module.exports=networkAccessStatus; |
function SimpleProfileMapper (pu) {
if(!(this instanceof SimpleProfileMapper)) {
return new SimpleProfileMapper(pu);
}
this._pu = pu;
}
SimpleProfileMapper.fromMetadata = function (metadata) {
function CustomProfileMapper(user) {
if(!(this instanceof CustomProfileMapper)) {
return new CustomProfileMapper(user);
}
SimpleProfileMapper.call(this, user);
}
CustomProfileMapper.prototype = Object.create(SimpleProfileMapper.prototype);
CustomProfileMapper.prototype.metadata = metadata;
return CustomProfileMapper;
}
SimpleProfileMapper.prototype.getClaims = function() {
var self = this;
var claims = {};
this.metadata.forEach(function(entry) {
claims[entry.id] = entry.multiValue ?
self._pu[entry.id].split(',') :
self._pu[entry.id];
});
return Object.keys(claims).length && claims;
};
SimpleProfileMapper.prototype.getNameIdentifier = function() {
return {
nameIdentifier: this._pu.userName,
nameIdentifierFormat: this._pu.nameIdFormat,
nameIdentifierNameQualifier: this._pu.nameIdNameQualifier,
nameIdentifierSPNameQualifier: this._pu.nameIdSPNameQualifier,
nameIdentifierSPProvidedID: this._pu.nameIdSPProvidedID
};
};
SimpleProfileMapper.prototype.metadata = [ {
id: "firstName",
optional: false,
displayName: 'First Name',
description: 'The given name of the user',
multiValue: false
}, {
id: "lastName",
optional: false,
displayName: 'Last Name',
description: 'The surname of the user',
multiValue: false
}, {
id: "displayName",
optional: true,
displayName: 'Display Name',
description: 'The display name of the user',
multiValue: false
}, {
id: "email",
optional: false,
displayName: 'E-Mail Address',
description: 'The e-mail address of the user',
multiValue: false
},{
id: "mobilePhone",
optional: true,
displayName: 'Mobile Phone',
description: 'The mobile phone of the user',
multiValue: false
}, {
id: "groups",
optional: true,
displayName: 'Groups',
description: 'Group memberships of the user',
multiValue: true
}];
module.exports = SimpleProfileMapper;
|
'use strict';
// lessons-model.js - A mongoose model
//
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const lessonsSchema = new Schema({
name: { type: String, required: true, unique: true },
createdAt: { type: Date, 'default': Date.now },
updatedAt: { type: Date, 'default': Date.now }
});
const lessonsModel = mongoose.model('lessons', lessonsSchema);
module.exports = lessonsModel;
|
function paginatedResultInterface(context) {
describe('the paginated result', function() {
var result;
beforeEach(function() {
result = context.result;
});
it('is defined', function(){
expect(result).toBeDefined();
});
it('has not previous page at the beginning', function() {
expect(result.hasPrevious).toBe(false);
});
it('allows to get parameters', function() {
var params = result.parameters();
expect(params.limit).toEqual(jasmine.any(Number));
expect(params.skip).toBe(0);
});
it('just sets descending when no keys are given', function(){
result.setDescending(true);
expect(result.parameters().startkey).toBeUndefined();
expect(result.parameters().endkey).toBeUndefined();
});
it('flips existing keys when changing descending', function(){
result.parameters({
startkey: 'start',
endkey: 'end'
});
result.setDescending(true);
expect(result.parameters()).toEqual({
startkey: 'end',
endkey: 'start',
descending: true,
limit : 20,
skip : 0
});
result.setDescending(false);
expect(result.parameters()).toEqual({
startkey: 'start',
endkey: 'end',
descending: false,
limit : 20,
skip : 0
});
});
describe('the expected property', function() {
[
'rows',
'firstIndex',
'lastIndex',
'totalRows',
'next',
'previous',
'hasNext',
'hasPrevious'
].forEach(function(property) {
it(property+' is there', function() {
expect(result[property]).toBeDefined();
});
});
});
describe('on page size change', function() {
beforeEach(function(){
result.setPageSize(20);
});
it('starts again from the beginning', function(){
expect(result.firstIndex).toBe(0);
});
});
describe('on parameters set', function() {
beforeEach(function() {
spyOn(result, 'update').andCallThrough();
result.parameters({ descending:true });
});
it('saves the new parameters', function() {
expect(result.parameters().descending).toBe(true);
});
it('triggers an update', function() {
expect(result.update).toHaveBeenCalled();
});
});
describe('on parameters set with a direct interface', function() {
beforeEach(function() {
spyOn(result, 'update').andCallThrough();
result.setParameter('descending', true);
});
it('saves the new parameters', function() {
expect(result.parameters().descending).toBe(true);
});
it('keeps the old parameters', function() {
expect(result.parameters().skip).toBe(0);
});
it('triggers an update', function() {
expect(result.update).toHaveBeenCalledWith();
});
});
});
}
|
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.Color = function ( color ) {
if ( arguments.length === 3 ) {
return this.fromArray( arguments );
}
return this.set( color );
};
THREE.Color.prototype = {
constructor: THREE.Color,
r: 1, g: 1, b: 1,
set: function ( value ) {
if ( value instanceof THREE.Color ) {
this.copy( value );
} else if ( typeof value === 'number' ) {
this.setHex( value );
} else if ( typeof value === 'string' ) {
this.setStyle( value );
}
return this;
},
setHex: function ( hex ) {
hex = Math.floor( hex );
this.r = ( hex >> 16 & 255 ) / 255;
this.g = ( hex >> 8 & 255 ) / 255;
this.b = ( hex & 255 ) / 255;
return this;
},
setRGB: function ( r, g, b ) {
this.r = r;
this.g = g;
this.b = b;
return this;
},
setHSL: function () {
function hue2rgb( p, q, t ) {
if ( t < 0 ) t += 1;
if ( t > 1 ) t -= 1;
if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
if ( t < 1 / 2 ) return q;
if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
return p;
}
return function ( h, s, l ) {
// h,s,l ranges are in 0.0 - 1.0
h = THREE.Math.euclideanModulo( h, 1 );
s = THREE.Math.clamp( s, 0, 1 );
l = THREE.Math.clamp( l, 0, 1 );
if ( s === 0 ) {
this.r = this.g = this.b = l;
} else {
var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
var q = ( 2 * l ) - p;
this.r = hue2rgb( q, p, h + 1 / 3 );
this.g = hue2rgb( q, p, h );
this.b = hue2rgb( q, p, h - 1 / 3 );
}
return this;
};
}(),
setStyle: function ( style ) {
function parseAlpha( strAlpha ) {
var alpha = parseFloat( strAlpha );
if ( alpha < 1 ) {
console.warn( 'THREE.Color: Alpha component of color ' + style + ' will be ignored.' );
}
return alpha;
}
var m;
if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
// rgb / hsl
var color;
var name = m[ 1 ];
var components = m[ 2 ];
switch ( name ) {
case 'rgb':
if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*$/.exec( components ) ) {
// rgb(255,0,0)
this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
return this;
}
if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*$/.exec( components ) ) {
// rgb(100%,0%,0%)
this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
return this;
}
break;
case 'rgba':
if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([0-9]*\.?[0-9]+)\s*$/.exec( components ) ) {
// rgba(255,0,0,0.5)
this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
parseAlpha( color[ 4 ] );
return this;
}
if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*([0-9]*\.?[0-9]+)\s*$/.exec( components ) ) {
// rgba(100%,0%,0%,0.5)
this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
parseAlpha( color[ 4 ] );
return this;
}
break;
case 'hsl':
if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*$/.exec( components ) ) {
// hsl(120,50%,50%)
var h = parseFloat( color[ 1 ] );
var s = parseInt( color[ 2 ], 10 ) / 100;
var l = parseInt( color[ 3 ], 10 ) / 100;
return this.setHSL( h, s, l );
}
break;
case 'hsla':
if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*([0-9]*\.?[0-9]+)\s*$/.exec( components ) ) {
// hsla(120,50%,50%,0.5)
var h = parseFloat( color[ 1 ] );
var s = parseInt( color[ 2 ], 10 ) / 100;
var l = parseInt( color[ 3 ], 10 ) / 100;
parseAlpha( color[ 4 ] );
return this.setHSL( h, s, l );
}
break;
}
} else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
// hex color
var hex = m[ 1 ];
var size = hex.length;
if ( size === 3 ) {
// #ff0
this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
return this;
} else if ( size === 6 ) {
// #ff0000
this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
return this;
}
}
if ( style && style.length > 0 ) {
// color keywords
var hex = THREE.ColorKeywords[ style ];
if ( hex !== undefined ) {
// red
this.setHex( hex );
} else {
// unknown color
console.warn( 'THREE.Color: Unknown color ' + style );
}
}
return this;
},
clone: function () {
return new this.constructor( this.r, this.g, this.b );
},
copy: function ( color ) {
this.r = color.r;
this.g = color.g;
this.b = color.b;
return this;
},
copyGammaToLinear: function ( color, gammaFactor ) {
if ( gammaFactor === undefined ) gammaFactor = 2.0;
this.r = Math.pow( color.r, gammaFactor );
this.g = Math.pow( color.g, gammaFactor );
this.b = Math.pow( color.b, gammaFactor );
return this;
},
copyLinearToGamma: function ( color, gammaFactor ) {
if ( gammaFactor === undefined ) gammaFactor = 2.0;
var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
this.r = Math.pow( color.r, safeInverse );
this.g = Math.pow( color.g, safeInverse );
this.b = Math.pow( color.b, safeInverse );
return this;
},
convertGammaToLinear: function () {
var r = this.r, g = this.g, b = this.b;
this.r = r * r;
this.g = g * g;
this.b = b * b;
return this;
},
convertLinearToGamma: function () {
this.r = Math.sqrt( this.r );
this.g = Math.sqrt( this.g );
this.b = Math.sqrt( this.b );
return this;
},
getHex: function () {
return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
},
getHexString: function () {
return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
},
getHSL: function ( optionalTarget ) {
// h,s,l ranges are in 0.0 - 1.0
var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
var r = this.r, g = this.g, b = this.b;
var max = Math.max( r, g, b );
var min = Math.min( r, g, b );
var hue, saturation;
var lightness = ( min + max ) / 2.0;
if ( min === max ) {
hue = 0;
saturation = 0;
} else {
var delta = max - min;
saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
switch ( max ) {
case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
case g: hue = ( b - r ) / delta + 2; break;
case b: hue = ( r - g ) / delta + 4; break;
}
hue /= 6;
}
hsl.h = hue;
hsl.s = saturation;
hsl.l = lightness;
return hsl;
},
getStyle: function () {
return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
},
offsetHSL: function ( h, s, l ) {
var hsl = this.getHSL();
hsl.h += h; hsl.s += s; hsl.l += l;
this.setHSL( hsl.h, hsl.s, hsl.l );
return this;
},
add: function ( color ) {
this.r += color.r;
this.g += color.g;
this.b += color.b;
return this;
},
addColors: function ( color1, color2 ) {
this.r = color1.r + color2.r;
this.g = color1.g + color2.g;
this.b = color1.b + color2.b;
return this;
},
addScalar: function ( s ) {
this.r += s;
this.g += s;
this.b += s;
return this;
},
multiply: function ( color ) {
this.r *= color.r;
this.g *= color.g;
this.b *= color.b;
return this;
},
multiplyScalar: function ( s ) {
this.r *= s;
this.g *= s;
this.b *= s;
return this;
},
lerp: function ( color, alpha ) {
this.r += ( color.r - this.r ) * alpha;
this.g += ( color.g - this.g ) * alpha;
this.b += ( color.b - this.b ) * alpha;
return this;
},
equals: function ( c ) {
return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
this.r = array[ offset ];
this.g = array[ offset + 1 ];
this.b = array[ offset + 2 ];
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this.r;
array[ offset + 1 ] = this.g;
array[ offset + 2 ] = this.b;
return array;
}
};
THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
|
'use strict';
require('busboy');
var dataPath1 = 'busboy/lib/types/test-y-require.js';
var data1 = require(dataPath1);
console.log(data1);
require('log4js/index.js');
var dataPath2 = 'log4js/lib/appenders/test-z-require.js';
var data2 = require(dataPath2);
console.log(data2);
|
var path = require("path");
var fs = require("fs");
function detectWithExtension(filename, extensions = [""], folders = [""]) {
if (extensions === null) {
extensions = [""];
}
if (folders === null) folders = [""];
extensions = [].concat(extensions);
return new Promise(function (ok, oh) {
filename = filename.replace(/\$/g, '/');
var prefix = 0;
var aftfix = 0;
var findedFolder;
var run = function () {
if (aftfix >= extensions.length) {
if (prefix + 1 < folders.length) {
prefix++;
aftfix = 0;
return run();
} else {
if (findedFolder) {
return ok(findedFolder);
}
return oh(`路径<gray>${filename}</gray>不存在`);
}
}
var f = path.join(folders[prefix], filename) + extensions[aftfix++];
if (fs.existsSync(f)) {
fs.stat(f, function (error, stats) {
if (error) return run();
if (stats.isFile()) {
f = path.normalize(f);
return ok(f);
}
if (!findedFolder) {
findedFolder = f;
}
run();
});
}
else run();
};
run();
});
}
module.exports = detectWithExtension; |
const {Stream} = require('stream')
/**
* This is taken from event-stream npm module.
*
* Merges the given streams into a new stream.
*
* @param {Stream[]) toMerge streams to be merged
*/
module.exports = function mergeStream (toMerge) {
const stream = new Stream()
stream.setMaxListeners(0) // allow adding more than 11 streams
let endCount = 0
stream.writable = stream.readable = true
toMerge.forEach(e => {
e.pipe(stream, {end: false})
let ended = false
e.on('end', () => {
if (ended) {
return
}
ended = true
endCount++
if (endCount === toMerge.length) {
stream.emit('end')
}
})
})
stream.write = function (data) {
this.emit('data', data)
}
return stream
}
|
import React from 'react'
/*
interface RDFISelector{
rdfi,
onRDFIChange
}
*/
export default class RDFISelector extends React.PureComponent{
render(){
const { rdfi, onRDFIChange } = this.props;
return React.createElement(
'div',
{
className: 'rdfi',
style: {
padding: "1em"
},
onClick: e => {
const t = e.currentTarget;
onRDFIChange(
t.querySelector('input[type="radio"][name="rd"]:checked').value +
t.querySelector('input[type="radio"][name="fi"]:checked').value
)
}
},
React.createElement('span', {}, 'Répartition des'),
React.createElement('div', {className: 'selector'},
React.createElement('label', {},
'dépenses',
React.createElement('input',
{name: 'rd', value: "D", type: "radio", defaultChecked: rdfi[0] === 'D'}
)
),
React.createElement('label', {},
'recettes',
React.createElement('input',
{name: 'rd', value: "R", type: "radio", defaultChecked: rdfi[0] === 'R'}
)
)
),
React.createElement('div', {className: 'selector'},
React.createElement('label', {},
'de fonctionnement',
React.createElement('input',
{name: 'fi', value: "F", type:"radio", defaultChecked: rdfi[1] === 'F'}
)
),
React.createElement('label', {},
"d'investissement",
React.createElement('input',
{name: 'fi', value: "I", type:"radio", defaultChecked: rdfi[1] === 'I'}
)
)
)
)
}
}
|
window.addEventListener( 'DOMContentLoaded', function () {
'use strict';
var i, l;
var $navs = document.querySelectorAll( '.CG2-compactNav' );
if ( $navs.length === 0 ) { return; }
for ( i = 0, l = $navs.length; i < l; i = ( i + 1 )|0 ) {
( function () {
var $nav = $navs[ i ];
var $current = $nav.querySelector( '.CG2-compactNav__item--current a' );
var $trigger = $nav.querySelector( '.CG2-compactNav__navOpener' );
var modifier = 'CG2-compactNav--show';
$current.addEventListener( 'click', toggle );
$trigger.addEventListener( 'click', toggle );
function toggle ( e ) {
if ( CG2.screenType === 'large' ) { return; }
e.preventDefault();
$nav.classList.toggle( modifier );
}
} )();
}
} );
|
var fs = require('fs');
var shaker = require('../lib/shaker.js')
module.exports = function(app,client_redis,__dirname){
app.get("/cms",function(req,res){
if(!req.session.authentificated)
res.redirect('/');
var f=[];
f[0]='';
f[1]='';
f[2]='';
f[3]='';
f[4]='';
var d=[];
d.push(f);
res.render('cms',{name: '',forms : d, buttons :d,selects:d});
});
app.get("/cms/edit_module/:module",function(req,res){
if(!req.session.authentificated)
res.redirect('/');
var f=[];
f[0]='';
f[1]='';
f[2]='';
f[3]='';
f[4]='';
var d=[];
d.push(f);
var module_name = req.params.module;
var forms=[];
var select=[];
var button=[];
var i = 0;
// get information about module
var info = {}
client_redis.hgetall('M:'+module_name+':Info',function(err,info){
if (info == null ){
info = new Array();
info['alias']=module_name;
}
client_redis.hgetall('M:'+module_name+':Forms',function(err,data){
for(var j in data){
forms.push(data[j].split(':'));
}
console.log(data);
i=i+1;
if(i==3){
console.log(forms);
console.log(button);
res.render('cms',{name: module_name,alias : info.alias,forms : forms, buttons : button,selects : select});
}
});
client_redis.hgetall('M:'+module_name+':Select',function(err,data){
for(var j in data){
select.push(data[j].split(':'));
}
select.push(f);
console.log(data);
i=i+1;
if(i==3){
console.log(forms);
console.log(button);
res.render('cms',{name: module_name,alias : info.alias,forms : forms, buttons : button,selects : select});
}
});
client_redis.hgetall('M:'+module_name+':Button',function(err,data){
for(var j in data){
button.push(data[j].split(':'));
}
button.push(f)
console.log(data);
i=i+1;
if(i==3){
console.log(forms);
console.log(button);
res.render('cms',{name: module_name,alias : info.alias,forms : forms, buttons : button,selects : select});
}
});
});
});
function CMS_create_setup_file(name_module,cmd){
var path_sc = __dirname+"/views/"+name_module+"/install.sh" ;
fs.appendFile(path_sc,cmd+'\n');
}
app.post("/cms/add_module",function(req,res){
if(!req.session.authentificated)
res.redirect('/');
var name_module = req.body.name_module;
// create folder for the module
fs.unlink(__dirname+"/views/"+name_module+"/install.sh");
var path_sc = __dirname+"/views/"+req.body.name_module ;
fs.mkdir(path_sc,function(e){
if(!e || (e && e.code === 'EEXIST')){
//do something with contents
console.log("folder created");
} else {
//debug
console.log(e);
}
});
// add form
console.log("post cms ");
var names = req.body.name_field;
var keys = req.body.key_field;
var index = req.body.index;
var show = req.body.show;
client_redis.del('M:'+name_module+':Button');
client_redis.del('M:'+name_module+':Forms');
client_redis.del('M:'+name_module+':Select');
client_redis.del('M:'+name_module+':Info');
for(i=0;i< names.length;i++){
var hash =index[i]+':'+show[i]+':'+names[i]+':'+keys[i];
CMS_create_setup_file(name_module,'redis-cli HSET M:'+name_module+':Forms '+i+' "'+hash+'"');
client_redis.hset('M:'+name_module+':Forms',i,hash,function (err){
if(err)
console.log(err);
});
}
// add selects
var select_names = req.body.select_name_field;
var select_keys = req.body.select_key_field;
var select_content = req.body.select_content_field;
var select_show = req.body.select_show;
for(i=0;i< select_names.length;i++){
var hash =select_show[i]+':'+select_names[i]+':'+select_keys[i]+':'+select_content[i];
CMS_create_setup_file(name_module,'redis-cli HSET M:'+name_module+':Select '+i+' "'+hash+'"');
client_redis.hset('M:'+name_module+':Select',i,hash,function (err){
if(err)
console.log(err);
});
}
// add button
var button_color = req.body.button_color;
var button_name = req.body.button_name;
var button_script = req.body.button_script;
var button_argv = req.body.button_argv;
for(i=0;i<button_color.length;i++){
var hash = button_color[i]+':'+button_name[i]+':'+button_script[i]+':'+button_argv[i].replace('$','');
CMS_create_setup_file(name_module,'redis-cli HSET M:'+name_module+':Button '+i+' "'+hash+'"');
client_redis.hset('M:'+name_module+':Button',i,hash,function (err){
if(err)
console.log(err);
});
}
// add information
var alias = req.body.alias;
CMS_create_setup_file(name_module,'redis-cli HSET M:'+name_module+':Info alias "'+alias+'"');
client_redis.hset('M:'+name_module+':Info','alias',alias,function (err){
if(err)
console.log(err);
});
// Shaker add module in list
client_redis.lrem("Shaker:module:list",1,name_module);
CMS_create_setup_file(name_module,'redis-cli RPUSH Shaker:module:list '+name_module);
client_redis.rpush("Shaker:module:list",name_module,function(err){
if(err)
console.log(err);
else
{
shaker.run_shaker("generate_shaker_layout_for_modules","");
//CMS_create_setup_file(name_module,'python ../../')
shaker.run_shaker("generate_module_view_and_form",name_module);
res.redirect('/cms/edit_module/'+name_module);
}
});
});
app.get("/module/:name/edit/:key",function(req,res){
var module_name = req.params.name;
var key = req.params.key;
client_redis.hgetall('DB:'+module_name+":"+key,function(err,data){
if(err){
console.log(err)
res.render(module_name+'/view');
}
else{
res.render(module_name+'/form',{data:data});
}
});
});
app.get("/module/:name/prompt/:pt",function(req,res){
var module = req.params.name;
var prom = req.params.pt;
res.render(module+'/prompt-'+prom);
});
app.get("/module/:name/:method",function(req,res){
if(!req.session.authentificated)
res.redirect('/');
if(req.params.method == "form")
res.render(req.params.name+"/form",{data:{}})
else
{
client_redis.LRANGE('DB:'+req.params.name+':list',0,-1,function(err,data_l){
console.log(data_l);
var list_machine=[];
if(data_l.length==0)
res.render(req.params.name+'/view',{'data':list_machine});
else
data_l.sort().forEach(function(item){
client_redis.hgetall(item,function(err,data)
{
data['key']=item;
list_machine.push(data);
console.log(data);
//console.log("list "+list_machine.length+" vs data "+length(data));
if(list_machine.length == data_l.length)
res.render(req.params.name+'/view',{'data':list_machine});
});
});
});
}
});
app.post("/module/:mod/post",function(req,res){
if(!req.session.authentificated)
res.redirect('/');
var module_name = req.params.mod;
var forms=[];
var select =[];
var index;
var i = 0;
client_redis.hgetall('M:'+module_name+':Forms',function(err,data){
for(var j in data){
var tmp = data[j].split(':');
if(tmp[0]=='yes')
index = j;
forms.push(tmp);
}
for(var j in forms){
client_redis.HSET('DB:'+module_name+':'+req.body[forms[index][3]],forms[j][3],req.body[forms[j][3]],function(err){
if(err)
console.log(err);
});
}
// store data from SelectBoxes
client_redis.HGETALL('M:'+module_name+':Select',function(err,data){
for(var j in data){
var tmp = data[j].split(':');
select.push(tmp);
}
for(var j in select){
client_redis.HSET('DB:'+module_name+':'+req.body[forms[index][3]],select[j][2],req.body[select[j][2]],function(err){
if(err)
console.log(err);
});
}
});
client_redis.lrem('DB:'+module_name+':list',1,'DB:'+module_name+':'+req.body[forms[index][3]]);
client_redis.rpush('DB:'+module_name+':list','DB:'+module_name+':'+req.body[forms[index][3]],function(err){
if(err)
console.log('erreur'+err);
res.redirect('/module/'+module_name+'/view');});
});
});
app.post("/module/:mod/del",function(req,res){
if(!req.session.authentificated)
res.redirect('/');
var name = req.params.mod;
var key = req.body.key;
client_redis.lrem('DB:'+name+':list',1,'DB:'+name+':'+key);
client_redis.del('DB:'+name+':'+key);
res.send("ok");
});
}
|
let utils = require('../core/utils.js');
let _ = require('underscore');
/*
* beware of distance (period) versus
* values (date), see {date,nbr}Mgr.js
*/
let computeTicks = function(first,last,minor,fac){
let mgr = utils.mgr(first);
let start = mgr.closestRoundUp(first,mgr.divide(mgr.distance(first,last),10));
let length = mgr.distance(start,last);
// distance min criteria 1
// 10 ticks max
let dec = mgr.divide(length,10);
let majDist = mgr.roundUp(dec);
let minDist = mgr.roundDown(majDist);
// redefine start to have the biggest rounded value
let biggestRounded = mgr.orderMagValue(last,first);
start = utils.isNil(biggestRounded) ? start : biggestRounded;
while(mgr.greaterThan(start,first) || mgr.equal(start,first)){
start = mgr.subtract(start,majDist);
}
start = mgr.add(start,majDist);
length = mgr.distance(start,last);
let llength = mgr.multiply(majDist,mgr.labelF);
let out = [];
let curValue = start;
// if a date, might want a first label with no tick
if(mgr.type === 'date'){
let pos = mgr.subtract(curValue,majDist);
if(mgr.greaterThan(mgr.distance(first,curValue),llength)){
out.push({
position: pos,
offset: {
along: mgr.offset(majDist),
perp: 0
},
label: mgr.label(pos,majDist,fac),
show: false,
showLabel: true
});
}
}
while(mgr.lowerThan(curValue,last)){
let lte = mgr.distance(curValue,last);
out.push({
position: curValue,
offset: {
along: mgr.offset(majDist),
perp: 0
},
extra: false,
label: mgr.type !== 'date' || mgr.greaterThan(lte, llength) ? mgr.label(curValue,majDist,fac) : '',
minor: false
});
// minor ticks
if(minor){
let curminValue = mgr.add(curValue,minDist);
let ceil = mgr.add(curValue,majDist);
while(mgr.lowerThan(curminValue,ceil)){
if(mgr.greaterThan(curminValue,last)){
break;
}
out.push({
position: curminValue,
offset: {
along: mgr.offset(minDist),
perp: 0
},
extra: false,
label: mgr.label(curminValue,minDist,fac),
minor: true
});
curminValue = mgr.add(curminValue,minDist);
}
}
curValue = mgr.add(curValue,majDist);
}
out = out.concat(mgr.extraTicks(majDist,first,last, out));
return out;
};
let m = {};
m.ticks = function(start,length,labels,minor,fac){
if(!!labels && labels.length > 0){
return _.map(labels, (lab) => {
return {
position: lab.coord,
label: lab.label,
offset: {
along: 0,
perp: 0
}
};
});
}
return computeTicks(start,length,minor,fac);
};
module.exports = m;
|
module.exports = require('./src/initializer');
|
import crypto from 'crypto';
export default function(method, username, password) {
const hash = crypto.createHmac(method, username);
hash.update(password);
return hash.digest('hex');
}
|
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var pug = require('pug');
var app = express();
var compiler = webpack(config);
app.locals.env = app.settings.env;
app.use(express.static('dist'));
app.use(require('webpack-hot-middleware')(compiler));
app.set('view engine', 'pug');
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.get('/', function (req, res) {
res.render('index', {
env: process.env.NODE_ENV || 'webpack-dev'
});
});
app.listen(3000, 'localhost', function(err) {
if (err) {
console.log(err);
return false;
}
console.log('Listening at http://localhost:3000');
}); |
'use strict';
var mongoose = require('mongoose');
var futures = require('../futures');
var _ = require('lodash');
var validateLoyalty = function(obj) {
if(!_.isObject(obj)) {
return false;
}
var allValid = true;
_.each(obj, function(val, key) {
if(!_.isNumber(val) || val <= 0 || val > 5) {
allValid = false;
}
if(!_.isString(key) || key.length === 0 || key.length > 99) {
allValid = false;
}
});
return allValid;
};
var ProgressSchema = new mongoose.Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
index: true
},
elo: {
type: Number,
min: 0,
max: 9999,
default: 150
},
fame: {
type: Number,
min: 0,
default: 0
},
fractures: {
type: Number,
min: 0,
default: 0
},
futures: {
type: Array,
default: ['norm']
},
updated: {
type: Date,
default: Date.now
},
favDecks: {
type: [String],
validate: function(arr, next) {
return next(arr.length < 100);
},
default: []
},
favCards: {
type: [String],
validate: function(arr, next) {
return next(arr.length < 100);
},
default: []
},
loyalty: {
type: Object,
validate: validateLoyalty,
default: {}
}
});
var isValidFuture = function(futureId) {
var arr = _.toArray(futures);
var isValid = arr.indexOf(futureId) !== -1;
return isValid;
};
ProgressSchema.pre('save', function (next) {
if(!_.isArray(this.futures)) {
this.futures = [];
}
this.futures = _.filter(this.futures, isValidFuture);
this.futures = _.unique(this.futures);
next();
});
var Progress = mongoose.model('Progress', ProgressSchema);
module.exports = Progress; |
var mime = require('mime'),
uuid = require('node-uuid'),
aws = require('aws-sdk'),
express = require('express');
function checkTrailingSlash(path) {
if (path && path[path.length-1] != '/') {
path += '/';
}
return path;
}
function S3Router(options) {
var S3_BUCKET = options.bucket,
getFileKeyDir = options.getFileKeyDir || function() { return ""; };
if (options.region) {
var REGION = options.region;
aws.config.update({region: REGION});
}
if (!S3_BUCKET) {
throw new Error("S3_BUCKET is required.");
}
var router = express.Router();
/**
* Redirects image requests with a temporary signed URL, giving access
* to GET an image.
*/
router.get(/\/img\/(.*)/, function(req, res) {
var params = {
Bucket: S3_BUCKET,
Key: checkTrailingSlash(getFileKeyDir(req)) + req.params[0]
};
var s3 = new aws.S3();
s3.getSignedUrl('getObject', params, function(err, url) {
res.redirect(url);
});
});
/**
* Returns an object with `signedUrl` and `publicUrl` properties that
* give temporary access to PUT an object in an S3 bucket.
*/
router.get('/sign', function(req, res) {
var filename = uuid.v4() + "_" + req.query.objectName;
var mimeType = mime.lookup(filename);
var fileKey = checkTrailingSlash(getFileKeyDir(req)) + filename;
var s3 = new aws.S3();
var params = {
Bucket: S3_BUCKET,
Key: fileKey,
Expires: 60,
ContentType: mimeType,
ACL: options.ACL || 'private'
};
s3.getSignedUrl('putObject', params, function(err, data) {
if (err) {
console.log(err);
return res.send(500, "Cannot create S3 signed URL");
}
res.json({
signedUrl: data,
publicUrl: '/s3/img/' + filename,
filename: filename
});
});
});
return router;
}
module.exports = S3Router;
|
/**
*
* Fetch a listing of user accounts.
*
* @author Salvatore Garbesi <sal@dolox.com>
* @module router/adminUserAnswerGet
*
* @return {undefined} Nothing is returned from this Function.
*
*/
module.exports = function(app) {
'use strict';
app.service.express.get('/admin/user/answer/', function(request, response) {
// If the client isn't logged in, then reject the request.
if (app.controller.loginRequired(request, response, true) === false) {
return;
}
// Define the options for the query.
var options = app.controller.pagination.router({
// Derive the question and answer values.
include: [{
key: 'questionAnswerId',
model: app.model.questionAnswer,
required: true,
include: [{
key: 'questionId',
model: app.model.question,
required: true
}]
}],
// The current page.
page: _.get(request, 'query.page'),
// The ordering of the query.
order: '`userQuestionAnswer`.`createdAt` DESC'
});
// Fetch the user accounts.
async.auto({
// Fetch the user answers.
userQuestionAnswer: function(callback) {
app.model.userQuestionAnswer.findAndCount(options).then(callback.bind(null, null), callback);
}
}, function(error, results) {
// If there's an error, then handle it.
if (error) {
console.error('router', 'adminUserAnswerGet', error);
}
// Render the template and ship it to the client.
response.render('admin/user/answer', {
// Display the error to the client if it exists.
error: error,
// The dataset from the datastore.
data: _.get(results, 'userQuestionAnswer'),
// The page heading.
h1: 'User Answers',
// The secondary page heading.
h2: _.get(results, 'userQuestionAnswer.count') + ' Results',
// The current page.
page: options.page,
// The pagination pages to display.
pagination: app.controller.pagination.handlebars(options.page, options.limit, _.get(results, 'userQuestionAnswer.count')),
// The page title.
title: app.service.package.title,
// The URL for the page.
url: './admin/user/answer/'
});
});
});
};
|
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "../src/index"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("../src/index");
var assert = (() => {
var Reset = "\x1b[0m";
var BgRed = "\x1b[41m";
var BgGreen = "\x1b[42m";
var FgRed = "\x1b[31m";
var FgGreen = "\x1b[32m";
var koLength = 0;
var okLength = 0;
return {
start: () => {
koLength = 0;
okLength = 0;
console.log("start");
},
equals: (a, b) => {
if (a !== b) {
console.log(FgRed, "ko " + a + " !== " + b + Reset);
koLength++;
}
else {
console.log(FgGreen, "ok " + a + " === " + b + Reset);
okLength++;
}
},
finish: () => {
console.log(koLength > 0 ? FgRed : FgGreen, "ko: " + koLength + ", ok: " + okLength + Reset);
console.log("finish");
},
};
})();
var log, log2, test;
var obj = index_1.observable();
var parent = index_1.observable({ test: test = index_1.observable() });
index_1.observer(() => {
log = obj();
});
index_1.observer(() => {
log2 = parent().test();
});
var x = {};
assert.start();
obj(0);
assert.equals(log, 0);
obj(1);
assert.equals(log, 1);
obj('a');
assert.equals(log, 'a');
obj(x);
assert.equals(log, x);
assert.finish();
assert.start();
parent().test(0);
assert.equals(log2, 0);
test(1);
assert.equals(log2, 1);
parent({ test: index_1.observable(3) });
test(2);
assert.equals(log2, 3);
test(4);
assert.equals(log2, 3);
parent({ test: test });
test(5);
assert.equals(log2, 5);
assert.finish();
var log3, log4;
var obj3 = index_1.observable();
assert.start();
index_1.observer(() => {
index_1.blind(() => {
log3 = obj3();
index_1.observer(() => {
log4 = obj3();
});
});
});
obj3(0);
assert.equals(log3, undefined);
assert.equals(log4, 0);
obj3(1);
assert.equals(log3, undefined);
assert.equals(log4, 1);
assert.finish();
});
//# sourceMappingURL=index.js.map |
(function () {
"use strict";
function bidderDescriptionStore(dispatcher, BIDDER_DESCRIPTION_ACTIONS) {
var self = this;
dispatcher.addListener({
actionType: BIDDER_DESCRIPTION_ACTIONS.ADD_OR_UPDATE,
callback: function (options) {
self.storeInstance.addOrUpdate({ data: options.data });
self.storeInstance.emitChange({ id: options.id });
}
});
dispatcher.addListener({
actionType: BIDDER_DESCRIPTION_ACTIONS.ALL,
callback: function (options) {
self.storeInstance.items = options.data;
self.storeInstance.emitChange({ id: options.id });
}
});
return self;
}
ngX.Store({ store: bidderDescriptionStore, providers: ["dispatcher", "BIDDER_DESCRIPTION_ACTIONS"] });
})(); |
// <img src="http://www.kegg.jp/kegg/pathway/pti/pti00630.png"/>
// http://rest.kegg.jp/get/pti00630/kgml
//http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format
if (!String.format) {
String.format = function(format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
//<area shape=rect coords=1126,440,1172,457 href="/dbget-bin/www_bget?pti:PHATRDRAFT_51088" title="PHATRDRAFT_51088" />
//
// <entry id="82" name="pti:PHATRDRAFT_51088" type="gene" reaction="rn:R00479"
// link="http://www.kegg.jp/dbget-bin/www_bget?pti:PHATRDRAFT_51088">
// <graphics name="PHATRDRAFT_51088" fgcolor="#000000" bgcolor="#BFFFBF"
// type="rectangle" x="1149" y="449" width="46" height="17"/>
// </entry>
// for rectangles, the position is defined by x = x="359" - (width="46" /2) y = y="510" - ( height="17" / 2 )
function add_if_dos_not_exists(obj, key, val) {
if (!(key in obj)) { obj[key] = [ val ]; } else { if (obj[key].indexOf(val) == -1) { obj[key].push( val ) } }
}
var kgml_to_svg = function kgml_to_svg(kgml, c_id, clbk) {
this.kgml = kgml;
this.c_id = c_id;
this.tagNames = {"rect": 1, "circle": 1};
var fill_opacity = '0.0';
var img_src_s = kgml.indexOf('image=');
var img_src_e = kgml.indexOf('"', img_src_s+7);
var img_src = kgml.substring(img_src_s+7, img_src_e);
var ld = this;
var img = new Image();
img.src = img_src;
img.onload = function(){
ld.width = img.width;
ld.height = img.height;
console.log("loaded img", ld.width, ld.height);
ld.svg = kgml;
console.log('width', ld.width, 'height', ld.height);
ld.svg = ld.svg
.replace(/\s*<\?xml[\s|\S]+?\n/g ,'' ) //delete xml
.replace(/<!DOCTYPE[\s|\S]+?>\n/g ,'' ) //delete doctype
.replace(/"\n +/g ,'" ') //delete multilines
.replace(/ +/g ,' ' ) //delete multiple spaces
.replace(/\s*<relation[\s|\S]+?<\/relation>\n/g ,'' ) //delete relation tag
.replace(/\s*<reaction[\s|\S]+?<\/reaction>\n/g ,'' ) //delete reaction tag
.replace(/\s*<substrate[\s|\S]+?\/>\n/g ,'' ) //delete substrate tag
.replace(/\s*<product[\s|\S]+?\/>\n/g ,'' ) //delete product tag
.replace(/\s*<subtype[\s|\S]+?\/>\n/g ,'' ) //delete subtype tag
.replace(/<\/pathway[\s|\S]+?>\n?/ ,'' ) //delete closure of pathwat tag
.replace(/<entry([\S|\s]+?)link="(\S+?)"/g ,'\t<a$1xlink:href="$2"') //convert entry tag into a tag and link attribute into xlink:href attribute
.replace(/<\/entry>/g ,'\t</a>' ) //convert closure of entry tag into closure of a tag
//convert pathway into image
.replace(/<pathway([\S|\s]+?)image="(\S+)"([\S|\s]+?)>/gm,'\t<image x="0" y="0" render-order="1" filter="url(#matrix-black)" width="'+ld.width+'px" height="'+ld.height+'px" $1xlink:href="$2"$3></image>')
//convert graphics into rect|circle depending on its type attribute
//converts coordinate system from center to top-left
//converts coordinate from diameter to radius
//converts roundrectangle to rectangle with radius 10
.replace(/<graphics([\S|\s]+?)bgcolor="(\S+?)"([\S|\s]+?)type="(\S+)" x="(\d+)" y="(\d+)" width="(\d+)" height="(\d+)"([\S|\s]+?)>/gm ,
function( $all, $begin, $fill, $between, $type, $x, $y, $w, $h, $end) {
//console.log($all, $begin, $fill, $between, $type, $x, $y, $w, $h, $end);
//$fill = '#333';
if ($type == 'rectangle') {
return String.format('\t\t<rect {0} fill="{1}" {2} x="{3}" y="{4}" width="{5}" height="{6}" fill-opacity="'+fill_opacity+'"{7}>', $begin, $fill, $between, ($x-($w/2)), ($y-($h/2)), $w, $h, $end);
} else
if ($type == 'roundrectangle'){
return String.format('\t\t<rect {0} fill="{1}" {2} x="{3}" y="{4}" width="{5}" height="{6}" rx="10" fill-opacity="'+fill_opacity+'"{7}>', $begin, $fill, $between, ($x-($w/2)), ($y-($h/2)), $w, $h, $end);
} else
if ($type == 'circle'){
return String.format('\t\t<circle {0} fill="{1}" {2} cx="{3}" cy="{4}" r="{5}" fill-opacity="'+fill_opacity+'"{7}>', $begin, $fill, $between, $x, $y, ($w/2), $h, $end);
}
}
)
//duplicate image for background and inverted image foregound
//create groups for links (top), labels(middle), areas (colors, bottom) and image (background)
.replace(/(<image[\S|\s]+?)(><\/image>)/gm ,
function($all, $beg, $end) {
return String.format(
'\n'+
'<g id="image">\n{0}{1}</g>\n'+
'<g id="areas"></g>\n'+
'<g id="labels" filter="url(#matrix-invert)">'+
'{0}filter="url(#matrix-black)" mask="url(#name_inverter)"{1}'+
'</g>\n'+
'<g id="links"></g>\n'+
'<g id="alls">'+
'\n'
, $beg, $end);
}
);
//add filters to convert green into white and the background into transparency
//http://docs.webplatform.org/wiki/svg/elements/feColorMatrix
var filters = '\t<defs id="svg_defs">\n'+
'\t\t<filter id="matrix-black">\n' +
'\t\t\t<feColorMatrix in="SourceGraphic" type="matrix" values="1 1 0 0 0\n' +
'\t\t\t 0 1 0 0 0\n' +
'\t\t\t 0 1 1 0 0\n' +
'\t\t\t 0 0 0 0 1"/>\n' +
'\t\t\t<feColorMatrix in="SourceGraphic" type="matrix" values="0 0 0 0 0\n' +
'\t\t\t 0 0 0 0 0\n' +
'\t\t\t 0 0 0 0 0\n' +
'\t\t\t -1 -1 -1 1 0"/>\n' +
'\t\t</filter>\n' +
'\t\t<filter id="saturate">\n' +
'\t\t\t<feColorMatrix in="SourceGraphic" type="saturate" values=".5" result="A"/>\n' +
'\t\t</filter>\n' +
'\t\t<filter id="hueRotate">\n' +
'\t\t\t<feColorMatrix in="SourceGraphic" type="hueRotate" values="45" result="A"/>\n' +
'\t\t</filter>\n' +
'\t\t<filter id="L2A">\n' +
'\t\t\t<feColorMatrix in="SourceGraphic" type="luminanceToAlpha" result="A"/>\n' +
'\t\t</filter>\n' +
'\t\t<filter id="grayscale">\n' +
'\t\t\t<feColorMatrix type="saturate" values="0"/>\n' +
'\t\t</filter>\n' +
'\t\t<filter id="matrix-greyscale">\n' +
'\t\t\t<feColorMatrix in="SourceGraphic" type="matrix" values=".33 .33 .33 0 0 \n' +
'\t\t .33 .33 .33 0 0 \n' +
'\t\t .33 .33 .33 0 0\n' +
'\t\t 0 0 0 1 0"/>\n' +
'\t\t</filter>\n' +
'\t\t<filter id="matrix-invert">\n' +
'\t\t\t<feColorMatrix in="SourceGraphic" type="matrix" values="-1 0 0 0 1 \n' +
'\t\t 0 -1 0 0 1 \n' +
'\t\t 0 0 -1 0 1\n' +
'\t\t 0 0 0 1 0"/>\n' +
'\t\t</filter>\n'+
'\t\t<mask id="name_inverter">\n' +
'\t\t\t<rect fgcolor="#fff" fill="#fff" x="937.5" y="215" width="73" height="34" rx="10" fill-opacity="0.5"></rect>\n' +
'\t\t</mask>\n'+
'\t</defs>\n'
;
//filter="url(#matrix-invert)"
//add SVG header and filters
//close the group tag
ld.svg = '<svg id="kegg_svg" viewbox="0 0 '+ld.width+' '+ld.height+'" width="'+ld.width+'px" height="'+ld.height+'px" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n' +
filters +
ld.svg +
"</g>\n</svg>"
//console.log(ld.svg);
//add to container
document.getElementById(ld.c_id).innerHTML = ld.svg;
ld.svgEl = document.getElementById('kegg_svg'); //svg
ld.linksEl = document.getElementById('links'); //links
ld.labelsEl = document.getElementById('labels'); //labels
ld.areasEl = document.getElementById('areas'); //areas (color)
ld.imageEl = document.getElementById('image'); //image (background)
ld.allsEl = document.getElementById('alls'); //leftover group tag
ld.masker(); //reorder objects
ld.indexer(); //index areas (colors)
try {
clbk(); //call callback
}
catch(e){
}
}
}
kgml_to_svg.prototype.masker = function() {
console.log('masker');
//get inverter mask object
this.mask = document.getElementById('name_inverter');
//get all links
var as = this.allsEl.getElementsByTagName('a');
//move links to group links and areas to group areas
//console.log(' as', as.length, as);
for ( var a = as.length-1; a >=0 ; a-- ) {
var al = as[a];
var alid = al.getAttribute('id');
//change id so that the id can be set in the area
al.setAttribute('id', alid+'_label');
//get respective area
//console.log(' al', a, al);
var children = al.childNodes;
//console.log(' child', children.length, children);
//transfer area to group areas
for ( var c = children.length-1; c >=0 ; c-- ) {
var cel = children[c];
//console.log(' cel', c, cel);
if (cel.tagName in this.tagNames ) {
//set area id
cel.setAttribute('id', alid);
//clone area and add to link so that link is clickable
var cl = cel.cloneNode(true);
cl.removeAttribute("id");
//append clone of area into link
al.appendChild(cl);
}
//move area to group areas
this.areasEl.appendChild(cel);
}
//move link+areaClone to links group
this.linksEl.appendChild(al);
}
}
kgml_to_svg.prototype.indexer = function() {
//index all ids for easy color change
console.log('indexing');
var names = {}; //all ids and their names
//extract ids and names from fields
this.svg.replace(/id="([\S|\s]+?)"[\S|\s]+?name="([\S|\s]+?)"/g,
function($all, $id, $name){
//console.log("id", $id, "name", $name);
//add full name to names under the id
add_if_dos_not_exists(names, $name, $id);
//split if there are spaces
var parts = $name.split(/\s/);
//console.log(" parts", parts);
for ( var p in parts ) {
var part = parts[p];
//console.log(" part", part);
//add name part to names under the id
add_if_dos_not_exists(names, part, $id);
//split if there are colons
var segs = part.split(":");
//console.log(" segs", segs);
if (segs.length == 1) {
var seg = segs[0];
//console.log(" seg1", seg);
//add name without colon under the id
add_if_dos_not_exists(names, seg, $id);
} else
if (segs.length == 2) {
var sty = segs[0];
var seg = segs[1];
//console.log(" seg2", "type:", sty, "val:", seg);
//add name without colon under the id
add_if_dos_not_exists(names, seg, $id);
}
}
}
);
console.log("names", names);
this.index = names;
}
kgml_to_svg.prototype.highlight = function(code, color, fill_opacity) {
console.log('highlight','code:',code, 'color:',color, 'fill_opacity:"', fill_opacity);
//if code in index, proceed
if (code in this.index) {
console.log(' EXISTS');
var els = this.index[code];//ids containing the code
console.log(' els',els);
//for each element
for ( var e in els ) {
var el = els[e];
var nel = document.getElementById(el);
var tagName = nel.tagName;
console.log(' el', el, nel, tagName);
//verify if tag name is correct and change color and opacity
if (tagName in this.tagNames) {
nel.setAttribute('fill' , color );
nel.setAttribute('fill-opacity', fill_opacity);
} else {
console.warn('TAG', tagName, 'NOT ALLOWED', this.tagNames);
}
}
} else {
console.log('highlight',code,"DOES NO EXISTS");
}
}
//http://gamedev.stackexchange.com/questions/19257/how-do-i-make-magenta-in-my-png-transparent-in-html5-canvas-js
// color to make transparent. Magenta here...
function make_transparency(r,g,b,file,src,dst) {
var transparentColor = {
r : r,
g : g,
b : b
};
var img = new Image();
img.src = file;
img.onload = function(){
// create a source canvas. This is our pixel source
var srcCanvas = document.createElement("canvas");
srcCanvas.width = img.width;
srcCanvas.height = img.height;
// create a destination canvas. Here the altered image will be placed
var dstCanvas = document.createElement("canvas");
dstCanvas.width = img.width;
dstCanvas.height = img.height;
// append the canvas elements to the container
document.getElementById(src).appendChild(srcCanvas);
document.getElementById(dst).appendChild(dstCanvas);
// get context to work with
var srcContext = srcCanvas.getContext("2d");
var dstContext = dstCanvas.getContext("2d");
// draw the loaded image on the source canvas
srcContext.drawImage(img, 0, 0);
// read pixels from source
var pixels = srcContext.getImageData(0, 0, img.width, img.height);
// iterate through pixel data (1 pixels consists of 4 ints in the array)
for(var i = 0, len = pixels.data.length; i < len; i += 4){
var r = pixels.data[i];
var g = pixels.data[i+1];
var b = pixels.data[i+2];
// if the pixel matches our transparent color, set alpha to 0
if(r == transparentColor.r && g == transparentColor.g && b == transparentColor.b){
pixels.data[i+3] = 0;
}
}
// write pixel data to destination context
dstContext.putImageData(pixels,0,0);
}
}
|
describe('Ionic Checkbox', function() {
var el, scope, compile;
beforeEach(module('ionic'));
beforeEach(inject(function($compile, $rootScope) {
compile = $compile;
scope = $rootScope;
}));
it('should set the checkbox name', function() {
el = compile('<ion-checkbox name="myname"></ion-checkbox>')(scope);
var input = el.find('input');
expect(input.attr('name')).toEqual('myname');
});
it('should setup checkbox markup', function() {
el = compile('<ion-checkbox>INNER TEXT</ion-checkbox>')(scope);
expect(el.hasClass('item')).toEqual(true);
expect(el.hasClass('item-checkbox')).toEqual(true);
var label = el.find('div');
expect(label.hasClass('checkbox')).toEqual(true);
var input = el.find('input');
expect(input.attr('type')).toEqual('checkbox');
var div = el.find('div');
expect(div.hasClass('item-content')).toEqual(true);
expect(div.text()).toEqual('INNER TEXT');
});
it('should pass down attrs', function() {
el = compile('<ion-checkbox name="name" ng-model="model" ng-checked="checked" ng-disabled="disabled" ng-true-value="true" ng-false-value="false" ng-change="change">')(scope);
scope.$apply();
var input = el.find('input');
expect(input.attr('name')).toBe('name');
expect(input.attr('ng-model')).toBe('model');
expect(input.attr('ng-checked')).toBe('checked');
expect(input.attr('ng-disabled')).toBe('disabled');
expect(input.attr('ng-true-value')).toBe('true');
expect(input.attr('ng-false-value')).toBe('false');
expect(input.attr('ng-change')).toBe('change');
});
it('should ngChecked properly', function() {
el = compile('<ion-checkbox ng-checked="shouldCheck">')(scope);
scope.$apply();
var input = el.find('input');
expect(input[0].hasAttribute('checked')).toBe(false);
scope.$apply('shouldCheck = true');
expect(input[0].hasAttribute('checked')).toBe(true);
scope.$apply('shouldCheck = false');
expect(input[0].hasAttribute('checked')).toBe(false);
});
it('should ngChange properly', function() {
el = compile('<ion-checkbox ng-change="change(val)" ng-model="val">')(scope);
scope.change = jasmine.createSpy('change');
scope.$apply();
var input = el.find('input');
var ngModel = input.controller('ngModel');
expect(scope.change).not.toHaveBeenCalled();
ngModel.$setViewValue(true);
scope.$apply();
expect(scope.change).toHaveBeenCalledWith(true);
scope.change.reset();
ngModel.$setViewValue(false);
scope.$apply();
expect(scope.change).toHaveBeenCalledWith(false);
});
});
|
'use strict';
angular.module('gisto.directive.editor', []).directive('editor', ['$timeout', 'appSettings', function ($timeout, appSettings) {
return {
restrict: 'E',
template: '<div ng-if="showmd" class="special-editor-markdown" ng-bind-html="file.content | markDown"></div>' +
'<pre id="editor-{{$index}}" class="editor">{{file.content}}</pre>',
link: function ($scope, $element, $attrs) {
$scope.showmd = false;
if ($attrs.language === 'markdown') {
$scope.showmd = true;
}
appSettings.loadSettings().then(function (appSettingsResult) {
$timeout(function () {
var lang = $attrs.language,
font = parseInt(appSettingsResult.font_size),
indexed = $attrs.index,
editor = ace.edit($element.find('.editor')[0]),
session = editor.getSession(),
theme = $attrs.theme,
inUpdateProcess = false;
$scope.$on('tidy', function (event, args) {
if (!$scope.edit) {
$scope.enableEdit();
}
$scope.tidyFileType = args.type;
$scope.tidyFIleName = args.name;
if ($scope.tidyFileType === 'text/css' && $scope.tidyFIleName === $scope.file.filename) {
editor.setValue(css_beautify($scope.file.content));
}
if (($scope.tidyFileType === 'text/html' || $scope.tidyFileType === 'application/xml') && $scope.tidyFIleName === $scope.file.filename) {
editor.setValue(html_beautify($scope.file.content));
}
if ($scope.tidyFileType === 'application/javascript' && $scope.tidyFIleName === $scope.file.filename) {
editor.setValue(js_beautify($scope.file.content));
}
if ($scope.tidyFileType === 'application/json' && $scope.tidyFIleName === $scope.file.filename) {
editor.setValue(JSON.stringify(JSON.parse($scope.file.content), null, '\t'));
}
$scope.file.content = editor.getValue();
});
// Observe changes to syntax attribute on <editor> element (on create gist partial only)
$attrs.$observe('syntax', function (newSyntax) {
// Refresh the ace session with new syntax mode
editor.getSession().setMode("ace/mode/" + newSyntax);
console.log('new syntax', newSyntax);
});
// Emmet
if (lang === 'html' && appSettingsResult.editor_ext.emmet) {
console.log('Emmet should be loaded');
ace.require("ace/ext/emmet");
editor.setOptions({
enableEmmet: true
});
} else {
editor.setOptions({
enableEmmet: false
});
}
// Auto-completion
if (appSettingsResult.editor_ext.emmet) {
console.log('language tools should be loaded');
ace.require("ace/ext/language_tools");
editor.setOptions({
enableBasicAutocompletion: true,
enableSnippets: true
});
}
// Status bar
if (appSettingsResult.editor_ext.statusbar) {
var statusBarElement = angular.element('<div><i class="icon-info-sign"></i> </div>');
$element.append(statusBarElement);
var StatusBar = ace.require('ace/ext/statusbar').StatusBar;
new StatusBar(editor, statusBarElement[0]);
}
// VIM mode
if (appSettingsResult.editor_vim_mode) {
editor.setKeyboardHandler("ace/keyboard/vim");
}
// word wrap
if (appSettingsResult.editor_word_wrap) {
editor.getSession().setUseWrapMode(true);
}
editor.setTheme("ace/theme/" + theme);
editor.getSession().setMode("ace/mode/" + lang);
editor.getSession().setTabSize(parseInt(appSettingsResult.editor_tab_size));
editor.setFontSize(font);
editor.setShowPrintMargin(false);
editor.renderer.setShowGutter(true);
editor.setAutoScrollEditorIntoView(true);
var maxLinesSettings = appSettingsResult.max_lines.toString();
var minLinesSettings = (appSettingsResult.min_lines !== 0) ? appSettingsResult.min_lines.toString() : editor.session.getLength().toString();
editor.setOption("maxLines", maxLinesSettings);
editor.setOption("minLines", minLinesSettings);
editor.resize(true);
console.log('language:', lang);
console.log('tab size:', lang);
console.log('Theme:', theme);
console.log('Font size:', font);
console.log('renderer.lineHeight', editor.renderer.lineHeight);
console.log('# of LINES', editor.session.getLength());
console.log('max_lines', appSettingsResult.max_lines);
console.log('min_lines', appSettingsResult.min_lines);
editor.on('paste', function (text) {
// delay the change event to the end of the call stack
// and fire a change event with an extra parameter indicating
// that this is a paste event and continue to update the reference
// to angular file model.
$timeout(function () {
editor._emit('change', {target: editor, pasteEvent: true});
}, 0);
});
editor.on('change', function (data) {
// change coming from manually changing the value using the api
// skip the update
if (inUpdateProcess) {
return;
}
// only react to user actions
if (data.pasteEvent || editor.curOp && editor.curOp.command.name) {
$scope.$apply(function () {
$scope.file.content = editor.getValue();
if (!$scope.edit) {
$scope.enableEdit();
}
});
}
});
// listen to ngModel render and update the session
$scope.$on('ace-update', function (e, updatedFile) {
if ($scope.file.filename === updatedFile) {
inUpdateProcess = true;
session.setValue($scope.file.content);
inUpdateProcess = false;
}
});
}, 0);
});
}
};
}]);
|
br: {
year: [ 'ano', 'anos' ],
month: [ 'mês', 'meses' ],
week: [ 'semana', 'semanas' ],
day: [ 'dia', 'dias' ],
hour: [ 'hora', 'horas' ],
minute: [ 'minuto', 'minutos' ],
past: function (vagueTime, unit) {
return vagueTime + ' ' + unit + ' atrás';
},
future: function (vagueTime, unit) {
return 'em ' + vagueTime + ' ' + unit;
},
defaults: {
past: 'agora mesmo',
future: 'em breve'
}
}
|
/**
* Select2 Norwegian translation.
*
* Author: Torgeir Veimo <torgeir.veimo@gmail.com>
*/
(function ($) {
"use strict";
$.extend($.fn.select2.defaults, {
formatNoMatches: function () { return "Ingen treff"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "Vennligst skriv inn " + n + (n>1 ? " flere tegn" : " tegn til"); },
formatInputTooLong: function (input, max) { var n = input.length - max; return "Vennligst fjern " + n + " tegn"; },
formatSelectionTooBig: function (limit) { return "Du kan velge maks " + limit + " elementer"; },
formatLoadMore: function (pageNumber) { return "Laster flere resultater..."; },
formatSearching: function () { return "Søker..."; }
});
})(jQuery);
|
import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-js-harmony';
export default {
entry: 'lib/index.js',
format: 'umd',
dest: 'js-csvparser.umd.min.js',
moduleName: 'CSVParser',
plugins: [
uglify({}, minify)
]
}; |
const debug = require('debug')('cygnus:api:project');
const express = require('express');
const router = express.Router();
const ProjectService = require('../service/srv.project');
// Get all actived projects.
router.get('/all', (req, res) => {
var service = new ProjectService();
service.getAllProjects(true)
.then(ret => {
res.json({
code: 0,
data: ret
});
})
.fail(err => {
res.status(500).send('GET /project/all error');
});
});
// Get a project by specified project id.
router.get('/:id', (req, res) => {
let prjId = req.params.id;
if (prjId) {
prjId = parseInt(prjId);
}
var service = new ProjectService();
service.getProjectById(prjId)
.then(ret => {
res.json({
code: 0,
data: ret
});
})
.fail(err => {
res.status(500).send('GET /project/:id error');
});
});
module.exports = router; |
$(document).ready(
function()
{
$('#newWeddingBtn').click(
function(e)
{
var regExp = new RegExp("^[A-z]*$");
if(regExp.test($('#weddingName').val()))
{
regExp = new RegExp("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$");
if(regExp.test($('#brideEmail').val()))
{
regExp = new RegExp("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$");
if(regExp.test($('#bridegroomEmail').val()))
{
regExp = new RegExp("^[0-2][0-9][0-9][0-9]\-([0][0-9]|[1][1-2])\-([0-2][0-9]|[3][0-1])$");
if(regExp.test($('#date').val()))
{
regExp = new RegExp("^([0-1][0-9]|[2][0-3])\:([0-5][0-9])$");
if(regExp.test($('#time').val()))
{
regExp = new RegExp(/^[A-z]*$/);
if(regExp.test($('#venue').val()))
{
if($('#e1Name').val()!=="")
foo($('#e1Name').val(),$('#e1Date').val(),$('#e1Time').val(),$('#e1Venue').val());
if($('#e2Name').val()!=="")
foo($('#e2Name').val(),$('#e2Date').val(),$('#e2Time').val(),$('#e2Venue').val());
if($('#e3Name').val()!=="")
foo($('#e3Name').val(),$('#e3Date').val(),$('#e3Time').val(),$('#e3Venue').val());
}
else
{
alert("Check Venue here!");
e.preventDefault();
}
}
else
{
alert("Time id format not valid!");
e.preventDefault();
}
}
else
{
alert("Date format is not valid!");
e.preventDefault();
}
}
else
{
alert("Bridegroom email id format is not valid!");
e.preventDefault();
}
}
else
{
alert("Bride email id format is not valid!");
e.preventDefault();
}
}
else
{
alert("Wedding Name error! Change name");
e.preventDefault();
}
}
);
}
);
function foo(a,b,c,d)
{
var regExp= new RegExp("^[A-z]*$");
if(regExp.test(a))
{
regExp = new RegExp("^[0-2][0-9][0-9][0-9]\-([0][0-9]|[1][1-2])\-([0-2][0-9]|[3][0-1])$");
if(regExp.test(b))
{
regExp = new RegExp("^([0-1][0-9]|[2][0-3])\:([0-5][0-9])$");
if(regExp.test(c))
{ regExp=new RegExp("^[A-z]*$");
if(regExp.test(d))
{
}
else
{
alert("Event Venue format is not correct!");
e.preventDefault();
}
}
else
{
alert("Event Time format is not correct!");
e.preventDefault();
}
}
else
{
alert("Event Date format is not correct!");
e.preventDefault();
}
}
else
{
alert("Event Name format is not correct!");
e.preventDefault();
}
} |
import { test, module } from 'qunit';
import { setupTest } from 'ember-qunit';
import { setupPact, given, interaction } from 'ember-cli-pact';
import { run } from '@ember/runloop';
module('Pact | People', function(hooks) {
setupTest(hooks);
setupPact(hooks);
test('listing people', async function(assert) {
given('a department exists', { id: '1', name: 'People' });
given('a person exists', { id: '1', name: 'Alice', departmentId: '1' });
given('a person exists', { id: '2', name: 'Bob', departmentId: '1' });
let people = await interaction(() => this.store().findAll('person'));
assert.deepEqual([...people.mapBy('id')], ['1', '2']);
assert.deepEqual([...people.mapBy('name')], ['Alice', 'Bob']);
assert.deepEqual([...people.mapBy('department.name')], ['People', 'People']);
});
test('querying people', async function(assert) {
given('a person exists', { id: '1', name: 'Alice' });
given('a person exists', { id: '2', name: 'Bob' });
let people = await interaction(() => this.store().query('person', { name: 'Bob' }));
assert.equal(people.get('length'), 1);
assert.equal(people.get('firstObject.id'), '2');
assert.equal(people.get('firstObject.name'), 'Bob');
});
test('fetching a person by ID', async function(assert) {
given('a person exists', { id: '1', name: 'Alice' });
let person = await interaction(() => this.store().findRecord('person', '1'));
assert.equal(person.get('id'), '1');
assert.equal(person.get('name'), 'Alice');
});
test('updating a person', async function(assert) {
given('a person exists', { id: '1', name: 'Alice' });
let person = await run(() => this.store().findRecord('person', '1'));
await interaction(() => {
person.set('name', 'Alicia');
return person.save();
});
assert.equal(person.get('name'), 'Alicia');
});
});
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Plugin, Cordova } from './plugin';
/**
* @beta
* @name SpeechRecognition
* @description
* This plugin does speech recognition using cloud services
*
* @usage
* ```
* import { SpeechRecognition } from 'ionic-native';
*
* // Check feature available
* SpeechRecognition.isRecognitionAvailable()
* .then((available: boolean) => console.log(available))
*
* // Start the recognition process
* SpeechRecognition.startListening(options)
* .subscribe(
* (matches: Array<string>) => console.log(matches),
* (onerror) => console.log('error:', onerror)
* )
*
* // Stop the recognition process (iOS only)
* SpeechRecognition.stopListening()
*
* // Get the list of supported languages
* SpeechRecognition.getSupportedLanguages()
* .then(
* (languages: Array<string>) => console.log(languages),
* (error) => console.log(error)
* )
*
* // Check permission
* SpeechRecognition.hasPermission()
* .then((hasPermission: boolean) => console.log(hasPermission))
*
* // Request permissions
* SpeechRecognition.requestPermission()
* .then(
* () => console.log('Granted'),
* () => console.log('Denied')
* )
*
* ```
*/
export var SpeechRecognition = (function () {
function SpeechRecognition() {
}
/**
* Check feature available
* @return {Promise<boolean>}
*/
SpeechRecognition.isRecognitionAvailable = function () {
return;
};
/**
* Start the recognition process
* @return {Promise< Array<string> >} list of recognized terms
*/
SpeechRecognition.startListening = function (options) {
return;
};
/**
* Stop the recognition process
*/
SpeechRecognition.stopListening = function () {
return;
};
/**
* Get the list of supported languages
* @return {Promise< Array<string> >} list of languages
*/
SpeechRecognition.getSupportedLanguages = function () {
return;
};
/**
* Check permission
* @return {Promise<boolean>} has permission
*/
SpeechRecognition.hasPermission = function () {
return;
};
/**
* Request permissions
* @return {Promise<void>}
*/
SpeechRecognition.requestPermission = function () {
return;
};
__decorate([
Cordova()
], SpeechRecognition, "isRecognitionAvailable", null);
__decorate([
Cordova({
callbackOrder: 'reverse',
observable: true,
})
], SpeechRecognition, "startListening", null);
__decorate([
Cordova({
platforms: ['iOS']
})
], SpeechRecognition, "stopListening", null);
__decorate([
Cordova()
], SpeechRecognition, "getSupportedLanguages", null);
__decorate([
Cordova()
], SpeechRecognition, "hasPermission", null);
__decorate([
Cordova()
], SpeechRecognition, "requestPermission", null);
SpeechRecognition = __decorate([
Plugin({
pluginName: 'SpeechRecognition',
plugin: 'cordova-plugin-speechrecognition',
pluginRef: 'plugins.speechRecognition',
repo: 'https://github.com/pbakondy/cordova-plugin-speechrecognition',
platforms: ['Android', 'iOS']
})
], SpeechRecognition);
return SpeechRecognition;
}());
//# sourceMappingURL=speech-recognition.js.map |
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
//Allow using this built library as an AMD module
//in another project. That other project will only
//see this AMD call, not the internal modules in
//the closure below.
define([], factory);
} else {
//Browser globals case. Just assign the
//result to a property on the global.
root.JWTStore = factory();
}
}(this, function () {
|
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2267',"Tlece.Recruitment.Models.RecruitmentPlanning Namespace","topic_0000000000000692.html"],['2709',"VacancyVm Class","topic_0000000000000923.html"],['2710',"VacancyVm Constructor","topic_0000000000000924.html"]]; |
module.exports = function(grunt){
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
all:['src/*.js']
},
concat: {
dist:{
src:'src/*.js',
dest:'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build:{
src: 'dist/<%= pkg.name %>.js',
dest:'dist/<%= pkg.name %>.min.js'
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default',['jshint','concat','uglify']);
};
|
import React from 'react';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.DateTimeInput.
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Control', './library', 'sap/ui/model/type/Date'],
function(jQuery, Control, library, Date1) {
"use strict";
/**
* Constructor for a new DateTimeInput.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* Allows end users to interact with date and/or time and select from a date and/or time pad.
*
* <b>Note:</b> This control should not be used any longer, instead please use the dedicated <code>sap.m.DatePicker</code>, <code>sap.m.TimePicker</code> or <code>sap.m.DateTimePicker</code> control.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.38.4
*
* @constructor
* @public
* @since 1.9.1
* @deprecated Since version 1.32.8. Instead, use the dedicated <code>sap.m.DatePicker</code>, <code>sap.m.TimePicker</code> or <code>sap.m.DateTimePicker</code> controls.
* @alias sap.m.DateTimeInput
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var DateTimeInput = Control.extend("sap.m.DateTimeInput", /** @lends sap.m.DateTimeInput.prototype */ { metadata : {
library : "sap.m",
properties : {
/**
* Defines the value of the control.
*
* The new value must be in the format set by <code>valueFormat</code>.
*
* The "Now" literal can also be assigned as a parameter to show the current date and/or time.
*/
value: { type: "string", group: "Data", defaultValue: null, bindable: "bindable" },
/**
* Defines the width of the control.
*/
width: { type: "sap.ui.core.CSSSize", group: "Dimension", defaultValue: "100%" },
/**
* Indicates whether the user can interact with the control or not.
* <b>Note:</b> Disabled controls cannot be focused and they are out of the tab-chain.
*/
enabled: { type: "boolean", group: "Behavior", defaultValue: true },
/**
* Defines whether the control can be modified by the user or not.
* <b>Note:</b> A user can tab to non-editable control, highlight it, and copy the text from it.
* @since 1.12.0
*/
editable: { type: "boolean", group: "Behavior", defaultValue: true },
/**
* Visualizes the validation state of the control, e.g. <code>Error</code>, <code>Warning</code>, <code>Success</code>.
*/
valueState: { type: "sap.ui.core.ValueState", group: "Appearance", defaultValue: sap.ui.core.ValueState.None },
/**
* Defines the text that appears in the value state message pop-up. If this is not specified, a default text is shown from the resource bundle.
* @since 1.26.0
*/
valueStateText: { type: "string", group: "Misc", defaultValue: null },
/**
* Indicates whether the value state message should be shown or not.
* @since 1.26.0
*/
showValueStateMessage: { type: "boolean", group: "Misc", defaultValue: true },
/**
* Defines the name of the control for the purposes of form submission.
*/
name: { type: "string", group: "Misc", defaultValue: null },
/**
* Defines a short hint intended to aid the user with data entry when the control has no value.
*/
placeholder: { type: "string", group: "Misc", defaultValue: null },
/**
* Defines the horizontal alignment of the text that is shown inside the input field.
* @since 1.26.0
*/
textAlign: { type: "sap.ui.core.TextAlign", group: "Appearance", defaultValue: sap.ui.core.TextAlign.Initial },
/**
* Defines the text directionality of the input field, e.g. <code>RTL</code>, <code>LTR</code>
* @since 1.28.0
*/
textDirection: { type: "sap.ui.core.TextDirection", group: "Appearance", defaultValue: sap.ui.core.TextDirection.Inherit },
/**
* Type of DateTimeInput (e.g. Date, Time, DateTime)
*/
type : {type : "sap.m.DateTimeInputType", group : "Data", defaultValue : sap.m.DateTimeInputType.Date},
/**
* Displays date value in this given format in text field. Default value is taken from locale settings.
* If you use data-binding on value property with type sap.ui.model.type.Date then you can ignore this property or the latter wins.
* If the user's browser supports native picker then this property is overwritten by browser with locale settings.
*/
displayFormat : {type : "string", group : "Appearance", defaultValue : null},
/**
* Given value property should match with valueFormat to parse date. Default value is taken from locale settings.
* You can only set and get value in this format.
* If you use data-binding on value property with type sap.ui.model.type.Date you can ignore this property or the latter wins.
*/
valueFormat : {type : "string", group : "Data", defaultValue : null},
/**
* This property as JavaScript Date Object can be used to assign a new value which is independent from valueFormat.
*/
dateValue : {type : "object", group : "Data", defaultValue : null}
},
aggregations: {
_picker: {type: "sap.ui.core.Control", multiple: false, visibility: "hidden"}
},
associations: {
/**
* Association to controls / IDs that label this control (see WAI-ARIA attribute aria-labelledby).
* @since 1.27.0
*/
ariaLabelledBy: { type: "sap.ui.core.Control", multiple: true, singularName: "ariaLabelledBy" }
},
events : {
/**
* This event gets fired when the selection has finished and the value has changed.
*/
change : {
parameters : {
/**
* The string value of the control in given valueFormat (or locale format).
*/
value : {type : "string"},
/**
* The value of control as JavaScript Date Object or null if value is empty.
*/
dateValue : {type : "object"},
/**
* if set, the entered value is a valid date.
* If not set the entered value cannot be converted to a date.
* @since 1.38.0
*/
valid : {type : "boolean"}
}
}
}
}});
!(function(oPrototype, $, oDevice) {
var oi18n = sap.m.getLocaleData();
$.extend(oPrototype, {
_types : {
Date : {
valueFormat : oi18n.getDatePattern("short"),
displayFormat : oi18n.getDatePattern("medium")
},
Time : {
valueFormat : oi18n.getTimePattern("short"),
displayFormat : oi18n.getTimePattern("short")
},
DateTime : {
valueFormat : oi18n.getDateTimePattern("short"), // does not include pattern but e.g "{1} {0}"
displayFormat : oi18n.getDateTimePattern("short") // does not include pattern but e.g "{1} {0}"
}
}
});
// build DateTime formats from Date And Time values
["Time", "Date"].forEach(function(sType, nIndex) {
["valueFormat", "displayFormat"].forEach(function(sFormat) {
var oTypes = oPrototype._types;
oTypes.DateTime[sFormat] = oTypes.DateTime[sFormat].replace("{" + nIndex + "}", oTypes[sType][sFormat]);
});
});
}(DateTimeInput.prototype, jQuery, sap.ui.Device));
DateTimeInput.prototype.init = function(){
// as date is the default type - > initialize with DatePicker
this.setType(sap.m.DateTimeInputType.Date);
};
DateTimeInput.prototype.onBeforeRendering = function() {
_updateFormatFromBinding.call(this);
};
DateTimeInput.prototype.getFocusDomRef = function() {
var oPicker = _getPicker.call(this);
return oPicker.getFocusDomRef();
};
DateTimeInput.prototype.getIdForLabel = function() {
var oPicker = _getPicker.call(this);
return oPicker.getIdForLabel();
};
DateTimeInput.prototype.setType = function(sType){
if (sType == this.getType() && _getPicker.call(this)) {
return this;
}
this.destroyAggregation("_picker");
var oPicker;
switch (sType) {
case sap.m.DateTimeInputType.DateTime:
jQuery.sap.require("sap.m.DateTimePicker");
oPicker = new sap.m.DateTimePicker(this.getId() + "-Picker");
break;
case sap.m.DateTimeInputType.Time:
jQuery.sap.require("sap.m.TimePicker");
oPicker = new sap.m.TimePicker(this.getId() + "-Picker",
{localeId: sap.ui.getCore().getConfiguration().getFormatSettings().getFormatLocale().toString()});
break;
default: // default is date
jQuery.sap.require("sap.m.DatePicker");
oPicker = new sap.m.DatePicker(this.getId() + "-Picker");
break;
}
// forward properties (also set default, may be different)
oPicker.setDisplayFormat(this.getDisplayFormat() || this._types[sType].displayFormat);
oPicker.setValueFormat(this.getValueFormat() || this._types[sType].valueFormat);
if (this.getDateValue()) {
oPicker.setDateValue(this.getDateValue()); // don't set Value -> as by switching type information can be lost
}
oPicker.setEnabled(this.getEnabled());
oPicker.setEditable(this.getEditable());
oPicker.setValueState(this.getValueState());
oPicker.setValueStateText(this.getValueStateText());
oPicker.setShowValueStateMessage(this.getShowValueStateMessage());
oPicker.setName(this.getName());
oPicker.setPlaceholder(this.getPlaceholder());
oPicker.setTextAlign(this.getTextAlign());
oPicker.setTextDirection(this.getTextDirection());
oPicker.setWidth("100%");
oPicker.attachChange(_handleChange, this);
var aAriaLabelledBy = this.getAriaLabelledBy();
for (var i = 0; i < aAriaLabelledBy.length; i++) {
oPicker.addAriaLabelledBy(aAriaLabelledBy[i]);
}
this.setAggregation("_picker", oPicker);
this.setProperty("type", sType); // re-render because picker control changes
return this;
};
DateTimeInput.prototype.setWidth = function(sWidth) {
this.setProperty("width", sWidth);
if (this.getDomRef()) {
sWidth = this.getWidth(); // to use validator
this.$().css("width", sWidth);
}
return this;
};
DateTimeInput.prototype.setValue = function(sValue) {
_updateFormatFromBinding.call(this); // to be sure to have the right format
sValue = this.validateProperty("value", sValue);
if (sValue.toLowerCase() == "now") {
return this.setDateValue(new Date());
}
if (sValue === this.getValue()) {
return this;
}
this.setProperty("value", sValue, true);
var oPicker = _getPicker.call(this);
oPicker.setValue(sValue);
var oDate = oPicker.getDateValue();
this.setProperty("dateValue", oDate, true);
return this;
};
DateTimeInput.prototype.setDateValue = function(oDate) {
if (oDate && !(oDate instanceof Date)) {
throw new Error("Date must be a JavaScript date object; " + this);
}
_updateFormatFromBinding.call(this); // to be sure to have the right format
this.setProperty("dateValue", oDate, true);
var oPicker = _getPicker.call(this);
oPicker.setDateValue(oDate);
var sValue = oPicker.getValue();
this.setProperty("value", sValue, true);
return this;
};
DateTimeInput.prototype.setDisplayFormat = function(sDisplayFormat) {
this.setProperty("displayFormat", sDisplayFormat, true);
var oPicker = _getPicker.call(this);
oPicker.setDisplayFormat(sDisplayFormat || this._types[this.getType()].displayFormat);
return this;
};
DateTimeInput.prototype.setValueFormat = function(sValueFormat) {
this.setProperty("valueFormat", sValueFormat, true);
var oPicker = _getPicker.call(this);
oPicker.setValueFormat(sValueFormat || this._types[this.getType()].ValueFormat);
return this;
};
DateTimeInput.prototype.setEnabled = function(bEnabled) {
this.setProperty("enabled", bEnabled, true);
var oPicker = _getPicker.call(this);
oPicker.setEnabled(bEnabled);
return this;
};
DateTimeInput.prototype.setEditable = function(bEditable) {
this.setProperty("editable", bEditable, true);
var oPicker = _getPicker.call(this);
oPicker.setEditable(bEditable);
return this;
};
DateTimeInput.prototype.setValueState = function(sValueState) {
this.setProperty("valueState", sValueState, true);
var oPicker = _getPicker.call(this);
oPicker.setValueState(sValueState);
return this;
};
DateTimeInput.prototype.setValueStateText = function(sValueStateText) {
this.setProperty("valueStateText", sValueStateText, true);
var oPicker = _getPicker.call(this);
oPicker.setValueStateText(sValueStateText);
return this;
};
DateTimeInput.prototype.setShowValueStateMessage = function(bShowValueStateMessage) {
this.setProperty("showValueStateMessage", bShowValueStateMessage, true);
var oPicker = _getPicker.call(this);
oPicker.setShowValueStateMessage(bShowValueStateMessage);
return this;
};
DateTimeInput.prototype.setName = function(sName) {
this.setProperty("name", sName, true);
var oPicker = _getPicker.call(this);
oPicker.setName(sName);
return this;
};
DateTimeInput.prototype.setPlaceholder = function(sPlaceholder) {
this.setProperty("placeholder", sPlaceholder, true);
var oPicker = _getPicker.call(this);
oPicker.setPlaceholder(sPlaceholder);
return this;
};
DateTimeInput.prototype.setTextAlign = function(sTextAlign) {
this.setProperty("textAlign", sTextAlign, true);
var oPicker = _getPicker.call(this);
oPicker.setTextAlign(sTextAlign);
return this;
};
DateTimeInput.prototype.setTextDirection = function(sTextDirection) {
this.setProperty("textDirection", sTextDirection, true);
var oPicker = _getPicker.call(this);
oPicker.setTextDirection(sTextDirection);
return this;
};
DateTimeInput.prototype.addAriaLabelledBy = function(sID) {
this.addAssociation("ariaLabelledBy", sID, true);
var oPicker = _getPicker.call(this);
oPicker.addAriaLabelledBy(sID);
return this;
};
DateTimeInput.prototype.removeAriaLabelledBy = function(sID) {
this.removeAssociation("ariaLabelledBy", sID, true);
var oPicker = _getPicker.call(this);
oPicker.removeAriaLabelledBy(sID);
return this;
};
DateTimeInput.prototype.removeAllAriaLabelledBy = function() {
this.removeAssociation("ariaLabelledBy", true);
var oPicker = _getPicker.call(this);
oPicker.removeAllAriaLabelledBy();
return this;
};
/**
* @see {sap.ui.core.Control#getAccessibilityInfo}
* @protected
*/
DateTimeInput.prototype.getAccessibilityInfo = function() {
var oPicker = _getPicker.call(this);
return oPicker && oPicker.getAccessibilityInfo ? oPicker.getAccessibilityInfo() : null;
};
function _getPicker(){
return this.getAggregation("_picker");
}
function _updateFormatFromBinding(){
var oBinding = this.getBinding("value");
if (oBinding && oBinding.oType && (oBinding.oType instanceof Date1)) {
var sPattern = oBinding.oType.getOutputPattern();
var oPicker = _getPicker.call(this);
if (oPicker.getValueFormat() != sPattern) {
oPicker.setValueFormat(sPattern);
}
if (oPicker.getDisplayFormat() != sPattern) {
oPicker.setDisplayFormat(sPattern);
}
}
}
function _handleChange(oEvent) {
var sValue = oEvent.getParameter("value");
var oDateValue;
var bValid = oEvent.getParameter("valid");
this.setProperty("value", sValue, true);
if (bValid) {
oDateValue = oEvent.oSource.getDateValue();
this.setProperty("dateValue", oDateValue, true);
}
// newValue and newDateValue for compatibility reasons
this.fireChange({value: sValue, newValue: sValue, valid: bValid, dateValue: oDateValue, newDateValue: oDateValue});
}
return DateTimeInput;
}, /* bExport= */ true);
|
import {
RESULTS_PAGINATION,
SET_SHOWMORE
} from '../actions/types';
const INITIAL_STATE = { };
export default function(state = INITIAL_STATE, action) {
switch(action.type) {
case RESULTS_PAGINATION:
return { ...state, ...action.payload }
case SET_SHOWMORE:
return { ...state, ...action.payload }
default:
return state;
}
}
|
c['24']=[['25',"Methods","topic_0000000000000009_methods--.html",1]]; |
'use strict'
/**
* Modules (Electron)
* @constant
*/
const { app, ipcMain } = require('electron')
/**
* Modules (Third party)
* @constant
*/
const logger = require('@sidneys/logger')({ write: true })
const notificationProvider = require('@sidneys/electron-notification-provider')
/**
* Modules (Local)
* @constant
*/
/**
* @class SnoozerService
* @property {Number} snoozeUntil
* @namespace Electron
*/
class SnoozerService {
/**
* @constructor
*/
constructor() {
this.snoozeUntil = 0
}
/**
* @param {Boolean} isSnoozing - Snooze state
* @fires Snoozer#EventEmitter:snooze
*
* @private
*/
onSnooze(isSnoozing) {
logger.debug('onSnooze')
ipcMain.emit('snooze', isSnoozing)
}
/**
* Snooze until indefinitely
*
* @private
*/
infinitySnooze() {
logger.debug('infinitySnooze')
// Set timestamp
this.snoozeUntil = Infinity
// Emit
this.onSnooze(true)
// Notification
const notification = notificationProvider.create({
title: 'Snooze started',
subtitle: 'Snoozing indefinitely.'
})
notification.show()
}
/**
* Schedule snooze
* @param {Number} durationMinutes - Snooze duration
* @param {Electron.MenuItem} menuItem - Menu item
*
* @private
*/
scheduleSnooze(durationMinutes, menuItem) {
logger.debug('scheduleSnooze')
if (durationMinutes === Infinity) {
this.infinitySnooze()
return
}
const durationMilliseconds = Math.round(durationMinutes * (60 * 1000))
// Set timestamp
this.snoozeUntil = Date.now() + durationMilliseconds
const snoozeRemaining = this.snoozeUntil - Date.now()
// Notification
const notification = notificationProvider.create({
title: 'Snooze started',
subtitle: `Snooze ends in ${durationMinutes} minutes.`
})
notification.show()
// Emit
this.onSnooze(true)
// Schedule wake up
let timeout = setTimeout(() => {
logger.debug('setTimeout()', 'durationMinutes:', durationMinutes)
// Set timestamp
this.snoozeUntil = 0
// Uncheck menuItem
menuItem.checked = false
// Notification
const notification = notificationProvider.create({
title: 'Snooze ended',
subtitle: `Snooze ended after ${durationMinutes} minutes.`
})
notification.show()
// Emit
this.onSnooze(false)
clearTimeout(timeout)
}, snoozeRemaining)
}
/**
* Start snooze
* @param {Number} durationMinutes - Snooze duration
* @param {Electron.MenuItem} menuItem - Menu item
*
* @public
*/
startSnooze(durationMinutes, menuItem) {
logger.debug('startSnooze')
// Get menuItem state
let isEnabled = menuItem.checked
// Get sibling menuItems
let siblingMenuItemList = menuItem['menu'].items.filter((item) => item.id && item.id.startsWith('snooze') && item.id !== menuItem['id'])
// Uncheck sibling menuItems
siblingMenuItemList.forEach(item => item.checked = false)
// Cancel existing Snooze
if (this.snoozeUntil !== 0) {
this.snoozeUntil = 0
// Notification
const notification = notificationProvider.create({
title: 'Snooze ended',
subtitle: 'Snooze aborted.'
})
notification.show()
// Emit
this.onSnooze(false)
}
// Init Snooze
if ((this.snoozeUntil === 0) && isEnabled) {
this.scheduleSnooze(durationMinutes, menuItem)
}
}
}
/**
* Init
*/
let init = () => {
logger.debug('init')
// Ensure single instance
if (!global.snoozerService) {
global.snoozerService = new SnoozerService()
}
}
/**
* @listens Electron.App#Event:ready
*/
app.once('ready', () => {
logger.debug('app#ready')
init()
})
/**
* @exports
*/
module.exports = global.snoozerService
|
var showf = require('../');
var test = require('tape');
test('Infinity', function (t) {
t.equal(showf( Infinity, 0), undefined);
t.equal(showf(-Infinity, 0), undefined);
t.equal(showf( Infinity, 1), undefined);
t.equal(showf(-Infinity, 1), undefined);
t.equal(showf( Infinity, 2), ' I');
t.equal(showf(-Infinity, 2), '-I');
t.equal(showf( Infinity, 3), ' In');
t.equal(showf(-Infinity, 3), '-In');
t.equal(showf( Infinity, 4), ' Inf');
t.equal(showf(-Infinity, 4), '-Inf');
t.equal(showf( Infinity, 5), ' Inf');
t.equal(showf(-Infinity, 5), ' -Inf');
t.equal(showf( Infinity, 6), ' Inf');
t.equal(showf(-Infinity, 6), ' -Inf');
t.equal(showf( Infinity, 7), ' Inf');
t.equal(showf(-Infinity, 7), ' -Inf');
t.equal(showf( Infinity, 8), ' Inf');
t.equal(showf(-Infinity, 8), ' -Inf');
t.equal(showf( Infinity, 9), ' Infinity');
t.equal(showf(-Infinity, 9), '-Infinity');
t.equal(showf( Infinity, 10), ' Infinity');
t.equal(showf(-Infinity, 10), ' -Infinity');
t.equal(showf( Infinity, 11), ' Infinity');
t.equal(showf(-Infinity, 11), ' -Infinity');
t.equal(showf( Infinity, 15), ' Infinity');
t.equal(showf(-Infinity, 15), ' -Infinity');
t.end();
});
|
var Model = require('ampersand-model');
module.exports = Model.extend({
type: 'repo',
props: {
// npm slug
id: ['string', true],
description: ['string', true],
tags: ['array', true],
author: ['string', true, ''],
homepage: ['string', true, '']
},
derived: {
tagLinks: {
fn: function () {
return this.tags.map(function (item) {
return '<a href="#" class="tag">' + item + '</a>';
}).join(', ');
}
},
searchString: {
cache: true,
fn: function () {
return [this.id, this.description, this.author, this.homepage].concat(this.tags).join(' ').toLowerCase();
}
},
npmUrl: {
cache: true,
fn: function () {
return 'http://npmjs.org/package/' + this.id;
}
},
npmUserUrl: {
cache: true,
fn: function () {
return 'http://npmjs.org/~' + this.author.toLowerCase();
}
}
},
session: {
active: ['boolean', true, true]
},
// whether or not this model matches the filter string
matches: function (str) {
var query = (str || '').toLowerCase();
this.active = this.searchString.indexOf(query) !== -1;
}
});
|
'use strict';
var mongoose = require('mongoose') // mongo abstraction
, request = require('request') // to place http requests
, cheerio = require('cheerio') // to parse fetched DOM data
, async = require('async') // to call many async functions in a loop
, provider = require('../controllers/provider') // provider's controller
, Provider = require('../models/provider') // model of provider
, Person = require('../models/person') // model of person
, config = require('../config') // global configuration
;
var local = {};
var log = config.log;
exports.syncPosts = function(search, callback) {
Provider.find({ type: 'reviews' }).lean().exec(function(err, providers) {
if (err) {
return log.error('error getting providers:', err);
}
var posts = [];
var topics = [];
async.each(
providers, // 1st param in async.each() is the array of items
function(prov, callbackInner) { // 2nd param is the function that each item is passed to
local.searchTopics(prov, search, function(err, results) {
if (err) {
return callbackInner(err);
}
topics = topics.concat(results);
local.searchPosts(prov, results[0], function(err, results) { // TODO...
if (err) {
return callbackInner(err);
}
//console.log('posts.length before concat:', posts.length);
posts = posts.concat(results);
//console.log('posts.length after concat:', posts.length);
callbackInner(null);
});
});
},
function(err) { // 3rd param is the function to call when everything's done (outer callback)
if (err) {
return callback(err);
}
//console.log('FINAL POSTS:', posts);
callback(null, posts);
}
);
});
};
local.searchTopics = function(provider, search, callback) {
//var url = 'http://gnoccaforum.com/escort/search2';
//var origin = 'http://gnoccaforum.com';
//var referer = 'http://gnoccaforum.com/escort/search';
//var resultsPerPage = 15;
//var provider = {};
//provider.key = 'GF';
var url = provider.url + provider.pathSearch;
request(
{
url: url,
method: 'POST',
form: { search: search },
timeout: config.networking.timeout, // number of milliseconds to wait for a server to send response headers before aborting the request
},
function (err, response, body) {
if (err || response.statusCode !== 200) {
return callback(new Error('Error on response' + (response ? ' (' + response.statusCode + ')' : '') + ':' + err + ' : ' + body), null);
}
//console.log(body);
var $ = cheerio.load(body);
var topics = local.getTopics($, provider);
callback(null, topics);
}
);
};
local.getTopics = function($, provider) {
var topics = [];
if (provider.key === 'GF') {
$('div[class~="topic_details"]').each(function (i, element) { // topics loop
var topic = {};
//console.log($(element).html());
topic.counter = $(element).find('div[class^="counter"]').text();
topic.section = $(element).find('a').eq(0).text();
topic.url = $(element).find('a').eq(1).attr('href');
topic.title = $(element).find('a').eq(1).text();
topic.author = {};
topic.author.name = $(element).find('a').eq(2).text();
topic.author.url = $(element).find('a').eq(2).attr('href');
topic.dateOfCreation = $(element).find('em').text().trim();
topics.push(topic);
});
}
return topics;
};
local.searchPosts = function(provider, topic, callback) {
log.info('searchPosts:', provider);
if (provider.key === 'GF') {
var topicUrlStart = topic.url.replace(/\/msg\d+\/.*/, '');
var url = topicUrlStart;
var posts = [];
async.whilst(
function() { return url !== null; },
function(callbackWhilst) {
console.log('REQUESTING');
request(url, function(err, response, body) {
if (err || response.statusCode !== 200) {
return callback(new Error('Error on response' + (response ? ' (' + response.statusCode + ')' : '') + ':' + err + ' : ' + body), null);
}
var $ = cheerio.load(body);
$('table[border-color="#cccccc"]').each(function(i, element) { // post elements
var post = {};
post.n = 1 + posts.length;
var postHtml = $(element).html();
post.author = {};
post.author.name = $(element).find('a[title^="View the profile of "]').text(); // post author name regex
var authorHtml = $(element).find('span[class="smalltext"]').html();
var authorKarmaRE = /Karma:\s*(.*?)\s*<br>/; // post author karma regex
post.author.karma = authorKarmaRE.exec(authorHtml)[1];
var authorPostsRE = /Posts:\s*(.*?)\s*<br>/; // post author posts count regex
post.author.postsCount = authorPostsRE.exec(authorHtml)[1];
var dateRE = /«\s*<b>(?:.*?)\s*on\:<\/b>\s*(.*?)\s*»/; // post date regex
post.date = dateRE.exec(postHtml)[1];
// remove quotes of previous post from post
var contents = $(element).find('div.post').html();
var contentsQuotesRE = /(.*?)(<div class="quoteheader"><div class="topslice_quote"><a .*?>.*?<\/a><\/div><\/div><blockquote.*?>.*?<\/blockquote><div class="quotefooter"><div class="botslice_quote"><\/div><\/div>)(.*)/;
var quotes = contentsQuotesRE.exec(contents);
if (quotes) {
contents = quotes[1] + quotes[3];
}
contents = contents.replace(/^\s*/, '');
contents = contents.replace(/\s*$/, '');
contents = contents.replace(/^(<br>)*/, '');
contents = contents.replace(/(<br>)*$/, '');
post.contents = contents;
posts.push(post);
});
//console.log('posts:', posts);
var last = $('a[name="lastPost"]').next().html();
//console.log(' *** LAST:', last);
var nextRE = /\[<strong>\d+<\/strong>\] <a class="navPages" href="(.*?)".*>/g;
var match = nextRE.exec(last);
if (match && match[1]) {
url = match[1];
//console.log(' QQQQQQQQQ next page url found:', url);
} else {
url = null;
//console.log(' QQQQQQQQQ NO NEXT URL FOUND');
}
callbackWhilst();
});
},
function(err, done) {
//console.log(' ************************** done:', done ? done : '');
callback(null, posts);
}
);
}
};
local.searchEscortAdvisorPosts = function(search, callback) {
var url = 'http://www.escort-advisor.com/ea/Numbers/?num=' + search;
// TODO: ...
// NOT FOUND: <div class='light30'>Numero non trovato</div>
};
module.exports = exports;
// test /////////////////////////////////////////////////
var db = require('../models/db'); // database wiring
/*
var topic = {};
topic.url = 'http://gnoccaforum.com/escort/info-torino-e-provincia-111/una-nuova-e-bella-russa-nastia-(ma-sara-anche-nasty)/msg1326531/#msg1326531';
//topic.url = 'http://gnoccaforum.com/escort/girlescort-torino/italiana-semplice-ma-molto-disponibile/';
//topic.url = 'http://gnoccaforum.com/escort/info-torino-e-provincia-111/scuderia-russe-bollettino/1290/';
exports.searchPosts({}, topic, function(err, results) {
if (err) {
return console.error(err);
}
console.log('results.length:', results.length);
});
/////////////////////////////////////////////////////////
*/
//var phone = '3888350421'; // SANDRA
//var phone = '3240810872'; // ANE MARIE
//var phone = '3897876672'; // KSIUSCHA
//var phone = '3426856330'; // GIULIA
var phone = '3276104785'; // ILARIA
exports.syncPosts(phone, function(err, results) {
//local.searchTopics(phone, function(err, results) {
if (err) {
return console.error(err);
}
console.log(results);
});
/////////////////////////////////////////////////////////
|
import configureStore from 'store/configureStore';
/*const state = (<window>window).__initialState__ || undefined;*/
export const store = configureStore({});
|
const iconWithOptionsDriverFactory = component => ({
element: () => component,
mouseEnter: () => browser.actions().mouseMove(component.$('[data-hook=icon-wrapper')).perform(),
mouseLeave: () => browser.actions().mouseMove({x: 400, y: -100}).perform(),
getDropdown: () => component.$(`[data-hook="iconWithOptions-dropdownLayout"]`),
getDropdownItem: index => component.$$(`[data-hook="dropdown-layout-options"] div`).get(index),
getDropdownItemsCount: () => component.$$(`[data-hook="dropdown-layout-options"] div`).getText().count()
});
export default iconWithOptionsDriverFactory;
|
// Quartz.Points
// require:core.point
var Points = null;
(function () {
Points = qz.Points = function (points) {
this._points = [];
if (Util.isArray(points)) {
this.addMultiplePoint(points);
}
};
// yeni eleman ekler
Points.prototype.addPoint = function (p , index) {
p = Point(p);
if (index != null) {
if (index < 0) index = this.size() + index;
this.getPoints().splice(index , 0 , p);
} else {
this.getPoints().push(p);
}
return this;
};
Points.prototype.addMultiplePoint = function (points) {
for (var i = 0; i < points.length;i++) {
this.addPoint(points[i]);
}
};
// elemanları döndürür
Points.prototype.getPoints = function () {
return this._points;
};
// eleman sayısını döndürür
Points.prototype.getPointsLength = function () {
return this._points.length;
};
// nokta var mı?
Points.prototype.hasPoints = function () {
return !!this._points.length;
};
// elemanlarda noktayı arar
Points.prototype.searchPoint = function (p , s) {
var elements = this.getPoints(),
length = this.getPointsLength(),
i = s || 0;
p = point(p);
for ( ; i < length ; i++) {
if (p.equals(elements[i])) {
return i;
}
}
return false;
};
// belirtilen noktayı kaldırır
// i , qz.Point veya number tipinde olabilir
Points.prototype.removePoint = function (i) {
if (typeof i != 'number') {
i = this.searchPoint(i);
}
if (i < 0) i = this.countPoints() + i;
return this.get().splice(i , 1);
};
Points.prototype.applyTransformationToPoints = function (transform) {
var elements = this._points,
length = elements.length,
points = new Points,
i = 0;
if (this.hasPoints()) {
for ( ; i < length ; i++) {
points.addPoint(transform.point(elements[i]));
}
}
return points;
};
Points.prototype.setPoints = function (points) {
this._points = points;
};
})(); |
// Rdio Utils 0.0.1
// Copyright 2013, Rdio, Inc.
// https://github.com/rdio/jsapi-examples/tree/master/utils
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
(function(R) {
var verbose = false;
// ----------
var log = function() {
/*globals console */
if (verbose && window.console && console.log) {
console.log.apply(console, arguments);
}
};
// ----------
var assert = function(condition, message) {
/*globals console */
if (!window.console) {
return;
}
if (console.assert) {
console.assert(condition, message);
} else if (condition && console.error) {
console.error('Rdio Utils assert failed: ' + message);
}
};
// ----------
var bind = function(element, eventName, handler) {
if(element.addEventListener)
element.addEventListener(eventName, handler, true);
else
element.attachEvent("on" + eventName, handler);
};
// ----------
var unbind = function(element, eventName, handler) {
if(element.removeEventListener)
element.removeEventListener(eventName, handler, true);
else
element.detachEvent("on" + eventName, handler);
};
// ----------
function dialog(message) {
var body = document.getElementsByTagName('body')[0];
var el = document.createElement('div');
el.className = "rdio-utils-dialog";
el.innerHTML = '<div>'
+ message
+ '</div><br><button>OK</button>';
var button = el.getElementsByTagName('button')[0];
bind(button, 'click', function() {
body.removeChild(el);
});
body.appendChild(el);
}
// ----------
window.rdioUtils = {
// ----------
startupChecks: function() {
var self = this;
if (!R) {
dialog('Unable to contact Rdio API. Please try again later.');
return false;
}
R.on('flashError', function() {
dialog('The Rdio API requires Flash in this browser. Please install (or unblock) the Flash plug-in.');
});
R.on('cookieError', function() {
dialog('The Rdio API won\'t work while cookies are blocked. Please unblock cookies for rdio.com.');
});
return true;
},
// ----------
addToTopOfQueue: function(sourceKey) {
var handler = function(model, collection, info) {
if (model.get('key') == sourceKey) {
R.player.queue.off('add', handler);
R.player.queue.move(info.index, 0);
}
};
R.player.queue.on('add', handler);
R.player.queue.add(sourceKey);
},
// ----------
collectionAlbums: function(config) {
return new CollectionTracker(config);
},
// ----------
authWidget: function(el) {
if (el.jquery) {
el = el[0];
}
var showAuthenticated = function() {
el.innerHTML = 'Rdio: ' + R.currentUser.get('vanityName');
App.wait(false);
};
R.ready(function() {
if (R.authenticated()) {
showAuthenticated();
} else {
App.toggleInputOverlay('rdio-sign-in', null, function() {
App.wait(true);
R.authenticate(function(authenticated) {
if (authenticated) {
showAuthenticated();
}
});
});
}
});
}
};
// ----------
var CollectionTracker = function(config) {
var self = this;
this._config = {
onLoadComplete: config.onLoadComplete,
onAlbumsLoaded: config.onAlbumsLoaded,
onError: config.onError,
onAdded: config.onAdded,
onRemoved: config.onRemoved
};
if (config.localStorage && window.JSON) {
// Determine if localStorage is available.
// See: https://gist.github.com/paulirish/5558557
try {
var testKey = '__rdioUtilsTestKey';
localStorage.setItem(testKey, testKey);
localStorage.removeItem(testKey);
this._config.localStorage = true;
} catch(e) {
}
}
this._start = 0;
this._loading = null;
this._albums = [];
this._albumsByKey = {};
this._newAlbums = [];
this._newAlbumsByKey = {};
this._firstTime = true;
this._bigExtras = '-*,releaseDate,duration,isClean,canStream,icon,'
+ 'canSample,name,isExplicit,artist,url,length,trackKeys,artistUrl';
var whenAuthenticated = function() {
if (self._config.localStorage) {
var data = localStorage.__rdioUtilsCollectionAlbums;
if (data) {
var albums = JSON.parse(data);
if (albums instanceof Array && albums.length) {
var album;
for (var i = 0; i < albums.length; i++) {
album = albums[i];
self._albumsByKey[album.key] = album;
}
self._albums = albums;
self.length = self._albums.length;
self._firstTime = false;
if (self._config.onAlbumsLoaded) {
self._config.onAlbumsLoaded(albums);
}
if (self._config.onLoadComplete) {
self._config.onLoadComplete();
}
var libraryVersion = localStorage.__rdioUtilsCollectionVersion;
if (libraryVersion != R.currentUser.get('libraryVersion')) {
self._startLoad();
}
}
}
}
if (self._firstTime) {
self._startLoad();
}
R.currentUser.on('change:libraryVersion', function(value) {
log('change:libraryVersion: ' + value);
if (self._loading) {
self._loading.loadAgain = true;
if (!self._firstTime) {
assert(self._loading.request, '_loading.request must exist');
self._loading.request.abort();
}
} else {
self._startLoad();
}
});
};
R.ready(function() {
if (R.authenticated()) {
whenAuthenticated();
} else {
var handler = function(authenticated) {
if (authenticated) {
R.off('change:authenticated', handler);
whenAuthenticated();
}
};
R.on('change:authenticated', handler);
}
});
};
// ----------
CollectionTracker.prototype = {
// ----------
at: function(index) {
return this._albums[index];
},
// ----------
_startLoad: function() {
log('_startLoad');
this._start = 0;
this._newAlbums = [];
this._newAlbumsByKey = {};
this._loading = {};
if (this._firstTime) {
this._count = 100;
this._extras = this._bigExtras + ',albumKey,rawArtistKey';
} else {
this._count = 1000;
this._extras = '-*,albumKey';
}
this._load();
},
// ----------
_load: function() {
log('_load');
var self = this;
assert(this._loading, '_loading must exist');
assert(!this._loading.request, '_loading.request must not exist');
this._loading.request = R.request({
method: "getAlbumsInCollection",
content: {
user: R.currentUser.get("key"),
start: this._start,
count: this._count,
extras: this._extras,
sort: 'playCount'
},
success: function(data) {
self._loading.request = null;
if (data.result.length) {
var album;
for (var i = 0; i < data.result.length; i++) {
album = data.result[i];
album.key = album.albumKey;
delete album.albumKey;
album.artistKey = album.rawArtistKey;
delete album.rawArtistKey;
self._newAlbums.push(album);
self._newAlbumsByKey[album.key] = album;
}
if (self._firstTime && self._config.onAlbumsLoaded) {
self._config.onAlbumsLoaded(data.result);
}
}
if (data.result.length == self._count) {
self._start += self._count;
self._load();
} else {
var addedKeys = [];
var removedKeys = [];
if (self._firstTime) {
self._albums = self._newAlbums;
self._albumsByKey = self._newAlbumsByKey;
} else {
var key;
// Added
for (key in self._newAlbumsByKey) {
if (!self._albumsByKey[key]) {
addedKeys.push(key);
}
}
// Removed
for (key in self._albumsByKey) {
if (!self._newAlbumsByKey[key]) {
removedKeys.push(key);
}
}
// Grab full data for added albums
if (addedKeys.length) {
self._getAlbums(addedKeys, function(addedAlbums) {
self._finishLoad(addedAlbums, removedKeys);
});
return;
}
}
self._finishLoad([], removedKeys);
}
},
error: function(data) {
log('_load error: ' + data.status);
self._loading.request = null;
if (data.status != 'abort' && self._config.onError) {
self._config.onError(data.message);
}
self._loadingDone();
}
});
},
// ----------
_getAlbums: function(keys, callback) {
log('_getAlbums');
var self = this;
assert(this._loading, '_loading must exist');
assert(!this._loading.request, '_loading.request must not exist');
var chunkSize = 200;
var keysChunk = keys.slice(0, chunkSize);
var keysRemainder = keys.slice(chunkSize);
this._loading.request = R.request({
method: "get",
content: {
keys: keysChunk.join(','),
extras: this._bigExtras + ',key,artistKey'
},
success: function(data) {
self._loading.request = null;
var addedAlbums = [];
var album;
for (var key in data.result) {
album = data.result[key];
addedAlbums.push(album);
}
if (keysRemainder.length) {
self._getAlbums(keysRemainder, function(moreAddedAlbums) {
callback(addedAlbums.concat(moreAddedAlbums));
});
} else {
callback(addedAlbums);
}
},
error: function(data) {
log('_getAlbums error: ' + data.status);
self._loading.request = null;
if (data.status != 'abort' && self._config.onError) {
self._config.onError(data.message);
}
self._loadingDone();
}
});
},
// ----------
_finishLoad: function(addedAlbums, removedKeys) {
var i;
// Actually remove
var removedAlbums = [];
var key;
for (i = 0; i < removedKeys.length; i++) {
key = removedKeys[i];
removedAlbums.push(this._albumsByKey[key]);
delete this._albumsByKey[key];
for (var j = 0; j < this._albums.length; j++) {
if (this._albums[j].key == key) {
this._albums.splice(j, 1);
break;
}
}
}
// Actually add
var album;
for (i = 0; i < addedAlbums.length; i++) {
album = addedAlbums[i];
this._albums.push(album);
this._albumsByKey[album.key] = album;
}
// Finish up
var wasFirstTime = this._firstTime;
this._newAlbums = [];
this._newAlbumsByKey = {};
this.length = this._albums.length;
this._firstTime = false;
this._save();
// Send events
if (wasFirstTime && this._config.onLoadComplete) {
this._config.onLoadComplete();
}
if (addedAlbums.length && this._config.onAdded) {
this._config.onAdded(addedAlbums);
}
if (removedAlbums.length && this._config.onRemoved) {
this._config.onRemoved(removedAlbums);
}
// Final cleanup
this._loadingDone();
},
// ----------
_loadingDone: function() {
assert(this._loading, '_loading must exist');
assert(!this._loading.request, '_loading.request must not exist');
var loadAgain = this._loading.loadAgain;
this._loading = null;
if (loadAgain) {
this._startLoad();
}
},
// ----------
_save: function() {
if (!this._config.localStorage) {
return;
}
var data = JSON.stringify(this._albums);
localStorage.__rdioUtilsCollectionAlbums = data;
localStorage.__rdioUtilsCollectionVersion = R.currentUser.get('libraryVersion');
}
};
})(window.__rdio); |
'use strict';
export class NavbarComponent {
constructor(Auth) {
'ngInject';
this.isLoggedIn = Auth.isLoggedInSync;
this.isAdmin = Auth.isAdminSync;
this.getCurrentUser = Auth.getCurrentUserSync;
}
}
export default angular.module('directives.navbar', [])
.component('navbar', {
template: require('./navbar.html'),
controller: NavbarComponent
})
.name;
|
var undef;
console.log("Undefined: " + typeof undef);
var nil = null;
console.log ("Null: " + typeof nil);
|
import List from './list';
import React from 'react';
export default class ChannelSwitcher extends React.Component {
getHomeChannelClassName() {
return `account-channel ${this.getHomeChannelSelected() ? ' account-channel-selected' : ''}`;
}
getHomeChannelSelected() {
return this.props.channelId === 'HOME_TIMELINE_CHANNEL';
}
getSearchChannelClassName() {
return `account-channel ${this.getSearchChannelSelected() ? ' account-channel-selected' : ''}`;
}
getSearchChannelSelected() {
return this.props.channelId === 'SEARCH_CHANNEL';
}
onHomeChannelClicked(event) {
this.props.onChannelClicked('HOME_TIMELINE_CHANNEL');
}
onSearchChannelClicked(event) {
this.props.onChannelClicked('SEARCH_CHANNEL');
}
render() {
return(
<div className="channel-switcher">
<div className="account-screen-name">
@{this.props.account.screen_name}
</div>
<div className="account-section">
<h3 className="account-section-heading">
TIMELINES
</h3>
<ul>
<li className={this.getHomeChannelClassName()} onClick={this.onHomeChannelClicked.bind(this)}>
Home
</li>
<li className={this.getSearchChannelClassName()} onClick={this.onSearchChannelClicked.bind(this)}>
Search
</li>
</ul>
</div>
<div className="account-section">
<h3 className="account-section-heading">
LISTS
</h3>
<ul>
{this.renderLists()}
</ul>
</div>
</div>
);
}
renderLists() {
return this.props.lists.map((list) => {
return <List channelId={this.props.channelId} key={list.id_str} list={list} onChannelClicked={this.props.onChannelClicked} />;
});
}
}
|
import * as ReactNative from "react-native";
function getString(prim) {
return ReactNative.Clipboard.getString();
}
function setString(prim) {
ReactNative.Clipboard.setString(prim);
return /* () */0;
}
export {
getString ,
setString ,
}
/* react-native Not a pure module */
|
search_result['3173']=["topic_000000000000079D_attached_props--.html","AddVideoCommand Attached Properties",""]; |
//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License.
MooTools.More={version:"1.2.3.1"};var Log=new Class({log:function(){Log.logger.call(this,arguments);}});Log.logged=[];Log.logger=function(){if(window.console&&console.log){console.log.apply(console,arguments);
}else{Log.logged.push(arguments);}};Class.refactor=function(b,a){$each(a,function(e,d){var c=b.prototype[d];if(c&&(c=c._origin)&&typeof e=="function"){b.implement(d,function(){var f=this.previous;
this.previous=c;var g=e.apply(this,arguments);this.previous=f;return g;});}else{b.implement(d,e);}});return b;};(function(){var b={wait:function(c){return this.chain(function(){this.callChain.delay($pick(c,500),this);
}.bind(this));}};Chain.implement(b);if(window.Fx){Fx.implement(b);["Css","Tween","Elements"].each(function(c){if(Fx[c]){Fx[c].implement(b);}});}try{Element.implement({chains:function(c){$splat($pick(c,["tween","morph","reveal"])).each(function(d){d=this.get(d);
if(!d){return;}d.setOptions({link:"chain"});},this);return this;},pauseFx:function(d,c){this.chains(c).get($pick(c,"tween")).wait(d);return this;}});}catch(a){}})();
Element.implement({measure:function(e){var g=function(h){return !!(!h||h.offsetHeight||h.offsetWidth);};if(g(this)){return e.apply(this);}var d=this.getParent(),b=[],f=[];
while(!g(d)&&d!=document.body){b.push(d.expose());d=d.getParent();}var c=this.expose();var a=e.apply(this);c();b.each(function(h){h();});return a;},expose:function(){if(this.getStyle("display")!="none"){return $empty;
}var a=this.style.cssText;this.setStyles({display:"block",position:"absolute",visibility:"hidden"});return function(){this.style.cssText=a;}.bind(this);
},getDimensions:function(a){a=$merge({computeSize:false},a);var d={};var c=function(f,e){return(e.computeSize)?f.getComputedSize(e):f.getSize();};if(this.getStyle("display")=="none"){d=this.measure(function(){return c(this,a);
});}else{try{d=c(this,a);}catch(b){}}return $chk(d.x)?$extend(d,{width:d.x,height:d.y}):$extend(d,{x:d.width,y:d.height});},getComputedSize:function(a){a=$merge({styles:["padding","border"],plains:{height:["top","bottom"],width:["left","right"]},mode:"both"},a);
var c={width:0,height:0};switch(a.mode){case"vertical":delete c.width;delete a.plains.width;break;case"horizontal":delete c.height;delete a.plains.height;
break;}var b=[];$each(a.plains,function(g,f){g.each(function(h){a.styles.each(function(i){b.push((i=="border")?i+"-"+h+"-width":i+"-"+h);});});});var e={};
b.each(function(f){e[f]=this.getComputedStyle(f);},this);var d=[];$each(a.plains,function(g,f){var h=f.capitalize();c["total"+h]=0;c["computed"+h]=0;g.each(function(i){c["computed"+i.capitalize()]=0;
b.each(function(k,j){if(k.test(i)){e[k]=e[k].toInt()||0;c["total"+h]=c["total"+h]+e[k];c["computed"+i.capitalize()]=c["computed"+i.capitalize()]+e[k];}if(k.test(i)&&f!=k&&(k.test("border")||k.test("padding"))&&!d.contains(k)){d.push(k);
c["computed"+h]=c["computed"+h]-e[k];}});});});["Width","Height"].each(function(g){var f=g.toLowerCase();if(!$chk(c[f])){return;}c[f]=c[f]+this["offset"+g]+c["computed"+g];
c["total"+g]=c[f]+c["total"+g];delete c["computed"+g];},this);return $extend(e,c);}});(function(){var a=Element.prototype.position;Element.implement({position:function(r){if(r&&($defined(r.x)||$defined(r.y))){return a?a.apply(this,arguments):this;
}$each(r||{},function(t,s){if(!$defined(t)){delete r[s];}});r=$merge({relativeTo:document.body,position:{x:"center",y:"center"},edge:false,offset:{x:0,y:0},returnPos:false,relFixedPosition:false,ignoreMargins:false,allowNegative:false},r);
var b={x:0,y:0};var h=false;var c=this.measure(function(){return document.id(this.getOffsetParent());});if(c&&c!=this.getDocument().body){b=c.measure(function(){return this.getPosition();
});h=true;r.offset.x=r.offset.x-b.x;r.offset.y=r.offset.y-b.y;}var q=function(s){if($type(s)!="string"){return s;}s=s.toLowerCase();var t={};if(s.test("left")){t.x="left";
}else{if(s.test("right")){t.x="right";}else{t.x="center";}}if(s.test("upper")||s.test("top")){t.y="top";}else{if(s.test("bottom")){t.y="bottom";}else{t.y="center";
}}return t;};r.edge=q(r.edge);r.position=q(r.position);if(!r.edge){if(r.position.x=="center"&&r.position.y=="center"){r.edge={x:"center",y:"center"};}else{r.edge={x:"left",y:"top"};
}}this.setStyle("position","absolute");var p=document.id(r.relativeTo)||document.body;var i=p==document.body?window.getScroll():p.getPosition();var o=i.y;
var g=i.x;if(Browser.Engine.trident){var l=p.getScrolls();o+=l.y;g+=l.x;}var j=this.getDimensions({computeSize:true,styles:["padding","border","margin"]});
if(r.ignoreMargins){r.offset.x=r.offset.x-j["margin-left"];r.offset.y=r.offset.y-j["margin-top"];}var n={};var d=r.offset.y;var e=r.offset.x;var k=window.getSize();
switch(r.position.x){case"left":n.x=g+e;break;case"right":n.x=g+e+p.offsetWidth;break;default:n.x=g+((p==document.body?k.x:p.offsetWidth)/2)+e;break;}switch(r.position.y){case"top":n.y=o+d;
break;case"bottom":n.y=o+d+p.offsetHeight;break;default:n.y=o+((p==document.body?k.y:p.offsetHeight)/2)+d;break;}if(r.edge){var m={};switch(r.edge.x){case"left":m.x=0;
break;case"right":m.x=-j.x-j.computedRight-j.computedLeft;break;default:m.x=-(j.x/2);break;}switch(r.edge.y){case"top":m.y=0;break;case"bottom":m.y=-j.y-j.computedTop-j.computedBottom;
break;default:m.y=-(j.y/2);break;}n.x=n.x+m.x;n.y=n.y+m.y;}n={left:((n.x>=0||h||r.allowNegative)?n.x:0).toInt(),top:((n.y>=0||h||r.allowNegative)?n.y:0).toInt()};
if(p.getStyle("position")=="fixed"||r.relFixedPosition){var f=window.getScroll();n.top=n.top.toInt()+f.y;n.left=n.left.toInt()+f.x;}if(r.returnPos){return n;
}else{this.setStyles(n);}return this;}});})();Element.implement({isDisplayed:function(){return this.getStyle("display")!="none";},toggle:function(){return this[this.isDisplayed()?"hide":"show"]();
},hide:function(){var b;try{if("none"!=this.getStyle("display")){b=this.getStyle("display");}}catch(a){}return this.store("originalDisplay",b||"block").setStyle("display","none");
},show:function(a){return this.setStyle("display",a||this.retrieve("originalDisplay")||"block");},swapClass:function(a,b){return this.removeClass(a).addClass(b);
}});Fx.Elements=new Class({Extends:Fx.CSS,initialize:function(b,a){this.elements=this.subject=$$(b);this.parent(a);},compute:function(g,h,j){var c={};for(var d in g){var a=g[d],e=h[d],f=c[d]={};
for(var b in a){f[b]=this.parent(a[b],e[b],j);}}return c;},set:function(b){for(var c in b){var a=b[c];for(var d in a){this.render(this.elements[c],d,a[d],this.options.unit);
}}return this;},start:function(c){if(!this.check(c)){return this;}var h={},j={};for(var d in c){var f=c[d],a=h[d]={},g=j[d]={};for(var b in f){var e=this.prepare(this.elements[d],b,f[b]);
a[b]=e.from;g[b]=e.to;}}return this.parent(h,j);}});Fx.Move=new Class({Extends:Fx.Morph,options:{relativeTo:document.body,position:"center",edge:false,offset:{x:0,y:0}},start:function(a){return this.parent(this.element.position($merge(this.options,a,{returnPos:true})));
}});Element.Properties.move={set:function(a){var b=this.retrieve("move");if(b){b.cancel();}return this.eliminate("move").store("move:options",$extend({link:"cancel"},a));
},get:function(a){if(a||!this.retrieve("move")){if(a||!this.retrieve("move:options")){this.set("move",a);}this.store("move",new Fx.Move(this,this.retrieve("move:options")));
}return this.retrieve("move");}};Element.implement({move:function(a){this.get("move").start(a);return this;}});Fx.Reveal=new Class({Extends:Fx.Morph,options:{styles:["padding","border","margin"],transitionOpacity:!Browser.Engine.trident4,mode:"vertical",display:"block",hideInputs:Browser.Engine.trident?"select, input, textarea, object, embed":false},dissolve:function(){try{if(!this.hiding&&!this.showing){if(this.element.getStyle("display")!="none"){this.hiding=true;
this.showing=false;this.hidden=true;var d=this.element.getComputedSize({styles:this.options.styles,mode:this.options.mode});var g=(this.element.style.height===""||this.element.style.height=="auto");
this.element.setStyle("display","block");if(this.options.transitionOpacity){d.opacity=1;}var b={};$each(d,function(h,e){b[e]=[h,0];},this);var f=this.element.getStyle("overflow");
this.element.setStyle("overflow","hidden");var a=this.options.hideInputs?this.element.getElements(this.options.hideInputs):null;this.$chain.unshift(function(){if(this.hidden){this.hiding=false;
$each(d,function(h,e){d[e]=h;},this);this.element.setStyles($merge({display:"none",overflow:f},d));if(g){if(["vertical","both"].contains(this.options.mode)){this.element.style.height="";
}if(["width","both"].contains(this.options.mode)){this.element.style.width="";}}if(a){a.setStyle("visibility","visible");}}this.fireEvent("hide",this.element);
this.callChain();}.bind(this));if(a){a.setStyle("visibility","hidden");}this.start(b);}else{this.callChain.delay(10,this);this.fireEvent("complete",this.element);
this.fireEvent("hide",this.element);}}else{if(this.options.link=="chain"){this.chain(this.dissolve.bind(this));}else{if(this.options.link=="cancel"&&!this.hiding){this.cancel();
this.dissolve();}}}}catch(c){this.hiding=false;this.element.setStyle("display","none");this.callChain.delay(10,this);this.fireEvent("complete",this.element);
this.fireEvent("hide",this.element);}return this;},reveal:function(){try{if(!this.showing&&!this.hiding){if(this.element.getStyle("display")=="none"||this.element.getStyle("visiblity")=="hidden"||this.element.getStyle("opacity")==0){this.showing=true;
this.hiding=false;this.hidden=false;var g,d;this.element.measure(function(){g=(this.element.style.height===""||this.element.style.height=="auto");d=this.element.getComputedSize({styles:this.options.styles,mode:this.options.mode});
}.bind(this));$each(d,function(h,e){d[e]=h;});if($chk(this.options.heightOverride)){d.height=this.options.heightOverride.toInt();}if($chk(this.options.widthOverride)){d.width=this.options.widthOverride.toInt();
}if(this.options.transitionOpacity){this.element.setStyle("opacity",0);d.opacity=1;}var b={height:0,display:this.options.display};$each(d,function(h,e){b[e]=0;
});var f=this.element.getStyle("overflow");this.element.setStyles($merge(b,{overflow:"hidden"}));var a=this.options.hideInputs?this.element.getElements(this.options.hideInputs):null;
if(a){a.setStyle("visibility","hidden");}this.start(d);this.$chain.unshift(function(){this.element.setStyle("overflow",f);if(!this.options.heightOverride&&g){if(["vertical","both"].contains(this.options.mode)){this.element.style.height="";
}if(["width","both"].contains(this.options.mode)){this.element.style.width="";}}if(!this.hidden){this.showing=false;}if(a){a.setStyle("visibility","visible");
}this.callChain();this.fireEvent("show",this.element);}.bind(this));}else{this.callChain();this.fireEvent("complete",this.element);this.fireEvent("show",this.element);
}}else{if(this.options.link=="chain"){this.chain(this.reveal.bind(this));}else{if(this.options.link=="cancel"&&!this.showing){this.cancel();this.reveal();
}}}}catch(c){this.element.setStyles({display:this.options.display,visiblity:"visible",opacity:1});this.showing=false;this.callChain.delay(10,this);this.fireEvent("complete",this.element);
this.fireEvent("show",this.element);}return this;},toggle:function(){if(this.element.getStyle("display")=="none"||this.element.getStyle("visiblity")=="hidden"||this.element.getStyle("opacity")==0){this.reveal();
}else{this.dissolve();}return this;}});Element.Properties.reveal={set:function(a){var b=this.retrieve("reveal");if(b){b.cancel();}return this.eliminate("reveal").store("reveal:options",$extend({link:"cancel"},a));
},get:function(a){if(a||!this.retrieve("reveal")){if(a||!this.retrieve("reveal:options")){this.set("reveal",a);}this.store("reveal",new Fx.Reveal(this,this.retrieve("reveal:options")));
}return this.retrieve("reveal");}};Element.Properties.dissolve=Element.Properties.reveal;Element.implement({reveal:function(a){this.get("reveal",a).reveal();
return this;},dissolve:function(a){this.get("reveal",a).dissolve();return this;},nix:function(){var a=Array.link(arguments,{destroy:Boolean.type,options:Object.type});
this.get("reveal",a.options).dissolve().chain(function(){this[a.destroy?"destroy":"dispose"]();}.bind(this));return this;},wink:function(){var b=Array.link(arguments,{duration:Number.type,options:Object.type});
var a=this.get("reveal",b.options);a.reveal().chain(function(){(function(){a.dissolve();}).delay(b.duration||2000);});}});Fx.Sort=new Class({Extends:Fx.Elements,options:{mode:"vertical"},initialize:function(b,a){this.parent(b,a);
this.elements.each(function(c){if(c.getStyle("position")=="static"){c.setStyle("position","relative");}});this.setDefaultOrder();},setDefaultOrder:function(){this.currentOrder=this.elements.map(function(b,a){return a;
});},sort:function(e){if($type(e)!="array"){return false;}var i=0;var a=0;var h={};var d=this.options.mode=="vertical";var f=this.elements.map(function(m,j){var l=m.getComputedSize({styles:["border","padding","margin"]});
var n;if(d){n={top:i,margin:l["margin-top"],height:l.totalHeight};i+=n.height-l["margin-top"];}else{n={left:a,margin:l["margin-left"],width:l.totalWidth};
a+=n.width;}var k=d?"top":"left";h[j]={};var o=m.getStyle(k).toInt();h[j][k]=o||0;return n;},this);this.set(h);e=e.map(function(j){return j.toInt();});
if(e.length!=this.elements.length){this.currentOrder.each(function(j){if(!e.contains(j)){e.push(j);}});if(e.length>this.elements.length){e.splice(this.elements.length-1,e.length-this.elements.length);
}}i=0;a=0;var b=0;var c={};e.each(function(l,j){var k={};if(d){k.top=i-f[l].top-b;i+=f[l].height;}else{k.left=a-f[l].left;a+=f[l].width;}b=b+f[l].margin;
c[l]=k;},this);var g={};$A(e).sort().each(function(j){g[j]=c[j];});this.start(g);this.currentOrder=e;return this;},rearrangeDOM:function(a){a=a||this.currentOrder;
var b=this.elements[0].getParent();var c=[];this.elements.setStyle("opacity",0);a.each(function(d){c.push(this.elements[d].inject(b).setStyles({top:0,left:0}));
},this);this.elements.setStyle("opacity",1);this.elements=$$(c);this.setDefaultOrder();return this;},getDefaultOrder:function(){return this.elements.map(function(b,a){return a;
});},forward:function(){return this.sort(this.getDefaultOrder());},backward:function(){return this.sort(this.getDefaultOrder().reverse());},reverse:function(){return this.sort(this.currentOrder.reverse());
},sortByElements:function(a){return this.sort(a.map(function(b){return this.elements.indexOf(b);},this));},swap:function(c,b){if($type(c)=="element"){c=this.elements.indexOf(c);
}if($type(b)=="element"){b=this.elements.indexOf(b);}var a=$A(this.currentOrder);a[this.currentOrder.indexOf(c)]=b;a[this.currentOrder.indexOf(b)]=c;this.sort(a);
}});var Drag=new Class({Implements:[Events,Options],options:{snap:6,unit:"px",grid:false,style:true,limit:false,handle:false,invert:false,preventDefault:false,modifiers:{x:"left",y:"top"}},initialize:function(){var b=Array.link(arguments,{options:Object.type,element:$defined});
this.element=document.id(b.element);this.document=this.element.getDocument();this.setOptions(b.options||{});var a=$type(this.options.handle);this.handles=((a=="array"||a=="collection")?$$(this.options.handle):document.id(this.options.handle))||this.element;
this.mouse={now:{},pos:{}};this.value={start:{},now:{}};this.selection=(Browser.Engine.trident)?"selectstart":"mousedown";this.bound={start:this.start.bind(this),check:this.check.bind(this),drag:this.drag.bind(this),stop:this.stop.bind(this),cancel:this.cancel.bind(this),eventStop:$lambda(false)};
this.attach();},attach:function(){this.handles.addEvent("mousedown",this.bound.start);return this;},detach:function(){this.handles.removeEvent("mousedown",this.bound.start);
return this;},start:function(c){if(this.options.preventDefault){c.preventDefault();}this.mouse.start=c.page;this.fireEvent("beforeStart",this.element);
var a=this.options.limit;this.limit={x:[],y:[]};for(var d in this.options.modifiers){if(!this.options.modifiers[d]){continue;}if(this.options.style){this.value.now[d]=this.element.getStyle(this.options.modifiers[d]).toInt();
}else{this.value.now[d]=this.element[this.options.modifiers[d]];}if(this.options.invert){this.value.now[d]*=-1;}this.mouse.pos[d]=c.page[d]-this.value.now[d];
if(a&&a[d]){for(var b=2;b--;b){if($chk(a[d][b])){this.limit[d][b]=$lambda(a[d][b])();}}}}if($type(this.options.grid)=="number"){this.options.grid={x:this.options.grid,y:this.options.grid};
}this.document.addEvents({mousemove:this.bound.check,mouseup:this.bound.cancel});this.document.addEvent(this.selection,this.bound.eventStop);},check:function(a){if(this.options.preventDefault){a.preventDefault();
}var b=Math.round(Math.sqrt(Math.pow(a.page.x-this.mouse.start.x,2)+Math.pow(a.page.y-this.mouse.start.y,2)));if(b>this.options.snap){this.cancel();this.document.addEvents({mousemove:this.bound.drag,mouseup:this.bound.stop});
this.fireEvent("start",[this.element,a]).fireEvent("snap",this.element);}},drag:function(a){if(this.options.preventDefault){a.preventDefault();}this.mouse.now=a.page;
for(var b in this.options.modifiers){if(!this.options.modifiers[b]){continue;}this.value.now[b]=this.mouse.now[b]-this.mouse.pos[b];if(this.options.invert){this.value.now[b]*=-1;
}if(this.options.limit&&this.limit[b]){if($chk(this.limit[b][1])&&(this.value.now[b]>this.limit[b][1])){this.value.now[b]=this.limit[b][1];}else{if($chk(this.limit[b][0])&&(this.value.now[b]<this.limit[b][0])){this.value.now[b]=this.limit[b][0];
}}}if(this.options.grid[b]){this.value.now[b]-=((this.value.now[b]-(this.limit[b][0]||0))%this.options.grid[b]);}if(this.options.style){this.element.setStyle(this.options.modifiers[b],this.value.now[b]+this.options.unit);
}else{this.element[this.options.modifiers[b]]=this.value.now[b];}}this.fireEvent("drag",[this.element,a]);},cancel:function(a){this.document.removeEvent("mousemove",this.bound.check);
this.document.removeEvent("mouseup",this.bound.cancel);if(a){this.document.removeEvent(this.selection,this.bound.eventStop);this.fireEvent("cancel",this.element);
}},stop:function(a){this.document.removeEvent(this.selection,this.bound.eventStop);this.document.removeEvent("mousemove",this.bound.drag);this.document.removeEvent("mouseup",this.bound.stop);
if(a){this.fireEvent("complete",[this.element,a]);}}});Element.implement({makeResizable:function(a){var b=new Drag(this,$merge({modifiers:{x:"width",y:"height"}},a));
this.store("resizer",b);return b.addEvent("drag",function(){this.fireEvent("resize",b);}.bind(this));}});Drag.Move=new Class({Extends:Drag,options:{droppables:[],container:false,precalculate:false,includeMargins:true,checkDroppables:true},initialize:function(c,b){this.parent(c,b);
this.droppables=$$(this.options.droppables);this.container=document.id(this.options.container);if(this.container&&$type(this.container)!="element"){this.container=document.id(this.container.getDocument().body);
}var a=this.element.getStyle("position");if(a=="static"){a="absolute";}if([this.element.getStyle("left"),this.element.getStyle("top")].contains("auto")){this.element.position(this.element.getPosition(this.element.offsetParent));
}this.element.setStyle("position",a);this.addEvent("start",this.checkDroppables,true);this.overed=null;},start:function(f){if(this.container){var b=this.container.getCoordinates(this.element.getOffsetParent()),c={},e={};
["top","right","bottom","left"].each(function(g){c[g]=this.container.getStyle("border-"+g).toInt();e[g]=this.element.getStyle("margin-"+g).toInt();},this);
var d=this.element.offsetWidth+e.left+e.right;var a=this.element.offsetHeight+e.top+e.bottom;if(this.options.includeMargins){$each(e,function(h,g){e[g]=0;
});}if(this.container==this.element.getOffsetParent()){this.options.limit={x:[0-e.left,b.right-c.left-c.right-d+e.right],y:[0-e.top,b.bottom-c.top-c.bottom-a+e.bottom]};
}else{this.options.limit={x:[b.left+c.left-e.left,b.right-c.right-d+e.right],y:[b.top+c.top-e.top,b.bottom-c.bottom-a+e.bottom]};}}if(this.options.precalculate){this.positions=this.droppables.map(function(g){return g.getCoordinates();
});}this.parent(f);},checkAgainst:function(c,b){c=(this.positions)?this.positions[b]:c.getCoordinates();var a=this.mouse.now;return(a.x>c.left&&a.x<c.right&&a.y<c.bottom&&a.y>c.top);
},checkDroppables:function(){var a=this.droppables.filter(this.checkAgainst,this).getLast();if(this.overed!=a){if(this.overed){this.fireEvent("leave",[this.element,this.overed]);
}if(a){this.fireEvent("enter",[this.element,a]);}this.overed=a;}},drag:function(a){this.parent(a);if(this.options.checkDroppables&&this.droppables.length){this.checkDroppables();
}},stop:function(a){this.checkDroppables();this.fireEvent("drop",[this.element,this.overed,a]);this.overed=null;return this.parent(a);}});Element.implement({makeDraggable:function(a){var b=new Drag.Move(this,a);
this.store("dragger",b);return b;}});var Sortables=new Class({Implements:[Events,Options],options:{snap:4,opacity:1,clone:false,revert:false,handle:false,constrain:false},initialize:function(a,b){this.setOptions(b);
this.elements=[];this.lists=[];this.idle=true;this.addLists($$(document.id(a)||a));if(!this.options.clone){this.options.revert=false;}if(this.options.revert){this.effect=new Fx.Morph(null,$merge({duration:250,link:"cancel"},this.options.revert));
}},attach:function(){this.addLists(this.lists);return this;},detach:function(){this.lists=this.removeLists(this.lists);return this;},addItems:function(){Array.flatten(arguments).each(function(a){this.elements.push(a);
var b=a.retrieve("sortables:start",this.start.bindWithEvent(this,a));(this.options.handle?a.getElement(this.options.handle)||a:a).addEvent("mousedown",b);
},this);return this;},addLists:function(){Array.flatten(arguments).each(function(a){this.lists.push(a);this.addItems(a.getChildren());},this);return this;
},removeItems:function(){return $$(Array.flatten(arguments).map(function(a){this.elements.erase(a);var b=a.retrieve("sortables:start");(this.options.handle?a.getElement(this.options.handle)||a:a).removeEvent("mousedown",b);
return a;},this));},removeLists:function(){return $$(Array.flatten(arguments).map(function(a){this.lists.erase(a);this.removeItems(a.getChildren());return a;
},this));},getClone:function(b,a){if(!this.options.clone){return new Element("div").inject(document.body);}if($type(this.options.clone)=="function"){return this.options.clone.call(this,b,a,this.list);
}return a.clone(true).setStyles({margin:"0px",position:"absolute",visibility:"hidden",width:a.getStyle("width")}).inject(this.list).position(a.getPosition(a.getOffsetParent()));
},getDroppables:function(){var a=this.list.getChildren();if(!this.options.constrain){a=this.lists.concat(a).erase(this.list);}return a.erase(this.clone).erase(this.element);
},insert:function(c,b){var a="inside";if(this.lists.contains(b)){this.list=b;this.drag.droppables=this.getDroppables();}else{a=this.element.getAllPrevious().contains(b)?"before":"after";
}this.element.inject(b,a);this.fireEvent("sort",[this.element,this.clone]);},start:function(b,a){if(!this.idle){return;}this.idle=false;this.element=a;
this.opacity=a.get("opacity");this.list=a.getParent();this.clone=this.getClone(b,a);this.drag=new Drag.Move(this.clone,{snap:this.options.snap,container:this.options.constrain&&this.element.getParent(),droppables:this.getDroppables(),onSnap:function(){b.stop();
this.clone.setStyle("visibility","visible");this.element.set("opacity",this.options.opacity||0);this.fireEvent("start",[this.element,this.clone]);}.bind(this),onEnter:this.insert.bind(this),onCancel:this.reset.bind(this),onComplete:this.end.bind(this)});
this.clone.inject(this.element,"before");this.drag.start(b);},end:function(){this.drag.detach();this.element.set("opacity",this.opacity);if(this.effect){var a=this.element.getStyles("width","height");
var b=this.clone.computePosition(this.element.getPosition(this.clone.offsetParent));this.effect.element=this.clone;this.effect.start({top:b.top,left:b.left,width:a.width,height:a.height,opacity:0.25}).chain(this.reset.bind(this));
}else{this.reset();}},reset:function(){this.idle=true;this.clone.destroy();this.fireEvent("complete",this.element);},serialize:function(){var c=Array.link(arguments,{modifier:Function.type,index:$defined});
var b=this.lists.map(function(d){return d.getChildren().map(c.modifier||function(e){return e.get("id");},this);},this);var a=c.index;if(this.lists.length==1){a=0;
}return $chk(a)&&a>=0&&a<this.lists.length?b[a]:b;}});Request.implement({options:{initialDelay:5000,delay:5000,limit:60000},startTimer:function(b){var a=(function(){if(!this.running){this.send({data:b});
}});this.timer=a.delay(this.options.initialDelay,this);this.lastDelay=this.options.initialDelay;this.completeCheck=function(c){$clear(this.timer);if(c){this.lastDelay=this.options.delay;
}else{this.lastDelay=(this.lastDelay+this.options.delay).min(this.options.limit);}this.timer=a.delay(this.lastDelay,this);};this.addEvent("complete",this.completeCheck);
return this;},stopTimer:function(){$clear(this.timer);this.removeEvent("complete",this.completeCheck);return this;}}); |
const findLayoutDirectories = require('prefab/MaxBucknell_Prefab/lib/find-layout-directories');
const glob = require('glob');
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const magentoData = require('prefab/MaxBucknell_Prefab/lib/magento-data');
const cssPattern = /<css\s+src="([^"]+)\.css"/;
const removePattern = /<remove\s+src="([^"]+)\.css"/;
function getGlobs () {
return _.map(
findLayoutDirectories(),
(directory) => `${directory}/*.xml`
)
}
function findLessFiles()
{
const files = _.flatMap(
getGlobs(),
(g) => glob.sync(g)
);
const contents = _.map(
files,
(file) => fs.readFileSync(file, { encoding: 'utf-8' })
).join('\n');
const cssDeclarations = _.map(
contents.match(new RegExp(cssPattern, 'g')),
(match) => match.match(cssPattern)[1]
);
const removeDeclarations = _.map(
contents.match(new RegExp(removePattern, 'g')),
(match) => match.match(removePattern)[1]
);
const stylesheets = _.difference(
cssDeclarations,
removeDeclarations
);
const existingStylesheets = _.filter(
stylesheets,
(stylesheet) => fs.existsSync(path.join(magentoData.build_dir, 'flat/static', `${stylesheet}.less`))
);
return existingStylesheets;
}
module.exports = findLessFiles; |
var OdysseusLimiter = require('../index');
var express = require('express');
var request = require('supertest');
describe('limit', function(){
var app;
beforeEach(function(){
app = express();
});
describe('defaults', function(){
it('key should be general', (done) => {
app.use(OdysseusLimiter.limit({
amount: 2,
ttl: 100
}));
app.get('/', function(req, res, next){
res.status(200).json({status: 'ok'});
});
request(app)
.get('/?key=general')
.expect(200, function () {
request(app)
.get('/?key=general1')
.expect(200, function () {
request(app)
.get('/?key=general2')
.expect(429, done);
});
});
});
});
}); |
import Note from './Note'
export default Note
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.