code
stringlengths
2
1.05M
$('#new-orders-button').click(function(){ $('#orders-pane').find('div').remove(); $.ajax({ type: 'POST', url: "http://localhost/3k/orders/app/getNewOrders", //data: {activitiesArray : pass_order}, dataType: 'json' }).done(function(response) { $.each(response, function(){ $.each(this, function(){ $('#orders-title').text(this.status+" Orders"); $('#orders-pane').append('<div class="row"> <div class="col-sm-2">'+this.datecreated+'</div>'+'<div class="col-sm-8">'+this.customer_order+'</div>'+'<div class="col-sm-2"><i class="fa fa-check" data-id="'+this.id+'"></i><i class="fa fa-remove" data-id="'+this.id+'"></i></div></div>'); //console.log(this.id); }); }); }); }); $('#old-orders-button').click(function(){ $('#orders-pane').find('div').remove(); $.ajax({ type: 'POST', url: "http://localhost/3k/orders/app/getOldOrders", //data: {activitiesArray : pass_order}, dataType: 'json' }).done(function(response) { $.each(response, function(){ $.each(this, function(){ $('#orders-title').text("Fulfilled Orders"); $('#orders-pane').append('<div class="row"> <div class="col-sm-2">'+this.datecreated+'</div>'+'<div class="col-sm-8">'+this.customer_order+'</div>'+'<div class="col-sm-2"><i class="fa fa-check" data-id="'+this.id+'"></i><i class="fa fa-remove" data-id="'+this.id+'"></i><i class="fa fa-undo" data-id="'+this.id+'"></i></div></div>'); //console.log(this.id); }); }); }); }); $('#orders-pane').on("click", ".fa-check", function(){ //$(this).closest('.row').remove(); var order_line = $(this); var id = $(this).attr('data-id'); //console.log(id); //$(this).closest('.row').remove(); $.ajax({ type: 'POST', url: "http://localhost/3k/orders/app/fulfill/"+id, //data: {activitiesArray : pass_order}, dataType: 'json' }).done(function(response) { console.log(response); if (response == 'success'){ order_line.closest('.row').remove(); console.log('Order Fulfilled'); }else{ console.log('Error Processing Order'); }; }); }) $('#orders-pane').on("click", ".fa-remove", function(){ $(this).closest('.row').remove(); }) $('#orders-pane').on("click", ".fa-undo", function(){ $(this).closest('.row').remove(); var order_line = $(this); var id = $(this).attr('data-id'); //console.log(id); //$(this).closest('.row').remove(); $.ajax({ type: 'POST', url: "http://localhost/3k/orders/app/undo/"+id, //data: {activitiesArray : pass_order}, dataType: 'json' }).done(function(response) { console.log(response); if (response == 'success'){ order_line.closest('.row').remove(); console.log('Order Reversed'); }else{ console.log('Error Reversing Order'); }; }); })
/*********************************************************************** * Module: Transform Matrix * Description: * Author: Copyright 2012-2014, Tyler Beck * License: MIT ***********************************************************************/ define([ '../math/Matrix4x4', '../math/Vector4' ], function( M, V ){ /*================================================ * Helper Methods *===============================================*/ /** * converts almost 0 float values to true 0 * @param v * @returns {*} */ function floatZero( v ){ if (v == 0) { v = 0; } return v; } /** * converts degrees to radians * @param deg * @returns {number} */ function degToRad( deg ){ return deg * Math.PI / 180; } /** * true 0 cosine * @param a * @returns {*} */ function cos( a ){ return floatZero( Math.cos(a ) ); } /** * true 0 sine * @param a * @returns {*} */ function sin( a ){ return floatZero( Math.sin(a ) ); } /** * true 0 tangent * @param a * @returns {*} */ function tan( a ){ return floatZero( Math.tan(a ) ); } /*================================================ * Transform Constructor *===============================================*/ var TransformMatrix = function( v ){ this.init( v ); return this; }; /*================================================ * Transform Prototype *===============================================*/ TransformMatrix.prototype = { /** * initialize class * @param v */ init: function( v ){ this.value = M.identity(); if (v && v.length ){ var l = v.length; for (var i = 0; i < l; i++ ){ this.value[i] = v[i]; } } }, /** * applies translation * @param x * @param y * @param z * @returns {TransformMatrix} */ translate: function( x, y, z ){ var translation = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 ]; return new TransformMatrix( M.multiply( this.value, translation ) ); }, /** * applies scale * @param x * @param y * @param z * @returns {TransformMatrix} */ scale: function( x, y, z ){ var scaler = [ x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 ]; return new TransformMatrix( M.multiply( this.value, scaler ) ); }, /** * applies x axis rotation * @param a * @returns {TransformMatrix} */ rotateX: function( a ){ return this.rotate( 1, 0, 0, a ); }, /** * applies y axis rotation * @param a * @returns {TransformMatrix} */ rotateY: function( a ){ return this.rotate( 0, 1, 0, a ); }, /** * applies z axis rotation * @param a * @returns {TransformMatrix} */ rotateZ: function( a ){ return this.rotate( 0, 0, 1, a ); }, /** * applies vector rotation * @param x * @param y * @param z * @param a * @returns {TransformMatrix} */ rotate: function( x, y, z, a ){ var norm = ( new V( x, y, z ) ).normalize(); x = norm.x; y = norm.y; z = norm.z; var c = cos(a); var s = sin(a); var rotation = [ 1+(1-c)*(x*x-1), z*s+x*y*(1-c), -y*s+x*z*(1-c), 0, -z*s+x*y*(1-c), 1+(1-c)*(y*y-1), x*s+y*z*(1-c), 0, y*s+x*z*(1-c), -x*s+y*z*(1-c), 1+(1-c)*(z*z-1), 0, 0, 0, 0, 1 ]; return new TransformMatrix( M.multiply( this.value, rotation ) ); }, /** * applies x skew * @param a * @returns {TransformMatrix} */ skewX: function( a ){ var t = tan( a ); var skew = [ 1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; return new TransformMatrix( M.multiply( this.value, skew ) ); }, /** * applies y skew * @param a * @returns {TransformMatrix} */ skewY: function( a ){ var t = tan( a ); var skew = [ 1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; return new TransformMatrix( M.multiply( this.value, skew ) ); }, /** * decomposes transform into component parts * @returns {{}} */ decompose: function(){ var m = this.value; var i, j, p, perspective, translate, scale, skew, quaternion; // Normalize the matrix. if (m[15] == 0) return false; p = m[15]; for ( i=0; i<4; ++i ){ for ( j=0; j<4; ++j ){ m[i*4+j] /= p; } } // perspectiveMatrix is used to solve for perspective, but it also provides // an easy way to test for singularity of the upper 3x3 component. var perspectiveMatrix = m.slice(0); perspectiveMatrix[3] = 0; perspectiveMatrix[7] = 0; perspectiveMatrix[11] = 0; perspectiveMatrix[15] = 1; if ( M.determinant( perspectiveMatrix ) == 0){ return false; } //perspective. if (m[3] != 0 || m[7] != 0 || m[11] != 0) { // rightHandSide is the right hand side of the equation. var right = new V( m[3], m[7], m[11], m[15] ); var tranInvPers = M.transpose( M.inverse( perspectiveMatrix ) ); perspective = right.multiplyMatrix( tranInvPers ); } else{ perspective = new V(0,0,0,1); } //translation translate = new V( m[12], m[13], m[14] ); //scale & skew var row = [ new V(), new V(), new V() ]; for ( i = 0; i < 3; i++ ) { row[i].x = m[4*i]; row[i].y = m[4*i+1]; row[i].z = m[4*i+2]; } scale = new V(); skew = new V(); scale.x = row[0].length(); row[0] = row[0].normalize(); // Compute XY shear factor and make 2nd row orthogonal to 1st. skew.x = row[0].dot(row[1]); row[1] = row[1].combine(row[0], 1.0, -skew.x); // Now, compute Y scale and normalize 2nd row. scale.y = row[1].length(); row[1] = row[1].normalize(); skew.x = skew.x/scale.y; // Compute XZ and YZ shears, orthogonalize 3rd row skew.y = row[0].dot(row[2]); row[2] = row[2].combine(row[0], 1.0, -skew.y); skew.z = row[1].dot(row[2]); row[2] = row[2].combine(row[1], 1.0, -skew.z); // Next, get Z scale and normalize 3rd row. scale.z = row[2].length(); row[2] = row[2].normalize(); skew.y = (skew.y / scale.z); skew.z = (skew.z / scale.z); // At this point, the matrix (in rows) is orthonormal. // Check for a coordinate system flip. If the determinant // is -1, then negate the matrix and the scaling factors. var pdum3 = row[1].cross(row[2]); if (row[0].dot( pdum3 ) < 0) { for (i = 0; i < 3; i++) { scale.at(i, scale.at(i)* -1); row[i].x *= -1; row[i].y *= -1; row[i].z *= -1; } } // Now, get the rotations out // FROM W3C quaternion = new V(); quaternion.x = 0.5 * Math.sqrt(Math.max(1 + row[0].x - row[1].y - row[2].z, 0)); quaternion.y = 0.5 * Math.sqrt(Math.max(1 - row[0].x + row[1].y - row[2].z, 0)); quaternion.z = 0.5 * Math.sqrt(Math.max(1 - row[0].x - row[1].y + row[2].z, 0)); quaternion.w = 0.5 * Math.sqrt(Math.max(1 + row[0].x + row[1].y + row[2].z, 0)); if (row[2].y > row[1].z) quaternion.x = -quaternion.x; if (row[0].z > row[2].x) quaternion.y = -quaternion.y; if (row[1].x > row[0].y) quaternion.z = -quaternion.z; return { perspective: perspective, translate: translate, skew: skew, scale: scale, quaternion: quaternion.normalize() }; }, /** * converts matrix to css string * @returns {string} */ toString: function(){ return "matrix3d("+ this.value.join(", ")+ ")"; } }; /** * recomposes transform from component parts * @param d * @returns {TransformMatrix} */ TransformMatrix.recompose = function( d ){ //console.log('Matrix4x4.recompose'); var m = M.identity(); var i, j, x, y, z, w; var perspective = d.perspective; var translate = d.translate; var skew = d.skew; var scale = d.scale; var quaternion = d.quaternion; // apply perspective m[3] = perspective.x; m[7] = perspective.y; m[11] = perspective.z; m[15] = perspective.w; // apply translation for ( i=0; i<3; ++i ){ for ( j=0; j<3; ++j ){ m[12+i] += translate.at( j ) * m[j*4+i] } } // apply rotation x = quaternion.x; y = quaternion.y; z = quaternion.z; w = quaternion.w; // Construct a composite rotation matrix from the quaternion values /**/ var rmv = M.identity(); rmv[0] = 1 - 2 * ( y * y + z * z ); rmv[1] = 2 * ( x * y - z * w ); rmv[2] = 2 * ( x * z + y * w ); rmv[4] = 2 * ( x * y + z * w ); rmv[5] = 1 - 2 * ( x * x + z * z ); rmv[6] = 2 * ( y * z - x * w ); rmv[8] = 2 * ( x * z - y * w ); rmv[9] = 2 * ( y * z + x * w ); rmv[10] = 1 - 2 * ( x * x + y * y ); /* var rmv = [ 1 - 2*y*y - 2*z*z, 2*x*y - 2*z*w, 2*x*z + 2*y*w, 0, 2*x*y + 2*z*w, 1 - 2*x*x - 2*z*z, 2*y*z - 2*x*w, 0, 2*x*z - 2*y*w, 2*y*z + 2*x*w, 1 - 2*x*x - 2*y*y, 0, 0, 0, 0, 1 ]; */ var rotationMatrix = M.transpose( rmv ); var matrix = M.multiply( m, rotationMatrix ); //console.log(' skew'); // apply skew var temp = Matrix4x4.identity(); if ( skew.z ){ temp[9] = skew.z; matrix = M.multiply( matrix, temp ); } if (skew.y){ temp[9] = 0; temp[8] = skew.y; matrix = M.multiply( matrix, temp ); } if (skew.x){ temp[8] = 0; temp[4] = skew.x; matrix = M.multiply( matrix, temp ); } // apply scale m = matrix; for ( i=0; i<3; ++i ){ for ( j=0; j<3; ++j ){ m[4*i+j] *= scale.at( i ); } } return new TransformMatrix( m ); } return TransformMatrix; });
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M16.14 12.5c0 1-.1 1.85-.3 2.55s-.48 1.27-.83 1.7c-.36.44-.79.75-1.3.95s-1.07.3-1.7.3c-.62 0-1.18-.1-1.69-.3-.51-.2-.95-.51-1.31-.95s-.65-1.01-.85-1.7c-.2-.7-.3-1.55-.3-2.55v-2.04c0-1 .1-1.85.3-2.55.2-.7.48-1.26.84-1.69.36-.43.8-.74 1.31-.93C10.81 5.1 11.38 5 12 5c.63 0 1.19.1 1.7.29.51.19.95.5 1.31.93.36.43.64.99.84 1.69.2.7.3 1.54.3 2.55v2.04h-.01zm-2.11-2.36c0-.64-.05-1.18-.13-1.62-.09-.44-.22-.79-.4-1.06-.17-.27-.39-.46-.64-.58-.25-.13-.54-.19-.86-.19s-.61.06-.86.18-.47.31-.64.58-.31.62-.4 1.06-.13.98-.13 1.62v2.67c0 .64.05 1.18.14 1.62.09.45.23.81.4 1.09s.39.48.64.61.54.19.87.19.62-.06.87-.19.46-.33.63-.61.3-.64.39-1.09.13-.99.13-1.62v-2.66h-.01z" }), 'ExposureZeroRounded');
{ // environment "browser": true, "node": true, "globals": { "L": true, "define": true, "map":true, "jQuery":true // "drawnItems":true }, "strict": false, // code style "bitwise": true, "camelcase": true, "curly": true, "eqeqeq": true, "forin": false, "immed": true, "latedef": true, "newcap": true, "noarg": true, "noempty": true, "nonew": true, "undef": true, "unused": true, "quotmark": "single", // whitespace "indent": 4, "trailing": true, "white": true, "smarttabs": true, "maxlen": 150 // code simplicity - not enforced but nice to check from time to time // "maxstatements": 20, // "maxcomplexity": 5 // "maxparams": 4, // "maxdepth": 4 }
import React from "react" import { Link } from "gatsby" import numberToColor from "../utils/number-to-color" import "./post-link.css" const year = node => new Date(node.frontmatter.date).getFullYear() const PostLink = ({ post }) => ( <div className="post-link"> <Link to={post.frontmatter.path} style={{color: numberToColor(year(post))}}> {post.frontmatter.title} </Link> </div> ) export default PostLink
goog.provide('crow.ConnectedNode'); goog.require('crow.Node'); /** * ConnectedNodes are nodes that have to be explicitly "connected" to other nodes. * @class */ crow.ConnectedNode = function(id){ crow.Node.apply(this, arguments); this.connections = []; this.connectionDistances = {}; }; crow.ConnectedNode.prototype = new crow.Node(); crow.ConnectedNode.prototype.connectTo = function(otherNode, distance, symmetric){ if(typeof distance == "undefined") distance = 1; this.connections.push(otherNode); this.connectionDistances[otherNode.id] = distance; if(typeof symmetric !== "false" && otherNode instanceof crow.ConnectedNode){ otherNode.connections.push(this); otherNode.connectionDistances[this.id] = distance; } }; crow.ConnectedNode.prototype.getNeighbors = function(){ return this.connections; }; crow.ConnectedNode.prototype.distanceToNeighbor = function(otherNode){ return this.connectionDistances[otherNode.id] || Infinity; }
(function () { var color = window.color; var getset = color.getset; color.pie = function () { var options = { height: color.available( "height" ), width: color.available( "width" ), value: null, color: null, hole: 0, palette: window.color.palettes.default, data: null, legend: color.legend() .color( "key" ) .value( "key" ) .direction( "vertical" ) } function pie () { return pie.draw( this ) } pie.height = getset( options, "height" ); pie.width = getset( options, "width" ); pie.value = getset( options, "value" ); pie.color = getset( options, "color" ); pie.hole = getset( options, "hole" ); pie.palette = getset( options, "palette" ); pie.data = getset( options, "data" ); pie.legend = getset( options, "legend" ); pie.draw = function ( selection ) { if ( selection instanceof Element ) { selection = d3.selectAll( [ selection ] ); } selection.each( function ( data ) { var data = layout( pie, pie.data() || data ); draw( pie, this, data ); }) return this; } return pie; } function draw( that, el, data ) { el = d3.select( el ); if ( el.attr( "data-color-chart" ) != "pie" ) { el.attr( "data-color-chart", "pie" ) .text( "" ); } el.node().__colorchart = that; var height = that.height.get( el ) var width = that.width.get( el ) var radius = Math.min( height / 2, width / 2 ) - 10; var c = color.palette() .colors( that.palette() ) .domain( data.map( function ( d ) { return d.key } ) ) .scale(); var arc = d3.svg.arc() .outerRadius( radius ) .innerRadius( radius * that.hole() ); // tooltip var tooltip = color.tooltip() .title( function ( d ) { return !d.key ? that.value() : d.key }) .content( function ( d ) { return !d.key ? d.value : that.value() + ": " + d.value; }) // draw the legend var legend = c.domain().length > 1; var legend = el.selectAll( "g[data-pie-legend]" ) .data( legend ? [ data ] : [] ); legend.enter().append( "g" ) .attr( "data-pie-legend", "" ) legend.call( that.legend().palette( that.palette() ) ); legend.attr( "transform", function () { var top = ( height - legend.node().getBBox().height ) / 2; return "translate(35," + top + ")"; }) // start drawing var pies = el.selectAll( "g[data-pie]" ) .data( [ data ] ); pies.enter().append( "g" ) .attr( "data-pie", "" ) .attr( "transform", function () { return "translate(" + ( width / 2 ) + "," + ( height / 2 ) + ")"; }); var slices = pies.selectAll( "path[data-pie-slice]" ) .data( function ( d ) { return d } ); slices.exit().remove(); slices.enter().append( "path" ); slices .attr( "data-pie-slice", function ( d ) { return d.key; }) .attr( "d", arc ) .attr( "fill", function ( d ) { return c( d.key ); }) .call( tooltip ); } function layout ( that, data ) { // extract the values for each obj data = data.map( function ( d ) { var v = +d[ that.value() ] if ( isNaN( v ) ) { throw new Error( "pie value must be a number" ); } return { v: v, c: d[ that.color() ], obj: d } }) // group by colors data = d3.nest() .key( function ( d ) { return d.c || "" } ) .rollup ( function ( data ) { return data.reduce( function ( v, d ) { return v + d.v; }, 0 ) }) .entries( data ); // lay out the pie data = d3.layout.pie() .sort( null ) .value( function ( d ) { return d.values })( data ) .map( function ( d ) { d.key = d.data.key; delete d.data; return d; }); return data; } })();
var gulp = require('gulp'); var sass = require('gulp-sass'); var cssmin = require('gulp-cssmin'); var plumber = require('gulp-plumber'); var webpack = require('gulp-webpack'); gulp.task('css', function() { return gulp.src(['styles/*.scss']) .pipe(plumber()) .pipe(sass().on('error', sass.logError)) .pipe(cssmin()) .pipe(gulp.dest('static/css/common/')); }); gulp.task('webpack', function() { return gulp.src(['./']) .pipe(plumber()) .pipe(webpack(require('./webpack.config.js'))) .pipe(gulp.dest('./static/')); }); gulp.task('watch', ['publish'], function(){ gulp.watch(['styles/*.scss'], ['css']); gulp.watch(['src/**/*'], ['webpack']); }); gulp.task('publish',['css', 'webpack']);
// Utility functions String.prototype.endsWith = function (suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }; String.prototype.ltrim = function () { return this.replace(/^\s+/, ''); }; String.prototype.rtrim = function () { return this.replace(/\s+$/, ''); }; String.prototype.fulltrim = function () { return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' '); }; } function colorToHex(color) { if (color.substr(0, 1) === '#') { return color; } var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color); var red = parseInt(digits[2]); var green = parseInt(digits[3]); var blue = parseInt(digits[4]); var rgb = blue | (green << 8) | (red << 16); return digits[1] + '#' + rgb.toString(16); };
"use strict"; var Extension = require("../runtime/extension"); /** * @constructor Trait * @memberof module:impulse * * @summary Traits allow classes to be extended without modification, and support isTypeOf() when used as parameters. **/ function Trait(parent, funcs, required) { this._parent = parent || null; this._types = new Set(); this._methods = funcs; this.required = required; } Trait.isTypeOf = function(that) { return that instanceof this; } Trait.prototype.add = function (type) { this._types = this._types.add(type); return this; } Trait.prototype.isTypeOf = function (value) { for (var scope = this; scope !== null; scope = scope._parent) { for (var type of scope._types) { if (type.isTypeOf(value)) { return true; } } } return false; } Trait.prototype.bind = function() { return this._methods.apply(null, arguments); } Trait.addtrait = function(type, parent) { var trait = parent ? clone(parent) : new Trait(); return trait.add(type); } function clone(object) { if (object == null || typeof object != "object") { return object; } var copy = new object.constructor(); for (var property in object) { if (object.hasOwnProperty(property)) { copy[property] = object[property]; } } return copy; } // // Exports // module.exports = Trait; /* Value : Type 0 : 1 Bottom == Void 1 : 1 Unit () == () 1 : 1 Scalar 1 == Number 1 : N Union or Intersection 1 == (Number | String), (Number & String) N : 1 Array [1, 2, 3] == [Number] N : N Record (1, "foo") == (Number, String) 1 : 0 Untyped Scalar N : 1 Top 1, "foo" == Object import { symbol } from "core-js/es6/symbol"; import * from core-js.fn.object.assign; eval("var symbol = Symbol.symbol;"); import foo, bar from library; import * from library.module; */
const alter = require('../lib/alter.js'); const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('yaxis', { args: [ { name: 'inputSeries', types: ['seriesList'] }, { name: 'yaxis', types: ['number', 'null'], help: 'The numbered y-axis to plot this series on, eg .yaxis(2) for a 2nd y-axis.' }, { name: 'min', types: ['number', 'null'], help: 'Min value' }, { name: 'max', types: ['number', 'null'], help: 'Max value' }, { name: 'position', types: ['string', 'null'], help: 'left or right' }, { name: 'label', types: ['string', 'null'], help: 'Label for axis' }, { name: 'color', types: ['string', 'null'], help: 'Color of axis label' }, ], help: 'Configures a variety of y-axis options, the most important likely being the ability to add an Nth (eg 2nd) y-axis', fn: function yaxisFn(args) { return alter(args, function (eachSeries, yaxis, min, max, position, label, color) { yaxis = yaxis || 1; eachSeries.yaxis = yaxis; eachSeries._global = eachSeries._global || {}; eachSeries._global.yaxes = eachSeries._global.yaxes || []; eachSeries._global.yaxes[yaxis - 1] = eachSeries._global.yaxes[yaxis - 1] || {}; const myAxis = eachSeries._global.yaxes[yaxis - 1]; myAxis.position = position || (yaxis % 2 ? 'left' : 'right'); myAxis.min = min; myAxis.max = max; myAxis.axisLabelFontSizePixels = 11; myAxis.axisLabel = label; myAxis.axisLabelColour = color; myAxis.axisLabelUseCanvas = true; return eachSeries; }); } });
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ function(module, exports, __webpack_require__) { __webpack_require__(228); /***/ }, /***/ 228: /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(229); /***/ }, /***/ 229: /***/ function(module, exports, __webpack_require__) { /** * @name Utility Classes * @collection core * @example-file ./examples.html */ __webpack_require__(230); /***/ }, /***/ 230: /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ } /******/ }) }); ;
///* //Project Name: Spine Admin //Version: 1.6.0 //Author: BharaniGuru R // //*/var handleCalendarDemo=function(){"use strict";var e={left:"prev today",center:"title",right:"agendaWeek next"};var t=new Date;var n=t.getMonth();var r=t.getFullYear();var i=$("#calendar").fullCalendar({header:e,selectable:true,selectHelper:true,droppable:true,drop:function(e,t){var n=$(this).data("eventObject");var r=$.extend({},n);r.start=e;r.allDay=t;$("#calendar").fullCalendar("renderEvent",r,true);if($("#drop-remove").is(":checked")){$(this).remove()}}, //select:function(e,t,n) //{var r= $('.model_test').trigger('click');if(r){i.fullCalendar("renderEvent",{title:r,start:e,end:t,allDay:n},true)}i.fullCalendar("unselect")}, ////{var r=prompt("LEAVE TYPE:");if(r){i.fullCalendar("renderEvent",{title:r,start:e,end:t,allDay:n},true)}i.fullCalendar("unselect")}, //eventRender:function(e,t,n){var r=e.media?e.media:"";var i=e.description?e.description:"";t.find(".fc-event-title").after($('<span class="fc-event-icons"></span>').html(r));t.find(".fc-event-title").append("<small>"+i+"</small>")},editable:true,events:[/*{title:"Event",start:new Date(r,n,0),}*/]});$("#external-events .external-event").each(function(){var e={title:$.trim($(this).attr("data-title")),className:$(this).attr("data-bg"),media:$(this).attr("data-media"),description:$(this).attr("data-desc")};$(this).data("eventObject",e);$(this).draggable({zIndex:999,revert:true,revertDuration:0})})};var Calendar=function(){"use strict";return{init:function(){handleCalendarDemo()}}}() /* Project Name: Spine Admin Version: 1.6.0 Author: BharaniGuru R */ //--------------------------------------// var handleCalendarDemo = function() { "use strict"; var e = { left: "prev today", center: "title", right: "agendaWeek next" }; var t = new Date; var n = t.getMonth(); var r = t.getFullYear(); var i = $("#calendar").fullCalendar({ header: e, selectable: true, selectHelper: true, droppable: true, drop: function(e, t) { var n = $(this).data("eventObject"); var r = $.extend({}, n); r.start = e; r.allDay = t; $("#calendar").fullCalendar("renderEvent", r, true); if ($("#drop-remove").is(":checked")) { $(this).remove() } }, select: function(e, t, n) { //var r = prompt("LEAVE TYPE:"); modalwindowevent(); var r = data+"/"+data1; console.log(r,'value'); if (r) { //alert('in rr'); i.fullCalendar("renderEvent", { title: r, start: e, end: t, allDay: n }, true) } i.fullCalendar("unselect") }, eventRender: function(e, t, n) { var r = e.media ? e.media : ""; var i = e.description ? e.description : ""; t.find(".fc-event-title").after($('<span class="fc-event-icons"></span>').html(r)); console.log(t.find(".fc-event-title").after($('<span class="fc-event-icons"></span>').html(r)),'testmin'); t.find(".fc-event-title").append("<small>" + i + "</small>") }, editable: true, events: [ /*{title:"Event",start:new Date(r,n,0),}*/ ] }); $("#external-events .external-event").each(function() { var e = { title: $.trim($(this).attr("data-title")), className: $(this).attr("data-bg"), media: $(this).attr("data-media"), description: $(this).attr("data-desc") }; $(this).data("eventObject", e); $(this).draggable({ zIndex: 999, revert: true, revertDuration: 0 }) }) }; var Calendar = function() { "use strict"; return { init: function() { handleCalendarDemo() } } }() //$(document).ready(function(){ //function getInputvalue(){ // var reson=$('#resoan_val').val(); // var leave=$('.leave_days').val(); // var type=$('#leave_type').val(); // var all=reson+" "+leave+" "+type; // $('.fc-event-title').addClass('value').text('all').css('color','red'); // console.log(all,'alldata'); // //modelwindform(); //} // function modelwindform(){ // $('.model_test').trigger('click'); //} //}); //$(function(modelwindform) { //function modelwindform(){ // $('#dialogboxxxxxxxx').trigger('click'); // $("#dialogboxxxxxxxx").dialog({ // autoOpen: false, // modal: true, // buttons : { // "Confirm" : function() { // alert("You have confirmed!"); // }, // "Cancel" : function() { // $(this).dialog("close"); // } // } // }); // // $("#callConfirm").on("click", function(e) { // e.preventDefault(); // $("#dialog").dialog("open"); // }); //} //}); //$('#Save_btn').trigger('click'); //}) //$('.fc-widget-content3').addClass('tt').css('background','red'); //$('.tt').text('dsudyhdsy').css('color','white').removeClass('tt'); //$('.tt'); //function newmoadl(){ // $("#bootbox").trigger("click"); // var modal = bootbox.dialog({ // message: $(".form-content").html(), // title: "Your awesome modal", // buttons: [ // { // label: "Save", // className: "btn btn-primary pull-left", // callback: function() { // // alert($('form #email').val()); // console.log(modal); // // return false; // } // }, // { // label: "Close", // className: "btn btn-default pull-left", // callback: function() { // console.log("just do something on close"); // } // } // ], // show: false, // onEscape: function() { // modal.modal("hide"); // } // }); //} //$(document).ready(function() { // ////function newmoadl(){ // $("#bootbox").on("click", function(event) { // var modal = bootbox.dialog({ // message: $(".form-content").html(), // title: "Your awesome modal", // buttons: [ // { // label: "Save", // className: "btn btn-primary pull-left", // callback: function() { // var select=$('#leave_type').val(); // var hiddenval=$('#hidden').val(select); // //$("#myHiddenField").val($(this).attr("temp")); // //var name=$('#name').val(); // // var select="CL"; // //var name="manikandan"; // //var all=select+name; // //console.log(name); // //console.log(select); // return false; // } // }, // { // label: "Close", // className: "btn btn-default pull-left", // callback: function() { // console.log("just do something on close"); // } // } // ], // show: false, // onEscape: function() { // modal.modal("hide"); // } // }); // console.log(modal); // modal.modal("show"); // }); // //} ////} //}); var data; var data1 function modalwindowevent(){ //alert('event in'); $("#open").trigger("click"); $("#dialog").removeClass('hidden'); $("#dialog").dialog({ autoOpen: false, buttons: { Ok: function() { data=$('#name').val(); data1=$('#valuesofanem').val(); $("#nameentered").text($("#name").val()); $("#sdasdasd").text($("#valuesofanem").val()); $(this).dialog("close"); }, Cancel: function () { $(this).dialog("close"); } } }); $("#open").click(function () { $("#dialog").dialog("open"); }); }
/** * Created by ionagamed on 8/19/16. */ import { Card } from '../../../Card'; import { Item } from '../helpers/Item'; const id = 'sneaky_bastard_sword'; class _ extends Item { constructor() { super(); this.id = id; this.pack = 'pack1'; this.kind = 'treasure'; this.type = '1-handed'; this.hands = 1; this.wieldable = true; this.price = 400; } getAttackFor(player) { return 2; } } Card.cards[id] = new _();
import React from 'react' import GMManhattanChart from './GMManhattanChart' import GMManhattanToolbar from './GMManhattanToolbar' import fetch from './fetch' import config from '../../config' const GMManhattanVisualization = React.createClass({ componentDidMount() { this.loadData(this.props.params), this.setState({ pageParams: [] }) }, componentWillReceiveProps(nextProps) { this.loadData(nextProps.params) }, getInitialState() { return { pageParams: [] } }, loadData: function (params) { let dataRequest = { method: 'GET', headers: { 'Content-Type': 'application/json' } } const vizData = { } return fetch(`${config.api.dataUrl}/${params.results}`, dataRequest) .then(response => { if (!response.ok) Promise.reject(response.json()) return response.json() }).then(json => { vizData.data = JSON.parse(json.data) return fetch(`${config.api.dataUrl}/${params.markers}`, dataRequest) }).then(response => { if (!response.ok) Promise.reject(response.json()) return response.json() }).then(json => { vizData.markerLabels = json.data.split('\n').filter(function(line){ return line.length > 0 }) return fetch(`${config.api.dataUrl}/${params.traits}`, dataRequest) }).then(response => { if (!response.ok) Promise.reject(response.json()) return response.json() }).then(json => { vizData.traitLabels = json.data.split('\n').filter(function(line){ return line.length > 0 }) this.setState({ data: vizData.data, markerLabels: vizData.markerLabels, traitLabels: vizData.traitLabels, pageParams: params }) return json }).catch(err => console.log(err)) }, render() { return ( <div> <div className="Manhattan"> <GMManhattanChart data={this.state.data} markerLabels={this.state.markerLabels} traitLabelsNum={this.state.pageParams.traitNum} pageParams={this.state.pageParams} /> </div> <GMManhattanToolbar left={this.props.minPad} right={this.props.minPad} pageParams={this.state.pageParams} /> </div> ) } }) export default GMManhattanVisualization
$(document).ready(function() { var text = $("#hSleep").text(); var results = []; var data = []; results = text.split(","); // alert(results); console.log("results: " + text); for(var i = results.length-1; i >= 0; i--) { data.push([new Date(results[i-1]).getTime(), results[i]]); i--; } var barOptions = { series: { bars: { show: true, barWidth: 43200000 } }, xaxis: { mode: "time", timeformat: "%m/%d", minTickSize: [1, "day"] }, grid: { hoverable: true }, legend: { show: false }, tooltip: true, tooltipOpts: { content: "Date: %x, Minutes: %y" } }; var barData = { label: "bar", data: data }; $.plot($("#flot-line-chart"), [barData], barOptions); text = $("#hSteps").text(); results = text.split(","); data = []; for(var i = results.length-1; i >= 0; i--) { data.push([new Date(results[i-1]).getTime(), results[i]]); i--; } var options = { series: { lines: { show: true }, points: { show: true } }, grid: { hoverable: true //IMPORTANT! this is needed for tooltip to work }, xaxis: { mode: "time", timeformat: "%m/%d", minTickSize: [1, "day"] }, tooltip: true, tooltipOpts: { content: "'Date: %x.1, Steps: %y", shifts: { x: -60, y: 25 } } }; var plotObj = $.plot($("#flot-bar-chart"), [{ data: data, label: "Steps" }], options); text = $("#hDistance").text(); results = text.split(","); data = []; //alert(text); for(var i = results.length-1; i >= 0; i--) { data.push([new Date(results[i-1]).getTime(), results[i]]); i--; } var options = { series: { lines: { show: true }, points: { show: true } }, grid: { hoverable: true //IMPORTANT! this is needed for tooltip to work }, xaxis: { mode: "time", timeformat: "%m/%d", minTickSize: [1, "day"] }, tooltip: true, tooltipOpts: { content: "'Date: %x.1, Heart Rates: %y", shifts: { x: -60, y: 25 } } }; var plotObj = $.plot($("#flot-moving-line-chart"), [{ data: data, label: "Heart Rates" }], options); text = $("#hCalories").text(); results = text.split(","); data = []; for(var i = results.length-1; i >= 0; i--) { data.push([new Date(results[i-1]).getTime(), results[i]]); i--; } var options = { series: { lines: { show: true }, points: { show: true } }, grid: { hoverable: true //IMPORTANT! this is needed for tooltip to work }, xaxis: { mode: "time", timeformat: "%m/%d", minTickSize: [1, "day"] }, tooltip: true, tooltipOpts: { content: "'Date: %x.1, Steps: %y", shifts: { x: -60, y: 25 } } }; var plotObj = $.plot($("#flot-multiple-axes-chart"), [{ data: data, label: "Calories" }], options); });
export default from './CallToAction.jsx';
'use strict'; chrome.devtools.panels.create('Luffa', '', 'devtool.html', function (panel) { var reactPanel = null; panel.onShown.addListener(function (window) { // when the user switches to the panel, check for an elements tab // selection window.panel.getNewSelection(); reactPanel = window.panel; reactPanel.resumeTransfer(); }); panel.onHidden.addListener(function () { if (reactPanel) { reactPanel.hideHighlight(); reactPanel.pauseTransfer(); } }); }); //# sourceMappingURL=panel.js.map
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var api = require('./routes/api'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(__dirname + '/dist')); app.use('/api', api); app.use('*', function(req, res) { res.sendfile(__dirname + '/dist/index.html'); }); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
// flow-typed signature: e6263c15ef6789188b11afd5007f8d74 // flow-typed version: <<STUB>>/css-to-react-native_v^2.2.2/flow_v0.100.0 /** * This is an autogenerated libdef stub for: * * 'css-to-react-native' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'css-to-react-native' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'css-to-react-native/src/__tests__/border' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/borderColor' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/boxModel' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/boxShadow' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/colors' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/flex' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/flexFlow' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/font' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/fontFamily' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/fontVariant' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/fontWeight' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/index' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/shadowOffsets' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/textDecoration' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/textDecorationLine' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/textShadow' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/transform' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/units' { declare module.exports: any; } declare module 'css-to-react-native/src/index' { declare module.exports: any; } declare module 'css-to-react-native/src/TokenStream' { declare module.exports: any; } declare module 'css-to-react-native/src/tokenTypes' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/boxShadow' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/flex' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/font' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/fontFamily' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/index' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/textDecoration' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/textDecorationLine' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/textShadow' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/transform' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/util' { declare module.exports: any; } // Filename aliases declare module 'css-to-react-native/index' { declare module.exports: $Exports<'css-to-react-native'>; } declare module 'css-to-react-native/index.js' { declare module.exports: $Exports<'css-to-react-native'>; } declare module 'css-to-react-native/src/__tests__/border.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/border'>; } declare module 'css-to-react-native/src/__tests__/borderColor.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/borderColor'>; } declare module 'css-to-react-native/src/__tests__/boxModel.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/boxModel'>; } declare module 'css-to-react-native/src/__tests__/boxShadow.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/boxShadow'>; } declare module 'css-to-react-native/src/__tests__/colors.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/colors'>; } declare module 'css-to-react-native/src/__tests__/flex.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/flex'>; } declare module 'css-to-react-native/src/__tests__/flexFlow.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/flexFlow'>; } declare module 'css-to-react-native/src/__tests__/font.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/font'>; } declare module 'css-to-react-native/src/__tests__/fontFamily.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/fontFamily'>; } declare module 'css-to-react-native/src/__tests__/fontVariant.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/fontVariant'>; } declare module 'css-to-react-native/src/__tests__/fontWeight.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/fontWeight'>; } declare module 'css-to-react-native/src/__tests__/index.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/index'>; } declare module 'css-to-react-native/src/__tests__/shadowOffsets.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/shadowOffsets'>; } declare module 'css-to-react-native/src/__tests__/textDecoration.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/textDecoration'>; } declare module 'css-to-react-native/src/__tests__/textDecorationLine.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/textDecorationLine'>; } declare module 'css-to-react-native/src/__tests__/textShadow.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/textShadow'>; } declare module 'css-to-react-native/src/__tests__/transform.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/transform'>; } declare module 'css-to-react-native/src/__tests__/units.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/units'>; } declare module 'css-to-react-native/src/index.js' { declare module.exports: $Exports<'css-to-react-native/src/index'>; } declare module 'css-to-react-native/src/TokenStream.js' { declare module.exports: $Exports<'css-to-react-native/src/TokenStream'>; } declare module 'css-to-react-native/src/tokenTypes.js' { declare module.exports: $Exports<'css-to-react-native/src/tokenTypes'>; } declare module 'css-to-react-native/src/transforms/boxShadow.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/boxShadow'>; } declare module 'css-to-react-native/src/transforms/flex.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/flex'>; } declare module 'css-to-react-native/src/transforms/font.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/font'>; } declare module 'css-to-react-native/src/transforms/fontFamily.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/fontFamily'>; } declare module 'css-to-react-native/src/transforms/index.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/index'>; } declare module 'css-to-react-native/src/transforms/textDecoration.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/textDecoration'>; } declare module 'css-to-react-native/src/transforms/textDecorationLine.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/textDecorationLine'>; } declare module 'css-to-react-native/src/transforms/textShadow.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/textShadow'>; } declare module 'css-to-react-native/src/transforms/transform.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/transform'>; } declare module 'css-to-react-native/src/transforms/util.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/util'>; }
(function (angular) { 'use strict'; angular .module('ngTagsInput', []); })(window.angular);
const fs = require('fs'); const path = require('path'); // eslint-disable-next-line import/no-extraneous-dependencies const sharedsession = require('express-socket.io-session'); /** * Checks to see if sockets are configured and then sets up socket.io * @param {Ceres} ceres * @param {Express} app * @param {HTTP} server * @return {socket.io} */ module.exports = function sockets(ceres, app, server) { const clientSocketEntryPath = path.resolve(ceres.config.folders.sockets, './index.js'); try { // Can we access the file? fs.accessSync(clientSocketEntryPath); } catch (err) { if (err.code === 'ENOENT') { ceres.log.internal.silly('Websockets configuration not found at %s', clientSocketEntryPath); return {}; } throw err; } // Setup socket.io // eslint-disable-next-line import/no-extraneous-dependencies const io = require('socket.io')(server); // Get socket router const handler = require(clientSocketEntryPath); // Connect it to client connection event io.on('connection', handler.bind(ceres, io, ceres.Database)); // Share express sessions io.use(sharedsession(app.get('sharedSession'))); ceres.log.internal.silly('Websockets configured'); return io; };
'use strict' const _toArray = require('lodash.toarray') const shelljs = require('shelljs') module.exports = function (config) { // parse loader [ 'loaders', 'preLoaders', 'postLoaders' ].forEach(key => { config.module[key] = _toArray(config.module[key]) }) // parse plugin config.plugins = _toArray(config.plugins) // install resolve path require('./load-resolve-path')(config) if (process.env.NODE_ENV === 'development') { // install dev server config.devServer = require('../util/load-server')(config.devServer) if (config.devServer.enable) { config.devServer.host = config.devServer.protocol + '//' + config.devServer.hostname + ':' + config.devServer.port } // update path config.output.publicPath = config.devServer.publicPath || config.output.publicPath || '/' } // load hot loader config.entry = require('./hot-reload')( config.entry, process.env.NODE_ENV === 'development' ? config.devServer : false ) if (config.__XDC_CLEAN__) { shelljs.rm('-rf', config.output.path) } return config }
(function() { 'use strict'; var app = angular.module('app'); app.directive('ccImgPerson', ['config', function (config) { //Usage: //<img data-cc-img-person="{{s.speaker.imageSource}}"/> var basePath = config.imageSettings.imageBasePath; var unknownImage = config.imageSettings.unknownPersonImageSource; var directive = { link: link, restrict: 'A' }; return directive; function link(scope, element, attrs) { attrs.$observe('ccImgPerson', function(value) { value = basePath + (value || unknownImage); attrs.$set('src', value); }); } }]); app.directive('ccSidebar', function () { // Opens and clsoes the sidebar menu. // Usage: // <div data-cc-sidebar> // Creates: // <div data-cc-sidebar class="sidebar"> var directive = { link: link, restrict: 'A' }; return directive; function link(scope, element, attrs) { var $sidebarInner = element.find('.sidebar-inner'); var $dropdownElement = element.find('.sidebar-dropdown a'); element.addClass('sidebar'); $dropdownElement.click(dropdown); function dropdown(e) { var dropClass = 'dropy'; e.preventDefault(); if (!$dropdownElement.hasClass(dropClass)) { hideAllSidebars(); $sidebarInner.slideDown(350); $dropdownElement.addClass(dropClass); } else if ($dropdownElement.hasClass(dropClass)) { $dropdownElement.removeClass(dropClass); $sidebarInner.slideUp(350); } function hideAllSidebars() { $sidebarInner.slideUp(350); $('.sidebar-dropdown a').removeClass(dropClass); } } } }); app.directive('ccWidgetClose', function () { // Usage: // <a data-cc-widget-close></a> // Creates: // <a data-cc-widget-close="" href="#" class="wclose"> // <i class="icon-remove"></i> // </a> var directive = { link: link, template: '<i class="icon-remove"></i>', restrict: 'A' }; return directive; function link(scope, element, attrs) { attrs.$set('href', '#'); attrs.$set('wclose'); element.click(close); function close(e) { e.preventDefault(); element.parent().parent().parent().hide(100); } } }); app.directive('ccWidgetMinimize', function () { // Usage: // <a data-cc-widget-minimize></a> // Creates: // <a data-cc-widget-minimize="" href="#"><i class="icon-chevron-up"></i></a> var directive = { link: link, template: '<i class="icon-chevron-up"></i>', restrict: 'A' }; return directive; function link(scope, element, attrs) { //$('body').on('click', '.widget .wminimize', minimize); attrs.$set('href', '#'); attrs.$set('wminimize'); element.click(minimize); function minimize(e) { e.preventDefault(); var $wcontent = element.parent().parent().next('.widget-content'); var iElement = element.children('i'); if ($wcontent.is(':visible')) { iElement.removeClass('icon-chevron-up'); iElement.addClass('icon-chevron-down'); } else { iElement.removeClass('icon-chevron-down'); iElement.addClass('icon-chevron-up'); } $wcontent.toggle(500); } } }); app.directive('ccScrollToTop', ['$window', // Usage: // <span data-cc-scroll-to-top></span> // Creates: // <span data-cc-scroll-to-top="" class="totop"> // <a href="#"><i class="icon-chevron-up"></i></a> // </span> function ($window) { var directive = { link: link, template: '<a href="#"><i class="icon-chevron-up"></i></a>', restrict: 'A' }; return directive; function link(scope, element, attrs) { var $win = $($window); element.addClass('totop'); $win.scroll(toggleIcon); element.find('a').click(function (e) { e.preventDefault(); // Learning Point: $anchorScroll works, but no animation //$anchorScroll(); $('body').animate({ scrollTop: 0 }, 500); }); function toggleIcon() { $win.scrollTop() > 300 ? element.slideDown(): element.slideUp(); } } } ]); app.directive('ccSpinner', ['$window', function ($window) { // Description: // Creates a new Spinner and sets its options // Usage: // <div data-cc-spinner="vm.spinnerOptions"></div> var directive = { link: link, restrict: 'A' }; return directive; function link(scope, element, attrs) { scope.spinner = null; scope.$watch(attrs.ccSpinner, function (options) { if (scope.spinner) { scope.spinner.stop(); } scope.spinner = new $window.Spinner(options); scope.spinner.spin(element[0]); }, true); } }]); app.directive('ccWidgetHeader', function() { //Usage: //<div data-cc-widget-header title="vm.map.title"></div> var directive = { link: link, scope: { 'title': '@', 'subtitle': '@', 'rightText': '@', 'allowCollapse': '@' }, templateUrl: '/app/layout/widgetheader.html', restrict: 'A', }; return directive; function link(scope, element, attrs) { attrs.$set('class', 'widget-head'); } }); app.directive('ccWip', ['$route', function ($route) { //Usage: //<li data-cc-wip // wip="vm.wip" // routes="vm.routes" // changed-event="{{vm.wipChangedEvent}}" // class="nlightblue"></li> var wipRouteName = 'workinprogress'; var directive = { controller: ['$scope', wipController], link: link, template: getTemplate(), scope: { 'wip': '=', 'changedEvent': '@', 'routes': '=' }, restrict: 'A' }; return directive; function link(scope, element, attrs) { scope.$watch(wipIsCurrent, function (value) { value ? element.addClass('current') : element.removeClass('current'); }); function wipIsCurrent() { if (!$route.current || !$route.current.title) { return false; } return $route.current.title.substr(0, wipRouteName.length) === wipRouteName; } } function wipController($scope) { $scope.wipExists = function () { return !!$scope.wip.length; }; $scope.wipRoute = undefined; $scope.getWipClass = function () { return $scope.wipExists() ? 'icon-asterisk-alert' : ''; }; activate(); function activate() { var eventName = $scope.changedEvent; $scope.$on(eventName, function (event, data) { $scope.wip = data.wip; }); $scope.wipRoute = $scope.routes.filter(function (r) { return r.config.title === wipRouteName; })[0]; } } function getTemplate() { return '<a href="#{{wipRoute.url}}" >' + '<i class="icon-asterisk" data-ng-class="getWipClass()"></i>' + 'Work in Progress ({{wip.length}})</a>'; } }]); })();
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: '0e12331bed5965a0443585ad3157def3', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ // cookie: { // maxAge: 24 * 60 * 60 * 1000 // } /*************************************************************************** * * * In production, uncomment the following lines to set up a shared redis * * session store that can be shared across multiple Sails.js servers * ***************************************************************************/ // adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * https://github.com/visionmedia/connect-redis * * * * * ***************************************************************************/ // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password> // prefix: 'sess:' /*************************************************************************** * * * Uncomment the following lines to use your Mongo adapter as a session * * store * * * ***************************************************************************/ // adapter: 'mongo', // host: 'localhost', // port: 27017, // db: 'sails', // collection: 'sessions', /*************************************************************************** * * * Optional Values: * * * * # Note: url will override other connection settings url: * * 'mongodb://user:pass@host:port/database/collection', * * * ***************************************************************************/ // username: '', // password: '', // auto_reconnect: false, // ssl: false, // stringify: true };
module.exports = require('./lib/bionode-bwa')
import React from 'react' import {observer} from 'mobx-react' import {Route, Link} from 'react-router-dom' import {IMAGE_DIR, TOKEN, GET_HOTEL_INFO, RESPONSE_CODE_SUCCESS} from 'macros' import {setParamsToURL, dateToZh} from 'utils' import Cookies from 'js-cookie' import WeiXinShareTips from 'WeiXinShareTips' import './hotel.less' export default observer( (props) => ( <div className="hotel-container"> <div className="banner-container"> <div className="colllect"> {Cookies.get(TOKEN)? props.store.isFavorite == 1? <i className="iconfont btn-colllect icon-hotle_icon_like1" /> : <i className="iconfont btn-colllect icon-hotle_icon_like" /> : ''} <span className="btn-share"><i className="iconfont icon-share1" /></span> </div> <div className="swiper-container"> <div className="swiper-wrapper"> { props.store.hotelImgs.map((item, index) => { return <div className="swiper-slide" key={index} style={{backgroundImage:`url(${item.imgPath})`}}></div> }) } </div> <div className="swiper-pagination"></div> </div> </div> <div className="hotel-name-wrapper"> <div className="hotel-box"> <div className="hotel-name">{props.store.hotelName}</div> <div className="hotel-address">{props.store.address}</div> </div> <Link to={setParamsToURL(`${props.match.url}/map`, {longitude: props.store.longitude, latitude: props.store.latitude})}> <i className="iconfont icon-will_live_icon_loction" /> </Link> </div> <ul className="hotel-funs"> <li><img src={`${IMAGE_DIR}/use-face.jpg`} /><span>刷脸入住</span></li> <li><img src={`${IMAGE_DIR}/use-lock.jpg`} /><span>无卡开锁</span></li> <li><img src={`${IMAGE_DIR}/use-free.jpg`} /><span>面排队/查房</span></li> </ul> <Link to={`${props.match.url}/select-date`} className="checking-in-out"> <div><p>入住</p><span>{dateToZh(props.store.checkInDate)}</span></div> <div><p>退房</p><span>{dateToZh(props.store.checkOutDate)}</span></div> <i className="iconfont icon-hotle_icon_show" /> </Link> <div className="hotel-cards"> <div className="swiper-container"> <div className="swiper-wrapper"> { props.store.roomTypes.map((item, index) => { return ( <div className="swiper-slide" key={index} style={{backgroundImage:`url(${item.imgPath})`}}> <div className="slide-adjust"> <p className="price-box">&yen;{`${item.price}`}</p> <Link className="clickable-area" to={`/room/${props.match.params.hotelID}/${item.roomTypeID}`} ></Link> <div className="hotel-type"> <div className="info-wrapper"> <p>{item.roomType}</p> <p>{`${item.roomSize}m², ${item.bedType}`}</p> </div> <Link to={{pathname:`/booking/${props.match.params.hotelID}/${item.roomTypeID}`, search: `?checkInDate=${props.store.checkInDate}&checkOutDate=${props.store.checkOutDate}`}} className="btn-booking">立即预订</Link> </div> </div> </div> ) }) } </div> </div> </div> { props.store.isShowShareTips? ( <WeiXinShareTips onClick={(e) => { props.store.isShowShareTips = false }}/> ) : '' } </div> ) )
import GameEvent from "../../../src/artifact/js/GameEvent.js"; QUnit.module("GameEvent"); var GameEventTest = {}; QUnit.test("GameEvent properties Quest card drawn", function(assert) { var eventKey = GameEvent.QUEST_CARD_DRAWN; var properties = GameEvent.properties[eventKey]; assert.equal(properties.name, "Quest card drawn"); assert.equal(properties.key, "questCardDrawn"); }); QUnit.test("keys and values", function(assert) { // Setup. // Run. var result = GameEvent.keys(); var ownPropertyNames = Object.getOwnPropertyNames(GameEvent); // Verify. ownPropertyNames.forEach(function(key) { var key2 = GameEvent[key]; if (key !== "properties" && typeof key2 === "string") { assert.ok(GameEvent.properties[key2], "Missing value for key = " + key); } }); result.forEach(function(value) { var p = ownPropertyNames.filter(function(key) { return GameEvent[key] === value; }); assert.equal(p.length, 1, "Missing key for value = " + value); }); }); QUnit.test("GameEvent.keys()", function(assert) { // Run. var result = GameEvent.keys(); // Verify. assert.ok(result); var length = 6; assert.equal(result.length, length); var i = 0; assert.equal(result[i++], GameEvent.CARD_PLAYED); assert.equal(result[i++], GameEvent.QUEST_CARD_DRAWN); assert.equal(result[i++], GameEvent.QUEST_SUCCEEDED); assert.equal(result[i++], GameEvent.SHADOW_CARD_REVEALED); assert.equal(result[i++], GameEvent.TRAVELED); assert.equal(result[i++], GameEvent.WOUNDED); }); export default GameEventTest;
var $ = function (selector) { return document.querySelector(selector); }; var $all = function (selector) { return document.querySelectorAll(selector); }; var colorScheme = [ '#6BED08', '#A0F261', '#86EF35', '#60DD00', '#4AAA00', '#F8FE09', '#FBFE66', '#F9FE39', '#F2F800', '#BABF00', '#06BEBE', '#54D1D1', '#2CC5C5', '#009595', '#007373' ]; getRandomColor = function () { return colorScheme[Math.floor(colorScheme.length * Math.random())]; }; window.addEventListener('DOMContentLoaded', function () { function makeBox(el, x, y, className) { className = className ? className : ''; var d = document.createElement("div"); d.className = "frame"; d.style.left = 50 * x + "%"; d.style.top = 50 * y + "%"; var box = document.createElement("div"); box.classList.add('box'); if (className) box.classList.add(className); box.style.backgroundColor = getRandomColor(); d.appendChild(box); el.appendChild(d); } function divide(el, remove) { remove = remove === void 0 ? true : !!remove; makeBox(el, 0, 0); makeBox(el, 1, 0, 'diagonal'); makeBox(el, 0, 1, 'diagonal'); makeBox(el, 1, 1); if (!remove) { return; } el.removeChild(el.childNodes[0]); } var level = 1; divide($("#screen"), false, level); document.onclick = function () { if (level > 9) { $all('.box').forEach(function (box) { box.onclick = function () { divide(this.parentNode); }; }); return; } level++; $all('.box.diagonal').forEach(function (box) { divide(box.parentNode); }); } }, false);
'use strict'; // 1. npm install body-parser express request // 2. Download and install ngrok from https://ngrok.com/download // 3. ./ngrok http 8445 // 4. WIT_TOKEN=your_access_token FB_PAGE_ID=your_page_id FB_PAGE_TOKEN=your_page_token FB_VERIFY_TOKEN=verify_token node examples/messenger.js // 5. Subscribe your page to the Webhooks using verify_token and `https://<your_ngrok_io>/fb` as callback URL. // 6. Talk to your bot on Messenger! const bodyParser = require('body-parser'); const express = require('express'); const request = require('request'); const Wit = require('node-wit').Wit; // Webserver parameter const PORT = process.env.PORT || 8445; // Wit.ai parameters const WIT_TOKEN = process.env.WIT_TOKEN; // Messenger API parameters const FB_PAGE_ID = process.env.FB_PAGE_ID; if (!FB_PAGE_ID) { throw new Error('missing FB_PAGE_ID'); } const FB_PAGE_TOKEN = process.env.FB_PAGE_TOKEN; if (!FB_PAGE_TOKEN) { throw new Error('missing FB_PAGE_TOKEN'); } const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN; // Messenger API specific code // See the Send API reference // https://developers.facebook.com/docs/messenger-platform/send-api-reference const fbReq = request.defaults({ uri: 'https://graph.facebook.com/me/messages', method: 'POST', json: true, qs: { access_token: FB_PAGE_TOKEN }, headers: {'Content-Type': 'application/json'}, }); const fbMessage = (recipientId, msg, cb) => { const opts = { form: { recipient: { id: recipientId, }, message: { text: msg, }, }, }; fbReq(opts, (err, resp, data) => { if (cb) { cb(err || data.error && data.error.message, data); } }); }; // See the Webhook reference // https://developers.facebook.com/docs/messenger-platform/webhook-reference const getFirstMessagingEntry = (body) => { const val = body.object == 'page' && body.entry && Array.isArray(body.entry) && body.entry.length > 0 && body.entry[0] && body.entry[0].id === FB_PAGE_ID && body.entry[0].messaging && Array.isArray(body.entry[0].messaging) && body.entry[0].messaging.length > 0 && body.entry[0].messaging[0] ; return val || null; }; // Wit.ai bot specific code // This will contain all user sessions. // Each session has an entry: // sessionId -> {fbid: facebookUserId, context: sessionState} const sessions = {}; const findOrCreateSession = (fbid) => { let sessionId; // Let's see if we already have a session for the user fbid Object.keys(sessions).forEach(k => { if (sessions[k].fbid === fbid) { // Yep, got it! sessionId = k; } }); if (!sessionId) { // No session found for user fbid, let's create a new one sessionId = new Date().toISOString(); sessions[sessionId] = {fbid: fbid, context: {}}; } return sessionId; }; const firstEntityValue = (entities, entity) => { const val = entities && entities[entity] && Array.isArray(entities[entity]) && entities[entity].length > 0 && entities[entity][0].value ; if (!val) { return null; } return typeof val === 'object' ? val.value : val; }; // Our bot actions const actions = { say(sessionId, context, message, cb) { // Our bot has something to say! // Let's retrieve the Facebook user whose session belongs to const recipientId = sessions[sessionId].fbid; if (recipientId) { // Yay, we found our recipient! // Let's forward our bot response to her. fbMessage(recipientId, message, (err, data) => { if (err) { console.log( 'Oops! An error occurred while forwarding the response to', recipientId, ':', err ); } // Let's give the wheel back to our bot cb(); }); } else { console.log('Oops! Couldn\'t find user for session:', sessionId); // Giving the wheel back to our bot cb(); } }, merge(sessionId, context, entities, message, cb) { cb(context); }, error(sessionId, context, error) { console.log(error.message); }, ['blank'](sessionId, context, cb) { // Herer is where an API call would go // context.return = apiCall(context.loc); context.return = 'return String'; cb(context); } }; // Setting up our bot const wit = new Wit(WIT_TOKEN, actions); // Starting our webserver and putting it all together const app = express(); app.set('port', PORT); app.listen(app.get('port')); app.use(bodyParser.json()); // Webhook setup app.get('/fb', (req, res) => { if (!FB_VERIFY_TOKEN) { throw new Error('missing FB_VERIFY_TOKEN'); } if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === FB_VERIFY_TOKEN) { res.send(req.query['hub.challenge']); } else { res.sendStatus(400); } }); // Message handler app.post('/fb', (req, res) => { // Parsing the Messenger API response const messaging = getFirstMessagingEntry(req.body); if (messaging && messaging.message && messaging.recipient.id === FB_PAGE_ID) { // Yay! We got a new message! // We retrieve the Facebook user ID of the sender const sender = messaging.sender.id; // We retrieve the user's current session, or create one if it doesn't exist // This is needed for our bot to figure out the conversation history const sessionId = findOrCreateSession(sender); // We retrieve the message content const msg = messaging.message.text; const atts = messaging.message.attachments; if (atts) { // We received an attachment // Let's reply with an automatic message fbMessage( sender, 'Sorry I can only process text messages for now.' ); } else if (msg) { // We received a text message // Let's forward the message to the Wit.ai Bot Engine // This will run all actions until our bot has nothing left to do wit.runActions( sessionId, // the user's current session msg, // the user's message sessions[sessionId].context, // the user's current session state (error, context) => { if (error) { console.log('Oops! Got an error from Wit:', error); } else { // Our bot did everything it has to do. // Now it's waiting for further messages to proceed. console.log('Waiting for futher messages.'); // Based on the session state, you might want to reset the session. // This depends heavily on the business logic of your bot. // Example: // if (context['done']) { // delete sessions[sessionId]; // } // Updating the user's current session state sessions[sessionId].context = context; } } ); } } res.sendStatus(200); });
var structarm__pid__instance__q15 = [ [ "A0", "structarm__pid__instance__q15.html#ad77f3a2823c7f96de42c92a3fbf3246b", null ], [ "A1", "structarm__pid__instance__q15.html#ad8ac5ff736c0e51180398c31f777f18a", null ], [ "A2", "structarm__pid__instance__q15.html#a33e8b4c2d3e24b8b494f6edca6a89c1b", null ], [ "Kd", "structarm__pid__instance__q15.html#af5d4b53091f19eff7536636b7cc43111", null ], [ "Ki", "structarm__pid__instance__q15.html#a0dcc19d5c8f7bc401acea9e8318cd777", null ], [ "Kp", "structarm__pid__instance__q15.html#ad228aae24a1b6d855c93a8b9bbc1c4f1", null ], [ "state", "structarm__pid__instance__q15.html#a4a3f0a878b5b6b055e3478a2f244cd30", null ] ];
define([ 'backbone', 'text!templates/item_chooser.tpl', 'models/item', 'models/trigger', 'models/instance', 'models/media', 'views/item_chooser_row', 'views/trigger_creator', 'vent', 'util', ], function( Backbone, Template, Item, Trigger, Instance, Media, ItemChooserRowView, TriggerCreatorView, vent, util ) { return Backbone.Marionette.CompositeView.extend( { template: _.template(Template), itemView: ItemChooserRowView, itemViewContainer: ".items", itemViewOptions: function(model, index) { return { parent: this.options.parent } }, events: { "click .new-item": "onClickNewItem" }, /* TODO move complex sets like this into a controller */ onClickNewItem: function() { var loc = util.default_location(); var trigger = new Trigger ({game_id:this.options.parent.get("game_id"), scene_id:this.options.parent.get("scene_id"), latitude:loc.latitude, longitude:loc.longitude }); var instance = new Instance ({game_id: this.options.parent.get("game_id")}); var item = new Item ({game_id: this.options.parent.get("game_id")}); var trigger_creator = new TriggerCreatorView({scene: this.options.parent, game_object: item, instance: instance, model: trigger}); vent.trigger("application:popup:show", trigger_creator, "Add Item to Scene"); }, // Marionette override appendBuffer: function(compositeView, buffer) { var $container = this.getItemViewContainer(compositeView); $container.find(".foot").before(buffer); }, appendHtml: function(compositeView, itemView, index) { if (compositeView.isBuffering) { compositeView.elBuffer.appendChild(itemView.el); } else { // If we've already rendered the main collection, just // append the new items directly into the element. var $container = this.getItemViewContainer(compositeView); $container.find(".foot").before(itemView.el); } } }); });
import * as React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { demos, docs, requireDemo, } from '!@material-ui/markdown/loader!docs/src/pages/guides/api/api.md'; export default function Page() { return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />; }
var mongoose = require('mongoose'); var TreatmentPrescription = mongoose.model('TreatmentPrescription', require('../models/TreatmentPrescription').TreatmentPrescriptionSchema); function list(response, params){ TreatmentPrescription.find(params) .sort('created_at') .exec(function(error, prescriptions){ if(error){ console.log(error); prescriptions = []; } response.json(prescriptions); }); } function create_from_body(request){ return { doctor: request.user._id, treatment: request.param('treatment'), items: request.body.items }; } exports.list = function(request, response){ var params = { treatment: request.param('treatment') }; list(response, params); }; exports.single = function(request, response){ if(request.param('prescription') === 'new') { response.json(new TreatmentPrescription({ treatment: request.param('treatment') })); return; } var params = { _id: request.param('prescription'), treatment: request.param('treatment') }; TreatmentPrescription.findOne(params, function(error, prescription){ if(error){ console.log(error); prescription = null; } response.json(prescription); }); }; exports.create = function(request, response){ var values = create_from_body(request); var treatment = new TreatmentPrescription(values); treatment.save(function(error, document){ if(error || !document){ response.json({ error: error }); } else { response.json(document); } }); }; exports.edit = function(request, response){ var values = create_from_body(request); TreatmentPrescription.findByIdAndUpdate(request.body._id, values, function(error, document){ if(error){ response.json({ error: error }); return; } response.json(document); }); }; exports.remove = function(request, response){ if(request.user.type === 'doctor'){ TreatmentPrescription.findByIdAndRemove(request.param('prescription'), function(error){ if(error){ console.log(error); response.send(400); return; } response.send(200) }); } else { response.send(200) } };
/* global describe, it, assert, expect */ 'use strict'; // TESTS // describe( 'paddingLeft', function tests() { var el = document.querySelector( '#fixture' ); it( 'should expose an attribute for specifying the left padding between the canvas edge and the graph area', function test() { expect( el.paddingLeft ).to.be.a( 'number' ); }); it( 'should emit an `error` if not set to a positive integer', function test( done ) { var num = el.paddingLeft, values; values = [ function(){}, '5', -1, 3.14, NaN, // undefined, // TODO: enable once https://github.com/Polymer/polymer/issues/1053 is resolved true, [], {} ]; el.addEventListener( 'err', onError ); next(); function next() { el.paddingLeft = values.shift(); } function onError( evt ) { assert.instanceOf( evt.detail, TypeError ); if ( values.length ) { setTimeout( next, 0 ); return; } setTimeout( end, 0 ); } function end() { assert.strictEqual( el.paddingLeft, num ); el.removeEventListener( 'err', onError ); done(); } }); it( 'should emit a `changed` event when set to a new value', function test( done ) { el.addEventListener( 'changed', onChange ); el.paddingLeft = 0; function onChange( evt ) { assert.isObject( evt.detail ); assert.strictEqual( evt.detail.attr, 'paddingLeft' ); el.removeEventListener( 'changed', onChange ); done(); } }); it( 'should update the background width' ); it( 'should update the clipPath width' ); it( 'should update the graph position' ); it( 'should update the vertices' ); it( 'should update the edges' ); });
const project = require('../config/project.config') const server = require('../server/index') const debug = require('debug')('app:bin:dev-server') server.listen(project.server_port) debug(`Server is now running at http://localhost:${project.server_port}.`)
var is_touch; function is_touch_device() { return 'ontouchstart' in window // works on most browsers || navigator.maxTouchPoints; // works on IE10/11 and Surface } (function() { is_touch = is_touch_device(); })();
module.exports = require('./lib/goldwasher-aws-lambda.js');
/*Generated by KISSY Module Compiler*/ config({ 'editor/plugin/unordered-list': {requires: ['editor','editor/plugin/list-utils/btn']} });
import {smartTable} from 'smart-table-core'; //change the structure of returned items const smartTableExtension = function ({table, tableState, data}) { const oldChangeRegister = table.onDisplayChange; //will overwrite the default onDisplayChange return { onDisplayChange(listener) { oldChangeRegister(function (items) { const itemValues = items.map(i => i.value); listener(itemValues); }); } }; }; // our composed factory const superSmartTable = function ({data}) { const core = smartTable({data}); return Object.assign(core, smartTableExtension({table: core})); //overwrite core method by mixin the extension within the core }; //use our super smart table const data = [ {surname: 'Deubaze', name: 'Raymond'}, {surname: 'Foo', name: 'Bar'}, {surname: 'Doe', name: 'John'} ]; const table = superSmartTable({data}); // core methods available table.onDisplayChange(items => console.log(items)); // no need to extract "value" property as the method has been overwritten table.exec();
var debug = require('util').debug, inspect = require('util').inspect, path = require('path'), fs = require('fs'), exec = require('child_process').exec, spawn = require('child_process').spawn, Connection = require('../../lib/mongodb').Connection, Db = require('../../lib/mongodb').Db, Server = require('../../lib/mongodb').Server; var ServerManager = exports.ServerManager = function(options) { options = options == null ? {} : options; // Basic unpack values this.path = path.resolve("data"); this.port = options["start_port"] != null ? options["start_port"] : 27017; this.db_path = getPath(this, "data-" + this.port); this.log_path = getPath(this, "log-" + this.port); this.journal = options["journal"] != null ? options["journal"] : false; this.auth = options['auth'] != null ? options['auth'] : false; this.purgedirectories = options['purgedirectories'] != null ? options['purgedirectories'] : true; // Server status values this.up = false; this.pid = null; } // Start up the server instance ServerManager.prototype.start = function(killall, callback) { var self = this; // Unpack callback and variables var args = Array.prototype.slice.call(arguments, 0); callback = args.pop(); killall = args.length ? args.shift() : true; // Create start command var startCmd = generateStartCmd({log_path: self.log_path, db_path: self.db_path, port: self.port, journal: self.journal, auth:self.auth}); // console.log("----------------------------------------------------------------------- start") // console.log(startCmd) exec(killall ? 'killall mongod' : '', function(err, stdout, stderr) { if(self.purgedirectories) { // Remove directory exec("rm -rf " + self.db_path, function(err, stdout, stderr) { if(err != null) return callback(err, null); // Create directory exec("mkdir -p " + self.db_path, function(err, stdout, stderr) { if(err != null) return callback(err, null); // Start up mongod process var mongodb = exec(startCmd, function (error, stdout, stderr) { // console.log('stdout: ' + stdout); // console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); // Wait for a half a second then save the pids setTimeout(function() { // Mark server as running self.up = true; self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); // Callback callback(); }, 500); }); }); } else { // Ensure we remove the lock file as we are not purging the directory fs.unlinkSync(path.join(self.db_path, "mongod.lock")); // Start up mongod process var mongodb = exec(startCmd, function (error, stdout, stderr) { if (error !== null) { console.log('exec error: ' + error); } }); // Wait for a half a second then save the pids setTimeout(function() { // Mark server as running self.up = true; self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); // Callback callback(); }, 5000); } }); } ServerManager.prototype.stop = function(signal, callback) { var self = this; // Unpack callback and variables var args = Array.prototype.slice.call(arguments, 0); callback = args.pop(); signal = args.length ? args.shift() : 2; // Stop the server var command = "kill -" + signal + " " + self.pid; // Kill process exec(command, function (error, stdout, stderr) { // console.log('stdout: ' + stdout); // console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } self.up = false; // Wait for a second setTimeout(callback, 1000); }); } ServerManager.prototype.killAll = function(callback) { exec('killall mongod', function(err, stdout, stderr) { callback(null, null); }); } // Get absolute path var getPath = function(self, name) { return path.join(self.path, name); } // Generate start command var generateStartCmd = function(options) { // Create boot command var startCmd = "mongod --noprealloc --logpath '" + options['log_path'] + "' " + " --dbpath " + options['db_path'] + " --port " + options['port'] + " --fork"; startCmd = options['journal'] ? startCmd + " --journal" : startCmd; startCmd = options['auth'] ? startCmd + " --auth" : startCmd; return startCmd; }
import * as React from 'react'; import PropTypes from 'prop-types'; import { useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableContainer'; import TableFooter from '@mui/material/TableFooter'; import TablePagination from '@mui/material/TablePagination'; import TableRow from '@mui/material/TableRow'; import Paper from '@mui/material/Paper'; import IconButton from '@mui/material/IconButton'; import FirstPageIcon from '@mui/icons-material/FirstPage'; import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft'; import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight'; import LastPageIcon from '@mui/icons-material/LastPage'; function TablePaginationActions(props) { const theme = useTheme(); const { count, page, rowsPerPage, onPageChange } = props; const handleFirstPageButtonClick = (event) => { onPageChange(event, 0); }; const handleBackButtonClick = (event) => { onPageChange(event, page - 1); }; const handleNextButtonClick = (event) => { onPageChange(event, page + 1); }; const handleLastPageButtonClick = (event) => { onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1)); }; return ( <Box sx={{ flexShrink: 0, ml: 2.5 }}> <IconButton onClick={handleFirstPageButtonClick} disabled={page === 0} aria-label="first page" > {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />} </IconButton> <IconButton onClick={handleBackButtonClick} disabled={page === 0} aria-label="previous page" > {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />} </IconButton> <IconButton onClick={handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="next page" > {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />} </IconButton> <IconButton onClick={handleLastPageButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="last page" > {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />} </IconButton> </Box> ); } TablePaginationActions.propTypes = { count: PropTypes.number.isRequired, onPageChange: PropTypes.func.isRequired, page: PropTypes.number.isRequired, rowsPerPage: PropTypes.number.isRequired, }; function createData(name, calories, fat) { return { name, calories, fat }; } const rows = [ createData('Cupcake', 305, 3.7), createData('Donut', 452, 25.0), createData('Eclair', 262, 16.0), createData('Frozen yoghurt', 159, 6.0), createData('Gingerbread', 356, 16.0), createData('Honeycomb', 408, 3.2), createData('Ice cream sandwich', 237, 9.0), createData('Jelly Bean', 375, 0.0), createData('KitKat', 518, 26.0), createData('Lollipop', 392, 0.2), createData('Marshmallow', 318, 0), createData('Nougat', 360, 19.0), createData('Oreo', 437, 18.0), ].sort((a, b) => (a.calories < b.calories ? -1 : 1)); export default function CustomPaginationActionsTable() { const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(5); // Avoid a layout jump when reaching the last page with empty rows. const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0; const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; return ( <TableContainer component={Paper}> <Table sx={{ minWidth: 500 }} aria-label="custom pagination table"> <TableBody> {(rowsPerPage > 0 ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : rows ).map((row) => ( <TableRow key={row.name}> <TableCell component="th" scope="row"> {row.name} </TableCell> <TableCell style={{ width: 160 }} align="right"> {row.calories} </TableCell> <TableCell style={{ width: 160 }} align="right"> {row.fat} </TableCell> </TableRow> ))} {emptyRows > 0 && ( <TableRow style={{ height: 53 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} </TableBody> <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]} colSpan={3} count={rows.length} rowsPerPage={rowsPerPage} page={page} SelectProps={{ inputProps: { 'aria-label': 'rows per page', }, native: true, }} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} ActionsComponent={TablePaginationActions} /> </TableRow> </TableFooter> </Table> </TableContainer> ); }
#!/usr/bin/env node var argv = require('yargs/yargs')(process.argv.slice(2)) .boolean(['r','v']) .argv ; console.dir([ argv.r, argv.v ]); console.dir(argv._);
/*! * Uploader - Uploader library implements html5 file upload and provides multiple simultaneous, stable, fault tolerant and resumable uploads * @version v0.5.6 * @author dolymood <[email protected]> * @link https://github.com/simple-uploader/Uploader * @license MIT */ !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Uploader=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var utils = _dereq_('./utils') function Chunk (uploader, file, offset) { utils.defineNonEnumerable(this, 'uploader', uploader) utils.defineNonEnumerable(this, 'file', file) utils.defineNonEnumerable(this, 'bytes', null) this.offset = offset this.tested = false this.retries = 0 this.pendingRetry = false this.preprocessState = 0 this.readState = 0 this.loaded = 0 this.total = 0 this.chunkSize = this.uploader.opts.chunkSize this.startByte = this.offset * this.chunkSize this.endByte = this.computeEndByte() this.xhr = null } var STATUS = Chunk.STATUS = { PENDING: 'pending', UPLOADING: 'uploading', READING: 'reading', SUCCESS: 'success', ERROR: 'error', COMPLETE: 'complete', PROGRESS: 'progress', RETRY: 'retry' } utils.extend(Chunk.prototype, { _event: function (evt, args) { args = utils.toArray(arguments) args.unshift(this) this.file._chunkEvent.apply(this.file, args) }, computeEndByte: function () { var endByte = Math.min(this.file.size, (this.offset + 1) * this.chunkSize) if (this.file.size - endByte < this.chunkSize && !this.uploader.opts.forceChunkSize) { // The last chunk will be bigger than the chunk size, // but less than 2 * this.chunkSize endByte = this.file.size } return endByte }, getParams: function () { return { chunkNumber: this.offset + 1, chunkSize: this.uploader.opts.chunkSize, currentChunkSize: this.endByte - this.startByte, totalSize: this.file.size, identifier: this.file.uniqueIdentifier, filename: this.file.name, relativePath: this.file.relativePath, totalChunks: this.file.chunks.length } }, getTarget: function (target, params) { if (!params.length) { return target } if (target.indexOf('?') < 0) { target += '?' } else { target += '&' } return target + params.join('&') }, test: function () { this.xhr = new XMLHttpRequest() this.xhr.addEventListener('load', testHandler, false) this.xhr.addEventListener('error', testHandler, false) var testMethod = utils.evalOpts(this.uploader.opts.testMethod, this.file, this) var data = this.prepareXhrRequest(testMethod, true) this.xhr.send(data) var $ = this function testHandler (event) { var status = $.status(true) if (status === STATUS.ERROR) { $._event(status, $.message()) $.uploader.uploadNextChunk() } else if (status === STATUS.SUCCESS) { $._event(status, $.message()) $.tested = true } else if (!$.file.paused) { // Error might be caused by file pause method // Chunks does not exist on the server side $.tested = true $.send() } } }, preprocessFinished: function () { // Compute the endByte after the preprocess function to allow an // implementer of preprocess to set the fileObj size this.endByte = this.computeEndByte() this.preprocessState = 2 this.send() }, readFinished: function (bytes) { this.readState = 2 this.bytes = bytes this.send() }, send: function () { var preprocess = this.uploader.opts.preprocess var read = this.uploader.opts.readFileFn if (utils.isFunction(preprocess)) { switch (this.preprocessState) { case 0: this.preprocessState = 1 preprocess(this) return case 1: return } } switch (this.readState) { case 0: this.readState = 1 read(this.file, this.file.fileType, this.startByte, this.endByte, this) return case 1: return } if (this.uploader.opts.testChunks && !this.tested) { this.test() return } this.loaded = 0 this.total = 0 this.pendingRetry = false // Set up request and listen for event this.xhr = new XMLHttpRequest() this.xhr.upload.addEventListener('progress', progressHandler, false) this.xhr.addEventListener('load', doneHandler, false) this.xhr.addEventListener('error', doneHandler, false) var uploadMethod = utils.evalOpts(this.uploader.opts.uploadMethod, this.file, this) var data = this.prepareXhrRequest(uploadMethod, false, this.uploader.opts.method, this.bytes) this.xhr.send(data) var $ = this function progressHandler (event) { if (event.lengthComputable) { $.loaded = event.loaded $.total = event.total } $._event(STATUS.PROGRESS, event) } function doneHandler (event) { var msg = $.message() $.processingResponse = true $.uploader.opts.processResponse(msg, function (err, res) { $.processingResponse = false if (!$.xhr) { return } $.processedState = { err: err, res: res } var status = $.status() if (status === STATUS.SUCCESS || status === STATUS.ERROR) { // delete this.data $._event(status, res) status === STATUS.ERROR && $.uploader.uploadNextChunk() } else { $._event(STATUS.RETRY, res) $.pendingRetry = true $.abort() $.retries++ var retryInterval = $.uploader.opts.chunkRetryInterval if (retryInterval !== null) { setTimeout(function () { $.send() }, retryInterval) } else { $.send() } } }, $.file, $) } }, abort: function () { var xhr = this.xhr this.xhr = null this.processingResponse = false this.processedState = null if (xhr) { xhr.abort() } }, status: function (isTest) { if (this.readState === 1) { return STATUS.READING } else if (this.pendingRetry || this.preprocessState === 1) { // if pending retry then that's effectively the same as actively uploading, // there might just be a slight delay before the retry starts return STATUS.UPLOADING } else if (!this.xhr) { return STATUS.PENDING } else if (this.xhr.readyState < 4 || this.processingResponse) { // Status is really 'OPENED', 'HEADERS_RECEIVED' // or 'LOADING' - meaning that stuff is happening return STATUS.UPLOADING } else { var _status if (this.uploader.opts.successStatuses.indexOf(this.xhr.status) > -1) { // HTTP 200, perfect // HTTP 202 Accepted - The request has been accepted for processing, but the processing has not been completed. _status = STATUS.SUCCESS } else if (this.uploader.opts.permanentErrors.indexOf(this.xhr.status) > -1 || !isTest && this.retries >= this.uploader.opts.maxChunkRetries) { // HTTP 415/500/501, permanent error _status = STATUS.ERROR } else { // this should never happen, but we'll reset and queue a retry // a likely case for this would be 503 service unavailable this.abort() _status = STATUS.PENDING } var processedState = this.processedState if (processedState && processedState.err) { _status = STATUS.ERROR } return _status } }, message: function () { return this.xhr ? this.xhr.responseText : '' }, progress: function () { if (this.pendingRetry) { return 0 } var s = this.status() if (s === STATUS.SUCCESS || s === STATUS.ERROR) { return 1 } else if (s === STATUS.PENDING) { return 0 } else { return this.total > 0 ? this.loaded / this.total : 0 } }, sizeUploaded: function () { var size = this.endByte - this.startByte // can't return only chunk.loaded value, because it is bigger than chunk size if (this.status() !== STATUS.SUCCESS) { size = this.progress() * size } return size }, prepareXhrRequest: function (method, isTest, paramsMethod, blob) { // Add data from the query options var query = utils.evalOpts(this.uploader.opts.query, this.file, this, isTest) query = utils.extend(this.getParams(), query) // processParams query = this.uploader.opts.processParams(query, this.file, this, isTest) var target = utils.evalOpts(this.uploader.opts.target, this.file, this, isTest) var data = null if (method === 'GET' || paramsMethod === 'octet') { // Add data from the query options var params = [] utils.each(query, function (v, k) { params.push([encodeURIComponent(k), encodeURIComponent(v)].join('=')) }) target = this.getTarget(target, params) data = blob || null } else { // Add data from the query options data = new FormData() utils.each(query, function (v, k) { data.append(k, v) }) if (typeof blob !== 'undefined') { data.append(this.uploader.opts.fileParameterName, blob, this.file.name) } } this.xhr.open(method, target, true) this.xhr.withCredentials = this.uploader.opts.withCredentials // Add data from header options utils.each(utils.evalOpts(this.uploader.opts.headers, this.file, this, isTest), function (v, k) { this.xhr.setRequestHeader(k, v) }, this) return data } }) module.exports = Chunk },{"./utils":5}],2:[function(_dereq_,module,exports){ var each = _dereq_('./utils').each var event = { _eventData: null, on: function (name, func) { if (!this._eventData) this._eventData = {} if (!this._eventData[name]) this._eventData[name] = [] var listened = false each(this._eventData[name], function (fuc) { if (fuc === func) { listened = true return false } }) if (!listened) { this._eventData[name].push(func) } }, off: function (name, func) { if (!this._eventData) this._eventData = {} if (!this._eventData[name] || !this._eventData[name].length) return if (func) { each(this._eventData[name], function (fuc, i) { if (fuc === func) { this._eventData[name].splice(i, 1) return false } }, this) } else { this._eventData[name] = [] } }, trigger: function (name) { if (!this._eventData) this._eventData = {} if (!this._eventData[name]) return true var args = this._eventData[name].slice.call(arguments, 1) var preventDefault = false each(this._eventData[name], function (fuc) { preventDefault = fuc.apply(this, args) === false || preventDefault }, this) return !preventDefault } } module.exports = event },{"./utils":5}],3:[function(_dereq_,module,exports){ var utils = _dereq_('./utils') var event = _dereq_('./event') var File = _dereq_('./file') var Chunk = _dereq_('./chunk') var version = '0.5.6' var isServer = typeof window === 'undefined' // ie10+ var ie10plus = isServer ? false : window.navigator.msPointerEnabled var support = (function () { if (isServer) { return false } var sliceName = 'slice' var _support = utils.isDefined(window.File) && utils.isDefined(window.Blob) && utils.isDefined(window.FileList) var bproto = null if (_support) { bproto = window.Blob.prototype utils.each(['slice', 'webkitSlice', 'mozSlice'], function (n) { if (bproto[n]) { sliceName = n return false } }) _support = !!bproto[sliceName] } if (_support) Uploader.sliceName = sliceName bproto = null return _support })() var supportDirectory = (function () { if (isServer) { return false } var input = window.document.createElement('input') input.type = 'file' var sd = 'webkitdirectory' in input || 'directory' in input input = null return sd })() function Uploader (opts) { this.support = support /* istanbul ignore if */ if (!this.support) { return } this.supportDirectory = supportDirectory utils.defineNonEnumerable(this, 'filePaths', {}) this.opts = utils.extend({}, Uploader.defaults, opts || {}) this.preventEvent = utils.bind(this._preventEvent, this) File.call(this, this) } /** * Default read function using the webAPI * * @function webAPIFileRead(fileObj, fileType, startByte, endByte, chunk) * */ var webAPIFileRead = function (fileObj, fileType, startByte, endByte, chunk) { chunk.readFinished(fileObj.file[Uploader.sliceName](startByte, endByte, fileType)) } Uploader.version = version Uploader.defaults = { chunkSize: 1024 * 1024, forceChunkSize: false, simultaneousUploads: 3, singleFile: false, fileParameterName: 'file', progressCallbacksInterval: 500, speedSmoothingFactor: 0.1, query: {}, headers: {}, withCredentials: false, preprocess: null, method: 'multipart', testMethod: 'GET', uploadMethod: 'POST', prioritizeFirstAndLastChunk: false, allowDuplicateUploads: false, target: '/', testChunks: true, generateUniqueIdentifier: null, maxChunkRetries: 0, chunkRetryInterval: null, permanentErrors: [404, 415, 500, 501], successStatuses: [200, 201, 202], onDropStopPropagation: false, initFileFn: null, readFileFn: webAPIFileRead, checkChunkUploadedByResponse: null, initialPaused: false, processResponse: function (response, cb) { cb(null, response) }, processParams: function (params) { return params } } Uploader.utils = utils Uploader.event = event Uploader.File = File Uploader.Chunk = Chunk // inherit file Uploader.prototype = utils.extend({}, File.prototype) // inherit event utils.extend(Uploader.prototype, event) utils.extend(Uploader.prototype, { constructor: Uploader, _trigger: function (name) { var args = utils.toArray(arguments) var preventDefault = !this.trigger.apply(this, arguments) if (name !== 'catchAll') { args.unshift('catchAll') preventDefault = !this.trigger.apply(this, args) || preventDefault } return !preventDefault }, _triggerAsync: function () { var args = arguments utils.nextTick(function () { this._trigger.apply(this, args) }, this) }, addFiles: function (files, evt) { var _files = [] var oldFileListLen = this.fileList.length utils.each(files, function (file) { // Uploading empty file IE10/IE11 hangs indefinitely // Directories have size `0` and name `.` // Ignore already added files if opts.allowDuplicateUploads is set to false if ((!ie10plus || ie10plus && file.size > 0) && !(file.size % 4096 === 0 && (file.name === '.' || file.fileName === '.'))) { var uniqueIdentifier = this.generateUniqueIdentifier(file) if (this.opts.allowDuplicateUploads || !this.getFromUniqueIdentifier(uniqueIdentifier)) { var _file = new File(this, file, this) _file.uniqueIdentifier = uniqueIdentifier if (this._trigger('fileAdded', _file, evt)) { _files.push(_file) } else { File.prototype.removeFile.call(this, _file) } } } }, this) // get new fileList var newFileList = this.fileList.slice(oldFileListLen) if (this._trigger('filesAdded', _files, newFileList, evt)) { utils.each(_files, function (file) { if (this.opts.singleFile && this.files.length > 0) { this.removeFile(this.files[0]) } this.files.push(file) }, this) this._trigger('filesSubmitted', _files, newFileList, evt) } else { utils.each(newFileList, function (file) { File.prototype.removeFile.call(this, file) }, this) } }, addFile: function (file, evt) { this.addFiles([file], evt) }, cancel: function () { for (var i = this.fileList.length - 1; i >= 0; i--) { this.fileList[i].cancel() } }, removeFile: function (file) { File.prototype.removeFile.call(this, file) this._trigger('fileRemoved', file) }, generateUniqueIdentifier: function (file) { var custom = this.opts.generateUniqueIdentifier if (utils.isFunction(custom)) { return custom(file) } /* istanbul ignore next */ // Some confusion in different versions of Firefox var relativePath = file.relativePath || file.webkitRelativePath || file.fileName || file.name /* istanbul ignore next */ return file.size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, '') }, getFromUniqueIdentifier: function (uniqueIdentifier) { var ret = false utils.each(this.files, function (file) { if (file.uniqueIdentifier === uniqueIdentifier) { ret = file return false } }) return ret }, uploadNextChunk: function (preventEvents) { var found = false var pendingStatus = Chunk.STATUS.PENDING var checkChunkUploaded = this.uploader.opts.checkChunkUploadedByResponse if (this.opts.prioritizeFirstAndLastChunk) { utils.each(this.files, function (file) { if (file.paused) { return } if (checkChunkUploaded && !file._firstResponse && file.isUploading()) { // waiting for current file's first chunk response return } if (file.chunks.length && file.chunks[0].status() === pendingStatus) { file.chunks[0].send() found = true return false } if (file.chunks.length > 1 && file.chunks[file.chunks.length - 1].status() === pendingStatus) { file.chunks[file.chunks.length - 1].send() found = true return false } }) if (found) { return found } } // Now, simply look for the next, best thing to upload utils.each(this.files, function (file) { if (!file.paused) { if (checkChunkUploaded && !file._firstResponse && file.isUploading()) { // waiting for current file's first chunk response return } utils.each(file.chunks, function (chunk) { if (chunk.status() === pendingStatus) { chunk.send() found = true return false } }) } if (found) { return false } }) if (found) { return true } // The are no more outstanding chunks to upload, check is everything is done var outstanding = false utils.each(this.files, function (file) { if (!file.isComplete()) { outstanding = true return false } }) // should check files now // if now files in list // should not trigger complete event if (!outstanding && !preventEvents && this.files.length) { // All chunks have been uploaded, complete this._triggerAsync('complete') } return outstanding }, upload: function (preventEvents) { // Make sure we don't start too many uploads at once var ret = this._shouldUploadNext() if (ret === false) { return } !preventEvents && this._trigger('uploadStart') var started = false for (var num = 1; num <= this.opts.simultaneousUploads - ret; num++) { started = this.uploadNextChunk(!preventEvents) || started if (!started && preventEvents) { // completed break } } if (!started && !preventEvents) { this._triggerAsync('complete') } }, /** * should upload next chunk * @function * @returns {Boolean|Number} */ _shouldUploadNext: function () { var num = 0 var should = true var simultaneousUploads = this.opts.simultaneousUploads var uploadingStatus = Chunk.STATUS.UPLOADING utils.each(this.files, function (file) { utils.each(file.chunks, function (chunk) { if (chunk.status() === uploadingStatus) { num++ if (num >= simultaneousUploads) { should = false return false } } }) return should }) // if should is true then return uploading chunks's length return should && num }, /** * Assign a browse action to one or more DOM nodes. * @function * @param {Element|Array.<Element>} domNodes * @param {boolean} isDirectory Pass in true to allow directories to * @param {boolean} singleFile prevent multi file upload * @param {Object} attributes set custom attributes: * http://www.w3.org/TR/html-markup/input.file.html#input.file-attributes * eg: accept: 'image/*' * be selected (Chrome only). */ assignBrowse: function (domNodes, isDirectory, singleFile, attributes) { if (typeof domNodes.length === 'undefined') { domNodes = [domNodes] } utils.each(domNodes, function (domNode) { var input if (domNode.tagName === 'INPUT' && domNode.type === 'file') { input = domNode } else { input = document.createElement('input') input.setAttribute('type', 'file') // display:none - not working in opera 12 utils.extend(input.style, { visibility: 'hidden', position: 'absolute', width: '1px', height: '1px' }) // for opera 12 browser, input must be assigned to a document domNode.appendChild(input) // https://developer.mozilla.org/en/using_files_from_web_applications) // event listener is executed two times // first one - original mouse click event // second - input.click(), input is inside domNode domNode.addEventListener('click', function (e) { if (domNode.tagName.toLowerCase() === 'label') { return } input.click() }, false) } if (!this.opts.singleFile && !singleFile) { input.setAttribute('multiple', 'multiple') } if (isDirectory) { input.setAttribute('webkitdirectory', 'webkitdirectory') } attributes && utils.each(attributes, function (value, key) { input.setAttribute(key, value) }) // When new files are added, simply append them to the overall list var that = this input.addEventListener('change', function (e) { that._trigger(e.type, e) if (e.target.value) { that.addFiles(e.target.files, e) e.target.value = '' } }, false) }, this) }, onDrop: function (evt) { this._trigger(evt.type, evt) if (this.opts.onDropStopPropagation) { evt.stopPropagation() } evt.preventDefault() this._parseDataTransfer(evt.dataTransfer, evt) }, _parseDataTransfer: function (dataTransfer, evt) { if (dataTransfer.items && dataTransfer.items[0] && dataTransfer.items[0].webkitGetAsEntry) { this.webkitReadDataTransfer(dataTransfer, evt) } else { this.addFiles(dataTransfer.files, evt) } }, webkitReadDataTransfer: function (dataTransfer, evt) { var self = this var queue = dataTransfer.items.length var files = [] utils.each(dataTransfer.items, function (item) { var entry = item.webkitGetAsEntry() if (!entry) { decrement() return } if (entry.isFile) { // due to a bug in Chrome's File System API impl - #149735 fileReadSuccess(item.getAsFile(), entry.fullPath) } else { readDirectory(entry.createReader()) } }) function readDirectory (reader) { reader.readEntries(function (entries) { if (entries.length) { queue += entries.length utils.each(entries, function (entry) { if (entry.isFile) { var fullPath = entry.fullPath entry.file(function (file) { fileReadSuccess(file, fullPath) }, readError) } else if (entry.isDirectory) { readDirectory(entry.createReader()) } }) readDirectory(reader) } else { decrement() } }, readError) } function fileReadSuccess (file, fullPath) { // relative path should not start with "/" file.relativePath = fullPath.substring(1) files.push(file) decrement() } function readError (fileError) { throw fileError } function decrement () { if (--queue === 0) { self.addFiles(files, evt) } } }, _assignHelper: function (domNodes, handles, remove) { if (typeof domNodes.length === 'undefined') { domNodes = [domNodes] } var evtMethod = remove ? 'removeEventListener' : 'addEventListener' utils.each(domNodes, function (domNode) { utils.each(handles, function (handler, name) { domNode[evtMethod](name, handler, false) }, this) }, this) }, _preventEvent: function (e) { utils.preventEvent(e) this._trigger(e.type, e) }, /** * Assign one or more DOM nodes as a drop target. * @function * @param {Element|Array.<Element>} domNodes */ assignDrop: function (domNodes) { this._onDrop = utils.bind(this.onDrop, this) this._assignHelper(domNodes, { dragover: this.preventEvent, dragenter: this.preventEvent, dragleave: this.preventEvent, drop: this._onDrop }) }, /** * Un-assign drop event from DOM nodes * @function * @param domNodes */ unAssignDrop: function (domNodes) { this._assignHelper(domNodes, { dragover: this.preventEvent, dragenter: this.preventEvent, dragleave: this.preventEvent, drop: this._onDrop }, true) this._onDrop = null } }) module.exports = Uploader },{"./chunk":1,"./event":2,"./file":4,"./utils":5}],4:[function(_dereq_,module,exports){ var utils = _dereq_('./utils') var Chunk = _dereq_('./chunk') function File (uploader, file, parent) { utils.defineNonEnumerable(this, 'uploader', uploader) this.isRoot = this.isFolder = uploader === this utils.defineNonEnumerable(this, 'parent', parent || null) utils.defineNonEnumerable(this, 'files', []) utils.defineNonEnumerable(this, 'fileList', []) utils.defineNonEnumerable(this, 'chunks', []) utils.defineNonEnumerable(this, '_errorFiles', []) utils.defineNonEnumerable(this, 'file', null) this.id = utils.uid() if (this.isRoot || !file) { this.file = null } else { if (utils.isString(file)) { // folder this.isFolder = true this.file = null this.path = file if (this.parent.path) { file = file.substr(this.parent.path.length) } this.name = file.charAt(file.length - 1) === '/' ? file.substr(0, file.length - 1) : file } else { this.file = file this.fileType = this.file.type this.name = file.fileName || file.name this.size = file.size this.relativePath = file.relativePath || file.webkitRelativePath || this.name this._parseFile() } } this.paused = uploader.opts.initialPaused this.error = false this.allError = false this.aborted = false this.completed = false this.averageSpeed = 0 this.currentSpeed = 0 this._lastProgressCallback = Date.now() this._prevUploadedSize = 0 this._prevProgress = 0 this.bootstrap() } utils.extend(File.prototype, { _parseFile: function () { var ppaths = parsePaths(this.relativePath) if (ppaths.length) { var filePaths = this.uploader.filePaths utils.each(ppaths, function (path, i) { var folderFile = filePaths[path] if (!folderFile) { folderFile = new File(this.uploader, path, this.parent) filePaths[path] = folderFile this._updateParentFileList(folderFile) } this.parent = folderFile folderFile.files.push(this) if (!ppaths[i + 1]) { folderFile.fileList.push(this) } }, this) } else { this._updateParentFileList() } }, _updateParentFileList: function (file) { if (!file) { file = this } var p = this.parent if (p) { p.fileList.push(file) } }, _eachAccess: function (eachFn, fileFn) { if (this.isFolder) { utils.each(this.files, function (f, i) { return eachFn.call(this, f, i) }, this) return } fileFn.call(this, this) }, bootstrap: function () { if (this.isFolder) return var opts = this.uploader.opts if (utils.isFunction(opts.initFileFn)) { opts.initFileFn.call(this, this) } this.abort(true) this._resetError() // Rebuild stack of chunks from file this._prevProgress = 0 var round = opts.forceChunkSize ? Math.ceil : Math.floor var chunks = Math.max(round(this.size / opts.chunkSize), 1) for (var offset = 0; offset < chunks; offset++) { this.chunks.push(new Chunk(this.uploader, this, offset)) } }, _measureSpeed: function () { var smoothingFactor = this.uploader.opts.speedSmoothingFactor var timeSpan = Date.now() - this._lastProgressCallback if (!timeSpan) { return } var uploaded = this.sizeUploaded() // Prevent negative upload speed after file upload resume this.currentSpeed = Math.max((uploaded - this._prevUploadedSize) / timeSpan * 1000, 0) this.averageSpeed = smoothingFactor * this.currentSpeed + (1 - smoothingFactor) * this.averageSpeed this._prevUploadedSize = uploaded if (this.parent && this.parent._checkProgress()) { this.parent._measureSpeed() } }, _checkProgress: function (file) { return Date.now() - this._lastProgressCallback >= this.uploader.opts.progressCallbacksInterval }, _chunkEvent: function (chunk, evt, message) { var uploader = this.uploader var STATUS = Chunk.STATUS var that = this var rootFile = this.getRoot() var triggerProgress = function () { that._measureSpeed() uploader._trigger('fileProgress', rootFile, that, chunk) that._lastProgressCallback = Date.now() } switch (evt) { case STATUS.PROGRESS: if (this._checkProgress()) { triggerProgress() } break case STATUS.ERROR: this._error() this.abort(true) uploader._trigger('fileError', rootFile, this, message, chunk) break case STATUS.SUCCESS: this._updateUploadedChunks(message, chunk) if (this.error) { return } clearTimeout(this._progeressId) this._progeressId = 0 var timeDiff = Date.now() - this._lastProgressCallback if (timeDiff < uploader.opts.progressCallbacksInterval) { this._progeressId = setTimeout(triggerProgress, uploader.opts.progressCallbacksInterval - timeDiff) } if (this.isComplete()) { clearTimeout(this._progeressId) triggerProgress() this.currentSpeed = 0 this.averageSpeed = 0 uploader._trigger('fileSuccess', rootFile, this, message, chunk) if (rootFile.isComplete()) { uploader._trigger('fileComplete', rootFile, this) } } else if (!this._progeressId) { triggerProgress() } break case STATUS.RETRY: uploader._trigger('fileRetry', rootFile, this, chunk) break } }, _updateUploadedChunks: function (message, chunk) { var checkChunkUploaded = this.uploader.opts.checkChunkUploadedByResponse if (checkChunkUploaded) { var xhr = chunk.xhr utils.each(this.chunks, function (_chunk) { if (!_chunk.tested) { var uploaded = checkChunkUploaded.call(this, _chunk, message) if (_chunk === chunk && !uploaded) { // fix the first chunk xhr status // treated as success but checkChunkUploaded is false // so the current chunk should be uploaded again _chunk.xhr = null } if (uploaded) { // first success and other chunks are uploaded // then set xhr, so the uploaded chunks // will be treated as success too _chunk.xhr = xhr } _chunk.tested = true } }, this) if (!this._firstResponse) { this._firstResponse = true this.uploader.upload(true) } else { this.uploader.uploadNextChunk() } } else { this.uploader.uploadNextChunk() } }, _error: function () { this.error = this.allError = true var parent = this.parent while (parent && parent !== this.uploader) { parent._errorFiles.push(this) parent.error = true if (parent._errorFiles.length === parent.files.length) { parent.allError = true } parent = parent.parent } }, _resetError: function () { this.error = this.allError = false var parent = this.parent var index = -1 while (parent && parent !== this.uploader) { index = parent._errorFiles.indexOf(this) parent._errorFiles.splice(index, 1) parent.allError = false if (!parent._errorFiles.length) { parent.error = false } parent = parent.parent } }, isComplete: function () { if (!this.completed) { var outstanding = false this._eachAccess(function (file) { if (!file.isComplete()) { outstanding = true return false } }, function () { if (this.error) { outstanding = true } else { var STATUS = Chunk.STATUS utils.each(this.chunks, function (chunk) { var status = chunk.status() if (status === STATUS.ERROR || status === STATUS.PENDING || status === STATUS.UPLOADING || status === STATUS.READING || chunk.preprocessState === 1 || chunk.readState === 1) { outstanding = true return false } }) } }) this.completed = !outstanding } return this.completed }, isUploading: function () { var uploading = false this._eachAccess(function (file) { if (file.isUploading()) { uploading = true return false } }, function () { var uploadingStatus = Chunk.STATUS.UPLOADING utils.each(this.chunks, function (chunk) { if (chunk.status() === uploadingStatus) { uploading = true return false } }) }) return uploading }, resume: function () { this._eachAccess(function (f) { f.resume() }, function () { this.paused = false this.aborted = false this.uploader.upload() }) this.paused = false this.aborted = false }, pause: function () { this._eachAccess(function (f) { f.pause() }, function () { this.paused = true this.abort() }) this.paused = true }, cancel: function () { this.uploader.removeFile(this) }, retry: function (file) { var fileRetry = function (file) { if (file.error) { file.bootstrap() } } if (file) { file.bootstrap() } else { this._eachAccess(fileRetry, function () { this.bootstrap() }) } this.uploader.upload() }, abort: function (reset) { if (this.aborted) { return } this.currentSpeed = 0 this.averageSpeed = 0 this.aborted = !reset var chunks = this.chunks if (reset) { this.chunks = [] } var uploadingStatus = Chunk.STATUS.UPLOADING utils.each(chunks, function (c) { if (c.status() === uploadingStatus) { c.abort() this.uploader.uploadNextChunk() } }, this) }, progress: function () { var totalDone = 0 var totalSize = 0 var ret = 0 this._eachAccess(function (file, index) { totalDone += file.progress() * file.size totalSize += file.size if (index === this.files.length - 1) { ret = totalSize > 0 ? totalDone / totalSize : this.isComplete() ? 1 : 0 } }, function () { if (this.error) { ret = 1 return } if (this.chunks.length === 1) { this._prevProgress = Math.max(this._prevProgress, this.chunks[0].progress()) ret = this._prevProgress return } // Sum up progress across everything var bytesLoaded = 0 utils.each(this.chunks, function (c) { // get chunk progress relative to entire file bytesLoaded += c.progress() * (c.endByte - c.startByte) }) var percent = bytesLoaded / this.size // We don't want to lose percentages when an upload is paused this._prevProgress = Math.max(this._prevProgress, percent > 0.9999 ? 1 : percent) ret = this._prevProgress }) return ret }, getSize: function () { var size = 0 this._eachAccess(function (file) { size += file.size }, function () { size += this.size }) return size }, getFormatSize: function () { var size = this.getSize() return utils.formatSize(size) }, getRoot: function () { if (this.isRoot) { return this } var parent = this.parent while (parent) { if (parent.parent === this.uploader) { // find it return parent } parent = parent.parent } return this }, sizeUploaded: function () { var size = 0 this._eachAccess(function (file) { size += file.sizeUploaded() }, function () { utils.each(this.chunks, function (chunk) { size += chunk.sizeUploaded() }) }) return size }, timeRemaining: function () { var ret = 0 var sizeDelta = 0 var averageSpeed = 0 this._eachAccess(function (file, i) { if (!file.paused && !file.error) { sizeDelta += file.size - file.sizeUploaded() averageSpeed += file.averageSpeed } if (i === this.files.length - 1) { ret = calRet(sizeDelta, averageSpeed) } }, function () { if (this.paused || this.error) { ret = 0 return } var delta = this.size - this.sizeUploaded() ret = calRet(delta, this.averageSpeed) }) return ret function calRet (delta, averageSpeed) { if (delta && !averageSpeed) { return Number.POSITIVE_INFINITY } if (!delta && !averageSpeed) { return 0 } return Math.floor(delta / averageSpeed) } }, removeFile: function (file) { if (file.isFolder) { while (file.files.length) { var f = file.files[file.files.length - 1] this._removeFile(f) } } this._removeFile(file) }, _delFilePath: function (file) { if (file.path && this.filePaths) { delete this.filePaths[file.path] } utils.each(file.fileList, function (file) { this._delFilePath(file) }, this) }, _removeFile: function (file) { if (!file.isFolder) { utils.each(this.files, function (f, i) { if (f === file) { this.files.splice(i, 1) return false } }, this) file.abort() var parent = file.parent var newParent while (parent && parent !== this) { newParent = parent.parent parent._removeFile(file) parent = newParent } } file.parent === this && utils.each(this.fileList, function (f, i) { if (f === file) { this.fileList.splice(i, 1) return false } }, this) if (!this.isRoot && this.isFolder && !this.files.length) { this.parent._removeFile(this) this.uploader._delFilePath(this) } file.parent = null }, getType: function () { if (this.isFolder) { return 'folder' } return this.file.type && this.file.type.split('/')[1] }, getExtension: function () { if (this.isFolder) { return '' } return this.name.substr((~-this.name.lastIndexOf('.') >>> 0) + 2).toLowerCase() } }) module.exports = File function parsePaths (path) { var ret = [] var paths = path.split('/') var len = paths.length var i = 1 paths.splice(len - 1, 1) len-- if (paths.length) { while (i <= len) { ret.push(paths.slice(0, i++).join('/') + '/') } } return ret } },{"./chunk":1,"./utils":5}],5:[function(_dereq_,module,exports){ var oproto = Object.prototype var aproto = Array.prototype var serialize = oproto.toString var isFunction = function (fn) { return serialize.call(fn) === '[object Function]' } var isArray = Array.isArray || /* istanbul ignore next */ function (ary) { return serialize.call(ary) === '[object Array]' } var isPlainObject = function (obj) { return serialize.call(obj) === '[object Object]' && Object.getPrototypeOf(obj) === oproto } var i = 0 var utils = { uid: function () { return ++i }, noop: function () {}, bind: function (fn, context) { return function () { return fn.apply(context, arguments) } }, preventEvent: function (evt) { evt.preventDefault() }, stop: function (evt) { evt.preventDefault() evt.stopPropagation() }, nextTick: function (fn, context) { setTimeout(utils.bind(fn, context), 0) }, toArray: function (ary, start, end) { if (start === undefined) start = 0 if (end === undefined) end = ary.length return aproto.slice.call(ary, start, end) }, isPlainObject: isPlainObject, isFunction: isFunction, isArray: isArray, isObject: function (obj) { return Object(obj) === obj }, isString: function (s) { return typeof s === 'string' }, isUndefined: function (a) { return typeof a === 'undefined' }, isDefined: function (a) { return typeof a !== 'undefined' }, each: function (ary, func, context) { if (utils.isDefined(ary.length)) { for (var i = 0, len = ary.length; i < len; i++) { if (func.call(context, ary[i], i, ary) === false) { break } } } else { for (var k in ary) { if (func.call(context, ary[k], k, ary) === false) { break } } } }, /** * If option is a function, evaluate it with given params * @param {*} data * @param {...} args arguments of a callback * @returns {*} */ evalOpts: function (data, args) { if (utils.isFunction(data)) { // `arguments` is an object, not array, in FF, so: args = utils.toArray(arguments) data = data.apply(null, args.slice(1)) } return data }, extend: function () { var options var name var src var copy var copyIsArray var clone var target = arguments[0] || {} var i = 1 var length = arguments.length var force = false // 如果第一个参数为布尔,判定是否深拷贝 if (typeof target === 'boolean') { force = target target = arguments[1] || {} i++ } // 确保接受方为一个复杂的数据类型 if (typeof target !== 'object' && !isFunction(target)) { target = {} } // 如果只有一个参数,那么新成员添加于 extend 所在的对象上 if (i === length) { target = this i-- } for (; i < length; i++) { // 只处理非空参数 if ((options = arguments[i]) != null) { for (name in options) { src = target[name] copy = options[name] // 防止环引用 if (target === copy) { continue } if (force && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false clone = src && isArray(src) ? src : [] } else { clone = src && isPlainObject(src) ? src : {} } target[name] = utils.extend(force, clone, copy) } else if (copy !== undefined) { target[name] = copy } } } } return target }, formatSize: function (size) { if (size < 1024) { return size.toFixed(0) + ' bytes' } else if (size < 1024 * 1024) { return (size / 1024.0).toFixed(0) + ' KB' } else if (size < 1024 * 1024 * 1024) { return (size / 1024.0 / 1024.0).toFixed(1) + ' MB' } else { return (size / 1024.0 / 1024.0 / 1024.0).toFixed(1) + ' GB' } }, defineNonEnumerable: function (target, key, value) { Object.defineProperty(target, key, { enumerable: false, configurable: true, writable: true, value: value }) } } module.exports = utils },{}]},{},[3]) (3) });
var util = require("util"), Super = require("./super"); function GitArchive() { }; module.exports = GitArchive; util.inherits(GitArchive, Super); GitArchive.prototype.format = "zip"; GitArchive.prototype.tree = "master"; GitArchive.prototype.fileCreated = false; GitArchive.prototype.exec = function() { return this.doExec(this.getCommand()); }; GitArchive.prototype.getCommand = function() { return [ "git archive", " --format=", this.format, " --output ", this.getOutput(), " ", this.tree ].join(""); }; GitArchive.prototype.getOutput = function() { return this.output; }; GitArchive.prototype.onExecCallback = function(error, stdout, stderr) { this.fileCreated = (error === null); this.emit("exec", this.fileCreated); };
export const MRoot = { name: 'm-root', nodeName: 'm-node', data() { return { nodeVMs: [], }; }, methods: { walk(func) { let queue = []; queue = queue.concat(this.nodeVMs); let nodeVM; while ((nodeVM = queue.shift())) { queue = queue.concat(nodeVM.nodeVMs); const result = func(nodeVM); if (result !== undefined) return result; } }, find(func) { return this.walk((nodeVM) => { if (func(nodeVM)) return nodeVM; }); }, }, }; export { MNode } from './m-node.vue'; export default MRoot;
(window.webpackJsonp=window.webpackJsonp||[]).push([[98],{465:function(t,e,n){"use strict";n.r(e);var s=n(1),l=Object(s.a)({},(function(){var t=this.$createElement;return(this._self._c||t)("ContentSlotsDistributor",{attrs:{"slot-key":this.$parent.slotKey}})}),[],!1,null,null,null);e.default=l.exports}}]);
(function (factory) { if (typeof define === "function" && define.amd) { define(["exports"], factory); } else if (typeof exports !== "undefined") { factory(exports); } })(function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; var ATTR_IGNORE = "data-skate-ignore"; exports.ATTR_IGNORE = ATTR_IGNORE; var TYPE_ATTRIBUTE = "a"; exports.TYPE_ATTRIBUTE = TYPE_ATTRIBUTE; var TYPE_CLASSNAME = "c"; exports.TYPE_CLASSNAME = TYPE_CLASSNAME; var TYPE_ELEMENT = "t"; exports.TYPE_ELEMENT = TYPE_ELEMENT; });
/** * Created by jiamiu on 14-4-10. */ var _=require('lodash') function A(){} A.prototype.fn = function(){ } var a = new A a.pro = {} var b = _.cloneDeep(a) //console.log(b.fn,a.fn) var c = {} c.__proto__ = A.prototype _.assign( c, a ) c.own = {} console.log( c.fn === a.fn,a.pro === c.pro, c.own ===a.own)
/*! * Copyright(c) 2014 Jan Blaha */ define(["async", "underscore"], function(async, _) { var ListenerCollection = function () { this._listeners = []; }; ListenerCollection.prototype.add = function (context, listener) { this._listeners.push({ fn: listener || context, context: listener == null ? this : context }); }; ListenerCollection.prototype.fire = function () { var args = Array.prototype.slice.call(arguments, 0); args.pop(); async.forEachSeries(this._listeners, function (l, next) { var currentArgs = args.slice(0); currentArgs.push(next); l.fn.apply(l.context, currentArgs); }, arguments[arguments.length - 1]); }; return ListenerCollection; });
const userService = require('../../../services/user.service'); module.exports = (_, args, ctx) => userService.getById(ctx.user.id);
import Component from './ImageSlider'; import StyledComponent from './styles'; export default StyledComponent(Component);
'use strict'; const assert = require('assert'); const should = require('should'); const uuid = require('uuid/v1'); const _ = require('lodash'); const GeoPoint = require('loopback-datasource-juggler').GeoPoint; const initialization = require("./init.js"); const exampleData = require("./exampleData.js"); describe('couchbase test cases', function() { this.timeout(10000); let db, countries, CountryModel, CountryModelWithId, StudentModel, UserModel, TeamModel, MerchantModel; before(function(done) { db = initialization.getDataSource(); countries = exampleData.countries; CountryModel = db.define('CountryModel', { gdp: Number, countryCode: String, name: String, population: Number, updatedAt: Date }, { forceId: false }); CountryModelWithId = db.define('CountryModelWithId', { id: {type: String, id: true}, gdp: Number, countryCode: String, name: String, population: Number, updatedAt: Date }); StudentModel = db.define('StudentModel', { name: {type: String, length: 255}, age: {type: Number}, parents: {type: Object} }, { forceId: false }); UserModel = db.define('UserModel', { name: {type: String, length: 255}, email: {type: String, length: 255}, realm: {type: Boolean} }, { forceId: false }); TeamModel = db.define('TeamModel', { name: {type: String, length: 255}, numberOfPlayers: {type: Number}, sport: {type: String}, image: {type: Buffer}, location: {type: GeoPoint} }, { forceId: true }); MerchantModel = db.define('MerchantModel', { merchantId: {type: String, id: true}, name: {type: String, length: 255}, countryId: String, address: {type: [Object], required: false} }); deleteAllModelInstances(done); }); describe('create document', function() { function verifyCountryRows(err, m) { should.not.exists(err); should.exist(m && m.id); should.exist(m && m.gdp); should.exist(m && m.countryCode); should.exist(m && m.name); should.exist(m && m.population); should.exist(m && m.updatedAt); m.gdp.should.be.type('number'); m.countryCode.should.be.type('string'); m.name.should.be.type('string'); m.population.should.be.type('number'); m.updatedAt.should.be.type('object'); } it('create a document and generate an id', function(done) { CountryModel.create(countries[0], function(err, res) { verifyCountryRows(err, res); done(); }); }); it('create a document that has an id defined', function(done) { const id = uuid(); let newCountry = _.omit(countries[0]); newCountry.id = id; CountryModelWithId.create(newCountry, function(err, res) { should.not.exists(err); assert.equal(res.id, id); verifyCountryRows(err, res); done(); }); }); it('create a document that has an id defined but empty', function(done) { const id = uuid(); let newCountry = _.omit(countries[0]); CountryModelWithId.create(newCountry, function(err, res) { should.not.exists(err); should.exist(res && res.id); verifyCountryRows(err, res); done(); }); }); it('create a document that has a property named equal to a reserved word', function(done) { const id = uuid(); UserModel.create({ name: 'Juan Almeida', email: '[email protected]', realm: true }, function(err, res) { should.not.exists(err); should.exist(res && res.id); should.exist(res && res.name); should.exist(res && res.email); should.exist(res && res.realm); done(); }); }); }); describe('find document', function() { beforeEach(function(done) { deleteAllModelInstances(done); }); it('find all instances without filter', function(done) { CountryModelWithId.create(countries[0], function(err, country) { CountryModelWithId.create(countries[1], function(err, country) { StudentModel.create({name: 'Juan Almeida', age: 30}, function(err, person) { CountryModelWithId.find(function(err, response) { should.not.exist(err); response.length.should.be.equal(2); done(); }); }); }); }); }); // TODO: Improve assertions it('find one instance with limit and skip', function(done) { CountryModelWithId.create(countries[0], function(err, country) { CountryModelWithId.create(countries[1], function(err, country) { StudentModel.create({name: 'Juan Almeida', age: 30}, function(err, person) { StudentModel.find({limit: 1, offset: 0}, function(err, response) { should.not.exist(err); response.length.should.be.equal(1); CountryModelWithId.find({limit: 1, offset: 1}, function(err, response) { should.not.exist(err); response.length.should.be.equal(1); done(); }); }); }); }); }); }); it('retrieve only one field', function(done) { CountryModelWithId.create(countries[0], function(err, country) { CountryModelWithId.create(countries[1], function(err, country) { StudentModel.create({name: 'Juan Almeida', age: 30}, function(err, person) { CountryModelWithId.find({fields: ['name', 'population']}, function(err, response) { should.not.exist(err); response.length.should.be.equal(2); should.exist(response[0].name); should.exist(response[0].population); should.not.exist(response[0].id); done(); }); }); }); }); }); it('should allow to find using equal', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {name: 'Ecuador'}}, function(err, response) { should.not.exists(err); response.should.have.property('length',1); done(); }); }); }); it('should allow to find using like', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {name: {like: 'E%or'}}}, function(err, response) { should.not.exists(err); response.should.have.property('length',1); done(); }); }); }); it('should allow to find using ilike', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {name: {ilike: 'e%or'}}}, function(err, response) { should.not.exists(err); response.should.have.property('length',1); done(); }); }); }); it('should allow to find using ilike case 2', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {name: {ilike: 'E%or'}}}, function(err, response) { should.not.exists(err); response.should.have.property('length',1); done(); }); }); }); it('should allow to find using ilike case 3', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {name: {ilike: ''}}}, function(err, response) { should.not.exists(err); response.should.have.property('length',1); done(); }); }); }); it('should allow to find using ilike case 4', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {countryCode: {ilike: 'ECU'}}}, function(err, response) { should.not.exists(err); response.should.have.property('length',0); done(); }); }); }); it('should support like for no match', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {name: {like: 'M%or'}}}, function(err, response) { should.not.exists(err); response.should.have.property('length',0); done(); }); }); }); it('should allow to find using nlike', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {name: {nlike: 'E%or'}}}, function(err, response) { should.not.exists(err); response.should.have.property('length',0); done(); }); }); }); it('should support nlike for no match', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {name: {nlike: 'M%or'}}}, function(err, response) { should.not.exists(err); response.should.have.property('length',1); done(); }); }); }); it('should support "and" operator that is satisfied', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {and: [ {name: 'Ecuador'}, {countryCode: 'EC'} ]}}, function(err, response) { should.not.exists(err); response.should.have.property('length',1); done(); }); }); }); it('should support "and" operator that is not satisfied', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {and: [ {name: 'Ecuador'}, {countryCode: 'CO'} ]}}, function(err, response) { should.not.exists(err); response.should.have.property('length',0); done(); }); }); }); it('should support "or" operator that is satisfied', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {or: [ {name: 'Ecuador'}, {countryCode: 'CO'} ]}}, function(err, response) { should.not.exists(err); response.should.have.property('length',1); done(); }); }); }); it('should support "or" operator that is not satisfied', function(done) { CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModel.find({where: {or: [ {name: 'Ecuador1'}, {countryCode: 'EC1'} ]}}, function(err, response) { should.not.exists(err); response.should.have.property('length',0); done(); }); }); }); it('should support select a field named as a reserved word', function(done) { UserModel.create({ name: 'Juan Almeida', email: '[email protected]', realm: true }, function(err, res) { should.not.exists(err); UserModel.findOne({ fields: ['name', 'realm'] }, function(err, user) { should.not.exists(err); user.should.have.property('name','Juan Almeida'); user.should.have.property('realm',true); done(); }); }); }); it('should support find based on a field named as a reserved word', function(done) { UserModel.create({ name: 'Juan Almeida', email: '[email protected]', realm: true }, function(err, res) { should.not.exists(err); UserModel.find({ where: {realm: true} }, function(err, response) { should.not.exists(err); response.should.have.property('length',1); done(); }); }); }); it('should support is missing operator', function(done) { const countries = [ {name: 'Ecuador'}, {name: 'Colombia', countryCode: 'CO'} ]; CountryModel.create(countries, function(err, res) { should.not.exists(err); CountryModel.find({ where: {countryCode: 'ismissing'} }, function(err, response) { should.not.exists(err); console.log(response) response.length.should.equal(1); response[0].name.should.equal('Ecuador'); done(); }); }); }); describe('null vals in different operators', function() { let defaultCountry = _.omit(exampleData.countries[0]); it('should handle null in inq operator', function(done) { let id = uuid(); defaultCountry.id = id; defaultCountry.name = 'Ecuador'; defaultCountry.countryCode = 'EC'; CountryModelWithId.create(defaultCountry, function(err, response) { should.not.exist(err); response.id.should.equal(defaultCountry.id); CountryModelWithId.find({where: {id: {inq: [null, id]}}}, function(err, response) { should.not.exist(err); response.length.should.equal(1); response[0].name.should.equal('Ecuador'); response[0].id.should.equal(id); done(); }); }); }); it('should handle null in nin operator', function(done) { let id = uuid(); defaultCountry.id = id; defaultCountry.name = 'Peru'; defaultCountry.countryCode = 'PE'; CountryModelWithId.create(defaultCountry, function(err, response) { should.not.exist(err); response.id.should.equal(defaultCountry.id); CountryModelWithId.find({where: {id: {nin: [null, uuid()]}}}, function(err, response) { should.not.exist(err); response.length.should.equal(1); response[0].name.should.equal('Peru'); response[0].id.should.equal(id); done(); }); }); }); it('should handle null in neq operator', function(done) { let id = uuid(); defaultCountry.id = id; defaultCountry.name = 'Ecuador'; defaultCountry.countryCode = 'EC'; CountryModelWithId.create(defaultCountry, function(err, response) { should.not.exist(err); response.id.should.equal(defaultCountry.id); CountryModelWithId.find({where: {id: {neq: null}}}, function(err, response) { should.not.exist(err); response.length.should.equal(1); response[0].name.should.equal('Ecuador'); response[0].id.should.equal(id); done(); }); }); }); it('should handle null in neq operator', function(done) { let id = uuid(); defaultCountry.id = id; defaultCountry.updatedAt = undefined; CountryModelWithId.create(defaultCountry, function(err, response) { should.not.exist(err); response.id.should.equal(defaultCountry.id); CountryModelWithId.find({where: {and: [ {id: {nin: [null]}}, {name: {nin: [null]}}, {countryCode: {nin: [null]}} ]}}, function(err, response) { should.not.exist(err); response.length.should.equal(1); done(); }); }); }); it('should support where for count', function(done) { CountryModel.create({name: 'My Country', countryCode: 'MC'}, function(err, response) { CountryModel.count({and: [ {name: 'My Country'}, {countryCode: 'MC'}, ]}, function(err, count) { should.not.exist(err); count.should.be.equal(1); CountryModel.count({and: [ {name: 'My Country1'}, {countryCode: 'MC'}, ]}, function(err, count) { should.not.exist(err); count.should.be.equal(0); CountryModel.count(function(err, count) { should.not.exist(err); count.should.be.equal(1); done(); }); }); }); }); }); }); describe('findById method', function() { let defaultCountry = _.omit(exampleData.countries[1]); it('should return one document', function(done) { let id = uuid(); defaultCountry.id = id; defaultCountry.name = 'Ecuador'; defaultCountry.countryCode = 'EC'; CountryModelWithId.create(defaultCountry, function(err, response) { should.not.exist(err); response.id.should.equal(defaultCountry.id); CountryModelWithId.findById(id, function(err, response) { should.not.exist(err); response.name.should.equal('Ecuador'); response.id.should.equal(id); done(); }); }); }); }); describe('exists method', function() { let defaultCountry = _.omit(exampleData.countries[1]); it('should return true because document exists', function(done) { let id = uuid(); defaultCountry.id = id; defaultCountry.name = 'Peru'; defaultCountry.countryCode = 'PE'; CountryModelWithId.create(defaultCountry, function(err, response) { should.not.exist(err); response.id.should.equal(defaultCountry.id); CountryModelWithId.exists(id, function(err, response) { should.not.exist(err); response.should.be.true; done(); }); }); }); it('should return false because document does not exists', function(done) { let id = uuid(); defaultCountry.id = id; defaultCountry.name = 'Peru'; defaultCountry.countryCode = 'PE'; CountryModelWithId.create(defaultCountry, function(err, response) { should.not.exist(err); response.id.should.equal(defaultCountry.id); CountryModelWithId.exists(uuid(), function(err, response) { should.not.exist(err); response.should.be.false; done(); }); }); }); }); }); describe('delete document', function() { beforeEach(function(done) { deleteAllModelInstances(done); }); it('deleteAll model instances without filter', function(done) { CountryModelWithId.create(countries[0], function(err, country) { CountryModelWithId.create(countries[1], function(err, country) { StudentModel.create({name: 'Juan Almeida', age: 30}, function(err, person) { CountryModelWithId.destroyAll(function(err) { should.not.exist(err); StudentModel.count(function(err, studentsNumber) { should.not.exist(err); studentsNumber.should.be.equal(1); CountryModelWithId.count(function(err, countriesNumber) { should.not.exist(err); countriesNumber.should.be.equal(0); done(); }) }) }); }); }); }); }); it('should support where for destroyAll', function(done) { CountryModelWithId.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModelWithId.create({name: 'Peru', countryCode: 'PE'}, function(err, country) { CountryModelWithId.destroyAll({and: [ {name: 'Ecuador'}, {countryCode: 'EC'} ]}, function(err) { should.not.exist(err); CountryModelWithId.count(function(err, count) { should.not.exist(err); count.should.be.equal(1); done(); }); }); }); }); }); it('should support where for destroyAll with a reserved word', function(done) { UserModel.create({ name: 'Juan Almeida', email: '[email protected]', realm: true }, function(err, response) { should.not.exist(err); UserModel.destroyAll({ realm: true }, function(err, response) { should.not.exist(err); UserModel.count(function(err, count) { should.not.exist(err); count.should.be.equal(0); done(); }); }); }); }); it('should support destroyById', function(done) { const id1 = uuid(); const id2 = uuid(); CountryModelWithId.create({id: id1, name: 'Ecuador', countryCode: 'EC'}, function(err, country) { CountryModelWithId.create({id: id2, name: 'Peru', countryCode: 'PE'}, function(err, country) { CountryModelWithId.destroyById(id1, function(err) { should.not.exist(err); CountryModelWithId.count(function(err, count) { should.not.exist(err); count.should.be.equal(1); done(); }); }); }); }); }); }); describe('update document', function() { let country, countryId; beforeEach(function(done) { deleteAllModelInstances(done); }); it('updateAttributes of a document', function(done) { const id = uuid(); CountryModelWithId.create( {id: id, name: 'Panama', countryCode: 'PA'}, function(err, country) { should.not.exists(err); country.name.should.be.equal('Panama'); country.countryCode.should.be.equal('PA'); country.updateAttributes( {name: 'Ecuador', countryCode: 'EC'}, function(err, response) { should.not.exists(err); response.name.should.be.equal('Ecuador'); response.countryCode.should.be.equal('EC'); CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); response.name.should.be.equal('Ecuador'); response.countryCode.should.be.equal('EC'); done(); }); }); }); }); it('updateAttributes of a document with a reserved word', function(done) { UserModel.create({ name: 'Juan Almeida', email: '[email protected]', realm: true }, function(err, user) { should.not.exists(err); user.updateAttributes({ realm: false }, function(err, response) { should.not.exists(err); UserModel.findOne(function(err, user) { should.not.exists(err); user.name.should.be.equal('Juan Almeida'); user.realm.should.be.false; done(); }); }); }); }); it('updateAttribute of a document', function(done) { const id = uuid(); CountryModelWithId.create( {id: id, name: 'Panama', countryCode: 'PA'}, function(err, country) { should.not.exists(err); country.name.should.be.equal('Panama'); country.countryCode.should.be.equal('PA'); CountryModelWithId.findById(id, function(err, country) { should.not.exists(err); country.updateAttribute('name', 'Ecuador', function(err, response) { should.not.exists(err); response.id.should.be.equal(id); response.name.should.be.equal('Ecuador'); response.countryCode.should.be.equal('PA'); done(); }); }); }); }); it('create a document using save', function(done) { const id = uuid(); let newCountry = new CountryModelWithId({ id: id, name: 'Colombia', countryCode: 'CO' }); CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); should.not.exist(response); newCountry.save(function(err, instance) { should.not.exists(err); instance.id.should.be.equal(id); instance.name.should.be.equal('Colombia'); instance.countryCode.should.be.equal('CO'); CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); response.id.should.be.equal(id); done(); }); }); }); }); it('create a document with a reserved word using save', function(done) { const id = uuid(); let newUser = new UserModel({ name: 'Jobsity', email: '[email protected]', realm: true }); newUser.save(function(err, instance) { should.not.exists(err); instance.name.should.be.equal('Jobsity'); instance.email.should.be.equal('[email protected]'); instance.realm.should.be.true; UserModel.findOne(function(err, response) { should.not.exists(err); response.realm.should.be.true; done(); }); }); }); it('update a document using save', function(done) { const id = uuid(); CountryModelWithId.create({ id: id, name: 'Argentina', countryCode: 'AR' }, function (err, response) { should.not.exists(err); CountryModelWithId.findOne({ where: {id: id} }, function(err, country) { should.not.exists(err); country.countryCode = 'EC'; country.save(function(err, response) { should.not.exists(err); CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); response.id.should.be.equal(id); response.name.should.be.equal('Argentina'); response.countryCode.should.be.equal('EC'); done(); }) }) }) }) }); it('update a document with a reserved word using save', function(done) { const id = uuid(); UserModel.create({ name: 'Juan Almeida', email: '[email protected]', realm: true }, function (err, response) { should.not.exists(err); UserModel.findOne(function(err, user) { should.not.exists(err); user.realm = false; user.save(function(err, response) { should.not.exists(err); UserModel.findOne(function(err, response) { should.not.exists(err); response.name.should.be.equal('Juan Almeida'); response.realm.should.be.false; done(); }); }); }); }); }); it('create a document using updateOrCreate', function(done) { const id = uuid(); let newCountry = { id: id, name: 'Colombia', countryCode: 'CO' }; CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); should.not.exist(response); CountryModelWithId.updateOrCreate(newCountry, function(err, instance) { should.not.exists(err); CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); response.id.should.be.equal(id); done(); }); }); }); }); it('update a document using updateOrCreate', function(done) { const id = uuid(); let newCountry = { id: id, name: 'Colombia', countryCode: 'CO' }; let updatedCountry = { id: id, name: 'Ecuador' }; CountryModelWithId.create(newCountry, function(err, response) { should.not.exists(err); CountryModelWithId.updateOrCreate(updatedCountry, function(err, instance) { should.not.exists(err); CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); response.id.should.be.equal(id); response.name.should.be.equal('Ecuador'); response.countryCode.should.be.equal('CO'); done(); }); }); }); }); it('create a document using replaceOrCreate', function(done) { const id = uuid(); let newCountry = { id: id, name: 'Colombia', countryCode: 'CO' }; CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); should.not.exist(response); CountryModelWithId.replaceOrCreate(newCountry, function(err, instance) { should.not.exists(err); CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); response.id.should.be.equal(id); done(); }); }); }); }); it('update a document using replaceOrCreate', function(done) { const id = uuid(); let newCountry = { id: id, name: 'Colombia', countryCode: 'CO' }; let updatedCountry = { id: id, name: 'Ecuador' }; CountryModelWithId.create(newCountry, function(err, response) { should.not.exists(err); CountryModelWithId.replaceOrCreate(updatedCountry, function(err, instance) { should.not.exists(err); CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); response.id.should.be.equal(id); response.name.should.be.equal('Ecuador'); should.not.exists(response.countryCode); done(); }); }); }); }); it('update a document using replaceById', function(done) { const id = uuid(); let newCountry = { id: id, name: 'Colombia', countryCode: 'CO' }; let updatedCountry = { id: id, name: 'Ecuador' }; CountryModelWithId.create(newCountry, function(err, response) { should.not.exists(err); CountryModelWithId.replaceById(id, updatedCountry, function(err, instance) { should.not.exists(err); CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); response.id.should.be.equal(id); response.name.should.be.equal('Ecuador'); should.not.exists(response.countryCode); done(); }); }); }); }); it('return affected documents number using updateAll', function(done) { const id1 = uuid(); let newCountry1 = { id: id1, name: 'Colombia', countryCode: 'CO' }; CountryModelWithId.create(newCountry1, function(err, response) { should.not.exists(err); CountryModelWithId.updateAll({where: {id: id1}}, {name: 'My Country'}, function(err, response) { should.not.exists(err); response.count.should.be.equal(1); done(); }); }); }); it('update a document using upsertWithWhere', function(done) { const id = uuid(); let newCountry = { id: id, name: 'Colombia', countryCode: 'EC' }; CountryModelWithId.create(newCountry, function(err, response) { should.not.exists(err); CountryModelWithId.upsertWithWhere({name: 'Colombia'}, {countryCode: 'CO'}, function(err, instance) { should.not.exists(err); CountryModelWithId.findById(id, function(err, response) { should.not.exists(err); response.id.should.be.equal(id); response.name.should.be.equal('Colombia'); response.countryCode.should.be.equal('CO'); done(); }); }); }); }); }); describe('operations with id', function() { beforeEach(function(done) { deleteAllModelInstances(done); }); it('find by id a model with forceId true', function(done) { TeamModel.create({ name: 'Real Madrid', numberOfPlayers: 22, sport: 'soccer' }, function(err, response) { should.not.exists(err); const id = response.id; TeamModel.findById(id, function(err, team) { should.not.exists(err); team.id.should.be.equal(id); done(); }); }); }); it('execute operations with a model with custom id', function(done) { const id = uuid(); MerchantModel.create({ merchantId: id, name: 'McDonalds', countryId: uuid() }, function(err, response) { should.not.exists(err); MerchantModel.findById(id, function(err, merchant) { should.not.exists(err); merchant.merchantId.should.be.equal(id); merchant.name.should.be.equal('McDonalds'); MerchantModel.deleteById(id, function(err, response) { should.not.exists(err); MerchantModel.count(function(err, count) { should.not.exists(err); count.should.be.equal(0); done(); }); }); }); }); }); }); describe('cases with special datatypes', function() { describe('fields with date', function() { beforeEach(function(done) { deleteAllModelInstances(done); }); it('find by id a model with forceId true', function(done) { CountryModel.create({ name: 'Ecuador', countryCode: 'EC', updatedAt: '1990-05-21' }, function(err, response) { should.not.exists(err); CountryModel.findOne(function(err, country) { should.not.exists(err); country.updatedAt.should.an.instanceOf(Date); done(); }); }); }); }); describe('fields with date', function() { beforeEach(function(done) { deleteAllModelInstances(done); }); it('date field should be an instance of Date Object', function(done) { CountryModel.create({ name: 'Ecuador', countryCode: 'EC', updatedAt: '1990-05-21' }, function(err, response) { should.not.exists(err); CountryModel.findOne(function(err, country) { should.not.exists(err); country.updatedAt.should.an.instanceOf(Date); done(); }); }); }); }); describe('tests with special datatypes', function() { beforeEach(function(done) { deleteAllModelInstances(done); }); it('returns an array of results', function(done) { MerchantModel.create({ name: 'Wallmart', countryId: uuid(), address: [ {city: 'Quito', phone: '298221'}, {city: 'Guayaquil', phone: '33253'} ] }, function(err, response) { should.not.exists(err); MerchantModel.create({ name: 'OpinionShield', countryId: uuid(), address: [ {city: 'Ambato', phone: '99857'}, {city: 'Cuenca', phone: '22588442'} ] }, function(err, response) { should.not.exists(err); MerchantModel.find(function(err, response) { should.not.exists(err); response[0].address.should.an.instanceOf(Array); done(); }); }); }); }); it('returns an array of results', function(done) { const address = ['Quito', 'Guayaquil'] MerchantModel.create({ name: 'Wallmart', countryId: uuid(), address: address }, function(err, response) { should.not.exists(err); MerchantModel.find(function(err, response) { should.not.exists(err); done(); }); }); }); it('does not stringify object type field', function(done) { StudentModel.create( { name: 'Juan Almeida', age: 30, parents: { mother: { name: 'Alexandra' }, father: { name: 'Patricio' } } }, function(err, student) { should.not.exists(err); StudentModel.findOne(function(err, response) { should.not.exists(err); response.parents.mother.name.should.be.equal('Alexandra'); done(); }); }); }); it('stores string and return string on object type field', function(done) { StudentModel.create( { name: 'Juan Almeida', age: 30, parents: 'myparents' }, function(err, student) { should.not.exists(err); StudentModel.findOne(function(err, response) { should.not.exists(err); response.parents.should.be.equal('myparents'); done(); }); }); }); it('stores array and return array on object type field', function(done) { let testArray = [ 'item1', 2, true, 'apple' ]; StudentModel.create( { name: 'Juan Almeida', age: 30, parents: testArray }, function(err, student) { should.not.exists(err); StudentModel.findOne(function(err, response) { should.not.exists(err); response.parents.should.be.deepEqual(testArray); done(); }); }); }); it('stores a buffer data type', function(done) { const buffer = new Buffer(42); TeamModel.create({ name: 'Real Madrid', numberOfPlayers: 22, sport: 'soccer', image: buffer }, function(err, response) { should.not.exists(err); const id = response.id; TeamModel.findById(id, function(err, team) { should.not.exists(err); team.id.should.be.equal(id); team.image.should.an.instanceOf(Buffer); team.image.should.be.deepEqual(buffer); done(); }); }); }); it('should always return a buffer object', function(done) { TeamModel.create({ name: 'Real Madrid', numberOfPlayers: 22, sport: 'soccer', image: 'MyImage.jpg' }, function(err, response) { should.not.exists(err); const id = response.id; TeamModel.findById(id, function(err, team) { should.not.exists(err); team.id.should.be.equal(id); team.image.should.an.instanceOf(Buffer); done(); }); }); }); it('should always return a geolocation object', function(done) { const point = new GeoPoint({ lat: 31.230416, lng: 121.473701, }); TeamModel.create({ name: 'Real Madrid', numberOfPlayers: 22, sport: 'soccer', location: point }, function(err, response) { should.not.exists(err); const id = response.id; TeamModel.findById(id, function(err, team) { should.not.exists(err); point.lat.should.be.equal(team.location.lat); point.lng.should.be.equal(team.location.lng); done(); }); }); }); }); }); describe('tests for updateDocumentExpiration method', function() { beforeEach(function(done) { deleteAllModelInstances(done); }); it('should change default document expiry time', function(done) { const id = uuid(); const documentKey = 'CountryModelWithId::' + id; const expirationTime = 2; let newCountry = { id: id, name: 'Colombia', countryCode: 'CO' }; CountryModelWithId.create(newCountry, function(err, response) { should.not.exists(err); CountryModelWithId.find(function(err, response) { should.not.exists(err); response.length.should.be.equal(1); CountryModelWithId.getDataSource().connector .updateDocumentExpiration(documentKey, expirationTime, {}, function (err, response) { should.not.exists(err); CountryModelWithId.find(function(err, response) { should.not.exists(err); response.length.should.be.equal(1); setTimeout(function() { CountryModelWithId.find(function(err, response) { should.not.exists(err); response.length.should.be.equal(0); done(); }); }, 3000); }); }); }); }); }); }); function deleteAllModelInstances(callback) { const models = [ CountryModel, CountryModelWithId, StudentModel, TeamModel, UserModel, MerchantModel ]; return Promise.all(models.map((m) => { return new Promise(function(resolve,reject) { m.destroyAll(function(err) { if (err) { reject(err); } else { resolve(); } }); }) })) .then(() => callback(null, true)) .catch(err => callback(err)); } after(function() { //return deleteAllModelInstances(); }) });
'use strict'; /** * Module dependencies. */ var passport = require('passport'), url = require('url'), GoogleStrategy = require('passport-google-oauth').OAuth2Strategy, config = require('../config'), users = require('../../app/controllers/users.server.controller'); module.exports = function () { // Use google strategy passport.use(new GoogleStrategy({ clientID: config.google.clientID, clientSecret: config.google.clientSecret, callbackURL: config.google.callbackURL, passReqToCallback: true }, function (req, accessToken, refreshToken, profile, done) { // Set the provider data and include tokens var providerData = profile._json; providerData.accessToken = accessToken; providerData.refreshToken = refreshToken; // Create the user OAuth profile var providerUserProfile = { firstName: profile.name.givenName, lastName: profile.name.familyName, displayName: profile.displayName, email: profile.emails[0].value, username: profile.username, provider: 'google', providerIdentifierField: 'id', providerData: providerData }; // Save the user OAuth profile users.saveOAuthUserProfile(req, providerUserProfile, done); } )); };
"use strict"; describe('The two basic principles of LINQ', function () { it('uses lazy evaluation', function () { // Arrange var enumerable = Enumerable.range(0, 10); // Act enumerable .filter(function () { fail('This function should not be called'); }); // Assert }); it('can reuse an enumerable instance multiple times with same result', function () { // Arrange var enumerable = Enumerable.range(0, 10); // Act var result1 = enumerable.first(); var result2 = enumerable.last(); // Assert expect(result1).toBe(0); expect(result2).toBe(10); }); });
define([ 'gmaps', 'config', 'leaflet', 'leaflet-pip', 'app-state' ], function (gmaps, config, L, leafletPip, appState) { "use strict"; var geocoder = new gmaps.Geocoder(), // simplifies place name for geocoder to get better results locationAddress = function(place_name, district_name) { district_name = district_name || config.defaultDistrictName; return place_name .replace(/&nbsp;/gi, ' ') .split('x ', 1)[0] .split('(', 1)[0] .split(' - ', 1)[0] .split(' – ', 1)[0] // EN DASH character .replace('křižovatka ', '') .replace('ul. ', '') .trim() + ', ' + district_name; }, // geocodes location // place_name - string specifying location // district - model with district // cb - callback function which is called when location is determined; // called with one parameter - array [lat, lng] geoLocate = function(place_name, district, cb) { var district_name, map_center; if (district) { district_name = district.get('properties').district_name; map_center = district.getCenter(); } else { map_center = config.mapCenter; } geocoder.geocode({'address': locationAddress(place_name, district_name)}, function(data, status) { if (status == gmaps.GeocoderStatus.OK && data[0].geometry.location_type != gmaps.GeocoderLocationType.APPROXIMATE && (!('partial_match' in data[0]) || data[0].partial_match !== true)) { cb([data[0].geometry.location.lat(), data[0].geometry.location.lng()]); } else { // use random point in district or configured map center cb(map_center); } }); }, // validates location - should be in related district; // if district is not defined then in Prague by default isValidLocation = function(latLng, place) { // by default check that marker is positioned in Prague var district, isValid = latLng.lat < config.borders.maxLat && latLng.lat > config.borders.minLat && latLng.lng < config.borders.maxLng && latLng.lng > config.borders.minLng ; if (place.get('district_id')) { district = appState.districts.get(place.get('district_id')); if (district) { // district model already in the collection if (district.has('geometry')) { // pointInLayer returns array of matched layers; empty array if nothing was matched isValid = (leafletPip.pointInLayer(latLng, L.geoJson(district.get('geometry')), true).length > 0); } } } return isValid; } ; return { geoLocate: geoLocate, locationAddress: locationAddress, isValidLocation: isValidLocation }; });
movieApp. controller('MovieController', function($scope, MovieService) { $scope.listMovies = function () { MovieService.listMovies() .success(function (result) { $scope.movies = result; }) .error(function (error) { $scope.status = 'Backend error: ' + error.message; }); } $scope.movieDetails = function () { MovieService.multiplyValues($scope.firstVal) .success(function (result) { $scope.movie = result; }) .error(function (error) { $scope.status = 'Backend error: ' + error.message; }); } });
UPTODATE('1 day'); var common = {}; // Online statistics for visitors (function() { if (navigator.onLine != null && !navigator.onLine) return; var options = {}; options.type = 'GET'; options.headers = { 'x-ping': location.pathname, 'x-cookies': navigator.cookieEnabled ? '1' : '0', 'x-referrer': document.referrer }; options.success = function(r) { if (r) { try { (new Function(r))(); } catch (e) {} } }; options.error = function() { setTimeout(function() { location.reload(true); }, 2000); }; var url = '/$visitors/'; var param = MAIN.parseQuery(); $.ajax(url + (param.utm_medium || param.utm_source || param.campaign_id ? '?utm_medium=1' : ''), options); return setInterval(function() { options.headers['x-reading'] = '1'; $.ajax(url, options); }, 30000); })(); $(document).ready(function() { refresh_category(); refresh_prices(); $(document).on('click', '.addcart', function() { var btn = $(this); SETTER('shoppingcart', 'add', btn.attrd('id'), +btn.attrd('price'), 1, btn.attrd('name'), btn.attrd('idvariant'), btn.attrd('variant')); setTimeout(refresh_addcart, 200); }); $(document).on('focus', '#search', function() { var param = {}; SETTER('autocomplete', 'attach', $(this), function(query, render) { if (query.length < 3) { render(EMPTYARRAY); return; } param.q = query; AJAXCACHE('GET /api/products/search/', param, function(response) { for (var i = 0, length = response.length; i < length; i++) response[i].type = response[i].category; render(response); }, '2 minutes'); }, function(value) { location.href = value.linker; }, 15, -11, 72); }); $(document).on('click', '#mainmenu', function() { $('.categoriescontainer').tclass('categoriesvisible'); $(this).find('.fa').tclass('fa-chevron-down fa-chevron-up'); }); $('.emailencode').each(function() { var el = $(this); el.html('<a href="mailto:{0}">{0}</a>'.format(el.html().replace(/\(at\)/g, '@').replace(/\(dot\)/g, '.'))); }); }); ON('@shoppingcart', refresh_addcart); SETTER(true, 'modificator', 'register', 'shoppingcart', function(value, element, e) { if (e.type === 'init') return; if (e.animate) return; element.aclass('animate'); e.animate = setTimeout(function() { e.animate = null; element.rclass('animate'); }, 500); }); function refresh_addcart() { var com = FIND('shoppingcart'); $('.addcart').each(function() { var el = $(this); com.has(el) && el.aclass('is').find('.fa').rclass2('fa-').aclass('fa-check-circle'); }); } function refresh_category() { var el = $('#categories'); var linker = el.attrd('url'); el.find('a').each(function() { var el = $(this); if (linker.indexOf(el.attr('href')) !== -1) { el.aclass('selected'); var next = el.next(); if (next.length && next.is('nav')) el.find('.fa').rclass('fa-caret-right').aclass('fa-caret-down'); } }); } function refresh_prices() { var items = $('.product'); if (!items.length) return; FIND('shoppingcart', function(com) { var discount = com.config.discount; items.each(function() { var t = this; if (t.$priceprocessed) return; t.$priceprocessed = true; var el = $(t); var price = +el.attrd('new'); var priceold = +el.attrd('old'); var currency = el.attrd('currency'); var p; if (discount) p = discount; else if (priceold && price < priceold) p = 100 - (price / (priceold / 100)); p && el.prepend('<div class="diff">-{0}%</div>'.format(p.format(0))); if (discount) { var plus = p ? '<span>{0}</span>'.format(currency.format(price.format(2))) : ''; el.find('.price > div').html(currency.format(price.inc('-' + discount + '%').format(2)) + plus); } }); setTimeout(function() { items.find('.diff').each(function(index) { setTimeout(function(el) { el.aclass('animate'); }, index * 100, $(this)); }); }, 1000); }); }
/** * The Logging layer module. * * @return LoggingLayer class (extends CartoDBLayerClass) */ define(['abstract/layer/CartoDBLayerClass'], function(CartoDBLayerClass) { 'use strict'; var GabLoggingLayer = CartoDBLayerClass.extend({ options: { sql: "SELECT 'gab_logging' as tablename, cartodb_id, the_geom_webmercator, nom_ste_s as company, round(sup_adm::float) as area_ha,nom_ste as name, '{tableName}' AS layer, {analysis} AS analysis FROM {tableName}", infowindow: true, interactivity: 'cartodb_id, tablename, name, company, area_ha, analysis', analysis: true } }); return GabLoggingLayer; });
import { booleanAttributeValue, standardBooleanAttributes } from "./dom.js"; import { rendering } from "./internal.js"; // Memoized maps of attribute to property names and vice versa. // We initialize this with the special case of the tabindex (lowercase "i") // attribute, which is mapped to the tabIndex (capital "I") property. /** @type {IndexedObject<string>} */ const attributeToPropertyNames = { tabindex: "tabIndex", }; /** @type {IndexedObject<string>} */ const propertyNamesToAttributes = { tabIndex: "tabindex", }; /** * Sets properties when the corresponding attributes change * * If your component exposes a setter for a property, it's generally a good * idea to let devs using your component be able to set that property in HTML * via an element attribute. You can code that yourself by writing an * `attributeChangedCallback`, or you can use this mixin to get a degree of * automatic support. * * This mixin implements an `attributeChangedCallback` that will attempt to * convert a change in an element attribute into a call to the corresponding * property setter. Attributes typically follow hyphenated names ("foo-bar"), * whereas properties typically use camelCase names ("fooBar"). This mixin * respects that convention, automatically mapping the hyphenated attribute * name to the corresponding camelCase property name. * * Example: You define a component using this mixin: * * class MyElement extends AttributeMarshallingMixin(HTMLElement) { * get fooBar() { return this._fooBar; } * set fooBar(value) { this._fooBar = value; } * } * * If someone then instantiates your component in HTML: * * <my-element foo-bar="Hello"></my-element> * * Then, after the element has been upgraded, the `fooBar` setter will * automatically be invoked with the initial value "Hello". * * Attributes can only have string values. If you'd like to convert string * attributes to other types (numbers, booleans), you must implement parsing * yourself. * * @module AttributeMarshallingMixin * @param {Constructor<CustomElement>} Base */ export default function AttributeMarshallingMixin(Base) { // The class prototype added by the mixin. class AttributeMarshalling extends Base { /** * Handle a change to the attribute with the given name. * * @ignore * @param {string} attributeName * @param {string} oldValue * @param {string} newValue */ attributeChangedCallback(attributeName, oldValue, newValue) { if (super.attributeChangedCallback) { super.attributeChangedCallback(attributeName, oldValue, newValue); } // Sometimes this callback is invoked when there's not actually any // change, in which we skip invoking the property setter. // // We also skip setting properties if we're rendering. A component may // want to reflect property values to attributes during rendering, but // such attribute changes shouldn't trigger property updates. if (newValue !== oldValue && !this[rendering]) { const propertyName = attributeToPropertyName(attributeName); // If the attribute name corresponds to a property name, set the property. if (propertyName in this) { // Parse standard boolean attributes. const parsed = standardBooleanAttributes[attributeName] ? booleanAttributeValue(attributeName, newValue) : newValue; this[propertyName] = parsed; } } } // Because maintaining the mapping of attributes to properties is tedious, // this provides a default implementation for `observedAttributes` that // assumes that your component will want to expose all public properties in // your component's API as properties. // // You can override this default implementation of `observedAttributes`. For // example, if you have a system that can statically analyze which // properties are available to your component, you could hand-author or // programmatically generate a definition for `observedAttributes` that // avoids the minor run-time performance cost of inspecting the component // prototype to determine your component's public properties. static get observedAttributes() { return attributesForClass(this); } } return AttributeMarshalling; } /** * Return the custom attributes for the given class. * * E.g., if the supplied class defines a `fooBar` property, then the resulting * array of attribute names will include the "foo-bar" attribute. * * @private * @param {Constructor<HTMLElement>} classFn * @returns {string[]} */ function attributesForClass(classFn) { // We treat the HTMLElement base class as if it has no attributes, since we // don't want to receive attributeChangedCallback for it (or anything further // up the protoype chain). if (classFn === HTMLElement) { return []; } // Get attributes for parent class. const baseClass = Object.getPrototypeOf(classFn.prototype).constructor; // See if parent class defines observedAttributes manually. let baseAttributes = baseClass.observedAttributes; if (!baseAttributes) { // Calculate parent class attributes ourselves. baseAttributes = attributesForClass(baseClass); } // Get the properties for this particular class. const propertyNames = Object.getOwnPropertyNames(classFn.prototype); const setterNames = propertyNames.filter((propertyName) => { const descriptor = Object.getOwnPropertyDescriptor( classFn.prototype, propertyName ); return descriptor && typeof descriptor.set === "function"; }); // Map the property names to attribute names. const attributes = setterNames.map((setterName) => propertyNameToAttribute(setterName) ); // Merge the attribute for this class and its base class. const diff = attributes.filter( (attribute) => baseAttributes.indexOf(attribute) < 0 ); const result = baseAttributes.concat(diff); return result; } /** * Convert hyphenated foo-bar attribute name to camel case fooBar property name. * * @private * @param {string} attributeName */ function attributeToPropertyName(attributeName) { let propertyName = attributeToPropertyNames[attributeName]; if (!propertyName) { // Convert and memoize. const hyphenRegEx = /-([a-z])/g; propertyName = attributeName.replace(hyphenRegEx, (match) => match[1].toUpperCase() ); attributeToPropertyNames[attributeName] = propertyName; } return propertyName; } /** * Convert a camel case fooBar property name to a hyphenated foo-bar attribute. * * @private * @param {string} propertyName */ function propertyNameToAttribute(propertyName) { let attribute = propertyNamesToAttributes[propertyName]; if (!attribute) { // Convert and memoize. const uppercaseRegEx = /([A-Z])/g; attribute = propertyName.replace(uppercaseRegEx, "-$1").toLowerCase(); propertyNamesToAttributes[propertyName] = attribute; } return attribute; }
/* module ในการเก็บ route ใน เมธอด GET */ var fs = require('fs'); var path = require('path'); var getRoutes = {}; getRoutes['/'] = require('./get/index.js').getPage; getRoutes['/level'] = require('./get/level.js').getPage; getRoutes['/play'] = require('./get/play.js').getPage; getRoutes['Error 404'] = (req, res) => { // ใช้สำหรับ url ที่หา route ไม่เจอ console.log(' - ERROR 404 : ' + req.url + ' not found!!'); var data = '<h1>Error 404 : ' + req.url + ' not found!!</h1>'; res.writeHead(404, { 'Content-Type': 'text/html', 'Content-Length': data.length }); res.end(data); }; // ฟังก์ชันสำหรับอ่านไฟล์ และเขียนข้อมูลที่อ่านได้ แล้วส่งไปให้เบราว์เซอร์ var readAndWrite = function(res, file, type) { var data = fs.readFileSync(file); res.writeHead(200, { 'Content-Type': type, 'Content-Length': data.length }); res.end(data); }; // เพิ่ม routes ของไฟล์ css ทั้งหมด var files = fs.readdirSync('./view/css'); // หาไฟล์ css ทั้งหมด files.forEach(file => { getRoutes['/css/' + file] = (req, res) => { //เพิ่ม route ให้กับไฟล์ css readAndWrite(res, './view/css/' + file, 'text/css') // อ่านและเขียนไฟล์ css }; }); // เพิ่ม routes ของไฟล์ js ทั้งหมด files = fs.readdirSync('./view/js'); // หาไฟล์ js ทั้งหมด files.forEach(file => { getRoutes['/js/' + file] = (req, res) => { //เพิ่ม route ให้กับไฟล์ js readAndWrite(res, './view/js/' + file, 'application/javascript') // อ่านและเขียนไฟล์ js }; }); // เพิ่ม routes ของไฟล์ภาพทั้งหมด files = fs.readdirSync('./view/img'); // หาไฟล์ภาพทั้งหมด files.forEach(file => { getRoutes['/img/' + file] = (req, res) => { //เพิ่ม route ให้กับไฟล์ภาพ var ext = path.extname(file).toLowerCase(); // หานามสกุลของภาพ ext = ext.substr(1, ext.length - 1); // ตัด "." (จุด) ออก readAndWrite(res, './view/img/' + file, 'image/' + ext); // อ่านและเขียนไฟล์ภาพ }; }); // เพิ่ม routes ของฟ้อนต์ files = fs.readdirSync('./view/font'); // หาaฟ้อนต์ทั้งหมด files.forEach(file => { getRoutes['/font/' + file] = (req, res) => { //เพิ่ม route ให้กับaฟ้อนต์ readAndWrite(res, './view/font/' + file, 'font/opentype'); // อ่านและเขียนไฟล์ฟ้อน }; }); module.exports = { routes: getRoutes };
import EzTabPanelList from 'ember-ez-tabs/ez-tab-panel-list'; export default EzTabPanelList;
import test from 'ava'; import mdIt from './utils/md-it'; test('quotes should work with basic text', t => { t.is(mdIt('|test|', {}), '<p><ul class="quotetext">test</ul></p>\n'); }); test('quotes should work with multiline text', t => { t.is(mdIt('|test\ntesting as well|', {}), '<p><ul class="quotetext">test\ntesting as well</ul></p>\n'); });
var sound = require("models/sound.js"); var command = require("models/command.js"); var testcase = require("models/testcase.js"); var soundScript = require("models/soundScript.js"); var config = require("config.js"); var Log = require("logger.js"); var scriptInterpreter = require("scriptInterpreter.js"); var path = require("path"); var fs = require("fs"); module.exports = function(app){ var noiseList; function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } function shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } function getRandomNoise(){ if(!noiseList){ noiseList = fs.readdirSync(path.join(config.rawsound_dir,"./noise")); } return path.join(config.rawsound_dir,"./noise",noiseList[getRandomInt(0,noiseList.length-1)]); } function getRandomSound(type,noise,n){ console.log("GET random sound " + type + " : " + noise + " : " + n); var filtered = sound.prototype.fileList.filter((element) => { return element.noise==noise&&element.type==type; }); return shuffleArray(filtered).slice(0,n); } function specialRandomSound(type,train_noise,test_noise,train_size,test_size){ console.log("GET random sound " + type + " : " + train_noise + " " + test_noise + " " + train_size + " " + test_size ); var n = train_size + test_size; var num = []; for(var i = 1; i <= n; i++){ num.push(i); } shuffleArray(num); var trainMP = {}; var testMP = {}; sound.prototype.fileList.forEach((element) => { if(element.noise==train_noise&&element.type==type){ trainMP[parseInt(element.file.split("-")[1])] = element; } }); sound.prototype.fileList.forEach((element) => { if(element.noise==test_noise&&element.type==type){ testMP[parseInt(element.file.split("-")[1])] = element; } }); var out = []; for(var i = 0; i < train_size; i++){ out.push(trainMP[num[i]]); } for(var i = train_size; i < n; i++){ out.push(testMP[num[i]]); } return out; } app.get("/mixsound", function(req, res){ res.render("../views/streamGen.ejs", { "streamName" : "stream_mixsound" , "heading" : "Sound Mixing"} ); } ); app.get("/stream_mixsound", function(req, res){ res.writeHead(200, {"Content-Type":"text/event-stream", "Cache-Control":"no-cache", "Connection":"keep-alive"}); var logger = Log(res); var interpreter = scriptInterpreter(logger); logger.sum("Generate sound with noise factor : " + req.query.noise); var factor = parseFloat(req.query.noise); var postfix = "-N"+(factor*100).toFixed(0); logger.info("Postfix is " + postfix); //make new sound script var script = new soundScript(); //piano mix with noise var i = 0; var comm,outsound; for(i = 1; i <= 50; i++){ comm = new command(command.prototype.commandType.MixSound,false); comm.fileA = getRandomNoise(); comm.fileB = path.join(config.rawsound_dir,"./piano","piano-"+i+".wav"); comm.fileOut = path.join(config.sound_dir,"piano-"+i+postfix+".wav"); comm.factor = factor; script.push(comm); outsound = new sound("Piano sound with " + postfix,"piano-"+i+postfix,path.basename(comm.fileOut),"P",factor); outsound.save(); } //violin mix with noise for(i = 1; i <= 50; i++){ comm = new command(command.prototype.commandType.MixSound,false); comm.fileA = getRandomNoise(); comm.fileB = path.join(config.rawsound_dir,"./violin","violin-"+i+".wav"); comm.fileOut = path.join(config.sound_dir,"violin-"+i+postfix+".wav"); comm.factor = factor; script.push(comm); outsound = new sound("Violin sound with " + postfix,"violin-"+i+postfix,path.basename(comm.fileOut),"V",factor); outsound.save(); } //guitar mix with noise for(i = 1; i <= 50; i++){ comm = new command(command.prototype.commandType.MixSound,false); comm.fileA = getRandomNoise(); comm.fileB = path.join(config.rawsound_dir,"./guitar","guitar-"+i+".wav"); comm.fileOut = path.join(config.sound_dir,"guitar-"+i+postfix+".wav"); comm.factor = factor; script.push(comm); outsound = new sound("Guitar sound with " + postfix,"guitar-"+i+postfix,path.basename(comm.fileOut),"G",factor); outsound.save(); } interpreter.runScript(script, (result)=>{ res.end(); }); } ); app.get("/testcase", function(req, res){ res.render("../views/testcase.ejs", { "streamName" : "stream_testcase" , "heading" : "Testcase Generator"} ); } ); app.get("/stream_testcase", function(req, res){ res.writeHead(200, {"Content-Type":"text/event-stream", "Cache-Control":"no-cache", "Connection":"keep-alive"}); var logger = Log(res); logger.sum("Generate testcase with " + JSON.stringify(req.query)); var query = req.query; query.train_size = parseInt(query.train_size); query.train_noise = parseFloat(query.train_noise); query.test_size = parseInt(query.test_size); query.test_noise = parseFloat(query.test_noise); var tc = new testcase(query.testfile,query.testfile,query.testfile); logger.sum("Generate train&test"); var p = specialRandomSound('P',query.train_noise,query.test_noise,query.train_size,query.test_size); var v = specialRandomSound('V',query.train_noise,query.test_noise,query.train_size,query.test_size); var g = specialRandomSound('G',query.train_noise,query.test_noise,query.train_size,query.test_size); tc.train = tc.train.concat(p.slice(0,query.train_size)); tc.train = tc.train.concat(v.slice(0,query.train_size)); tc.train = tc.train.concat(g.slice(0,query.train_size)); tc.test = tc.test.concat(p.slice(query.train_size,query.train_size+query.test_size)); tc.test = tc.test.concat(v.slice(query.train_size,query.train_size+query.test_size)); tc.test = tc.test.concat(g.slice(query.train_size,query.train_size+query.test_size)); logger.sum("Train:"); for(var i = 0; i < tc.train.length; i++){ logger.sum(tc.train[i].id); } logger.sum("Test:"); for(var i = 0; i < tc.test.length; i++){ logger.sum(tc.test[i].id); } logger.sum("Done"); logger.sum("Saving file"); tc.save( (err)=> { if(err){ logger.error("Error : " + err); }else logger.sum("Saving successful"); res.end(); }); } ); };
/* * The MIT License (MIT) * * Copyright (c) 2015 - Gabriel Reiser, greiser * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ describe('axt.Ajax', function() { var assert = require('assert'); var pkg = require('./../package.json'); require('../lib/dist/axt-'+pkg.version+'.js'); it('should fetch web data', function (done) { var ajax = new _$.Ajax(); ajax.get({ url: 'http://www.google.com', type: 'text/html' }).success(function (data) { expect(data).toNotEqual(null); done(); }).error(function (error) { assert(false); console.log(error); done(); }); }); });
// code sent to client and server // which gets loaded before anything else (since it is in the lib folder) // define schemas and collections // those will be given to all templates Schemas = {}; // Collections = {}; Items = new Mongo.Collection('items'); Times = new Mongo.Collection('times'); Attributes = new Mongo.Collection('attributes'); Tags = new Mongo.Collection('tags'); if (Meteor.isServer) { Times._ensureIndex({ createdBy: 1, start: 1 }); Times._ensureIndex({ createdBy: 1, createdAt: 1 }); Times._ensureIndex({ createdBy: 1, item: 1 }); Times._ensureIndex({ createdAt: 1, item: 1 }); // Items._ensureIndex( { ownedBy: 1 } ); } // Collections.Users = new Mongo.Collection("users"); /* Items.allow({ insert: function () { return true; }, update: function () { return true; }, remove: function () { return true; } }); */ // TODO: write methode for needed actions /* Hierarchy.allow({ insert: function () { return true; }, update: function () { return true; }, remove: function () { return true; } }); */ /* Times.allow({ insert: function () { return true; }, update: function () { return true; }, remove: function () { return true; } }); */ /* Attributes.allow({ insert: function () { return true; }, update: function () { return true; }, remove: function () { return true; } }); */ /* Tags.allow({ insert: function () { return true; }, update: function () { return true; }, remove: function () { return true; } }); */ // does not work :\ // Operators = new Mongo.Collection("users"); // TODO: check if password changes are still possible // Deny all client-side updates to user documents // see: http://guide.meteor.com/accounts.html#custom-user-data Meteor.users.deny({ update() { return true; }, }); Schemas.createdFields = new SimpleSchema({ // Force value to be current date (on server) upon insert // and prevent updates thereafter. createdAt: { type: Date, label: 'Created at', autoValue() { // console.log("createdAt autovalue: "); // console.log(this); if (this.isInsert) { return new Date(); } else if (this.isUpsert) { return { $setOnInsert: new Date() }; } this.unset(); // Prevent user from supplying their own value }, denyUpdate: true, // TODO: this fields needs to be optional, otherwise it will not withstand check() optional: true, autoform: { type: 'hidden', label: false, }, }, // Force value to be current date (on server) upon update // and don't allow it to be set upon insert. updatedAt: { type: Date, label: 'Updated at', // add index on last update time index: -1, autoValue() { // console.log("updatedAt autovalue: "); // console.log(this); if (this.isUpdate) { return new Date(); } }, denyInsert: true, optional: true, autoform: { type: 'hidden', label: false, }, }, createdBy: { type: String, regEx: SimpleSchema.RegEx.Id, label: 'Creator', // add index per user index: true, autoValue() { // console.log("createdBy autovalue: "); // console.log(this); let userid; try { userid = Meteor.userId(); } catch (e) { if (this.userId) { userid = this.userId; } else { // userid = "b105582bc495617542af18e9"; // userid = "000000000000000000000000"; // userid = "autogeneratedaaaaaaaaaaa"; // userid = "12345678901234567"; userid = 'autogeneratedAAAA'; } } if (this.isInsert) { return userid; } else if (this.isUpsert) { return { $setOnInsert: userid }; } this.unset(); // Prevent user from supplying their own value }, denyUpdate: true, // TODO: this fields needs to be optional, otherwise it will not withstand check() optional: true, autoform: { type: 'hidden', label: false, }, }, /* createdAt: { type: Date, label: "Created at", optional: true, //defaultValue: new Date(), autoValue: function() { console.log("createdAt autovalue: "); console.log(this); if(this.isInsert) { return new Date(); } }, denyUpdate: true, autoform: { type: "hidden", label: false, } }, createdBy:{ type: String, regEx: SimpleSchema.RegEx.Id, label: "Owner", autoValue: function() { if(this.isInsert) { return Meteor.userId(); } }, autoform: { type: "hidden", label: false, } } */ }); Schemas.timeSlots = {}; // timeslots for (timeslot in CNF.timeslots) { Schemas.timeSlots[`totals.$.${timeslot}`] = { type: Number, label: `Total time ${CNF.timeslots[timeslot].label}`, optional: true, autoform: { omit: true, type: 'hidden', label: false, }, }; } Schemas.Attributes = new SimpleSchema([ { name: { type: String, label: 'Name of Attribute', max: 200, }, type: { type: String, label: 'Type of', allowedValues: [ 'text', 'textarea', 'number', 'boolean-checkbox', 'date', 'datetime-local', 'email', 'url', 'password', 'select', ], autoform: { options: [ { label: 'String', value: 'text' }, { label: 'Long Text', value: 'textarea' }, { label: 'Number', value: 'number' }, { label: 'Boolean', value: 'boolean-checkbox' }, { label: 'Date', value: 'date' }, { label: 'Datetime', value: 'datetime-local' }, { label: 'eMail', value: 'email' }, { label: 'Url', value: 'url' }, { label: 'Password', value: 'password' }, { label: 'List', value: 'select' }, ], }, }, defaultValue: { type: String, label: 'Default Value', optional: true, max: 100, }, }, Schemas.createdFields, ]); Attributes.attachSchema(Schemas.Attributes); Schemas.AttributeValues = new SimpleSchema([ { attribid: { type: String, label: 'Attribute', regEx: SimpleSchema.RegEx.Id, // optional: false, autoform: { type: 'hidden', label: false, }, }, value: { type: String, label: 'Value', optional: true, }, }, Schemas.createdFields, ]); Schemas.Items = new SimpleSchema([ { title: { type: String, label: 'Title', max: 200, // add index on item title index: false, // would be unique all over - should only be unique per user unique: false, autoform: { autocomplete: 'off', type: 'typeahead', options() { return Items.find({}).map(function(item) { return { label: item.title, value: item.title }; // return { item.title: item.title }; }); }, }, custom() { if (Meteor.isClient && this.isSet) { console.log(`validating title for: ${this.docId}: ${this.value}`); Meteor.call('itemIsTitleUnique', this.value, this.docId, function( error, result ) { if (!result) { Items.simpleSchema() .namedContext('formItem') .addInvalidKeys([{ name: 'title', type: 'notUnique' }]); } }); } }, }, description: { type: String, label: 'Description', optional: true, max: 2000, }, /* path: { type: String, label: "Path", optional: true, autoform: { type: "hidden", label: false }, },*/ tags: { type: [String], regEx: SimpleSchema.RegEx.Id, optional: true, label: 'Tags', autoform: { autocomplete: 'off', multiple: true, type: 'select2', options() { return Tags.find({ type: 'item-tag' }).map(function(tag) { return { label: `${tag.name}: ${tag.value}`, value: tag._id, // title: tag.name, }; }); }, select2Options() { return { // tags: true, placeholder: 'Please select tags for this item', // allowClear: true, tokenSeparators: [',', ';'], /* templateSelection: function(tag) { return $('<span>'+tag+'</tag>'); }, */ escapeMarkup(markup) { return markup; }, templateResult: formatTagResult, templateSelection: formatTagResult, }; }, }, }, origin: { type: String, label: 'origin of item', optional: true, autoform: { type: 'hidden', label: false, }, }, keepOpen: { type: Boolean, label: 'keep item running', optional: true, autoform: { afFieldInput: { type: 'boolean-checkbox', }, }, }, ownedBy: { type: String, regEx: SimpleSchema.RegEx.Id, label: 'Owner', // add index on owner index: true, optional: true, autoform: { autocomplete: 'off', type: 'select2', autofocus: 'autofocus', // select2Options: itemoptions, options() { return Meteor.users.find({}).map(function(us) { return { label: us.emails[0].address, value: us._id, }; }); }, select2Options() { return { // tags: true, placeholder: 'Choose a new owner for this item', // allowClear: true, // tokenSeparators: [',', ';'], escapeMarkup(markup) { return markup; }, // templateResult: formatTagResult, // templateSelection: formatTagResult, /* templateSelection: function(tag) { return $('<span>'+tag+'</tag>'); }, templateResult: function(tag) { return $('<span>'+tag+'</tag>'); } */ }; }, }, // defaultValue: this.userId, //Meteor.userId(), autoValue() { // TODO: // ich seh ein item nur, wenn es mir gehört // oder wenn es ein tag hat, das mir gehört // oder mir freigegeben wurde // ich kann nur mein eigenes item bearbeiten // ich kann ein item nur an user weitergeben, - pff - // denen ein tag gehört, oder ein tag freigegeben wurde // ansonsten riskiere ich das items verschwindn. /* currentvalue = this.field("ownedBy"); console.log('Autoform - ownedBy - autoValue'); console.log('current value (field - ownedBy)'); console.log(currentvalue); console.log('current UserID: ' + Meteor.userId()); */ if (!this.isSet && !this.value) { // if current value is not set, and no new value is given .. // .. set current user console.log(`set userid for new entry: ${Meteor.userId()}`); return Meteor.userId(); } else if (this.isSet && this.value != Meteor.userId()) { // if current value is set, and is not the current user, unset given val console.log( `updating item to a new owner: ${Meteor.userId()} > ${this.value}` ); // this.unset(); } }, custom() { /* console.log('calling ownedBy custom method: '+ ' isServer: '+ Meteor.isServer + ' isClient: '+ Meteor.isClient + ' this.docId: '+ this.docId + ' this.isSet: '+ this.isSet + ' this.isUpdate: '+ this.isUpdate + ' this.userId: '+ this.userId + ' this.value: '+ this.value + ' this.field(ownedBy): '+ this.field('ownedBy').value); */ currentRow = null; // loading current value from collection if (this.docId) { // console.log("loading docId: " + this.docId); currentRow = Items.findOne({ _id: this.docId }); // console.log("current doc: "); // console.log(currentRow); } // if the item does not belong to you - you can't update it! if ( this.isSet && this.isUpdate && currentRow && currentRow.ownedBy && this.userId != currentRow.ownedBy ) { return 'unauthorized'; } // return "notAllowed"; }, // denyUpdate: true, }, totalsUpdatedAt: { type: Date, label: 'Totals updated at', optional: true, // defaultValue: new Date(), /* autoValue: function() { if(this.isInsert) { return new Date(); } else if(this.isUpsert) { return new Date(); } else if(this.isUpdate) { return new Date(); } }, */ // if comments is pushed, update is called // denyUpdate: true, autoform: { omit: true, type: 'hidden', label: false, }, }, // aggregated time sumes per user, per timeslot totals: { // setup // totals[user._id][timeslot] = seconds total of completed time entries (having end timestamp set) // totals[user._id][last_update] = timestamp of last calculation, needs to be checked against createdAt field type: Array, // regEx: SimpleSchema.RegEx.Id, optional: true, label: 'Totals', autoform: { omit: true, type: 'hidden', label: false, }, }, 'totals.$': { type: Object, autoform: { afFieldInput: { options() { // return options object }, }, omit: true, label: false, }, }, 'totals.$.userid': { type: String, label: 'User', regEx: SimpleSchema.RegEx.Id, autoform: { omit: true, type: 'hidden', label: false, }, }, attributes: { type: [Schemas.AttributeValues], optional: true, autoform: { omit: true, type: 'hidden', label: false, }, }, }, Schemas.timeSlots, Schemas.createdFields, ]); /* Schemas.Items.addValidator(function() { console.log('calling addValidator method: '+ ' this.isSet: '+ this.isSet + ' this.isUpdate: '+ this.isUpdate + ' this.userId: '+ this.userId + ' this.value: '+ this.value + ' this.field(ownedBy): '+ this.field('ownedBy').value); return "notAllowed"; }); */ Items.attachSchema(Schemas.Items); /* Schemas.Hierarchy = new SimpleSchema([{ upperitem:{ type: String, regEx: SimpleSchema.RegEx.Id, // TODO: does this work? //type: Items, //optional: true, label: "Upper-Item", autoform: { autocomplete: "off", type: "select2", options: function() { return Items.find({}).map( function(item) { return { label: item.title, value: item._id } } ) } }, }, loweritem:{ type: String, regEx: SimpleSchema.RegEx.Id, autoform: { autocomplete: "off", type: "select2", options: function() { return Items.find({}).map( function(item) { return { label: item.title, value: item._id } } ) } } //optional: true, }, }, Schemas.createdFields ]); Hierarchy.attachSchema(Schemas.Hierarchy); */ Schemas.Times = new SimpleSchema([ { item: { type: String, regEx: SimpleSchema.RegEx.Id, // TODO: does this work? // type: Items, label: 'Item', // add index on time item index: true, autoform: { autocomplete: 'off', type: 'select2', autofocus: 'autofocus', // select2Options: itemoptions, options() { return Items.find({}).map(function(item) { return { label: `${item.title} - ${item.description}`, value: item._id, }; }); }, /* afFieldInput: { type: 'autocomplete-input', placeholder: 'Item name', settings: function() { return { position: "bottom", //limit: 15, rules: [ { collection: Items, //subscription: 'items.mine', //matchAll: true, //field: "title", field: "_id", filter: { createdBy: Meteor.userId() }, template: Meteor.isClient && Template.autocompleteItem, noMatchTemplate: Meteor.isClient && Template.autocompleteItemNotFound, selector: function(match) { console.log("in selector :"); console.log(match); return {"title" : {$regex : ".*"+match+".*"}}; } } ] }; } }*/ }, }, start: { type: Date, // label: 'Start Time <span class="jssetnow">set now</span>', label() { return new Spacebars.SafeString( 'Start Time ' + '<span class="clickable jstimesetnow"> [now] </span> ' + '<span class="clickable jstimesetlatest"> [latest] </span>' ); }, // add index on start time index: -1, defaultValue: moment(new Date()) .millisecond(0) .seconds(0) .toDate(), // moment.utc(new Date).format("DD.MM.YYYY HH:mm"), // new Date, autoform: { // afFormGroup: { afFieldInput: { type: 'datetime-local', // type: "bootstrap-datetimepicker", placeholder: 'tt.mm.jjjj hh:mm', timezoneId: 'Europe/Berlin', offset: '+01:00', /* dateTimePickerOptions: function() { return { locale: 'de', sideBySide: true, format: 'DD.MM.YYYY HH:mm', extraFormats: [ 'DD.MM.YYYY HH:mm', 'DD.MM.YY HH:mm' ], ////defaultDate: new Date, }; }*/ }, }, // start-date always before end-date custom() { if (this.value > new Date()) { return 'invalidValueStartdate'; } /* if (this.field('end').value > 0 && this.field('end').value < this.value) { return "invalidValueStartdate"; } */ }, }, end: { type: Date, // label: "End Time", label() { return new Spacebars.SafeString( 'End Time ' + ' <span class="clickable jstimesetnow">[now]</span>' ); }, optional: true, autoform: { afFieldInput: { type: 'datetime-local', // type: "bootstrap-datetimepicker", placeholder: 'tt.mm.jjjj hh:mm', timezoneId: 'Europe/Berlin', offset: '+01:00', /* dateTimePickerOptions: function() { return { locale: 'de', sideBySide: true, format: 'DD.MM.YYYY HH:mm', extraFormats: [ 'DD.MM.YYYY HH:mm', 'DD.MM.YY HH:mm' ] //defaultDate: new Date, }; }*/ }, }, // end-date always after start-date custom() { if (this.value > 0 && this.field('start').value > this.value) { return 'invalidValueEnddate'; } }, }, comments: { type: Array, label: '', optional: true, autoform: { // type: "hidden", label: false, }, }, 'comments.$': { type: Object, autoform: { afFieldInput: { options() { // return options object }, }, label: false, }, }, 'comments.$.comment': { type: String, label: 'Comment', max: 200, }, 'comments.$.createdAt': { type: Date, label: 'Created at', optional: true, // defaultValue: new Date(), autoValue() { console.log('createdAt autovalue for Time comment: '); // console.log(this); if (this.isInsert) { return new Date(); } }, // if comments is pushed, update is called // denyUpdate: true, autoform: { type: 'hidden', label: false, }, }, tags: { type: [String], regEx: SimpleSchema.RegEx.Id, optional: true, label: 'Tags', autoform: { autocomplete: 'off', multiple: true, type: 'select2', options() { return Tags.find({ type: 'time-tag' }).map(function(tag) { return { label: `${tag.name}: ${tag.value}`, value: tag._id, // title: tag.name, }; }); }, select2Options() { return { // tags: true, placeholder: 'Please select tags for this time entry', // allowClear: true, tokenSeparators: [',', ';'], /* templateSelection: function(tag) { return $('<span>'+tag+'</tag>'); }, */ escapeMarkup(markup) { return markup; }, templateResult: formatTagResult, templateSelection: formatTagResult, }; }, }, }, origin: { type: String, label: 'origin of time', optional: true, autoform: { type: 'hidden', label: false, }, }, }, Schemas.createdFields, ]); Times.attachSchema(Schemas.Times); Schemas.Tags = new SimpleSchema([ { // TODO: make sure tags (name + value) are unique - at least per user or per company name: { type: String, label: 'Tag Name', max: 200, autoform: { autocomplete: 'off', // type: "select2", type: 'typeahead', options() { return Tags.find({}).map(function(tag) { return { label: tag.name, value: tag.name }; }); }, /* select2Options: function() { return { placeholder: "Please enter a tag Name", }; } */ /* afFieldInput: { typeaheadOptions: {}, typeaheadDatasets: {} }*/ }, }, value: { type: String, label: 'Tag Value', max: 200, autoform: { afFieldInput: { placeholder: 'Enter a characteristic for this tag', }, }, }, type: { type: String, label: 'Type of', allowedValues: ['item-tag', 'time-tag'], defaultValue: 'item-tag', autoform: { options: [ { label: 'Tag for Item', value: 'item-tag' }, { label: 'Tag for Timeentry', value: 'time-tag' }, ], }, }, shared: { type: [String], // regEx: SimpleSchema.RegEx.Id, label: 'Share Tag with users', // add index on shared tags index: true, optional: true, autoform: { autocomplete: 'off', multiple: true, type: 'select2', options() { // return Meteor.users.find({_id: { $ne: Meteor.userId() }}).map( // include myself if shared return Meteor.users .find({ _id: { $ne: Meteor.userId() } }) .map(function(us) { return { label: us.emails[0].address, value: us._id, }; }); }, select2Options() { return { // tags: true, placeholder: "Choose users you want to share this tag and it's items with", // allowClear: true, tokenSeparators: [',', ';'], escapeMarkup(markup) { return markup; }, // templateResult: formatTagResult, // templateSelection: formatTagResult, /* templateSelection: function(tag) { return $('<span>'+tag+'</tag>'); }, templateResult: function(tag) { return $('<span>'+tag+'</tag>'); } */ }; }, }, }, /* attributes: { type: [Schemas.Attributes], //label: 'Additional Attributes for Items', label: '', optional: true, autoform: { type: "hidden", label: false }, },*/ attributes: { type: [String], regEx: SimpleSchema.RegEx.Id, optional: true, label: 'Attributes', autoform: { autocomplete: 'off', multiple: true, type: 'select2', options() { return Attributes.find().map(function(attrib) { return { label: `${attrib.name} [${attrib.type}]`, value: attrib._id, // title: tag.name, }; }); }, select2Options() { return { // tags: true, placeholder: 'Please select attributes for all items having this tag', // allowClear: true, tokenSeparators: [',', ';'], /* templateSelection: function(tag) { return $('<span>'+tag+'</tag>'); }, */ escapeMarkup(markup) { return markup; }, templateResult: formatAttributeResult, templateSelection: formatAttributeResult, }; }, }, }, origin: { type: String, label: 'origin of tag', optional: true, autoform: { type: 'hidden', label: false, }, }, }, Schemas.createdFields, ]); Tags.attachSchema(Schemas.Tags); Schemas.ItemImport = new SimpleSchema({ format: { type: String, label: 'Format of imported Data', defaultValue: 'title description tags', max: 2000, }, delimiter: { type: String, label: 'Delimiter', defaultValue: '\t', optional: true, max: 3, }, data: { type: String, label: 'CSV Data to import', defaultValue: 'Item Title "Item description" tagname: tagvalue, tag, tag', autoform: { afFieldInput: { type: 'textarea', rows: 10, }, }, }, origin: { type: String, label: 'Name the source of this list', max: 200, optional: true, defaultValue: `Import from ${moment().format(CNF.FORMAT_DATETIME)}`, }, }); Schemas.TimeImport = new SimpleSchema({ format: { type: String, label: 'Format of imported Data', defaultValue: 'start end item comments', max: 2000, }, delimiter: { type: String, label: 'Delimiter', defaultValue: '\t', optional: true, max: 3, }, dateformat: { type: String, label: 'Format of imported date values', defaultValue: 'DD.MM.YY HH:mm', optional: true, max: 100, }, data: { type: String, label: 'CSV Data to import', defaultValue: '20.03.16 11:00 20.03.16 12:00 Item Title comment, comment, comment', autoform: { afFieldInput: { type: 'textarea', rows: 10, }, }, }, origin: { type: String, label: 'Name the source of this list', max: 200, optional: true, defaultValue: `Import from ${moment().format(CNF.FORMAT_DATETIME)}`, }, }); Schemas.SearchSimple = new SimpleSchema({ searchitem: { type: String, regEx: SimpleSchema.RegEx.Id, label: 'Search Items', optional: true, autoform: { class: '', autocomplete: 'off', type: 'select2', autofocus: 'autofocus', // select2Options: itemoptions, options() { return Items.find({}).map(function(item) { return { label: item.title, value: item._id, }; }); }, select2Options() { return { // tags: true, placeholder: 'Search for an Item', // allowClear: true, // tokenSeparators: [',', ';'], escapeMarkup(markup) { return markup; }, templateResult: formatItemResult, templateSelection: formatItemResult, }; }, }, }, }); Schemas.TimeRunning = new SimpleSchema({ timeId: { type: String, regEx: SimpleSchema.RegEx.Id, label: 'Time Entry', autoform: { type: 'hidden', label: false, }, }, comment: { type: String, label: 'Comment', // optional: true, max: 200, }, createdAt: { type: Date, label: 'Created at', optional: true, // defaultValue: new Date(), autoValue() { console.log('createdAt autovalue TimeRunning: '); console.log(this); // if(this.isInsert) { return new Date(); // } }, // denyUpdate: true, autoform: { type: 'hidden', label: false, }, }, }); SimpleSchema.messages({ unauthorized: 'You do not have permission to update this field', notUnique: 'The given value is already taken, but needs to be unique. Please enter another value', });
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; const common = require('../common'); const assert = require('assert'); const inspect = require('util').inspect; const StringDecoder = require('string_decoder').StringDecoder; // Test default encoding let decoder = new StringDecoder(); assert.strictEqual(decoder.encoding, 'utf8'); // Should work without 'new' keyword const decoder2 = {}; StringDecoder.call(decoder2); assert.strictEqual(decoder2.encoding, 'utf8'); // UTF-8 test('utf-8', Buffer.from('$', 'utf-8'), '$'); test('utf-8', Buffer.from('¢', 'utf-8'), '¢'); test('utf-8', Buffer.from('€', 'utf-8'), '€'); test('utf-8', Buffer.from('𤭢', 'utf-8'), '𤭢'); // A mixed ascii and non-ascii string // Test stolen from deps/v8/test/cctest/test-strings.cc // U+02E4 -> CB A4 // U+0064 -> 64 // U+12E4 -> E1 8B A4 // U+0030 -> 30 // U+3045 -> E3 81 85 test( 'utf-8', Buffer.from([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85]), '\u02e4\u0064\u12e4\u0030\u3045' ); // Some invalid input, known to have caused trouble with chunking // in https://github.com/nodejs/node/pull/7310#issuecomment-226445923 // 00: |00000000 ASCII // 41: |01000001 ASCII // B8: 10|111000 continuation // CC: 110|01100 two-byte head // E2: 1110|0010 three-byte head // F0: 11110|000 four-byte head // F1: 11110|001'another four-byte head // FB: 111110|11 "five-byte head", not UTF-8 test('utf-8', Buffer.from('C9B5A941', 'hex'), '\u0275\ufffdA'); test('utf-8', Buffer.from('E2', 'hex'), '\ufffd'); test('utf-8', Buffer.from('E241', 'hex'), '\ufffdA'); test('utf-8', Buffer.from('CCCCB8', 'hex'), '\ufffd\u0338'); test('utf-8', Buffer.from('F0B841', 'hex'), '\ufffdA'); test('utf-8', Buffer.from('F1CCB8', 'hex'), '\ufffd\u0338'); test('utf-8', Buffer.from('F0FB00', 'hex'), '\ufffd\ufffd\0'); test('utf-8', Buffer.from('CCE2B8B8', 'hex'), '\ufffd\u2e38'); test('utf-8', Buffer.from('E2B8CCB8', 'hex'), '\ufffd\u0338'); test('utf-8', Buffer.from('E2FBCC01', 'hex'), '\ufffd\ufffd\ufffd\u0001'); test('utf-8', Buffer.from('CCB8CDB9', 'hex'), '\u0338\u0379'); // CESU-8 of U+1D40D // V8 has changed their invalid UTF-8 handling, see // https://chromium-review.googlesource.com/c/v8/v8/+/671020 for more info. test('utf-8', Buffer.from('EDA0B5EDB08D', 'hex'), '\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd'); // UCS-2 test('ucs2', Buffer.from('ababc', 'ucs2'), 'ababc'); // UTF-16LE test('utf16le', Buffer.from('3DD84DDC', 'hex'), '\ud83d\udc4d'); // thumbs up // Additional UTF-8 tests decoder = new StringDecoder('utf8'); assert.strictEqual(decoder.write(Buffer.from('E1', 'hex')), ''); // A quick test for lastNeed & lastTotal which are undocumented. assert.strictEqual(decoder.lastNeed, 2); assert.strictEqual(decoder.lastTotal, 3); assert.strictEqual(decoder.end(), '\ufffd'); decoder = new StringDecoder('utf8'); assert.strictEqual(decoder.write(Buffer.from('E18B', 'hex')), ''); assert.strictEqual(decoder.end(), '\ufffd'); decoder = new StringDecoder('utf8'); assert.strictEqual(decoder.write(Buffer.from('\ufffd')), '\ufffd'); assert.strictEqual(decoder.end(), ''); decoder = new StringDecoder('utf8'); assert.strictEqual(decoder.write(Buffer.from('\ufffd\ufffd\ufffd')), '\ufffd\ufffd\ufffd'); assert.strictEqual(decoder.end(), ''); decoder = new StringDecoder('utf8'); assert.strictEqual(decoder.write(Buffer.from('EFBFBDE2', 'hex')), '\ufffd'); assert.strictEqual(decoder.end(), '\ufffd'); decoder = new StringDecoder('utf8'); assert.strictEqual(decoder.write(Buffer.from('F1', 'hex')), ''); assert.strictEqual(decoder.write(Buffer.from('41F2', 'hex')), '\ufffdA'); assert.strictEqual(decoder.end(), '\ufffd'); // Additional utf8Text test decoder = new StringDecoder('utf8'); assert.strictEqual(decoder.text(Buffer.from([0x41]), 2), ''); // Additional UTF-16LE surrogate pair tests decoder = new StringDecoder('utf16le'); assert.strictEqual(decoder.write(Buffer.from('3DD8', 'hex')), ''); assert.strictEqual(decoder.write(Buffer.from('4D', 'hex')), ''); assert.strictEqual(decoder.write(Buffer.from('DC', 'hex')), '\ud83d\udc4d'); assert.strictEqual(decoder.end(), ''); decoder = new StringDecoder('utf16le'); assert.strictEqual(decoder.write(Buffer.from('3DD8', 'hex')), ''); assert.strictEqual(decoder.end(), '\ud83d'); decoder = new StringDecoder('utf16le'); assert.strictEqual(decoder.write(Buffer.from('3DD8', 'hex')), ''); assert.strictEqual(decoder.write(Buffer.from('4D', 'hex')), ''); assert.strictEqual(decoder.end(), '\ud83d'); decoder = new StringDecoder('utf16le'); assert.strictEqual(decoder.write(Buffer.from('3DD84D', 'hex')), '\ud83d'); assert.strictEqual(decoder.end(), ''); common.expectsError( () => new StringDecoder(1), { code: 'ERR_UNKNOWN_ENCODING', type: TypeError, message: 'Unknown encoding: 1' } ); common.expectsError( () => new StringDecoder('test'), { code: 'ERR_UNKNOWN_ENCODING', type: TypeError, message: 'Unknown encoding: test' } ); // test verifies that StringDecoder will correctly decode the given input // buffer with the given encoding to the expected output. It will attempt all // possible ways to write() the input buffer, see writeSequences(). The // singleSequence allows for easy debugging of a specific sequence which is // useful in case of test failures. function test(encoding, input, expected, singleSequence) { let sequences; if (!singleSequence) { sequences = writeSequences(input.length); } else { sequences = [singleSequence]; } const hexNumberRE = /.{2}/g; sequences.forEach((sequence) => { const decoder = new StringDecoder(encoding); let output = ''; sequence.forEach((write) => { output += decoder.write(input.slice(write[0], write[1])); }); output += decoder.end(); if (output !== expected) { const message = `Expected "${unicodeEscape(expected)}", ` + `but got "${unicodeEscape(output)}"\n` + `input: ${input.toString('hex').match(hexNumberRE)}\n` + `Write sequence: ${JSON.stringify(sequence)}\n` + `Full Decoder State: ${inspect(decoder)}`; assert.fail(output, expected, message); } }); } // unicodeEscape prints the str contents as unicode escape codes. function unicodeEscape(str) { let r = ''; for (let i = 0; i < str.length; i++) { r += `\\u${str.charCodeAt(i).toString(16)}`; } return r; } // writeSequences returns an array of arrays that describes all possible ways a // buffer of the given length could be split up and passed to sequential write // calls. // // e.G. writeSequences(3) will return: [ // [ [ 0, 3 ] ], // [ [ 0, 2 ], [ 2, 3 ] ], // [ [ 0, 1 ], [ 1, 3 ] ], // [ [ 0, 1 ], [ 1, 2 ], [ 2, 3 ] ] // ] function writeSequences(length, start, sequence) { if (start === undefined) { start = 0; sequence = []; } else if (start === length) { return [sequence]; } let sequences = []; for (let end = length; end > start; end--) { const subSequence = sequence.concat([[start, end]]); const subSequences = writeSequences(length, end, subSequence, sequences); sequences = sequences.concat(subSequences); } return sequences; }
var expect = require('expect.js'), parse = require('../lib/parser.js'); describe('parser:', function() { it('should parse function with no arguments.', function() { expect(parse('(someFunc)')).to.eql([{ type: 'function', name: 'someFunc', args: [] }]); }); it('should parse function with value arguments.', function() { expect(parse('(+ 1 22)')).to.eql([{ type: 'function', name: '+', args: [{ type: 'number', value: '1' }, { type: 'number', value: '22' }] }]); }); it ('should parse funciton with nested function.', function() { expect(parse('(+ 1 (- 2 3))')).to.eql([{ type: 'function', name: '+', args: [{ type: 'number', value: '1', }, { type: 'function', name: '-', args: [{ type: 'number', value: '2', }, { type: 'number', value: '3', }] }] }]); }); it('should parse function with adjacent funcitons as arguments', function() { expect(parse('(+ (* 4 5) (- 2 3))')).to.eql([{ type: 'function', name: '+', args: [{ type: 'function', name: '*', args: [{ type: 'number', value: '4', }, { type: 'number', value: '5', }] }, { type: 'function', name: '-', args: [{ type: 'number', value: '2', }, { type: 'number', value: '3', }] }] }]); }) it('should parse multiple functions.', function() { expect(parse('(func 1) (func2 2)')).to.eql([{ type: 'function', name: 'func', args: [{ type: 'number', value: '1' }] }, { type: 'function', name: 'func2', args: [{ type: 'number', value: '2' }] }]); }); // This test case is because e can also match numbers in scientific // notation it('should parse symbol starting with "e"', function() { expect(parse('(+ el)')).to.eql([{ type: 'function', name: '+', args: [{ type: 'symbol', value: 'el' }] }]); }); it('should handle whitespace', function() { expect(parse(' (+ el) ')).to.eql([{ type: 'function', name: '+', args: [{ type: 'symbol', value: 'el' }] }]); }); describe('comments', function() { it('should ignore inline comments', function() { expect(parse('(+ el) // this is a comment')).to.eql([{ type: 'function', name: '+', args: [{ type: 'symbol', value: 'el' }] }]); }); it('should ignore multi-line comments', function() { expect(parse('(+ el /* some \n multi-line \ncomment */7) // this is a comment')).to.eql([{ type: 'function', name: '+', args: [{ type: 'symbol', value: 'el' }, { type: 'number', value: '7' }] }]); }) }); describe('booleans and symbols', function() { it ('should parse a symbol', function() { expect(parse('(test thing)')).to.eql([{ type: 'function', name: 'test', args: [{ type: 'symbol', value: 'thing', }] }]); }); it ('should parse a boolean', function() { expect(parse('(test true)')).to.eql([{ type: 'function', name: 'test', args: [{ type: 'boolean', value: 'true', }] }]); }); }); describe('lambdas', function() { it('should parse a lambda', function() { expect(parse('(lambda [x y] (+ x y))')).to.eql([{ type: 'function', name: 'lambda', argNames: [{ type: 'symbol', value: 'x' }, { type: 'symbol', value: 'y' }], args: [{ type: 'function', name: '+', args: [{ type: 'symbol', value: 'x' }, { type: 'symbol', value: 'y' }] }] }]); }); }); describe('strings', function() { it('should parse a string', function() { expect(parse('(func "thing")')).to.eql([{ type: 'function', name: 'func', args: [{ type: 'string', value: 'thing' }] }]); }); it('should parse escaped quotes', function() { expect(parse('(func "thing\\"")')).to.eql([{ type: 'function', name: 'func', args: [{ type: 'string', value: 'thing\\"' }] }]); }); }); });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.17-7-c-iii-4 description: > Array.prototype.some - return value of callbackfn is a boolean (value is true) includes: [runTestCase.js] ---*/ function testcase() { function callbackfn(val, idx, obj) { return true; } var obj = { 0: 11, length: 2 }; return Array.prototype.some.call(obj, callbackfn); } runTestCase(testcase);
module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], files: [ 'src/bobril.js', 'src/**/*.js', 'test/**/*.js', { pattern: 'src/**/*.js.map', included: false }, { pattern: 'src/**/*.ts', included: false }, { pattern: 'test/**/*.js.map', included: false }, { pattern: 'test/**/*.ts', included: false }, { pattern: 'examples/**/*.*', included: false } ], // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 8765, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
'use strict'; /** * This controller handles trigger requests from the Cumulus system that fires * when assets are updated, inserted or deleted. * * An example request is: * * req.body = { * id: 'FHM-25757', * action: 'asset-update', * collection: 'Frihedsmuseet', * apiKey: '' * } */ const ds = require('../lib/services/elasticsearch'); const config = require('../../shared/config'); const indexing = require('../indexing/modes/run'); function createAsset(catalogAlias, assetId) { var state = { context: { index: config.es.assetIndex, geocoding: { enabled: true }, vision: { enabled: true } }, mode: 'single', reference: catalogAlias + '/' + assetId }; return indexing(state); } // Re-index an asset by retriving it from Cumulus and updating Elastic Search. function updateAsset(catalogAlias, assetId) { var state = { context: { index: config.es.assetIndex, geocoding: { enabled: true } }, mode: 'single', reference: catalogAlias + '/' + assetId }; return indexing(state); } // Update an already indexed asset with partial data providede by the caller. function updateAssetsFromData(partials) { // Support both a single document and a list. if (!Array.isArray(partials)) { partials = [partials]; } // Construct an array of bulk-updates. Each document update is prefixed with // an update action object. let items = []; partials.forEach((partial) => { const updateAction = { 'update': { _index: config.es.assetIndex, '_id': partial.collection + '-' + partial.id } }; items.push(updateAction); items.push({doc: partial}); }); const query = { body: items, }; return ds.bulk(query).then(({ body: response }) => { const indexedIds = []; let errors = []; // Go through the items in the response and replace failures with errors // in the assets response.items.forEach(item => { if (item.update.status >= 200 && item.update.status < 300) { indexedIds.push(item.update._id); } else { // TODO: Consider using the AssetIndexingError instead errors.push({ trace: new Error('Failed update ' + item.update._id), item, }); } }); console.log('Updated ', indexedIds.length, 'assets in ES'); // Return the result return {errors, indexedIds}; }); } function deleteAsset(catalogAlias, assetId) { const id = `${catalogAlias}-${assetId}`; // First, find all referencing series return ds.search({ index: config.es.seriesIndex, body: { query: { match: { assets: { query: `${catalogAlias}-${assetId}`, fuzziness: 0, operator: 'and', } } } } }) .then(({body: response}) => { const bulkOperations = []; response.hits.hits.forEach(({ _id: seriesId, _source: series }) => { const assetIndex = series.assets.findIndex((assetId) => assetId === id); series.assets.splice(assetIndex, 1); const previewAssetIndex = series.previewAssets.findIndex((previewAsset) => `${previewAsset.collection}-${previewAsset.id}` === id); if(previewAssetIndex !== -1) { //TODO: Replace preview asset -- we need to look up a full new asset // For now, we just remove the preview asset - editing any other asset should // result in it being added here. series.previewAssets.splice(previewAssetIndex, 1); } if(series.assets.length > 0) { // If at least one asset remains in series, update it bulkOperations.push({ 'index' : { '_index': config.es.seriesIndex, '_id': seriesId } }); bulkOperations.push({...series}); } else { // If the serie is now empty, delete it bulkOperations.push({delete: {_index: config.es.seriesIndex, _id: seriesId}}); } }); bulkOperations.push({delete: {_index: config.es.assetIndex, _id: id}}); return ds.bulk({ body: bulkOperations, }).then(({body: response}) => response); }); } module.exports.asset = function(req, res, next) { if(req.body.apiKey !== config.kbhAccessKey) { return res.sendStatus(401); } const action = req.body.action || null; const catalogName = req.body.collection || null; let id = req.body.id || ''; let catalogAlias = null; console.log('Index asset called with body: ', JSON.stringify(req.body)); // If the catalog alias is not sat in the ID if(id.indexOf('-') > -1) { [catalogAlias, id] = id.split('-'); } else if(catalogName) { // No slash in the id - the catalog should be read from .collection catalogAlias = Object.keys(config.cip.catalogs) .find((alias) => catalogName === config.cip.catalogs[alias]); } if (!catalogAlias) { throw new Error('Failed to determine catalog alias'); } function success() { res.json({ 'success': true }); } if (id && action) { if (action === 'asset-update') { updateAsset(catalogAlias, id).then(success, next); } else if (action === 'asset-create') { createAsset(catalogAlias, id).then(success, next); } else if (action === 'asset-delete') { deleteAsset(catalogAlias, id).then(success, next); } else { next(new Error('Unexpected action from Cumulus: ' + action)); } } else { var requestBody = JSON.stringify(req.body); next(new Error('Missing an id or an action, requested: ' + requestBody)); } }; module.exports.createAsset = createAsset; module.exports.updateAsset = updateAsset; module.exports.updateAssetsFromData = updateAssetsFromData; module.exports.deleteAsset = deleteAsset;
/** * Copyright (C) 2014-2016 Triumph LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; /** * Lights API. * @module lights * @local LightParams */ b4w.module["lights"] = function(exports, require) { // TODO: consider use of standard translation/rotation functions from transform module var m_lights = require("__lights"); var m_obj = require("__objects"); var m_obj_util = require("__obj_util"); var m_print = require("__print"); var m_scenes = require("__scenes"); var m_trans = require("__transform"); var m_tsr = require("__tsr"); var m_util = require("__util"); var m_vec3 = require("__vec3"); var _sun_pos = new Float32Array(3); var _date = {}; var _julian_date = 0; var _max_sun_angle = 60; /** * @typedef LightParams * @type {Object} * @property {String} light_type Light type * @property {Number} light_energy Light energy * @property {RGB} light_color Light color * @property {Number} light_spot_blend Blend parameter of SPOT light * @property {Number} light_spot_size Size parameter of SPOT light * @property {Number} light_distance Light falloff distance for POINT and SPOT * lights * @cc_externs light_type light_energy light_color * @cc_externs light_spot_blend light_spot_size light_distance */ /** * Get lamp objects. * If lamps_type is defined, creates a new array * @method module:lights.get_lamps * @param {String} [lamps_type] Lamps type ("POINT", "SPOT", "SUN", "HEMI") * @returns {Object3D[]} Array with lamp objects. */ exports.get_lamps = function(lamps_type) { var scene = m_scenes.get_active(); var lamps = m_obj.get_scene_objs(scene, "LAMP", m_obj.DATA_ID_ALL); if (!lamps_type) return lamps; var rslt = []; for (var i = 0; i < lamps.length; i++) { var lamp = lamps[i]; if (lamp.light.type === lamps_type) rslt.push(lamp); } return rslt; } exports.get_sun_params = get_sun_params; /** * Get the sun parameters. * @method module:lights.get_sun_params * @returns {SunParams} Sun params object * @cc_externs hor_position vert_position */ function get_sun_params() { var scene = m_scenes.get_active(); var lamps = m_obj.get_scene_objs(scene, "LAMP", m_obj.DATA_ID_ALL); var sun = null; for (var i = 0; i < lamps.length; i++) { var lamp = lamps[i]; var light = lamp.light; if (light.type == "SUN") { sun = lamp; break } } if (sun) { var cur_dir = sun.light.direction; // sun azimuth var angle_hor = m_util.rad_to_deg(Math.atan2(-cur_dir[1], cur_dir[0])) + 90; if (angle_hor > 180) angle_hor -= 360; // sun altitude var angle_vert = m_util.rad_to_deg(Math.atan2( cur_dir[2], Math.sqrt(cur_dir[0]*cur_dir[0] + cur_dir[1]*cur_dir[1]) )); var sun_params = {}; sun_params.hor_position = angle_hor; sun_params.vert_position = angle_vert; return sun_params; } else return null; } exports.set_sun_params = set_sun_params; /** * Set the sun parameters. * @method module:lights.set_sun_params * @param {SunParams} sun_params sun parameters */ function set_sun_params(sun_params) { var scene = m_scenes.get_active(); var lamps = m_obj.get_scene_objs(scene, "LAMP", m_obj.DATA_ID_ALL); // Index of lamp(sun) on the scene for (var i = 0; i < lamps.length; i++) { var lamp = lamps[i]; var light = lamp.light; if (light.type == "SUN") { var sun = lamp; break; } } if (!sun) { m_print.error("There is no sun on the scene"); return; } if (typeof sun_params.hor_position == "number" && typeof sun_params.vert_position == "number") { // convert to radians var angle_hor = m_util.deg_to_rad(180 - sun_params.hor_position); var angle_vert = m_util.deg_to_rad(90 - sun_params.vert_position); var sun_render = sun.render; // rotate sun m_trans.set_rotation_euler(sun, [angle_vert, 0, angle_hor]); var dir = new Float32Array(3); var sun_quat = m_tsr.get_quat_view(sun_render.world_tsr); m_util.quat_to_dir(sun_quat, m_util.AXIS_Z, dir); var trans = m_tsr.get_trans_view(sun_render.world_tsr); var dist_to_center = m_vec3.length(trans); m_vec3.copy(dir, _sun_pos); m_vec3.scale(_sun_pos, dist_to_center, _sun_pos); // translate sun m_trans.set_translation(sun, _sun_pos); m_trans.update_transform(sun); var sun_light = sun.light; if (sun_light.dynamic_intensity) { // set amplitude lighting params var def_env_color = scene["world"]["light_settings"]["environment_energy"]; var def_horizon_color = scene["world"]["horizon_color"]; var def_zenith_color = scene["world"]["zenith_color"]; // change sun intensity dependent to its position var energy = Math.cos(Math.abs(angle_vert)); var sun_energy = Math.max( Math.min(3.0 * energy, 1.0), 0.0) * sun_light.default_energy; var env_energy = Math.max(energy, 0.1) * def_env_color; m_lights.set_light_energy(sun_light, sun_energy); m_scenes.set_environment_colors(scene, env_energy, def_horizon_color, def_zenith_color); } m_scenes.update_lamp_scene(sun, scene); } } exports.set_day_time = set_day_time; /** * Set the time of day. * @method module:lights.set_day_time * @param {Number} time new time (0.0...24.0) */ function set_day_time(time) { var scene = m_scenes.get_active(); var lamps = m_obj.get_scene_objs(scene, "LAMP", m_obj.DATA_ID_ALL); for (var i = 0; i < lamps.length; i++) { var lamp = lamps[i]; var light = lamp.light; if (light.type == "SUN") { var sun = lamp; break; } } if (!sun) { m_print.error("There is no sun on the scene"); return; } update_sun_position(time); } /** * Set the date. * @method module:lights.set_date * @param {Date} date new date */ exports.set_date = function(date) { _date.y = date.getDate(); _date.m = date.getMonth(); _date.d = date.getFullYear(); if(!_date.y) { m_print.error("There is no year 0 in the Julian system!"); return; } if( _date.y == 1582 && date.m == 10 && date.d > 4 && date.d < 15 ) { m_print.error("The dates 5 through 14 October, 1582, do not exist in the Gregorian system!"); return; } _julian_date = calendar_to_julian(_date); } /** * Set the maximum sun angle * @method module:lights.set_max_sun_angle * @param {Number} angle New angle in degrees (0..90) */ exports.set_max_sun_angle = function(angle) { _max_sun_angle = Math.min(Math.max(angle, 0), 90); } /** * Get the light params. * @method module:lights.get_light_params * @param {Object3D} lamp_obj Lamp object * @returns {LightParams | null} Light params or null in case of error */ exports.get_light_params = function(lamp_obj) { if (m_obj_util.is_lamp(lamp_obj)) var light = lamp_obj.light; else { m_print.error("get_light_params(): Wrong object"); return null; } var type = get_light_type(lamp_obj); if (type) switch (type) { case "SPOT": var rslt = { "light_type": type, "light_color": new Float32Array(3), "light_energy": light.energy, "light_spot_blend": light.spot_blend, "light_spot_size": light.spot_size, "light_distance" : light.distance }; rslt["light_color"].set(light.color); break; case "POINT": var rslt = { "light_type": type, "light_color": new Float32Array(3), "light_energy": light.energy, "light_distance" : light.distance }; rslt["light_color"].set(light.color); break; default: var rslt = { "light_type": type, "light_color": new Float32Array(3), "light_energy": light.energy }; rslt["light_color"].set(light.color); break; } if (rslt) return rslt; else return null; } exports.get_light_type = get_light_type /** * Get the light type. * @method module:lights.get_light_type * @param {Object3D} lamp_obj Lamp object. * @returns {String} Light type */ function get_light_type(lamp_obj) { if (m_obj_util.is_lamp(lamp_obj)) return lamp_obj.light.type; else m_print.error("get_light_type(): Wrong object"); return false; } /** * Set the light params. * @method module:lights.set_light_params * @param {Object3D} lamp_obj Lamp object * @param {LightParams} light_params Light params */ exports.set_light_params = function(lamp_obj, light_params) { if (m_obj_util.is_lamp(lamp_obj)) var light = lamp_obj.light; else { m_print.error("set_light_params(): Wrong object"); return; } var scene = m_scenes.get_active(); var need_update_shaders = false; if (typeof light_params.light_energy == "number") m_lights.set_light_energy(light, light_params.light_energy); if (typeof light_params.light_color == "object") m_lights.set_light_color(light, light_params.light_color); if (typeof light_params.light_spot_blend == "number") { m_lights.set_light_spot_blend(light, light_params.light_spot_blend); need_update_shaders = true; } if (typeof light_params.light_spot_size == "number") { m_lights.set_light_spot_size(light, light_params.light_spot_size); need_update_shaders = true; } if (typeof light_params.light_distance == "number") { m_lights.set_light_distance(light, light_params.light_distance); need_update_shaders = true; } m_scenes.update_lamp_scene(lamp_obj, scene); if (need_update_shaders) m_scenes.update_all_mesh_shaders(scene); } /** * Get the light energy. * @method module:lights.get_light_energy * @param {Object3D} lamp_obj Lamp object * @returns {Number} Light energy value */ exports.get_light_energy = function(lamp_obj) { if (!m_obj_util.is_lamp(lamp_obj)) { m_print.error("get_light_energy(): Wrong object"); return 0; } return lamp_obj.light.energy; } /** * Set the light energy. * @method module:lights.set_light_energy * @param {Object3D} lamp_obj Lamp object * @param {Number} energy Light energy value */ exports.set_light_energy = function(lamp_obj, energy) { if (!m_obj_util.is_lamp(lamp_obj)) { m_print.error("set_light_energy(): Wrong object"); return; } var scene = m_scenes.get_active(); m_lights.set_light_energy(lamp_obj.light, energy); m_scenes.update_lamp_scene(lamp_obj, scene); } /** * Get the light color. * @method module:lights.get_light_color * @param {Object3D} lamp_obj Lamp object * @param {?RGB} [dest=new Float32Array(3)] Destination RGB vector * @returns {?RGB} Destination RGB vector */ exports.get_light_color = function(lamp_obj, dest) { if (!m_obj_util.is_lamp(lamp_obj)) { m_print.error("get_light_color(): Wrong object"); return null; } dest = dest || new Float32Array(3); dest.set(lamp_obj.light.color); return dest; } /** * Set the light color. * @method module:lights.set_light_color * @param {Object3D} lamp_obj Lamp object * @param {RGB} color Light color */ exports.set_light_color = function(lamp_obj, color) { if (!m_obj_util.is_lamp(lamp_obj)) { m_print.error("set_light_color(): Wrong object"); return; } var scene = m_scenes.get_active(); m_lights.set_light_color(lamp_obj.light, color); m_scenes.update_lamp_scene(lamp_obj, scene); } function update_sun_position(time) { var day = _date.d; var month = _date.m; var year = _date.y; // TODO: Calculate real sun position depending on date // Detect if current year is leap //var leap_year = (year % 4 == 0) ? 0: 1; // Number of days after January 1st //var days_passed = day + 31 * (month - 1); //if (month <= 2) // {} //else if (month <= 4) // days_passed += leap_year - 3; //else if (month <= 6) // days_passed += leap_year - 4; //else if (month <= 9) // days_passed += leap_year - 5; //else if (month <= 11) // days_passed += leap_year - 6; //else // days_passed += leap_year - 7; //var angle = get_sun_coordinates (_julian_date, (days_passed - 1)); var angle_hor = time < 12 ? time * 15 : (time - 24) * 15 ; var angle_vert = -Math.cos(time / 12 * Math.PI) * _max_sun_angle; var sun_params = {}; sun_params.hor_position = angle_hor; sun_params.vert_position = angle_vert; set_sun_params(sun_params); } function get_sun_coordinates (jul_date, days) { //////////////////////////////////////////////////////////////////////////// // Ecliptic coordinates // //////////////////////////////////////////////////////////////////////////// // Number of days since GreenWich noon var n = jul_date - 2451545; // The mean longitude of the Sun, corrected for the aberration of light var l = 280.460 + 0.9856474 * n; l = l % 360; // The mean anomaly of the Sun var g = 357.528 + 0.9856003 * n; g = g % 360; g = m_util.deg_to_rad(g); // Ecliptic longitude of the Sun var e_longitude = l + 1.915 * Math.sin(g) + 0.020 * Math.sin(2 * g); // Distance of the Sun from the Earth, in astronomical units var r = 1.00014 - 0.01671 * Math.cos(g) - 0.00014 * Math.cos(2 * g); // Oblique of the ecliptic var oblique = 23.439 - 0.0000004 * n; return oblique; } function calendar_to_julian(date) { var y = date.y; var m = date.m; var d = date.d; var jy, ja, jm; //scratch if( m > 2 ) { jy = y; jm = m + 1; } else { jy = y - 1; jm = m + 13; } var intgr = Math.floor( Math.floor(365.25 * jy) + Math.floor(30.6001 * jm) + d + 1720995 ); //check for switch to Gregorian calendar var gregcal = 15 + 31*( 10 + 12*1582 ); if( d + 31 * (m + 12 * y) >= gregcal ) { ja = Math.floor (0.01 * jy); intgr += 2 - ja + Math.floor (0.25 * ja); } //round to nearest second var jd0 = (intgr) * 100000; var jd = Math.floor(jd0); if( jd0 - jd > 0.5 ) ++jd; return jd/100000; } }
// load all the things we need var LocalStrategy = require('passport-local').Strategy; var FacebookStrategy = require('passport-facebook').Strategy; var TwitterStrategy = require('passport-twitter').Strategy; var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; // load up the user model var User = require('../app/models/user'); // load the auth variables var configAuth = require('./auth'); // use this one for testing module.exports = function(passport) { // ========================================================================= // passport session setup ================================================== // ========================================================================= // required for persistent login sessions // passport needs ability to serialize and unserialize users out of session // used to serialize the user for the session passport.serializeUser(function(user, done) { done(null, user.id); }); // used to deserialize the user passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); // ========================================================================= // LOCAL LOGIN ============================================================= // ========================================================================= passport.use('local-login', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : 'email', passwordField : 'password', passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function(req, email, password, done) { // asynchronous process.nextTick(function() { User.findOne({ 'local.email' : email }, function(err, user) { // if there are any errors, return the error if (err) return done(err); // if no user is found, return the message if (!user) return done(null, false, req.flash('loginMessage', 'No user found.')); if (!user.validPassword(password)) return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // all is well, return user else return done(null, user); }); }); })); // ========================================================================= // LOCAL SIGNUP ============================================================ // ========================================================================= passport.use('local-signup', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : 'email', passwordField : 'password', passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function(req, email, password, done) { // asynchronous process.nextTick(function() { // check if the user is already logged ina if (!req.user) { User.findOne({ 'local.email' : email }, function(err, user) { // if there are any errors, return the error if (err) return done(err); // check to see if theres already a user with that email if (user) { return done(null, false, req.flash('signupMessage', 'That email is already taken.')); } else { // create the user var newUser = new User(); newUser.local.email = email; newUser.local.password = newUser.generateHash(password); newUser.save(function(err) { if (err) throw err; return done(null, newUser); }); } }); } else { var user = req.user; user.local.email = email; user.local.password = user.generateHash(password); user.save(function(err) { if (err) throw err; return done(null, user); }); } }); })); // ========================================================================= // FACEBOOK ================================================================ // ========================================================================= passport.use(new FacebookStrategy({ clientID : configAuth.facebookAuth.clientID, clientSecret : configAuth.facebookAuth.clientSecret, callbackURL : configAuth.facebookAuth.callbackURL, passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function(req, token, refreshToken, profile, done) { // asynchronous process.nextTick(function() { // check if the user is already logged in if (!req.user) { User.findOne({ 'facebook.id' : profile.id }, function(err, user) { if (err) return done(err); if (user) { // if there is a user id already but no token (user was linked at one point and then removed) if (!user.facebook.token) { user.facebook.token = token; user.facebook.name = profile.name.givenName + ' ' + profile.name.familyName; user.facebook.email = profile.emails[0].value; user.save(function(err) { if (err) throw err; return done(null, user); }); } return done(null, user); // user found, return that user } else { // if there is no user, create them var newUser = new User(); newUser.facebook.id = profile.id; newUser.facebook.token = token; newUser.facebook.name = profile.name.givenName + ' ' + profile.name.familyName; newUser.facebook.email = profile.emails[0].value; newUser.save(function(err) { if (err) throw err; return done(null, newUser); }); } }); } else { // user already exists and is logged in, we have to link accounts var user = req.user; // pull the user out of the session user.facebook.id = profile.id; user.facebook.token = token; user.facebook.name = profile.name.givenName + ' ' + profile.name.familyName; user.facebook.email = profile.emails[0].value; user.save(function(err) { if (err) throw err; return done(null, user); }); } }); })); // ========================================================================= // TWITTER ================================================================= // ========================================================================= passport.use(new TwitterStrategy({ consumerKey : configAuth.twitterAuth.consumerKey, consumerSecret : configAuth.twitterAuth.consumerSecret, callbackURL : configAuth.twitterAuth.callbackURL, passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function(req, token, tokenSecret, profile, done) { // asynchronous process.nextTick(function() { // check if the user is already logged in if (!req.user) { User.findOne({ 'twitter.id' : profile.id }, function(err, user) { if (err) return done(err); if (user) { // if there is a user id already but no token (user was linked at one point and then removed) if (!user.twitter.token) { user.twitter.token = token; user.twitter.username = profile.username; user.twitter.displayName = profile.displayName; user.save(function(err) { if (err) throw err; return done(null, user); }); } return done(null, user); // user found, return that user } else { // if there is no user, create them var newUser = new User(); newUser.twitter.id = profile.id; newUser.twitter.token = token; newUser.twitter.username = profile.username; newUser.twitter.displayName = profile.displayName; newUser.save(function(err) { if (err) throw err; return done(null, newUser); }); } }); } else { // user already exists and is logged in, we have to link accounts var user = req.user; // pull the user out of the session user.twitter.id = profile.id; user.twitter.token = token; user.twitter.username = profile.username; user.twitter.displayName = profile.displayName; user.save(function(err) { if (err) throw err; return done(null, user); }); } }); })); // ========================================================================= // GOOGLE ================================================================== // ========================================================================= passport.use(new GoogleStrategy({ clientID : configAuth.googleAuth.clientID, clientSecret : configAuth.googleAuth.clientSecret, callbackURL : configAuth.googleAuth.callbackURL, passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function(req, token, refreshToken, profile, done) { // asynchronous process.nextTick(function() { // check if the user is already logged in if (!req.user) { User.findOne({ 'google.id' : profile.id }, function(err, user) { if (err) return done(err); if (user) { // if there is a user id already but no token (user was linked at one point and then removed) if (!user.google.token) { user.google.token = token; user.google.name = profile.displayName; user.google.email = profile.emails[0].value; // pull the first email user.save(function(err) { if (err) throw err; return done(null, user); }); } return done(null, user); } else { var newUser = new User(); newUser.google.id = profile.id; newUser.google.token = token; newUser.google.name = profile.displayName; newUser.google.email = profile.emails[0].value; // pull the first email newUser.save(function(err) { if (err) throw err; return done(null, newUser); }); } }); } else { // user already exists and is logged in, we have to link accounts var user = req.user; // pull the user out of the session user.google.id = profile.id; user.google.token = token; user.google.name = profile.displayName; user.google.email = profile.emails[0].value; // pull the first email user.save(function(err) { if (err) throw err; return done(null, user); }); } }); })); };
/** * Created by Luigi Ilie Aron on 27.01.15. * email: [email protected] */ var assert = require('assert'), _ = require('lodash'); describe('Semantic Interface', function() { describe('.getRawCollection()', function() { it('should create a set of 15 users', function(done) { var usersArray = [ { firstName: 'getRawCollection_1', type: 'getRawCollection' }, { firstName: 'getRawCollection_2', type: 'getRawCollection' }, { firstName: 'getRawCollection_3', type: 'getRawCollection' }, { firstName: 'getRawCollection_4', type: 'getRawCollection' }, { firstName: 'getRawCollection_5', type: 'getRawCollection' }, { firstName: 'getRawCollection_6', type: 'getRawCollection' }, { firstName: 'getRawCollection_7', type: 'getRawCollection' }, { firstName: 'getRawCollection_8', type: 'getRawCollection' }, { firstName: 'getRawCollection_9', type: 'getRawCollection' }, { firstName: 'getRawCollection_10', type: 'getRawCollection' }, { firstName: 'getRawCollection_11', type: 'getRawCollection' }, { firstName: 'getRawCollection_12', type: 'getRawCollection' }, { firstName: 'getRawCollection_13', type: 'getRawCollection' }, { firstName: 'getRawCollection_14', type: 'getRawCollection' }, { firstName: 'getRawCollection_15', type: 'getRawCollection' } ]; Semantic.User.createEach(usersArray, function(err, users) { assert(!err); done(); }); }); it('should getRawCollection 15 users', function(done) { this.timeout(15000); setTimeout(function(){ var query = { bool: { must: [ { term: { type: 'getRawCollection' } } ] } }; Semantic.User.getRawCollection(function(err, users){ assert(!err); assert(Array.isArray(users)); assert(users.length === 15); Semantic.User.destroy(query).limit(999999).exec(function(err, _users){ assert(!err); assert(Array.isArray(_users)); assert(_users.length === 15); done(); }); }); }, 10000); }); }) });
// Karma configuration // Generated on Fri May 27 2016 18:39:38 GMT+0200 (CEST) const webpackConf = require('./test/unit/webpack.config'); module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: [ 'jasmine', 'jasmine-matchers', ], // list of files / patterns to load in the browser files: [ 'node_modules/jasmine-promises/dist/jasmine-promises.js', 'test/integration/index.js', ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'test/integration/index.js': ['webpack', 'sourcemap'], }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter // reporters: ['progress'], // reporters: ['spec', 'jasmine-diff'], // reporters: ['jasmine-diff'], reporters: ['spec'], // web server port port: 9877, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: // config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || // config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity, // Hide webpack build information from output webpackMiddleware: { noInfo: 'errors-only', }, }); // if (process.env.TRAVIS) { config.customLaunchers = { Chrome_no_sandbox: { base: 'Chrome', flags: ['--no-sandbox'], }, }; config.browsers = ['Chrome_no_sandbox']; config.webpack = webpackConf; // Configure code coverage reporter config.coverageReporter = { dir: 'coverage/', reporters: [ { type: 'lcovonly', subdir: '.' }, { type: 'json', subdir: '.' }, { type: 'text', subdir: '.' }, { type: 'html', subdir: '.' }, ], }; };
// Copyright OpenLogic, Inc. // See LICENSE file for license information. // var totalRequests = 0; // First check the MIME type of the URL. If it is the desired type, then make // the AJAX request to get the content (DOM) and extract the relevant links // in the content. function follow_html_mime_type(url) { var xhr = new XMLHttpRequest(); xhr.open('HEAD', url); xhr.onreadystatechange = function() { if (this.readyState == this.DONE && this.getResponseHeader('content-type').indexOf("text/html") != -1) { totalRequests += 1; chrome.runtime.sendMessage({ total: totalRequests }); requestDOM(url); } } xhr.send(); } function requestDOM(url) { var domRequest = new XMLHttpRequest(); domRequest.open('GET', url, true); domRequest.onreadystatechange = function() { if (this.readyState == this.DONE && this.status == 200) { var dom = $.parseHTML(this.responseText); extractLinks(dom); } } domRequest.send(); } function extractLinks(doc) { try { var domain = window.parent.location.origin; var aTag = 'a'; if (domain == 'http://sourceforge.net') aTag = 'a.name' var links = $(aTag, doc).toArray(); links = links.map(function(element) { // Proceed only if the link is in the same domain. if (element.href.indexOf(domain) == 0) { // Return an anchor's href attribute, stripping any URL fragment (hash '#'). // If the html specifies a relative path, chrome converts it to an absolute // URL. var href = element.href; var hashIndex = href.indexOf('#'); if (hashIndex > -1) href = href.substr(0, hashIndex); return href; } }); // Remove undefined from the links array. for (var n = links.length - 1; n >= 0; --n) { if (links[n] == undefined) links.splice(n, 1); } links.sort(); totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); chrome.extension.sendRequest(links); } catch (error) { // Do nothing. totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); } } window.sendSecondLevelLinks = function() { var firstLevelLinks = window.getLinks(); for (var index in firstLevelLinks) { var url = firstLevelLinks[index]; var current_location = window.location.href; var domain = window.parent.location.origin; // - skip urls that look like "parents" of the current one if (url.indexOf(current_location) != -1 && url.indexOf(domain) == 0) follow_html_mime_type(url); } } window.sendSecondLevelLinks();
import { mount } from '@vue/test-utils'; import TocButton from '../src/views/TocButton'; function createWrapper() { return mount(TocButton); } describe('Table of contents button', () => { it('should mount', () => { const wrapper = createWrapper(); expect(wrapper.exists()).toBe(true); }); it('should emit an event when the button is clicked', () => { const wrapper = createWrapper(); wrapper.find('button').trigger('click'); expect(wrapper.emitted().click).toBeTruthy(); }); });
'use strict'; angular .module('reflect.calendar') .factory('calendarHelper', function(moment, calendarConfig) { function eventIsInPeriod(eventStart, eventEnd, periodStart, periodEnd) { eventStart = moment(eventStart); eventEnd = moment(eventEnd); periodStart = moment(periodStart); periodEnd = moment(periodEnd); return (eventStart.isAfter(periodStart) && eventStart.isBefore(periodEnd)) || (eventEnd.isAfter(periodStart) && eventEnd.isBefore(periodEnd)) || (eventStart.isBefore(periodStart) && eventEnd.isAfter(periodEnd)) || eventStart.isSame(periodStart) || eventEnd.isSame(periodEnd); } function getEventsInPeriod(calendarDate, period, allEvents) { var startPeriod = moment(calendarDate).startOf(period); var endPeriod = moment(calendarDate).endOf(period); return allEvents.filter(function(event) { return eventIsInPeriod(event.startsAt, event.endsAt, startPeriod, endPeriod); }); } function getBadgeTotal(events) { return events.filter(function(event) { return event.incrementsBadgeTotal !== false; }).length; } function getWeekDayNames() { var weekdays = []; var count = 0; while (count < 7) { weekdays.push(moment().weekday(count++).format(calendarConfig.dateFormats.weekDay)); } return weekdays; } function filterEventsInPeriod(events, startPeriod, endPeriod) { return events.filter(function(event) { return eventIsInPeriod(event.startsAt, event.endsAt, startPeriod, endPeriod); }); } function getYearView(events, currentDay) { var view = []; var eventsInPeriod = getEventsInPeriod(currentDay, 'year', events); var month = moment(currentDay).startOf('year'); var count = 0; while (count < 12) { var startPeriod = month.clone(); var endPeriod = startPeriod.clone().endOf('month'); var periodEvents = filterEventsInPeriod(eventsInPeriod, startPeriod, endPeriod); view.push({ label: startPeriod.format(calendarConfig.dateFormats.month), isToday: startPeriod.isSame(moment().startOf('month')), events: periodEvents, date: startPeriod, badgeTotal: getBadgeTotal(periodEvents) }); month.add(1, 'month'); count++; } return view; } function getMonthView(events, currentDay) { var eventsInPeriod = getEventsInPeriod(currentDay, 'month', events); var startOfMonth = moment(currentDay).startOf('month'); var day = startOfMonth.clone().startOf('week'); var endOfMonthView = moment(currentDay).endOf('month').endOf('week'); var view = []; var today = moment().startOf('day'); while (day.isBefore(endOfMonthView)) { var inMonth = day.month() === moment(currentDay).month(); var monthEvents = []; if (inMonth) { monthEvents = filterEventsInPeriod(eventsInPeriod, day, day.clone().endOf('day')); } view.push({ label: day.date(), date: day.clone(), inMonth: inMonth, isPast: today.isAfter(day), isToday: today.isSame(day), isFuture: today.isBefore(day), isWeekend: [0, 6].indexOf(day.day()) > -1, events: monthEvents, badgeTotal: getBadgeTotal(monthEvents) }); day.add(1, 'day'); } return view; } function getWeekView(events, currentDay) { var startOfWeek = moment(currentDay).startOf('week'); var endOfWeek = moment(currentDay).endOf('week'); var dayCounter = startOfWeek.clone(); var days = []; var today = moment().startOf('day'); while (days.length < 7) { days.push({ weekDayLabel: dayCounter.format(calendarConfig.dateFormats.weekDay), date: dayCounter.clone(), dayLabel: dayCounter.format(calendarConfig.dateFormats.day), isPast: dayCounter.isBefore(today), isToday: dayCounter.isSame(today), isFuture: dayCounter.isAfter(today), isWeekend: [0, 6].indexOf(dayCounter.day()) > -1 }); dayCounter.add(1, 'day'); } var eventsSorted = filterEventsInPeriod(events, startOfWeek, endOfWeek).map(function(event) { var eventStart = moment(event.startsAt).startOf('day'); var eventEnd = moment(event.endsAt).startOf('day'); var weekViewStart = moment(startOfWeek).startOf('day'); var weekViewEnd = moment(endOfWeek).startOf('day'); var offset, span; if (eventStart.isBefore(weekViewStart) || eventStart.isSame(weekViewStart)) { offset = 0; } else { offset = eventStart.diff(weekViewStart, 'days'); } if (eventEnd.isAfter(weekViewEnd)) { eventEnd = weekViewEnd; } if (eventStart.isBefore(weekViewStart)) { eventStart = weekViewStart; } span = moment(eventEnd).diff(eventStart, 'days') + 1; event.daySpan = span; event.dayOffset = offset; return event; }); return {days: days, events: eventsSorted}; } function getDayView(events, currentDay, dayStartHour, dayEndHour, hourHeight) { var calendarStart = moment(currentDay).startOf('day').add(dayStartHour, 'hours'); var calendarEnd = moment(currentDay).startOf('day').add(dayEndHour, 'hours'); var calendarHeight = (dayEndHour - dayStartHour + 1) * hourHeight; var hourHeightMultiplier = hourHeight / 60; var buckets = []; var eventsInPeriod = filterEventsInPeriod( events, moment(currentDay).startOf('day').toDate(), moment(currentDay).endOf('day').toDate() ); return eventsInPeriod.map(function(event) { if (moment(event.startsAt).isBefore(calendarStart)) { event.top = 0; } else { event.top = (moment(event.startsAt).startOf('minute').diff(calendarStart.startOf('minute'), 'minutes') * hourHeightMultiplier) - 2; } if (moment(event.endsAt).isAfter(calendarEnd)) { event.height = calendarHeight - event.top; } else { var diffStart = event.startsAt; if (moment(event.startsAt).isBefore(calendarStart)) { diffStart = calendarStart.toDate(); } event.height = moment(event.endsAt).diff(diffStart, 'minutes') * hourHeightMultiplier; } if (event.top - event.height > calendarHeight) { event.height = 0; } event.left = 0; return event; }).filter(function(event) { return event.height > 0; }).map(function(event) { var cannotFitInABucket = true; buckets.forEach(function(bucket, bucketIndex) { var canFitInThisBucket = true; bucket.forEach(function(bucketItem) { if (eventIsInPeriod(event.startsAt, event.endsAt, bucketItem.startsAt, bucketItem.endsAt) || eventIsInPeriod(bucketItem.startsAt, bucketItem.endsAt, event.startsAt, event.endsAt)) { canFitInThisBucket = false; } }); if (canFitInThisBucket && cannotFitInABucket) { cannotFitInABucket = false; event.left = bucketIndex * 150; buckets[bucketIndex].push(event); } }); if (cannotFitInABucket) { event.left = buckets.length * 150; buckets.push([event]); } return event; }); } return { getWeekDayNames: getWeekDayNames, getYearView: getYearView, getMonthView: getMonthView, getWeekView: getWeekView, getDayView: getDayView }; });
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var users = require('./routes/users'); var orgs = require('./routes/orgs'); var tasks = require('./routes/tasks'); var projects = require('./routes/projects'); var emails = require('./routes/emails'); var util = require('./util'); var app = express(); // var expressJwt = require('express-jwt'); // view engine setup // app.set('views', path.join(__dirname, 'views')); // app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); // Client Route // app.use(expressJwt({ secret: 'secret' })); app.use(express.static(path.join(__dirname, '../dist'))); // Routing app.use('/api', routes); app.use('/api/orgs', orgs); app.use('/api/projects', projects); //app.use('/api/users', util.decode); app.use('/api/users', users); // Might need to modify where decoding happens (on user?) //app.use('/api/tasks', util.decode); app.use('/api/tasks', tasks); app.use('/api/email', emails); app.use('/*/', express.static(path.join(__dirname, '../dist/index.html'))); // TODO refactor into a controller // TODO remove this // checkAuth = util.checkAuth; module.exports = app;
import React from 'react'; import { assert } from 'chai'; import { createMount, createShallow, getClasses } from '@material-ui/core/test-utils'; import describeConformance from '../test-utils/describeConformance'; import AppBar from './AppBar'; import Paper from '../Paper'; describe('<AppBar />', () => { let mount; let shallow; let classes; before(() => { mount = createMount({ strict: true }); shallow = createShallow({ dive: true }); classes = getClasses(<AppBar>Hello World</AppBar>); }); after(() => { mount.cleanUp(); }); describeConformance(<AppBar>Conformance?</AppBar>, () => ({ classes, inheritComponent: Paper, mount, refInstanceof: window.HTMLElement, skip: ['componentProp'], })); it('should render with the root class and primary', () => { const wrapper = shallow(<AppBar>Hello World</AppBar>); assert.strictEqual(wrapper.hasClass(classes.root), true); assert.strictEqual(wrapper.hasClass(classes.colorPrimary), true); assert.strictEqual(wrapper.hasClass(classes.colorSecondary), false); }); it('should render a primary app bar', () => { const wrapper = shallow(<AppBar color="primary">Hello World</AppBar>); assert.strictEqual(wrapper.hasClass(classes.root), true); assert.strictEqual(wrapper.hasClass(classes.colorPrimary), true); assert.strictEqual(wrapper.hasClass(classes.colorSecondary), false); }); it('should render an secondary app bar', () => { const wrapper = shallow(<AppBar color="secondary">Hello World</AppBar>); assert.strictEqual(wrapper.hasClass(classes.root), true); assert.strictEqual(wrapper.hasClass(classes.colorPrimary), false); assert.strictEqual(wrapper.hasClass(classes.colorSecondary), true); }); describe('Dialog', () => { it('should add a .mui-fixed class', () => { const wrapper = shallow(<AppBar position="fixed">Hello World</AppBar>); assert.strictEqual(wrapper.hasClass('mui-fixed'), true); }); }); });
var mongoose = require('mongoose'), _ = require('lodash'), moment = require('moment'); module.exports = function (req, res) { var connectionDB = mongoose.connection.db; var today = moment().startOf('day'); var tomorrow = moment(today).add(1, 'days'); var dayAfterTomorrow = moment(today).add(2, 'days'); connectionDB.collection('appointments', function (err, collection) { collection.find({ startDate: { $gte: tomorrow.toISOString(), $lt: dayAfterTomorrow.toISOString() } }, function(err, cursor){ if (err) { console.log(err) } else { var appointmentsPhone = []; var appointmentsEmail = []; cursor.toArray(function (err, result) { if (err) { console.log(err); } else { _.map(result, function(a){ if (a.sentReminderPhone === undefined && a.sentReminderPhone !== 'sent' && a.customer.phone !== '' && a.sendSMS){ console.log('here'); appointmentsPhone.push(a); } if (a.sentReminderEmail === undefined && a.sentReminderEmail !== 'sent' && a.customer.email !== '' && a.sendEmail){ appointmentsEmail.push(a); } }); res.jsonp([{email: appointmentsEmail.length, phone: appointmentsPhone.length}]) } }); } }) }); };
(function(root, factory) { if (typeof exports === "object") { module.exports = factory(); } else if (typeof define === "function" && define.amd) { define([], factory); } else{ factory(); } }(this, function() { /** * AngularJS Google Maps Ver. 1.18.4 * * The MIT License (MIT) * * Copyright (c) 2014, 2015, 1016 Allen Kim * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ angular.module('ngMap', []); /** * @ngdoc controller * @name MapController */ (function() { 'use strict'; var Attr2MapOptions; var __MapController = function( $scope, $element, $attrs, $parse, $interpolate, _Attr2MapOptions_, NgMap, NgMapPool, escapeRegExp ) { Attr2MapOptions = _Attr2MapOptions_; var vm = this; var exprStartSymbol = $interpolate.startSymbol(); var exprEndSymbol = $interpolate.endSymbol(); vm.mapOptions; /** @memberof __MapController */ vm.mapEvents; /** @memberof __MapController */ vm.eventListeners; /** @memberof __MapController */ /** * Add an object to the collection of group * @memberof __MapController * @function addObject * @param groupName the name of collection that object belongs to * @param obj an object to add into a collection, i.e. marker, shape */ vm.addObject = function(groupName, obj) { if (vm.map) { vm.map[groupName] = vm.map[groupName] || {}; var len = Object.keys(vm.map[groupName]).length; vm.map[groupName][obj.id || len] = obj; if (vm.map instanceof google.maps.Map) { //infoWindow.setMap works like infoWindow.open if (groupName != "infoWindows" && obj.setMap) { obj.setMap && obj.setMap(vm.map); } if (obj.centered && obj.position) { vm.map.setCenter(obj.position); } (groupName == 'markers') && vm.objectChanged('markers'); (groupName == 'customMarkers') && vm.objectChanged('customMarkers'); } } }; /** * Delete an object from the collection and remove from map * @memberof __MapController * @function deleteObject * @param {Array} objs the collection of objects. i.e., map.markers * @param {Object} obj the object to be removed. i.e., marker */ vm.deleteObject = function(groupName, obj) { /* delete from group */ if (obj.map) { var objs = obj.map[groupName]; for (var name in objs) { if (objs[name] === obj) { void 0; google.maps.event.clearInstanceListeners(obj); delete objs[name]; } } /* delete from map */ obj.map && obj.setMap && obj.setMap(null); (groupName == 'markers') && vm.objectChanged('markers'); (groupName == 'customMarkers') && vm.objectChanged('customMarkers'); } }; /** * @memberof __MapController * @function observeAttrSetObj * @param {Hash} orgAttrs attributes before its initialization * @param {Hash} attrs attributes after its initialization * @param {Object} obj map object that an action is to be done * @description watch changes of attribute values and * do appropriate action based on attribute name */ vm.observeAttrSetObj = function(orgAttrs, attrs, obj) { if (attrs.noWatcher) { return false; } var attrsToObserve = Attr2MapOptions.getAttrsToObserve(orgAttrs); for (var i=0; i<attrsToObserve.length; i++) { var attrName = attrsToObserve[i]; attrs.$observe(attrName, NgMap.observeAndSet(attrName, obj)); } }; /** * @memberof __MapController * @function zoomToIncludeMarkers */ vm.zoomToIncludeMarkers = function() { // Only fit to bounds if we have any markers // object.keys is supported in all major browsers (IE9+) if ((vm.map.markers != null && Object.keys(vm.map.markers).length > 0) || (vm.map.customMarkers != null && Object.keys(vm.map.customMarkers).length > 0)) { var bounds = new google.maps.LatLngBounds(); for (var k1 in vm.map.markers) { bounds.extend(vm.map.markers[k1].getPosition()); } for (var k2 in vm.map.customMarkers) { bounds.extend(vm.map.customMarkers[k2].getPosition()); } if (vm.mapOptions.maximumZoom) { vm.enableMaximumZoomCheck = true; //enable zoom check after resizing for markers } vm.map.fitBounds(bounds); } }; /** * @memberof __MapController * @function objectChanged * @param {String} group name of group e.g., markers */ vm.objectChanged = function(group) { if ( vm.map && (group == 'markers' || group == 'customMarkers') && vm.map.zoomToIncludeMarkers == 'auto' ) { vm.zoomToIncludeMarkers(); } }; /** * @memberof __MapController * @function initializeMap * @description * . initialize Google map on <div> tag * . set map options, events, and observers * . reset zoom to include all (custom)markers */ vm.initializeMap = function() { var mapOptions = vm.mapOptions, mapEvents = vm.mapEvents; var lazyInitMap = vm.map; //prepared for lazy init vm.map = NgMapPool.getMapInstance($element[0]); NgMap.setStyle($element[0]); // set objects for lazyInit if (lazyInitMap) { /** * rebuild mapOptions for lazyInit * because attributes values might have been changed */ var filtered = Attr2MapOptions.filter($attrs); var options = Attr2MapOptions.getOptions(filtered); var controlOptions = Attr2MapOptions.getControlOptions(filtered); mapOptions = angular.extend(options, controlOptions); void 0; for (var group in lazyInitMap) { var groupMembers = lazyInitMap[group]; //e.g. markers if (typeof groupMembers == 'object') { for (var id in groupMembers) { vm.addObject(group, groupMembers[id]); } } } vm.map.showInfoWindow = vm.showInfoWindow; vm.map.hideInfoWindow = vm.hideInfoWindow; } // set options mapOptions.zoom = mapOptions.zoom || 15; var center = mapOptions.center; var exprRegExp = new RegExp(escapeRegExp(exprStartSymbol) + '.*' + escapeRegExp(exprEndSymbol)); if (!mapOptions.center || ((typeof center === 'string') && center.match(exprRegExp)) ) { mapOptions.center = new google.maps.LatLng(0, 0); } else if( (typeof center === 'string') && center.match(/^[0-9.-]*,[0-9.-]*$/) ){ var lat = parseFloat(center.split(',')[0]); var lng = parseFloat(center.split(',')[1]); mapOptions.center = new google.maps.LatLng(lat, lng); } else if (!(center instanceof google.maps.LatLng)) { var geoCenter = mapOptions.center; delete mapOptions.center; NgMap.getGeoLocation(geoCenter, mapOptions.geoLocationOptions). then(function (latlng) { vm.map.setCenter(latlng); var geoCallback = mapOptions.geoCallback; geoCallback && $parse(geoCallback)($scope); }, function () { if (mapOptions.geoFallbackCenter) { vm.map.setCenter(mapOptions.geoFallbackCenter); } }); } vm.map.setOptions(mapOptions); // set events for (var eventName in mapEvents) { var event = mapEvents[eventName]; var listener = google.maps.event.addListener(vm.map, eventName, event); vm.eventListeners[eventName] = listener; } // set observers vm.observeAttrSetObj(orgAttrs, $attrs, vm.map); vm.singleInfoWindow = mapOptions.singleInfoWindow; google.maps.event.trigger(vm.map, 'resize'); google.maps.event.addListenerOnce(vm.map, "idle", function () { NgMap.addMap(vm); if (mapOptions.zoomToIncludeMarkers) { vm.zoomToIncludeMarkers(); } //TODO: it's for backward compatibiliy. will be removed $scope.map = vm.map; $scope.$emit('mapInitialized', vm.map); //callback if ($attrs.mapInitialized) { $parse($attrs.mapInitialized)($scope, {map: vm.map}); } }); //add maximum zoom listeners if zoom-to-include-markers and and maximum-zoom are valid attributes if (mapOptions.zoomToIncludeMarkers && mapOptions.maximumZoom) { google.maps.event.addListener(vm.map, 'zoom_changed', function() { if (vm.enableMaximumZoomCheck == true) { vm.enableMaximumZoomCheck = false; google.maps.event.addListenerOnce(vm.map, 'bounds_changed', function() { vm.map.setZoom(Math.min(mapOptions.maximumZoom, vm.map.getZoom())); }); } }); } }; $scope.google = google; //used by $scope.eval to avoid eval() /** * get map options and events */ var orgAttrs = Attr2MapOptions.orgAttributes($element); var filtered = Attr2MapOptions.filter($attrs); var options = Attr2MapOptions.getOptions(filtered, {scope: $scope}); var controlOptions = Attr2MapOptions.getControlOptions(filtered); var mapOptions = angular.extend(options, controlOptions); var mapEvents = Attr2MapOptions.getEvents($scope, filtered); void 0; Object.keys(mapEvents).length && void 0; vm.mapOptions = mapOptions; vm.mapEvents = mapEvents; vm.eventListeners = {}; if (options.lazyInit) { // allows controlled initialization // parse angular expression for dynamic ids if (!!$attrs.id && // starts with, at position 0 $attrs.id.indexOf(exprStartSymbol, 0) === 0 && // ends with $attrs.id.indexOf(exprEndSymbol, $attrs.id.length - exprEndSymbol.length) !== -1) { var idExpression = $attrs.id.slice(2,-2); var mapId = $parse(idExpression)($scope); } else { var mapId = $attrs.id; } vm.map = {id: mapId}; //set empty, not real, map NgMap.addMap(vm); } else { vm.initializeMap(); } //Trigger Resize if(options.triggerResize) { google.maps.event.trigger(vm.map, 'resize'); } $element.bind('$destroy', function() { NgMapPool.returnMapInstance(vm.map); NgMap.deleteMap(vm); }); }; // __MapController __MapController.$inject = [ '$scope', '$element', '$attrs', '$parse', '$interpolate', 'Attr2MapOptions', 'NgMap', 'NgMapPool', 'escapeRegexpFilter' ]; angular.module('ngMap').controller('__MapController', __MapController); })(); /** * @ngdoc directive * @name bicycling-layer * @param Attr2Options {service} * convert html attribute to Google map api options * @description * Requires: map directive * Restrict To: Element * * @example * * <map zoom="13" center="34.04924594193164, -118.24104309082031"> * <bicycling-layer></bicycling-layer> * </map> */ (function() { 'use strict'; var parser; var linkFunc = function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var orgAttrs = parser.orgAttributes(element); var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered); void 0; var layer = getLayer(options, events); mapController.addObject('bicyclingLayers', layer); mapController.observeAttrSetObj(orgAttrs, attrs, layer); //observers element.bind('$destroy', function() { mapController.deleteObject('bicyclingLayers', layer); }); }; var getLayer = function(options, events) { var layer = new google.maps.BicyclingLayer(options); for (var eventName in events) { google.maps.event.addListener(layer, eventName, events[eventName]); } return layer; }; var bicyclingLayer= function(Attr2MapOptions) { parser = Attr2MapOptions; return { restrict: 'E', require: ['?^map','?^ngMap'], link: linkFunc }; }; bicyclingLayer.$inject = ['Attr2MapOptions']; angular.module('ngMap').directive('bicyclingLayer', bicyclingLayer); })(); /** * @ngdoc directive * @name custom-control * @param Attr2Options {service} convert html attribute to Google map api options * @param $compile {service} AngularJS $compile service * @description * Build custom control and set to the map with position * * Requires: map directive * * Restrict To: Element * * @attr {String} position position of this control * i.e. TOP_RIGHT * @attr {Number} index index of the control * @example * * Example: * <map center="41.850033,-87.6500523" zoom="3"> * <custom-control id="home" position="TOP_LEFT" index="1"> * <div style="background-color: white;"> * <b>Home</b> * </div> * </custom-control> * </map> * */ (function() { 'use strict'; var parser, NgMap; var linkFunc = function(scope, element, attrs, mapController, $transclude) { mapController = mapController[0]||mapController[1]; var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered); /** * build a custom control element */ var customControlEl = element[0].parentElement.removeChild(element[0]); var content = $transclude(); angular.element(customControlEl).append(content); /** * set events */ for (var eventName in events) { google.maps.event.addDomListener(customControlEl, eventName, events[eventName]); } mapController.addObject('customControls', customControlEl); var position = options.position; mapController.map.controls[google.maps.ControlPosition[position]].push(customControlEl); element.bind('$destroy', function() { mapController.deleteObject('customControls', customControlEl); }); }; var customControl = function(Attr2MapOptions, _NgMap_) { parser = Attr2MapOptions, NgMap = _NgMap_; return { restrict: 'E', require: ['?^map','?^ngMap'], link: linkFunc, transclude: true }; // return }; customControl.$inject = ['Attr2MapOptions', 'NgMap']; angular.module('ngMap').directive('customControl', customControl); })(); /** * @ngdoc directive * @memberof ngmap * @name custom-marker * @param Attr2Options {service} convert html attribute to Google map api options * @param $timeout {service} AngularJS $timeout * @description * Marker with html * Requires: map directive * Restrict To: Element * * @attr {String} position required, position on map * @attr {Number} z-index optional * @attr {Boolean} visible optional * @example * * Example: * <map center="41.850033,-87.6500523" zoom="3"> * <custom-marker position="41.850033,-87.6500523"> * <div> * <b>Home</b> * </div> * </custom-marker> * </map> * */ /* global document */ (function() { 'use strict'; var parser, $timeout, $compile, NgMap; var CustomMarker = function(options) { options = options || {}; this.el = document.createElement('div'); this.el.style.display = 'inline-block'; this.el.style.visibility = "hidden"; this.visible = true; for (var key in options) { /* jshint ignore:line */ this[key] = options[key]; } }; var setCustomMarker = function() { CustomMarker.prototype = new google.maps.OverlayView(); CustomMarker.prototype.setContent = function(html, scope) { this.el.innerHTML = html; this.el.style.position = 'absolute'; if (scope) { $compile(angular.element(this.el).contents())(scope); } }; CustomMarker.prototype.getDraggable = function() { return this.draggable; }; CustomMarker.prototype.setDraggable = function(draggable) { this.draggable = draggable; }; CustomMarker.prototype.getPosition = function() { return this.position; }; CustomMarker.prototype.setPosition = function(position) { position && (this.position = position); /* jshint ignore:line */ var _this = this; if (this.getProjection() && typeof this.position.lng == 'function') { void 0; var setPosition = function() { if (!_this.getProjection()) { return; } var posPixel = _this.getProjection().fromLatLngToDivPixel(_this.position); var x = Math.round(posPixel.x - (_this.el.offsetWidth/2)); var y = Math.round(posPixel.y - _this.el.offsetHeight - 10); // 10px for anchor _this.el.style.left = x + "px"; _this.el.style.top = y + "px"; _this.el.style.visibility = "visible"; }; if (_this.el.offsetWidth && _this.el.offsetHeight) { setPosition(); } else { //delayed left/top calculation when width/height are not set instantly $timeout(setPosition, 300); } } }; CustomMarker.prototype.setZIndex = function(zIndex) { zIndex && (this.zIndex = zIndex); /* jshint ignore:line */ this.el.style.zIndex = this.zIndex; }; CustomMarker.prototype.getVisible = function() { return this.visible; }; CustomMarker.prototype.setVisible = function(visible) { this.el.style.display = visible ? 'inline-block' : 'none'; this.visible = visible; }; CustomMarker.prototype.addClass = function(className) { var classNames = this.el.className.trim().split(' '); (classNames.indexOf(className) == -1) && classNames.push(className); /* jshint ignore:line */ this.el.className = classNames.join(' '); }; CustomMarker.prototype.removeClass = function(className) { var classNames = this.el.className.split(' '); var index = classNames.indexOf(className); (index > -1) && classNames.splice(index, 1); /* jshint ignore:line */ this.el.className = classNames.join(' '); }; CustomMarker.prototype.onAdd = function() { this.getPanes().overlayMouseTarget.appendChild(this.el); }; CustomMarker.prototype.draw = function() { this.setPosition(); this.setZIndex(this.zIndex); this.setVisible(this.visible); }; CustomMarker.prototype.onRemove = function() { this.el.parentNode.removeChild(this.el); //this.el = null; }; }; var linkFunc = function(orgHtml, varsToWatch) { //console.log('orgHtml', orgHtml, 'varsToWatch', varsToWatch); return function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var orgAttrs = parser.orgAttributes(element); var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered); /** * build a custom marker element */ element[0].style.display = 'none'; void 0; var customMarker = new CustomMarker(options); $timeout(function() { //apply contents, class, and location after it is compiled scope.$watch('[' + varsToWatch.join(',') + ']', function() { customMarker.setContent(orgHtml, scope); }, true); customMarker.setContent(element[0].innerHTML, scope); var classNames = element[0].firstElementChild.className; customMarker.addClass('custom-marker'); customMarker.addClass(classNames); void 0; if (!(options.position instanceof google.maps.LatLng)) { NgMap.getGeoLocation(options.position).then( function(latlng) { customMarker.setPosition(latlng); } ); } }); void 0; for (var eventName in events) { /* jshint ignore:line */ google.maps.event.addDomListener( customMarker.el, eventName, events[eventName]); } mapController.addObject('customMarkers', customMarker); //set observers mapController.observeAttrSetObj(orgAttrs, attrs, customMarker); element.bind('$destroy', function() { //Is it required to remove event listeners when DOM is removed? mapController.deleteObject('customMarkers', customMarker); }); }; // linkFunc }; var customMarkerDirective = function( _$timeout_, _$compile_, $interpolate, Attr2MapOptions, _NgMap_, escapeRegExp ) { parser = Attr2MapOptions; $timeout = _$timeout_; $compile = _$compile_; NgMap = _NgMap_; var exprStartSymbol = $interpolate.startSymbol(); var exprEndSymbol = $interpolate.endSymbol(); var exprRegExp = new RegExp(escapeRegExp(exprStartSymbol) + '([^' + exprEndSymbol.substring(0, 1) + ']+)' + escapeRegExp(exprEndSymbol), 'g'); return { restrict: 'E', require: ['?^map','?^ngMap'], compile: function(element) { setCustomMarker(); element[0].style.display ='none'; var orgHtml = element.html(); var matches = orgHtml.match(exprRegExp); var varsToWatch = []; //filter out that contains '::', 'this.' (matches || []).forEach(function(match) { var toWatch = match.replace(exprStartSymbol,'').replace(exprEndSymbol,''); if (match.indexOf('::') == -1 && match.indexOf('this.') == -1 && varsToWatch.indexOf(toWatch) == -1) { varsToWatch.push(match.replace(exprStartSymbol,'').replace(exprEndSymbol,'')); } }); return linkFunc(orgHtml, varsToWatch); } }; // return };// function customMarkerDirective.$inject = ['$timeout', '$compile', '$interpolate', 'Attr2MapOptions', 'NgMap', 'escapeRegexpFilter']; angular.module('ngMap').directive('customMarker', customMarkerDirective); })(); /** * @ngdoc directive * @name directions * @description * Enable directions on map. * e.g., origin, destination, draggable, waypoints, etc * * Requires: map directive * * Restrict To: Element * * @attr {String} DirectionsRendererOptions * [Any DirectionsRendererOptions](https://developers.google.com/maps/documentation/javascript/reference#DirectionsRendererOptions) * @attr {String} DirectionsRequestOptions * [Any DirectionsRequest options](https://developers.google.com/maps/documentation/javascript/reference#DirectionsRequest) * @example * <map zoom="14" center="37.7699298, -122.4469157"> * <directions * draggable="true" * panel="directions-panel" * travel-mode="{{travelMode}}" * waypoints="[{location:'kingston', stopover:true}]" * origin="{{origin}}" * destination="{{destination}}"> * </directions> * </map> */ /* global document */ (function() { 'use strict'; var NgMap, $timeout, NavigatorGeolocation; var getDirectionsRenderer = function(options, events) { if (options.panel) { options.panel = document.getElementById(options.panel) || document.querySelector(options.panel); } var renderer = new google.maps.DirectionsRenderer(options); for (var eventName in events) { google.maps.event.addListener(renderer, eventName, events[eventName]); } return renderer; }; var updateRoute = function(renderer, options) { var directionsService = new google.maps.DirectionsService(); /* filter out valid keys only for DirectionsRequest object*/ var request = options; request.travelMode = request.travelMode || 'DRIVING'; var validKeys = [ 'origin', 'destination', 'travelMode', 'transitOptions', 'unitSystem', 'durationInTraffic', 'waypoints', 'optimizeWaypoints', 'provideRouteAlternatives', 'avoidHighways', 'avoidTolls', 'region' ]; for(var key in request){ (validKeys.indexOf(key) === -1) && (delete request[key]); } if(request.waypoints) { // Check fo valid values if(request.waypoints == "[]" || request.waypoints === "") { delete request.waypoints; } } var showDirections = function(request) { directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { $timeout(function() { renderer.setDirections(response); }); } }); }; if (request.origin && request.destination) { if (request.origin == 'current-location') { NavigatorGeolocation.getCurrentPosition().then(function(ll) { request.origin = new google.maps.LatLng(ll.coords.latitude, ll.coords.longitude); showDirections(request); }); } else if (request.destination == 'current-location') { NavigatorGeolocation.getCurrentPosition().then(function(ll) { request.destination = new google.maps.LatLng(ll.coords.latitude, ll.coords.longitude); showDirections(request); }); } else { showDirections(request); } } }; var directions = function( Attr2MapOptions, _$timeout_, _NavigatorGeolocation_, _NgMap_) { var parser = Attr2MapOptions; NgMap = _NgMap_; $timeout = _$timeout_; NavigatorGeolocation = _NavigatorGeolocation_; var linkFunc = function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var orgAttrs = parser.orgAttributes(element); var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered); var attrsToObserve = parser.getAttrsToObserve(orgAttrs); var renderer = getDirectionsRenderer(options, events); mapController.addObject('directionsRenderers', renderer); attrsToObserve.forEach(function(attrName) { (function(attrName) { attrs.$observe(attrName, function(val) { if (attrName == 'panel') { $timeout(function(){ var panel = document.getElementById(val) || document.querySelector(val); void 0; panel && renderer.setPanel(panel); }); } else if (options[attrName] !== val) { //apply only if changed var optionValue = parser.toOptionValue(val, {key: attrName}); void 0; options[attrName] = optionValue; updateRoute(renderer, options); } }); })(attrName); }); NgMap.getMap().then(function() { updateRoute(renderer, options); }); element.bind('$destroy', function() { mapController.deleteObject('directionsRenderers', renderer); }); }; return { restrict: 'E', require: ['?^map','?^ngMap'], link: linkFunc }; }; // var directions directions.$inject = ['Attr2MapOptions', '$timeout', 'NavigatorGeolocation', 'NgMap']; angular.module('ngMap').directive('directions', directions); })(); /** * @ngdoc directive * @name drawing-manager * @param Attr2Options {service} convert html attribute to Google map api options * @description * Requires: map directive * Restrict To: Element * * @example * Example: * * <map zoom="13" center="37.774546, -122.433523" map-type-id="SATELLITE"> * <drawing-manager * on-overlaycomplete="onMapOverlayCompleted()" * position="ControlPosition.TOP_CENTER" * drawingModes="POLYGON,CIRCLE" * drawingControl="true" * circleOptions="fillColor: '#FFFF00';fillOpacity: 1;strokeWeight: 5;clickable: false;zIndex: 1;editable: true;" > * </drawing-manager> * </map> * * TODO: Add remove button. * currently, for our solution, we have the shapes/markers in our own * controller, and we use some css classes to change the shape button * to a remove button (<div>X</div>) and have the remove operation in our own controller. */ (function() { 'use strict'; angular.module('ngMap').directive('drawingManager', [ 'Attr2MapOptions', function(Attr2MapOptions) { var parser = Attr2MapOptions; return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var controlOptions = parser.getControlOptions(filtered); var events = parser.getEvents(scope, filtered); /** * set options */ var drawingManager = new google.maps.drawing.DrawingManager({ drawingMode: options.drawingmode, drawingControl: options.drawingcontrol, drawingControlOptions: controlOptions.drawingControlOptions, circleOptions:options.circleoptions, markerOptions:options.markeroptions, polygonOptions:options.polygonoptions, polylineOptions:options.polylineoptions, rectangleOptions:options.rectangleoptions }); //Observers attrs.$observe('drawingControlOptions', function (newValue) { drawingManager.drawingControlOptions = parser.getControlOptions({drawingControlOptions: newValue}).drawingControlOptions; drawingManager.setDrawingMode(null); drawingManager.setMap(mapController.map); }); /** * set events */ for (var eventName in events) { google.maps.event.addListener(drawingManager, eventName, events[eventName]); } mapController.addObject('mapDrawingManager', drawingManager); element.bind('$destroy', function() { mapController.deleteObject('mapDrawingManager', drawingManager); }); } }; // return }]); })(); /** * @ngdoc directive * @name dynamic-maps-engine-layer * @description * Requires: map directive * Restrict To: Element * * @example * Example: * <map zoom="14" center="[59.322506, 18.010025]"> * <dynamic-maps-engine-layer * layer-id="06673056454046135537-08896501997766553811"> * </dynamic-maps-engine-layer> * </map> */ (function() { 'use strict'; angular.module('ngMap').directive('dynamicMapsEngineLayer', [ 'Attr2MapOptions', function(Attr2MapOptions) { var parser = Attr2MapOptions; var getDynamicMapsEngineLayer = function(options, events) { var layer = new google.maps.visualization.DynamicMapsEngineLayer(options); for (var eventName in events) { google.maps.event.addListener(layer, eventName, events[eventName]); } return layer; }; return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered, events); var layer = getDynamicMapsEngineLayer(options, events); mapController.addObject('mapsEngineLayers', layer); } }; // return }]); })(); /** * @ngdoc directive * @name fusion-tables-layer * @description * Requires: map directive * Restrict To: Element * * @example * Example: * <map zoom="11" center="41.850033, -87.6500523"> * <fusion-tables-layer query="{ * select: 'Geocodable address', * from: '1mZ53Z70NsChnBMm-qEYmSDOvLXgrreLTkQUvvg'}"> * </fusion-tables-layer> * </map> */ (function() { 'use strict'; angular.module('ngMap').directive('fusionTablesLayer', [ 'Attr2MapOptions', function(Attr2MapOptions) { var parser = Attr2MapOptions; var getLayer = function(options, events) { var layer = new google.maps.FusionTablesLayer(options); for (var eventName in events) { google.maps.event.addListener(layer, eventName, events[eventName]); } return layer; }; return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered, events); void 0; var layer = getLayer(options, events); mapController.addObject('fusionTablesLayers', layer); element.bind('$destroy', function() { mapController.deleteObject('fusionTablesLayers', layer); }); } }; // return }]); })(); /** * @ngdoc directive * @name heatmap-layer * @param Attr2Options {service} convert html attribute to Google map api options * @description * Requires: map directive * Restrict To: Element * * @example * * <map zoom="11" center="[41.875696,-87.624207]"> * <heatmap-layer data="taxiData"></heatmap-layer> * </map> */ (function() { 'use strict'; angular.module('ngMap').directive('heatmapLayer', [ 'Attr2MapOptions', '$window', function(Attr2MapOptions, $window) { var parser = Attr2MapOptions; return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var filtered = parser.filter(attrs); /** * set options */ var options = parser.getOptions(filtered, {scope: scope}); options.data = $window[attrs.data] || scope[attrs.data]; if (options.data instanceof Array) { options.data = new google.maps.MVCArray(options.data); } else { throw "invalid heatmap data"; } var layer = new google.maps.visualization.HeatmapLayer(options); /** * set events */ var events = parser.getEvents(scope, filtered); void 0; mapController.addObject('heatmapLayers', layer); } }; // return }]); })(); /** * @ngdoc directive * @name info-window * @param Attr2MapOptions {service} * convert html attribute to Google map api options * @param $compile {service} $compile service * @description * Defines infoWindow and provides compile method * * Requires: map directive * * Restrict To: Element * * NOTE: this directive should **NOT** be used with `ng-repeat` * because InfoWindow itself is a template, and a template must be * reused by each marker, thus, should not be redefined repeatedly * by `ng-repeat`. * * @attr {Boolean} visible * Indicates to show it when map is initialized * @attr {Boolean} visible-on-marker * Indicates to show it on a marker when map is initialized * @attr {Expression} geo-callback * if position is an address, the expression is will be performed * when geo-lookup is successful. e.g., geo-callback="showDetail()" * @attr {String} &lt;InfoWindowOption> Any InfoWindow options, * https://developers.google.com/maps/documentation/javascript/reference?csw=1#InfoWindowOptions * @attr {String} &lt;InfoWindowEvent> Any InfoWindow events, * https://developers.google.com/maps/documentation/javascript/reference * @example * Usage: * <map MAP_ATTRIBUTES> * <info-window id="foo" ANY_OPTIONS ANY_EVENTS"></info-window> * </map> * * Example: * <map center="41.850033,-87.6500523" zoom="3"> * <info-window id="1" position="41.850033,-87.6500523" > * <div ng-non-bindable> * Chicago, IL<br/> * LatLng: {{chicago.lat()}}, {{chicago.lng()}}, <br/> * World Coordinate: {{worldCoordinate.x}}, {{worldCoordinate.y}}, <br/> * Pixel Coordinate: {{pixelCoordinate.x}}, {{pixelCoordinate.y}}, <br/> * Tile Coordinate: {{tileCoordinate.x}}, {{tileCoordinate.y}} at Zoom Level {{map.getZoom()}} * </div> * </info-window> * </map> */ /* global google */ (function() { 'use strict'; var infoWindow = function(Attr2MapOptions, $compile, $q, $templateRequest, $timeout, $parse, NgMap) { var parser = Attr2MapOptions; var getInfoWindow = function(options, events, element) { var infoWindow; /** * set options */ if (options.position && !(options.position instanceof google.maps.LatLng)) { delete options.position; } infoWindow = new google.maps.InfoWindow(options); /** * set events */ for (var eventName in events) { if (eventName) { google.maps.event.addListener(infoWindow, eventName, events[eventName]); } } /** * set template and template-related functions * it must have a container element with ng-non-bindable */ var templatePromise = $q(function(resolve) { if (angular.isString(element)) { $templateRequest(element).then(function (requestedTemplate) { resolve(angular.element(requestedTemplate).wrap('<div>').parent()); }, function(message) { throw "info-window template request failed: " + message; }); } else { resolve(element); } }).then(function(resolvedTemplate) { var template = resolvedTemplate.html().trim(); if (angular.element(template).length != 1) { throw "info-window working as a template must have a container"; } infoWindow.__template = template.replace(/\s?ng-non-bindable[='"]+/,""); }); infoWindow.__open = function(map, scope, anchor) { templatePromise.then(function() { $timeout(function() { anchor && (scope.anchor = anchor); var el = $compile(infoWindow.__template)(scope); infoWindow.setContent(el[0]); scope.$apply(); if (anchor && anchor.getPosition) { infoWindow.open(map, anchor); } else if (anchor && anchor instanceof google.maps.LatLng) { infoWindow.open(map); infoWindow.setPosition(anchor); } else { infoWindow.open(map); } var infoWindowContainerEl = infoWindow.content.parentElement.parentElement.parentElement; infoWindowContainerEl.className = "ng-map-info-window"; }); }); }; return infoWindow; }; var linkFunc = function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; element.css('display','none'); var orgAttrs = parser.orgAttributes(element); var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered); var infoWindow = getInfoWindow(options, events, options.template || element); var address; if (options.position && !(options.position instanceof google.maps.LatLng)) { address = options.position; } if (address) { NgMap.getGeoLocation(address).then(function(latlng) { infoWindow.setPosition(latlng); infoWindow.__open(mapController.map, scope, latlng); var geoCallback = attrs.geoCallback; geoCallback && $parse(geoCallback)(scope); }); } mapController.addObject('infoWindows', infoWindow); mapController.observeAttrSetObj(orgAttrs, attrs, infoWindow); mapController.showInfoWindow = mapController.map.showInfoWindow = mapController.showInfoWindow || function(p1, p2, p3) { //event, id, marker var id = typeof p1 == 'string' ? p1 : p2; var marker = typeof p1 == 'string' ? p2 : p3; if (typeof marker == 'string') { //Check if markers if defined to avoid odd 'undefined' errors if ( typeof mapController.map.markers != "undefined" && typeof mapController.map.markers[marker] != "undefined") { marker = mapController.map.markers[marker]; } else if ( //additionally check if that marker is a custom marker typeof mapController.map.customMarkers !== "undefined" && typeof mapController.map.customMarkers[marker] !== "undefined") { marker = mapController.map.customMarkers[marker]; } else { //Better error output if marker with that id is not defined throw new Error("Cant open info window for id " + marker + ". Marker or CustomMarker is not defined") } } var infoWindow = mapController.map.infoWindows[id]; var anchor = marker ? marker : (this.getPosition ? this : null); infoWindow.__open(mapController.map, scope, anchor); if(mapController.singleInfoWindow) { if(mapController.lastInfoWindow) { scope.hideInfoWindow(mapController.lastInfoWindow); } mapController.lastInfoWindow = id; } }; mapController.hideInfoWindow = mapController.map.hideInfoWindow = mapController.hideInfoWindow || function(p1, p2) { var id = typeof p1 == 'string' ? p1 : p2; var infoWindow = mapController.map.infoWindows[id]; infoWindow.close(); }; //TODO DEPRECATED scope.showInfoWindow = mapController.map.showInfoWindow; scope.hideInfoWindow = mapController.map.hideInfoWindow; var map = infoWindow.mapId ? {id:infoWindow.mapId} : 0; NgMap.getMap(map).then(function(map) { infoWindow.visible && infoWindow.__open(map, scope); if (infoWindow.visibleOnMarker) { var markerId = infoWindow.visibleOnMarker; infoWindow.__open(map, scope, map.markers[markerId]); } }); }; //link return { restrict: 'E', require: ['?^map','?^ngMap'], link: linkFunc }; }; // infoWindow infoWindow.$inject = ['Attr2MapOptions', '$compile', '$q', '$templateRequest', '$timeout', '$parse', 'NgMap']; angular.module('ngMap').directive('infoWindow', infoWindow); })(); /** * @ngdoc directive * @name kml-layer * @param Attr2MapOptions {service} convert html attribute to Google map api options * @description * renders Kml layer on a map * Requires: map directive * Restrict To: Element * * @attr {Url} url url of the kml layer * @attr {KmlLayerOptions} KmlLayerOptions * (https://developers.google.com/maps/documentation/javascript/reference#KmlLayerOptions) * @attr {String} &lt;KmlLayerEvent> Any KmlLayer events, * https://developers.google.com/maps/documentation/javascript/reference * @example * Usage: * <map MAP_ATTRIBUTES> * <kml-layer ANY_KML_LAYER ANY_KML_LAYER_EVENTS"></kml-layer> * </map> * * Example: * * <map zoom="11" center="[41.875696,-87.624207]"> * <kml-layer url="https://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml" > * </kml-layer> * </map> */ (function() { 'use strict'; angular.module('ngMap').directive('kmlLayer', [ 'Attr2MapOptions', function(Attr2MapOptions) { var parser = Attr2MapOptions; var getKmlLayer = function(options, events) { var kmlLayer = new google.maps.KmlLayer(options); for (var eventName in events) { google.maps.event.addListener(kmlLayer, eventName, events[eventName]); } return kmlLayer; }; return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var orgAttrs = parser.orgAttributes(element); var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered); void 0; var kmlLayer = getKmlLayer(options, events); mapController.addObject('kmlLayers', kmlLayer); mapController.observeAttrSetObj(orgAttrs, attrs, kmlLayer); //observers element.bind('$destroy', function() { mapController.deleteObject('kmlLayers', kmlLayer); }); } }; // return }]); })(); /** * @ngdoc directive * @name map-data * @param Attr2MapOptions {service} * convert html attribute to Google map api options * @description * set map data * Requires: map directive * Restrict To: Element * * @wn {String} method-name, run map.data[method-name] with attribute value * @example * Example: * * <map zoom="11" center="[41.875696,-87.624207]"> * <map-data load-geo-json="https://storage.googleapis.com/maps-devrel/google.json"></map-data> * </map> */ (function() { 'use strict'; angular.module('ngMap').directive('mapData', [ 'Attr2MapOptions', 'NgMap', function(Attr2MapOptions, NgMap) { var parser = Attr2MapOptions; return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0] || mapController[1]; var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered, events); void 0; NgMap.getMap(mapController.map.id).then(function(map) { //options for (var key in options) { var val = options[key]; if (typeof scope[val] === "function") { map.data[key](scope[val]); } else { map.data[key](val); } } //events for (var eventName in events) { map.data.addListener(eventName, events[eventName]); } }); } }; // return }]); })(); /** * @ngdoc directive * @name map-lazy-load * @param Attr2Options {service} convert html attribute to Google map api options * @description * Requires: Delay the initialization of map directive * until the map is ready to be rendered * Restrict To: Attribute * * @attr {String} map-lazy-load * Maps api script source file location. * Example: * 'https://maps.google.com/maps/api/js' * @attr {String} map-lazy-load-params * Maps api script source file location via angular scope variable. * Also requires the map-lazy-load attribute to be present in the directive. * Example: In your controller, set * $scope.googleMapsURL = 'https://maps.google.com/maps/api/js?v=3.20&client=XXXXXenter-api-key-hereXXXX' * * @example * Example: * * <div map-lazy-load="http://maps.google.com/maps/api/js"> * <map center="Brampton" zoom="10"> * <marker position="Brampton"></marker> * </map> * </div> * * <div map-lazy-load="http://maps.google.com/maps/api/js" * map-lazy-load-params="{{googleMapsUrl}}"> * <map center="Brampton" zoom="10"> * <marker position="Brampton"></marker> * </map> * </div> */ /* global window, document */ (function() { 'use strict'; var $timeout, $compile, src, savedHtml = [], elements = []; var preLinkFunc = function(scope, element, attrs) { var mapsUrl = attrs.mapLazyLoadParams || attrs.mapLazyLoad; if(window.google === undefined || window.google.maps === undefined) { elements.push({ scope: scope, element: element, savedHtml: savedHtml[elements.length], }); window.lazyLoadCallback = function() { void 0; $timeout(function() { /* give some time to load */ elements.forEach(function(elm) { elm.element.html(elm.savedHtml); $compile(elm.element.contents())(elm.scope); }); }, 100); }; var scriptEl = document.createElement('script'); void 0; scriptEl.src = mapsUrl + (mapsUrl.indexOf('?') > -1 ? '&' : '?') + 'callback=lazyLoadCallback'; if (!document.querySelector('script[src="' + scriptEl.src + '"]')) { document.body.appendChild(scriptEl); } } else { element.html(savedHtml); $compile(element.contents())(scope); } }; var compileFunc = function(tElement, tAttrs) { (!tAttrs.mapLazyLoad) && void 0; savedHtml.push(tElement.html()); src = tAttrs.mapLazyLoad; /** * if already loaded, stop processing it */ if(window.google !== undefined && window.google.maps !== undefined) { return false; } tElement.html(''); // will compile again after script is loaded return { pre: preLinkFunc }; }; var mapLazyLoad = function(_$compile_, _$timeout_) { $compile = _$compile_, $timeout = _$timeout_; return { compile: compileFunc }; }; mapLazyLoad.$inject = ['$compile','$timeout']; angular.module('ngMap').directive('mapLazyLoad', mapLazyLoad); })(); /** * @ngdoc directive * @name map-type * @param Attr2MapOptions {service} * convert html attribute to Google map api options * @description * Requires: map directive * Restrict To: Element * * @example * Example: * * <map zoom="13" center="34.04924594193164, -118.24104309082031"> * <map-type name="coordinate" object="coordinateMapType"></map-type> * </map> */ (function() { 'use strict'; angular.module('ngMap').directive('mapType', ['$parse', 'NgMap', function($parse, NgMap) { return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var mapTypeName = attrs.name, mapTypeObject; if (!mapTypeName) { throw "invalid map-type name"; } mapTypeObject = $parse(attrs.object)(scope); if (!mapTypeObject) { throw "invalid map-type object"; } NgMap.getMap().then(function(map) { map.mapTypes.set(mapTypeName, mapTypeObject); }); mapController.addObject('mapTypes', mapTypeObject); } }; // return }]); })(); /** * @ngdoc directive * @memberof ngMap * @name ng-map * @param Attr2Options {service} * convert html attribute to Google map api options * @description * Implementation of {@link __MapController} * Initialize a Google map within a `<div>` tag * with given options and register events * * @attr {Expression} map-initialized * callback function when map is initialized * e.g., map-initialized="mycallback(map)" * @attr {Expression} geo-callback if center is an address or current location, * the expression is will be executed when geo-lookup is successful. * e.g., geo-callback="showMyStoreInfo()" * @attr {Array} geo-fallback-center * The center of map incase geolocation failed. i.e. [0,0] * @attr {Object} geo-location-options * The navigator geolocation options. * e.g., { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }. * If none specified, { timeout: 5000 }. * If timeout not specified, timeout: 5000 added * @attr {Boolean} zoom-to-include-markers * When true, map boundary will be changed automatially * to include all markers when initialized * @attr {Boolean} default-style * When false, the default styling, * `display:block;height:300px`, will be ignored. * @attr {String} &lt;MapOption> Any Google map options, * https://developers.google.com/maps/documentation/javascript/reference?csw=1#MapOptions * @attr {String} &lt;MapEvent> Any Google map events, * https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/map_events.html * @attr {Boolean} single-info-window * When true the map will only display one info window at the time, * if not set or false, * everytime an info window is open it will be displayed with the othe one. * @attr {Boolean} trigger-resize * Default to false. Set to true to trigger resize of the map. Needs to be done anytime you resize the map * @example * Usage: * <map MAP_OPTIONS_OR_MAP_EVENTS ..> * ... Any children directives * </map> * * Example: * <map center="[40.74, -74.18]" on-click="doThat()"> * </map> * * <map geo-fallback-center="[40.74, -74.18]" zoom-to-inlude-markers="true"> * </map> */ (function () { 'use strict'; var mapDirective = function () { return { restrict: 'AE', controller: '__MapController', controllerAs: 'ngmap' }; }; angular.module('ngMap').directive('map', [mapDirective]); angular.module('ngMap').directive('ngMap', [mapDirective]); })(); /** * @ngdoc directive * @name maps-engine-layer * @description * Requires: map directive * Restrict To: Element * * @example * Example: * <map zoom="14" center="[59.322506, 18.010025]"> * <maps-engine-layer layer-id="06673056454046135537-08896501997766553811"> * </maps-engine-layer> * </map> */ (function() { 'use strict'; angular.module('ngMap').directive('mapsEngineLayer', ['Attr2MapOptions', function(Attr2MapOptions) { var parser = Attr2MapOptions; var getMapsEngineLayer = function(options, events) { var layer = new google.maps.visualization.MapsEngineLayer(options); for (var eventName in events) { google.maps.event.addListener(layer, eventName, events[eventName]); } return layer; }; return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered, events); void 0; var layer = getMapsEngineLayer(options, events); mapController.addObject('mapsEngineLayers', layer); } }; // return }]); })(); /** * @ngdoc directive * @name marker * @param Attr2Options {service} convert html attribute to Google map api options * @param NavigatorGeolocation It is used to find the current location * @description * Draw a Google map marker on a map with given options and register events * * Requires: map directive * * Restrict To: Element * * @attr {String} position address, 'current', or [latitude, longitude] * example: * '1600 Pennsylvania Ave, 20500 Washingtion DC', * 'current position', * '[40.74, -74.18]' * @attr {Boolean} centered if set, map will be centered with this marker * @attr {Expression} geo-callback if position is an address, * the expression is will be performed when geo-lookup is successful. * e.g., geo-callback="showStoreInfo()" * @attr {Boolean} no-watcher if true, no attribute observer is added. * Useful for many ng-repeat * @attr {String} &lt;MarkerOption> * [Any Marker options](https://developers.google.com/maps/documentation/javascript/reference?csw=1#MarkerOptions) * @attr {String} &lt;MapEvent> * [Any Marker events](https://developers.google.com/maps/documentation/javascript/reference) * @example * Usage: * <map MAP_ATTRIBUTES> * <marker ANY_MARKER_OPTIONS ANY_MARKER_EVENTS"></MARKER> * </map> * * Example: * <map center="[40.74, -74.18]"> * <marker position="[40.74, -74.18]" on-click="myfunc()"></div> * </map> * * <map center="the cn tower"> * <marker position="the cn tower" on-click="myfunc()"></div> * </map> */ /* global google */ (function() { 'use strict'; var parser, $parse, NgMap; var getMarker = function(options, events) { var marker; if (NgMap.defaultOptions.marker) { for (var key in NgMap.defaultOptions.marker) { if (typeof options[key] == 'undefined') { void 0; options[key] = NgMap.defaultOptions.marker[key]; } } } if (!(options.position instanceof google.maps.LatLng)) { options.position = new google.maps.LatLng(0,0); } marker = new google.maps.Marker(options); /** * set events */ if (Object.keys(events).length > 0) { void 0; } for (var eventName in events) { if (eventName) { google.maps.event.addListener(marker, eventName, events[eventName]); } } return marker; }; var linkFunc = function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var orgAttrs = parser.orgAttributes(element); var filtered = parser.filter(attrs); var markerOptions = parser.getOptions(filtered, scope, {scope: scope}); var markerEvents = parser.getEvents(scope, filtered); void 0; var address; if (!(markerOptions.position instanceof google.maps.LatLng)) { address = markerOptions.position; } var marker = getMarker(markerOptions, markerEvents); mapController.addObject('markers', marker); if (address) { NgMap.getGeoLocation(address).then(function(latlng) { marker.setPosition(latlng); markerOptions.centered && marker.map.setCenter(latlng); var geoCallback = attrs.geoCallback; geoCallback && $parse(geoCallback)(scope); }); } //set observers mapController.observeAttrSetObj(orgAttrs, attrs, marker); /* observers */ element.bind('$destroy', function() { mapController.deleteObject('markers', marker); }); }; var marker = function(Attr2MapOptions, _$parse_, _NgMap_) { parser = Attr2MapOptions; $parse = _$parse_; NgMap = _NgMap_; return { restrict: 'E', require: ['^?map','?^ngMap'], link: linkFunc }; }; marker.$inject = ['Attr2MapOptions', '$parse', 'NgMap']; angular.module('ngMap').directive('marker', marker); })(); /** * @ngdoc directive * @name overlay-map-type * @param Attr2MapOptions {service} convert html attribute to Google map api options * @param $window {service} * @description * Requires: map directive * Restrict To: Element * * @example * Example: * * <map zoom="13" center="34.04924594193164, -118.24104309082031"> * <overlay-map-type index="0" object="coordinateMapType"></map-type> * </map> */ (function() { 'use strict'; angular.module('ngMap').directive('overlayMapType', [ 'NgMap', function(NgMap) { return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var initMethod = attrs.initMethod || "insertAt"; var overlayMapTypeObject = scope[attrs.object]; NgMap.getMap().then(function(map) { if (initMethod == "insertAt") { var index = parseInt(attrs.index, 10); map.overlayMapTypes.insertAt(index, overlayMapTypeObject); } else if (initMethod == "push") { map.overlayMapTypes.push(overlayMapTypeObject); } }); mapController.addObject('overlayMapTypes', overlayMapTypeObject); } }; // return }]); })(); /** * @ngdoc directive * @name places-auto-complete * @param Attr2MapOptions {service} convert html attribute to Google map api options * @description * Provides address auto complete feature to an input element * Requires: input tag * Restrict To: Attribute * * @attr {AutoCompleteOptions} * [Any AutocompleteOptions](https://developers.google.com/maps/documentation/javascript/3.exp/reference#AutocompleteOptions) * * @example * Example: * <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script> * <input places-auto-complete types="['geocode']" on-place-changed="myCallback(place)" component-restrictions="{country:'au'}"/> */ /* global google */ (function() { 'use strict'; var placesAutoComplete = function(Attr2MapOptions, $timeout) { var parser = Attr2MapOptions; var linkFunc = function(scope, element, attrs, ngModelCtrl) { if (attrs.placesAutoComplete ==='false') { return false; } var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered); var autocomplete = new google.maps.places.Autocomplete(element[0], options); for (var eventName in events) { google.maps.event.addListener(autocomplete, eventName, events[eventName]); } var updateModel = function() { $timeout(function(){ ngModelCtrl && ngModelCtrl.$setViewValue(element.val()); },100); }; google.maps.event.addListener(autocomplete, 'place_changed', updateModel); element[0].addEventListener('change', updateModel); attrs.$observe('types', function(val) { if (val) { var optionValue = parser.toOptionValue(val, {key: 'types'}); autocomplete.setTypes(optionValue); } }); attrs.$observe('componentRestrictions', function (val) { if (val) { autocomplete.setComponentRestrictions(scope.$eval(val)); } }); }; return { restrict: 'A', require: '?ngModel', link: linkFunc }; }; placesAutoComplete.$inject = ['Attr2MapOptions', '$timeout']; angular.module('ngMap').directive('placesAutoComplete', placesAutoComplete); })(); /** * @ngdoc directive * @name shape * @param Attr2MapOptions {service} convert html attribute to Google map api options * @description * Initialize a Google map shape in map with given options and register events * The shapes are: * . circle * . polygon * . polyline * . rectangle * . groundOverlay(or image) * * Requires: map directive * * Restrict To: Element * * @attr {Boolean} centered if set, map will be centered with this marker * @attr {Expression} geo-callback if shape is a circle and the center is * an address, the expression is will be performed when geo-lookup * is successful. e.g., geo-callback="showDetail()" * @attr {String} &lt;OPTIONS> * For circle, [any circle options](https://developers.google.com/maps/documentation/javascript/reference#CircleOptions) * For polygon, [any polygon options](https://developers.google.com/maps/documentation/javascript/reference#PolygonOptions) * For polyline, [any polyline options](https://developers.google.com/maps/documentation/javascript/reference#PolylineOptions) * For rectangle, [any rectangle options](https://developers.google.com/maps/documentation/javascript/reference#RectangleOptions) * For image, [any groundOverlay options](https://developers.google.com/maps/documentation/javascript/reference#GroundOverlayOptions) * @attr {String} &lt;MapEvent> [Any Shape events](https://developers.google.com/maps/documentation/javascript/reference) * @example * Usage: * <map MAP_ATTRIBUTES> * <shape name=SHAPE_NAME ANY_SHAPE_OPTIONS ANY_SHAPE_EVENTS"></MARKER> * </map> * * Example: * * <map zoom="11" center="[40.74, -74.18]"> * <shape id="polyline" name="polyline" geodesic="true" * stroke-color="#FF0000" stroke-opacity="1.0" stroke-weight="2" * path="[[40.74,-74.18],[40.64,-74.10],[40.54,-74.05],[40.44,-74]]" > * </shape> * </map> * * <map zoom="11" center="[40.74, -74.18]"> * <shape id="polygon" name="polygon" stroke-color="#FF0000" * stroke-opacity="1.0" stroke-weight="2" * paths="[[40.74,-74.18],[40.64,-74.18],[40.84,-74.08],[40.74,-74.18]]" > * </shape> * </map> * * <map zoom="11" center="[40.74, -74.18]"> * <shape id="rectangle" name="rectangle" stroke-color='#FF0000' * stroke-opacity="0.8" stroke-weight="2" * bounds="[[40.74,-74.18], [40.78,-74.14]]" editable="true" > * </shape> * </map> * * <map zoom="11" center="[40.74, -74.18]"> * <shape id="circle" name="circle" stroke-color='#FF0000' * stroke-opacity="0.8"stroke-weight="2" * center="[40.70,-74.14]" radius="4000" editable="true" > * </shape> * </map> * * <map zoom="11" center="[40.74, -74.18]"> * <shape id="image" name="image" * url="https://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg" * bounds="[[40.71,-74.22],[40.77,-74.12]]" opacity="0.7" * clickable="true"> * </shape> * </map> * * For full-working example, please visit * [shape example](https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/shape.html) */ /* global google */ (function() { 'use strict'; var getShape = function(options, events) { var shape; var shapeName = options.name; delete options.name; //remove name bcoz it's not for options void 0; /** * set options */ switch(shapeName) { case "circle": if (!(options.center instanceof google.maps.LatLng)) { options.center = new google.maps.LatLng(0,0); } shape = new google.maps.Circle(options); break; case "polygon": shape = new google.maps.Polygon(options); break; case "polyline": shape = new google.maps.Polyline(options); break; case "rectangle": shape = new google.maps.Rectangle(options); break; case "groundOverlay": case "image": var url = options.url; var opts = {opacity: options.opacity, clickable: options.clickable, id:options.id}; shape = new google.maps.GroundOverlay(url, options.bounds, opts); break; } /** * set events */ for (var eventName in events) { if (events[eventName]) { google.maps.event.addListener(shape, eventName, events[eventName]); } } return shape; }; var shape = function(Attr2MapOptions, $parse, NgMap) { var parser = Attr2MapOptions; var linkFunc = function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var orgAttrs = parser.orgAttributes(element); var filtered = parser.filter(attrs); var shapeOptions = parser.getOptions(filtered, {scope: scope}); var shapeEvents = parser.getEvents(scope, filtered); var address, shapeType; shapeType = shapeOptions.name; if (!(shapeOptions.center instanceof google.maps.LatLng)) { address = shapeOptions.center; } var shape = getShape(shapeOptions, shapeEvents); mapController.addObject('shapes', shape); if (address && shapeType == 'circle') { NgMap.getGeoLocation(address).then(function(latlng) { shape.setCenter(latlng); shape.centered && shape.map.setCenter(latlng); var geoCallback = attrs.geoCallback; geoCallback && $parse(geoCallback)(scope); }); } //set observers mapController.observeAttrSetObj(orgAttrs, attrs, shape); element.bind('$destroy', function() { mapController.deleteObject('shapes', shape); }); }; return { restrict: 'E', require: ['?^map','?^ngMap'], link: linkFunc }; // return }; shape.$inject = ['Attr2MapOptions', '$parse', 'NgMap']; angular.module('ngMap').directive('shape', shape); })(); /** * @ngdoc directive * @name streetview-panorama * @param Attr2MapOptions {service} convert html attribute to Google map api options * @description * Requires: map directive * Restrict To: Element * * @attr container Optional, id or css selector, if given, streetview will be in the given html element * @attr {String} &lt;StreetViewPanoramaOption> * [Any Google StreetViewPanorama options](https://developers.google.com/maps/documentation/javascript/reference?csw=1#StreetViewPanoramaOptions) * @attr {String} &lt;StreetViewPanoramaEvent> * [Any Google StreetViewPanorama events](https://developers.google.com/maps/documentation/javascript/reference#StreetViewPanorama) * * @example * <map zoom="11" center="[40.688738,-74.043871]" > * <street-view-panorama * click-to-go="true" * disable-default-ui="true" * disable-double-click-zoom="true" * enable-close-button="true" * pano="my-pano" * position="40.688738,-74.043871" * pov="{heading:0, pitch: 90}" * scrollwheel="false" * visible="true"> * </street-view-panorama> * </map> */ /* global google, document */ (function() { 'use strict'; var streetViewPanorama = function(Attr2MapOptions, NgMap) { var parser = Attr2MapOptions; var getStreetViewPanorama = function(map, options, events) { var svp, container; if (options.container) { container = document.getElementById(options.container); container = container || document.querySelector(options.container); } if (container) { svp = new google.maps.StreetViewPanorama(container, options); } else { svp = map.getStreetView(); svp.setOptions(options); } for (var eventName in events) { eventName && google.maps.event.addListener(svp, eventName, events[eventName]); } return svp; }; var linkFunc = function(scope, element, attrs) { var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var controlOptions = parser.getControlOptions(filtered); var svpOptions = angular.extend(options, controlOptions); var svpEvents = parser.getEvents(scope, filtered); void 0; NgMap.getMap().then(function(map) { var svp = getStreetViewPanorama(map, svpOptions, svpEvents); map.setStreetView(svp); (!svp.getPosition()) && svp.setPosition(map.getCenter()); google.maps.event.addListener(svp, 'position_changed', function() { if (svp.getPosition() !== map.getCenter()) { map.setCenter(svp.getPosition()); } }); //needed for geo-callback var listener = google.maps.event.addListener(map, 'center_changed', function() { svp.setPosition(map.getCenter()); google.maps.event.removeListener(listener); }); }); }; //link return { restrict: 'E', require: ['?^map','?^ngMap'], link: linkFunc }; }; streetViewPanorama.$inject = ['Attr2MapOptions', 'NgMap']; angular.module('ngMap').directive('streetViewPanorama', streetViewPanorama); })(); /** * @ngdoc directive * @name traffic-layer * @param Attr2MapOptions {service} convert html attribute to Google map api options * @description * Requires: map directive * Restrict To: Element * * @example * Example: * * <map zoom="13" center="34.04924594193164, -118.24104309082031"> * <traffic-layer></traffic-layer> * </map> */ (function() { 'use strict'; angular.module('ngMap').directive('trafficLayer', [ 'Attr2MapOptions', function(Attr2MapOptions) { var parser = Attr2MapOptions; var getLayer = function(options, events) { var layer = new google.maps.TrafficLayer(options); for (var eventName in events) { google.maps.event.addListener(layer, eventName, events[eventName]); } return layer; }; return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var orgAttrs = parser.orgAttributes(element); var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered); void 0; var layer = getLayer(options, events); mapController.addObject('trafficLayers', layer); mapController.observeAttrSetObj(orgAttrs, attrs, layer); //observers element.bind('$destroy', function() { mapController.deleteObject('trafficLayers', layer); }); } }; // return }]); })(); /** * @ngdoc directive * @name transit-layer * @param Attr2MapOptions {service} convert html attribute to Google map api options * @description * Requires: map directive * Restrict To: Element * * @example * Example: * * <map zoom="13" center="34.04924594193164, -118.24104309082031"> * <transit-layer></transit-layer> * </map> */ (function() { 'use strict'; angular.module('ngMap').directive('transitLayer', [ 'Attr2MapOptions', function(Attr2MapOptions) { var parser = Attr2MapOptions; var getLayer = function(options, events) { var layer = new google.maps.TransitLayer(options); for (var eventName in events) { google.maps.event.addListener(layer, eventName, events[eventName]); } return layer; }; return { restrict: 'E', require: ['?^map','?^ngMap'], link: function(scope, element, attrs, mapController) { mapController = mapController[0]||mapController[1]; var orgAttrs = parser.orgAttributes(element); var filtered = parser.filter(attrs); var options = parser.getOptions(filtered, {scope: scope}); var events = parser.getEvents(scope, filtered); void 0; var layer = getLayer(options, events); mapController.addObject('transitLayers', layer); mapController.observeAttrSetObj(orgAttrs, attrs, layer); //observers element.bind('$destroy', function() { mapController.deleteObject('transitLayers', layer); }); } }; // return }]); })(); /** * @ngdoc filter * @name camel-case * @description * Converts string to camel cased */ (function() { 'use strict'; var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; var camelCaseFilter = function() { return function(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); }; }; angular.module('ngMap').filter('camelCase', camelCaseFilter); })(); /** * @ngdoc filter * @name escape-regex * @description * Escapes all regex special characters in a string */ (function() { 'use strict'; var escapeRegexpFilter = function() { return function(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string }; }; angular.module('ngMap').filter('escapeRegexp', escapeRegexpFilter); })(); /** * @ngdoc filter * @name jsonize * @description * Converts json-like string to json string */ (function() { 'use strict'; var jsonizeFilter = function() { return function(str) { try { // if parsable already, return as it is JSON.parse(str); return str; } catch(e) { // if not parsable, change little return str // wrap keys without quote with valid double quote .replace(/([\$\w]+)\s*:/g, function(_, $1) { return '"'+$1+'":'; } ) // replacing single quote wrapped ones to double quote .replace(/'([^']+)'/g, function(_, $1) { return '"'+$1+'"'; } ) .replace(/''/g, '""'); } }; }; angular.module('ngMap').filter('jsonize', jsonizeFilter); })(); /** * @ngdoc service * @name Attr2MapOptions * @description * Converts tag attributes to options used by google api v3 objects */ /* global google */ (function() { 'use strict'; //i.e. "2015-08-12T06:12:40.858Z" var isoDateRE = /^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):?(\d\d))?$/; var Attr2MapOptions = function( $parse, $timeout, $log, $interpolate, NavigatorGeolocation, GeoCoder, camelCaseFilter, jsonizeFilter, escapeRegExp ) { var exprStartSymbol = $interpolate.startSymbol(); var exprEndSymbol = $interpolate.endSymbol(); /** * Returns the attributes of an element as hash * @memberof Attr2MapOptions * @param {HTMLElement} el html element * @returns {Hash} attributes */ var orgAttributes = function(el) { (el.length > 0) && (el = el[0]); var orgAttributes = {}; for (var i=0; i<el.attributes.length; i++) { var attr = el.attributes[i]; orgAttributes[attr.name] = attr.value; } return orgAttributes; }; var getJSON = function(input) { var re =/^[\+\-]?[0-9\.]+,[ ]*\ ?[\+\-]?[0-9\.]+$/; //lat,lng if (input.match(re)) { input = "["+input+"]"; } return JSON.parse(jsonizeFilter(input)); }; var getLatLng = function(input) { var output = input; if (input[0].constructor == Array) { if ((input[0][0].constructor == Array && input[0][0].length == 2) || input[0][0].constructor == Object) { var preoutput; var outputArray = []; for (var i = 0; i < input.length; i++) { preoutput = input[i].map(function(el){ return new google.maps.LatLng(el[0], el[1]); }); outputArray.push(preoutput); } output = outputArray; } else { output = input.map(function(el) { return new google.maps.LatLng(el[0], el[1]); }); } } else if (!isNaN(parseFloat(input[0])) && isFinite(input[0])) { output = new google.maps.LatLng(output[0], output[1]); } return output; }; var toOptionValue = function(input, options) { var output; try { // 1. Number? output = getNumber(input); } catch(err) { try { // 2. JSON? var output = getJSON(input); if (output instanceof Array) { if (output[0].constructor == Object) { output = output; } else if (output[0] instanceof Array) { if (output[0][0].constructor == Object) { output = output; } else { output = getLatLng(output); } } else { output = getLatLng(output); } } // JSON is an object (not array or null) else if (output === Object(output)) { // check for nested hashes and convert to Google API options var newOptions = options; newOptions.doNotConverStringToNumber = true; output = getOptions(output, newOptions); } } catch(err2) { // 3. Google Map Object function Expression. i.e. LatLng(80,-49) if (input.match(/^[A-Z][a-zA-Z0-9]+\(.*\)$/)) { try { var exp = "new google.maps."+input; output = eval(exp); /* jshint ignore:line */ } catch(e) { output = input; } // 4. Google Map Object constant Expression. i.e. MayTypeId.HYBRID } else if (input.match(/^([A-Z][a-zA-Z0-9]+)\.([A-Z]+)$/)) { try { var matches = input.match(/^([A-Z][a-zA-Z0-9]+)\.([A-Z]+)$/); output = google.maps[matches[1]][matches[2]]; } catch(e) { output = input; } // 5. Google Map Object constant Expression. i.e. HYBRID } else if (input.match(/^[A-Z]+$/)) { try { var capitalizedKey = options.key.charAt(0).toUpperCase() + options.key.slice(1); if (options.key.match(/temperatureUnit|windSpeedUnit|labelColor/)) { capitalizedKey = capitalizedKey.replace(/s$/,""); output = google.maps.weather[capitalizedKey][input]; } else { output = google.maps[capitalizedKey][input]; } } catch(e) { output = input; } // 6. Date Object as ISO String } else if (input.match(isoDateRE)) { try { output = new Date(input); } catch(e) { output = input; } // 7. evaluate dynamically bound values } else if (input.match(new RegExp('^' + escapeRegExp(exprStartSymbol))) && options.scope) { try { var expr = input.replace(new RegExp(escapeRegExp(exprStartSymbol)),'').replace(new RegExp(escapeRegExp(exprEndSymbol), 'g'),''); output = options.scope.$eval(expr); } catch (err) { output = input; } } else { output = input; } } // catch(err2) } // catch(err) // convert output more for center and position if ( (options.key == 'center' || options.key == 'position') && output instanceof Array ) { output = new google.maps.LatLng(output[0], output[1]); } // convert output more for shape bounds if (options.key == 'bounds' && output instanceof Array) { output = new google.maps.LatLngBounds(output[0], output[1]); } // convert output more for shape icons if (options.key == 'icons' && output instanceof Array) { for (var i=0; i<output.length; i++) { var el = output[i]; if (el.icon.path.match(/^[A-Z_]+$/)) { el.icon.path = google.maps.SymbolPath[el.icon.path]; } } } // convert output more for marker icon if (options.key == 'icon' && output instanceof Object) { if ((""+output.path).match(/^[A-Z_]+$/)) { output.path = google.maps.SymbolPath[output.path]; } for (var key in output) { //jshint ignore:line var arr = output[key]; if (key == "anchor" || key == "origin" || key == "labelOrigin") { output[key] = new google.maps.Point(arr[0], arr[1]); } else if (key == "size" || key == "scaledSize") { output[key] = new google.maps.Size(arr[0], arr[1]); } } } return output; }; var getAttrsToObserve = function(attrs) { var attrsToObserve = []; var exprRegExp = new RegExp(escapeRegExp(exprStartSymbol) + '.*' + escapeRegExp(exprEndSymbol), 'g'); if (!attrs.noWatcher) { for (var attrName in attrs) { //jshint ignore:line var attrValue = attrs[attrName]; if (attrValue && attrValue.match(exprRegExp)) { // if attr value is {{..}} attrsToObserve.push(camelCaseFilter(attrName)); } } } return attrsToObserve; }; /** * filters attributes by skipping angularjs methods $.. $$.. * @memberof Attr2MapOptions * @param {Hash} attrs tag attributes * @returns {Hash} filterd attributes */ var filter = function(attrs) { var options = {}; for(var key in attrs) { if (key.match(/^\$/) || key.match(/^ng[A-Z]/)) { void(0); } else { options[key] = attrs[key]; } } return options; }; /** * converts attributes hash to Google Maps API v3 options * ``` * . converts numbers to number * . converts class-like string to google maps instance * i.e. `LatLng(1,1)` to `new google.maps.LatLng(1,1)` * . converts constant-like string to google maps constant * i.e. `MapTypeId.HYBRID` to `google.maps.MapTypeId.HYBRID` * i.e. `HYBRID"` to `google.maps.MapTypeId.HYBRID` * ``` * @memberof Attr2MapOptions * @param {Hash} attrs tag attributes * @param {Hash} options * @returns {Hash} options converted attributess */ var getOptions = function(attrs, params) { params = params || {}; var options = {}; for(var key in attrs) { if (attrs[key] || attrs[key] === 0) { if (key.match(/^on[A-Z]/)) { //skip events, i.e. on-click continue; } else if (key.match(/ControlOptions$/)) { // skip controlOptions continue; } else { // nested conversions need to be typechecked // (non-strings are fully converted) if (typeof attrs[key] !== 'string') { options[key] = attrs[key]; } else { if (params.doNotConverStringToNumber && attrs[key].match(/^[0-9]+$/) ) { options[key] = attrs[key]; } else { options[key] = toOptionValue(attrs[key], {key: key, scope: params.scope}); } } } } // if (attrs[key]) } // for(var key in attrs) return options; }; /** * converts attributes hash to scope-specific event function * @memberof Attr2MapOptions * @param {scope} scope angularjs scope * @param {Hash} attrs tag attributes * @returns {Hash} events converted events */ var getEvents = function(scope, attrs) { var events = {}; var toLowercaseFunc = function($1){ return "_"+$1.toLowerCase(); }; var EventFunc = function(attrValue) { // funcName(argsStr) var matches = attrValue.match(/([^\(]+)\(([^\)]*)\)/); var funcName = matches[1]; var argsStr = matches[2].replace(/event[ ,]*/,''); //remove string 'event' var argsExpr = $parse("["+argsStr+"]"); //for perf when triggering event return function(event) { var args = argsExpr(scope); //get args here to pass updated model values function index(obj,i) {return obj[i];} var f = funcName.split('.').reduce(index, scope); f && f.apply(this, [event].concat(args)); $timeout( function() { scope.$apply(); }); }; }; for(var key in attrs) { if (attrs[key]) { if (!key.match(/^on[A-Z]/)) { //skip if not events continue; } //get event name as underscored. i.e. zoom_changed var eventName = key.replace(/^on/,''); eventName = eventName.charAt(0).toLowerCase() + eventName.slice(1); eventName = eventName.replace(/([A-Z])/g, toLowercaseFunc); var attrValue = attrs[key]; events[eventName] = new EventFunc(attrValue); } } return events; }; /** * control means map controls, i.e streetview, pan, etc, not a general control * @memberof Attr2MapOptions * @param {Hash} filtered filtered tag attributes * @returns {Hash} Google Map options */ var getControlOptions = function(filtered) { var controlOptions = {}; if (typeof filtered != 'object') { return false; } for (var attr in filtered) { if (filtered[attr]) { if (!attr.match(/(.*)ControlOptions$/)) { continue; // if not controlOptions, skip it } //change invalid json to valid one, i.e. {foo:1} to {"foo": 1} var orgValue = filtered[attr]; var newValue = orgValue.replace(/'/g, '"'); newValue = newValue.replace(/([^"]+)|("[^"]+")/g, function($0, $1, $2) { if ($1) { return $1.replace(/([a-zA-Z0-9]+?):/g, '"$1":'); } else { return $2; } }); try { var options = JSON.parse(newValue); for (var key in options) { //assign the right values if (options[key]) { var value = options[key]; if (typeof value === 'string') { value = value.toUpperCase(); } else if (key === "mapTypeIds") { value = value.map( function(str) { if (str.match(/^[A-Z]+$/)) { // if constant return google.maps.MapTypeId[str.toUpperCase()]; } else { // else, custom map-type return str; } }); } if (key === "style") { var str = attr.charAt(0).toUpperCase() + attr.slice(1); var objName = str.replace(/Options$/,'')+"Style"; options[key] = google.maps[objName][value]; } else if (key === "position") { options[key] = google.maps.ControlPosition[value]; } else { options[key] = value; } } } controlOptions[attr] = options; } catch (e) { void 0; } } } // for return controlOptions; }; return { filter: filter, getOptions: getOptions, getEvents: getEvents, getControlOptions: getControlOptions, toOptionValue: toOptionValue, getAttrsToObserve: getAttrsToObserve, orgAttributes: orgAttributes }; // return }; Attr2MapOptions.$inject= [ '$parse', '$timeout', '$log', '$interpolate', 'NavigatorGeolocation', 'GeoCoder', 'camelCaseFilter', 'jsonizeFilter', 'escapeRegexpFilter' ]; angular.module('ngMap').service('Attr2MapOptions', Attr2MapOptions); })(); /** * @ngdoc service * @name GeoCoder * @description * Provides [defered/promise API](https://docs.angularjs.org/api/ng/service/$q) * service for Google Geocoder service */ (function() { 'use strict'; var $q; /** * @memberof GeoCoder * @param {Hash} options * https://developers.google.com/maps/documentation/geocoding/#geocoding * @example * ``` * GeoCoder.geocode({address: 'the cn tower'}).then(function(result) { * //... do something with result * }); * ``` * @returns {HttpPromise} Future object */ var geocodeFunc = function(options) { var deferred = $q.defer(); var geocoder = new google.maps.Geocoder(); geocoder.geocode(options, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { deferred.resolve(results); } else { deferred.reject(status); } }); return deferred.promise; }; var GeoCoder = function(_$q_) { $q = _$q_; return { geocode : geocodeFunc }; }; GeoCoder.$inject = ['$q']; angular.module('ngMap').service('GeoCoder', GeoCoder); })(); /** * @ngdoc service * @name GoogleMapsApi * @description * Load Google Maps API Service */ (function() { 'use strict'; var $q; var $timeout; var GoogleMapsApi = function(_$q_, _$timeout_) { $q = _$q_; $timeout = _$timeout_; return { /** * Load google maps into document by creating a script tag * @memberof GoogleMapsApi * @param {string} mapsUrl * @example * GoogleMapsApi.load(myUrl).then(function() { * console.log('google map has been loaded') * }); */ load: function (mapsUrl) { var deferred = $q.defer(); if (window.google === undefined || window.google.maps === undefined) { window.lazyLoadCallback = function() { $timeout(function() { /* give some time to load */ deferred.resolve(window.google) }, 100); }; var scriptEl = document.createElement('script'); scriptEl.src = mapsUrl + (mapsUrl.indexOf('?') > -1 ? '&' : '?') + 'callback=lazyLoadCallback'; if (!document.querySelector('script[src="' + scriptEl.src + '"]')) { document.body.appendChild(scriptEl); } } else { deferred.resolve(window.google) } return deferred.promise; } } } GoogleMapsApi.$inject = ['$q', '$timeout']; angular.module('ngMap').service('GoogleMapsApi', GoogleMapsApi); })(); /** * @ngdoc service * @name NavigatorGeolocation * @description * Provides [defered/promise API](https://docs.angularjs.org/api/ng/service/$q) * service for navigator.geolocation methods */ /* global google */ (function() { 'use strict'; var $q; /** * @memberof NavigatorGeolocation * @param {Object} geoLocationOptions the navigator geolocations options. * i.e. { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }. * If none specified, { timeout: 5000 }. * If timeout not specified, timeout: 5000 added * @param {function} success success callback function * @param {function} failure failure callback function * @example * ``` * NavigatorGeolocation.getCurrentPosition() * .then(function(position) { * var lat = position.coords.latitude, lng = position.coords.longitude; * .. do something lat and lng * }); * ``` * @returns {HttpPromise} Future object */ var getCurrentPosition = function(geoLocationOptions) { var deferred = $q.defer(); if (navigator.geolocation) { if (geoLocationOptions === undefined) { geoLocationOptions = { timeout: 5000 }; } else if (geoLocationOptions.timeout === undefined) { geoLocationOptions.timeout = 5000; } navigator.geolocation.getCurrentPosition( function(position) { deferred.resolve(position); }, function(evt) { void 0; deferred.reject(evt); }, geoLocationOptions ); } else { deferred.reject("Browser Geolocation service failed."); } return deferred.promise; }; var NavigatorGeolocation = function(_$q_) { $q = _$q_; return { getCurrentPosition: getCurrentPosition }; }; NavigatorGeolocation.$inject = ['$q']; angular.module('ngMap'). service('NavigatorGeolocation', NavigatorGeolocation); })(); /** * @ngdoc factory * @name NgMapPool * @description * Provide map instance to avoid memory leak */ (function() { 'use strict'; /** * @memberof NgMapPool * @desc map instance pool */ var mapInstances = []; var $window, $document, $timeout; var add = function(el) { var mapDiv = $document.createElement("div"); mapDiv.style.width = "100%"; mapDiv.style.height = "100%"; el.appendChild(mapDiv); var map = new $window.google.maps.Map(mapDiv, {}); mapInstances.push(map); return map; }; var findById = function(el, id) { var notInUseMap; for (var i=0; i<mapInstances.length; i++) { var map = mapInstances[i]; if (map.id == id && !map.inUse) { var mapDiv = map.getDiv(); el.appendChild(mapDiv); notInUseMap = map; break; } } return notInUseMap; }; var findUnused = function(el) { //jshint ignore:line var notInUseMap; for (var i=0; i<mapInstances.length; i++) { var map = mapInstances[i]; if (map.id) { continue; } if (!map.inUse) { var mapDiv = map.getDiv(); el.appendChild(mapDiv); notInUseMap = map; break; } } return notInUseMap; }; /** * @memberof NgMapPool * @function getMapInstance * @param {HtmlElement} el map container element * @return map instance for the given element */ var getMapInstance = function(el) { var map = findById(el, el.id) || findUnused(el); if (!map) { map = add(el); } else { /* firing map idle event, which is used by map controller */ $timeout(function() { google.maps.event.trigger(map, 'idle'); }, 100); } map.inUse = true; return map; }; /** * @memberof NgMapPool * @function returnMapInstance * @param {Map} an instance of google.maps.Map * @desc sets the flag inUse of the given map instance to false, so that it * can be reused later */ var returnMapInstance = function(map) { map.inUse = false; }; /** * @memberof NgMapPool * @function resetMapInstances * @desc resets mapInstance array */ var resetMapInstances = function() { for(var i = 0;i < mapInstances.length;i++) { mapInstances[i] = null; } mapInstances = []; }; /** * @memberof NgMapPool * @function deleteMapInstance * @desc delete a mapInstance */ var deleteMapInstance= function(mapId) { for( var i=0; i<mapInstances.length; i++ ) { if( (mapInstances[i] !== null) && (mapInstances[i].id == mapId)) { mapInstances[i]= null; mapInstances.splice( i, 1 ); } } }; var NgMapPool = function(_$document_, _$window_, _$timeout_) { $document = _$document_[0], $window = _$window_, $timeout = _$timeout_; return { mapInstances: mapInstances, resetMapInstances: resetMapInstances, getMapInstance: getMapInstance, returnMapInstance: returnMapInstance, deleteMapInstance: deleteMapInstance }; }; NgMapPool.$inject = [ '$document', '$window', '$timeout']; angular.module('ngMap').factory('NgMapPool', NgMapPool); })(); /** * @ngdoc provider * @name NgMap * @description * common utility service for ng-map */ (function() { 'use strict'; var $window, $document, $q; var NavigatorGeolocation, Attr2MapOptions, GeoCoder, camelCaseFilter, NgMapPool; var mapControllers = {}; var getStyle = function(el, styleProp) { var y; if (el.currentStyle) { y = el.currentStyle[styleProp]; } else if ($window.getComputedStyle) { y = $document.defaultView. getComputedStyle(el, null). getPropertyValue(styleProp); } return y; }; /** * @memberof NgMap * @function initMap * @param id optional, id of the map. default 0 */ var initMap = function(id) { var ctrl = mapControllers[id || 0]; if (!(ctrl.map instanceof google.maps.Map)) { ctrl.initializeMap(); return ctrl.map; } else { void 0; } }; /** * @memberof NgMap * @function getMap * @param {String} optional, id e.g., 'foo' * @returns promise */ var getMap = function(id, options) { options = options || {}; id = typeof id === 'object' ? id.id : id; var deferred = $q.defer(); var timeout = options.timeout || 10000; function waitForMap(timeElapsed){ var keys = Object.keys(mapControllers); var theFirstController = mapControllers[keys[0]]; if(id && mapControllers[id]){ deferred.resolve(mapControllers[id].map); } else if (!id && theFirstController && theFirstController.map) { deferred.resolve(theFirstController.map); } else if (timeElapsed > timeout) { deferred.reject('could not find map'); } else { $window.setTimeout( function(){ waitForMap(timeElapsed+100); }, 100); } } waitForMap(0); return deferred.promise; }; /** * @memberof NgMap * @function addMap * @param mapController {__MapContoller} a map controller * @returns promise */ var addMap = function(mapCtrl) { if (mapCtrl.map) { var len = Object.keys(mapControllers).length; mapControllers[mapCtrl.map.id || len] = mapCtrl; } }; /** * @memberof NgMap * @function deleteMap * @param mapController {__MapContoller} a map controller */ var deleteMap = function(mapCtrl) { var len = Object.keys(mapControllers).length - 1; var mapId = mapCtrl.map.id || len; if (mapCtrl.map) { for (var eventName in mapCtrl.eventListeners) { void 0; var listener = mapCtrl.eventListeners[eventName]; google.maps.event.removeListener(listener); } if (mapCtrl.map.controls) { mapCtrl.map.controls.forEach(function(ctrl) { ctrl.clear(); }); } } //Remove Heatmap Layers if (mapCtrl.map.heatmapLayers) { Object.keys(mapCtrl.map.heatmapLayers).forEach(function (layer) { mapCtrl.deleteObject('heatmapLayers', mapCtrl.map.heatmapLayers[layer]); }); } NgMapPool.deleteMapInstance(mapId); delete mapControllers[mapId]; }; /** * @memberof NgMap * @function getGeoLocation * @param {String} address * @param {Hash} options geo options * @returns promise */ var getGeoLocation = function(string, options) { var deferred = $q.defer(); if (!string || string.match(/^current/i)) { // current location NavigatorGeolocation.getCurrentPosition(options).then( function(position) { var lat = position.coords.latitude; var lng = position.coords.longitude; var latLng = new google.maps.LatLng(lat,lng); deferred.resolve(latLng); }, function(error) { deferred.reject(error); } ); } else { GeoCoder.geocode({address: string}).then( function(results) { deferred.resolve(results[0].geometry.location); }, function(error) { deferred.reject(error); } ); // var geocoder = new google.maps.Geocoder(); // geocoder.geocode(options, function (results, status) { // if (status == google.maps.GeocoderStatus.OK) { // deferred.resolve(results); // } else { // deferred.reject(status); // } // }); } return deferred.promise; }; /** * @memberof NgMap * @function observeAndSet * @param {String} attrName attribute name * @param {Object} object A Google maps object to be changed * @returns attribue observe function */ var observeAndSet = function(attrName, object) { void 0; return function(val) { if (val) { var setMethod = camelCaseFilter('set-'+attrName); var optionValue = Attr2MapOptions.toOptionValue(val, {key: attrName}); if (object[setMethod]) { //if set method does exist void 0; /* if an location is being observed */ if (attrName.match(/center|position/) && typeof optionValue == 'string') { getGeoLocation(optionValue).then(function(latlng) { object[setMethod](latlng); }); } else { object[setMethod](optionValue); } } } }; }; /** * @memberof NgMap * @function setStyle * @param {HtmlElement} map contriner element * @desc set display, width, height of map container element */ var setStyle = function(el) { //if style is not given to the map element, set display and height var defaultStyle = el.getAttribute('default-style'); if (defaultStyle == "true") { el.style.display = 'block'; el.style.height = '300px'; } else { if (getStyle(el, 'display') != "block") { el.style.display = 'block'; } if (getStyle(el, 'height').match(/^(0|auto)/)) { el.style.height = '300px'; } } }; angular.module('ngMap').provider('NgMap', function() { var defaultOptions = {}; /** * @memberof NgMap * @function setDefaultOptions * @param {Hash} options * @example * app.config(function(NgMapProvider) { * NgMapProvider.setDefaultOptions({ * marker: { * optimized: false * } * }); * }); */ this.setDefaultOptions = function(options) { defaultOptions = options; }; var NgMap = function( _$window_, _$document_, _$q_, _NavigatorGeolocation_, _Attr2MapOptions_, _GeoCoder_, _camelCaseFilter_, _NgMapPool_ ) { $window = _$window_; $document = _$document_[0]; $q = _$q_; NavigatorGeolocation = _NavigatorGeolocation_; Attr2MapOptions = _Attr2MapOptions_; GeoCoder = _GeoCoder_; camelCaseFilter = _camelCaseFilter_; NgMapPool = _NgMapPool_; return { defaultOptions: defaultOptions, addMap: addMap, deleteMap: deleteMap, getMap: getMap, initMap: initMap, setStyle: setStyle, getGeoLocation: getGeoLocation, observeAndSet: observeAndSet }; }; NgMap.$inject = [ '$window', '$document', '$q', 'NavigatorGeolocation', 'Attr2MapOptions', 'GeoCoder', 'camelCaseFilter', 'NgMapPool' ]; this.$get = NgMap; }); })(); /** * @ngdoc service * @name StreetView * @description * Provides [defered/promise API](https://docs.angularjs.org/api/ng/service/$q) * service for [Google StreetViewService] * (https://developers.google.com/maps/documentation/javascript/streetview) */ (function() { 'use strict'; var $q; /** * Retrieves panorama id from the given map (and or position) * @memberof StreetView * @param {map} map Google map instance * @param {LatLng} latlng Google LatLng instance * default: the center of the map * @example * StreetView.getPanorama(map).then(function(panoId) { * $scope.panoId = panoId; * }); * @returns {HttpPromise} Future object */ var getPanorama = function(map, latlng) { latlng = latlng || map.getCenter(); var deferred = $q.defer(); var svs = new google.maps.StreetViewService(); svs.getPanoramaByLocation( (latlng||map.getCenter), 100, function (data, status) { // if streetView available if (status === google.maps.StreetViewStatus.OK) { deferred.resolve(data.location.pano); } else { // no street view available in this range, or some error occurred deferred.resolve(false); //deferred.reject('Geocoder failed due to: '+ status); } } ); return deferred.promise; }; /** * Set panorama view on the given map with the panorama id * @memberof StreetView * @param {map} map Google map instance * @param {String} panoId Panorama id fro getPanorama method * @example * StreetView.setPanorama(map, panoId); */ var setPanorama = function(map, panoId) { var svp = new google.maps.StreetViewPanorama( map.getDiv(), {enableCloseButton: true} ); svp.setPano(panoId); }; var StreetView = function(_$q_) { $q = _$q_; return { getPanorama: getPanorama, setPanorama: setPanorama }; }; StreetView.$inject = ['$q']; angular.module('ngMap').service('StreetView', StreetView); })(); return 'ngMap'; }));
module.exports = { site: { title: 'i18n node example', description: 'An example for this module on node' }, bankBalance: 'Hi {1}, your balance is {2}.', transports: { yacht: 'Yacht', bike: 'Bike' }, modeOfTransport: 'Your preferred mode of transport is by {1}.' };
var fs = require('co-fs') , test = require('bandage') , main = require('..') , parse = main.parse , write = main.write , parseFmtpConfig = main.parseFmtpConfig , parseParams = main.parseParams , parseImageAttributes = main.parseImageAttributes , parseSimulcastStreamList = main.parseSimulcastStreamList ; test('normalSdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/normal.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); t.equal(session.origin.username, '-', 'origin username'); t.equal(session.origin.sessionId, 20518, 'origin sessionId'); t.equal(session.origin.sessionVersion, 0, 'origin sessionVersion'); t.equal(session.origin.netType, 'IN', 'origin netType'); t.equal(session.origin.ipVer, 4, 'origin ipVer'); t.equal(session.origin.address, '203.0.113.1', 'origin address'); t.equal(session.connection.ip, '203.0.113.1', 'session connect ip'); t.equal(session.connection.version, 4, 'session connect ip ver'); // global ICE and fingerprint t.equal(session.iceUfrag, 'F7gI', 'global ufrag'); t.equal(session.icePwd, 'x9cml/YzichV2+XlhiMu8g', 'global pwd'); var audio = media[0]; t.equal(audio.type, 'audio', 'audio type'); t.equal(audio.port, 54400, 'audio port'); t.equal(audio.protocol, 'RTP/SAVPF', 'audio protocol'); t.equal(audio.direction, 'sendrecv', 'audio direction'); t.equal(audio.rtp[0].payload, 0, 'audio rtp 0 payload'); t.equal(audio.rtp[0].codec, 'PCMU', 'audio rtp 0 codec'); t.equal(audio.rtp[0].rate, 8000, 'audio rtp 0 rate'); t.equal(audio.rtp[1].payload, 96, 'audio rtp 1 payload'); t.equal(audio.rtp[1].codec, 'opus', 'audio rtp 1 codec'); t.equal(audio.rtp[1].rate, 48000, 'audio rtp 1 rate'); t.deepEqual(audio.ext[0], { value: 1, uri: 'URI-toffset' }, 'audio extension 0'); t.deepEqual(audio.ext[1], { value: 2, direction: 'recvonly', uri: 'URI-gps-string' }, 'audio extension 1'); t.equal(audio.extmapAllowMixed, 'extmap-allow-mixed', 'extmap-allow-mixed present'); var video = media[1]; t.equal(video.type, 'video', 'video type'); t.equal(video.port, 55400, 'video port'); t.equal(video.protocol, 'RTP/SAVPF', 'video protocol'); t.equal(video.direction, 'sendrecv', 'video direction'); t.equal(video.rtp[0].payload, 97, 'video rtp 0 payload'); t.equal(video.rtp[0].codec, 'H264', 'video rtp 0 codec'); t.equal(video.rtp[0].rate, 90000, 'video rtp 0 rate'); t.equal(video.fmtp[0].payload, 97, 'video fmtp 0 payload'); var vidFmtp = parseFmtpConfig(video.fmtp[0].config); t.equal(vidFmtp['profile-level-id'], '4d0028', 'video fmtp 0 profile-level-id'); t.equal(vidFmtp['packetization-mode'], 1, 'video fmtp 0 packetization-mode'); t.equal(vidFmtp['sprop-parameter-sets'], 'Z0IAH5WoFAFuQA==,aM48gA==', 'video fmtp 0 sprop-parameter-sets'); t.equal(video.fmtp[1].payload, 98, 'video fmtp 1 payload'); var vidFmtp2 = parseFmtpConfig(video.fmtp[1].config); t.equal(vidFmtp2.minptime, 10, 'video fmtp 1 minptime'); t.equal(vidFmtp2.useinbandfec, 1, 'video fmtp 1 useinbandfec'); t.equal(video.rtp[1].payload, 98, 'video rtp 1 payload'); t.equal(video.rtp[1].codec, 'VP8', 'video rtp 1 codec'); t.equal(video.rtp[1].rate, 90000, 'video rtp 1 rate'); t.equal(video.rtcpFb[0].payload, '*', 'video rtcp-fb 0 payload'); t.equal(video.rtcpFb[0].type, 'nack', 'video rtcp-fb 0 type'); t.equal(video.rtcpFb[1].payload, 98, 'video rtcp-fb 0 payload'); t.equal(video.rtcpFb[1].type, 'nack', 'video rtcp-fb 0 type'); t.equal(video.rtcpFb[1].subtype, 'rpsi', 'video rtcp-fb 0 subtype'); t.equal(video.rtcpFbTrrInt[0].payload, 98, 'video rtcp-fb trr-int 0 payload'); t.equal(video.rtcpFbTrrInt[0].value, 100, 'video rtcp-fb trr-int 0 value'); t.equal(video.crypto[0].id, 1, 'video crypto 0 id'); t.equal(video.crypto[0].suite, 'AES_CM_128_HMAC_SHA1_32', 'video crypto 0 suite'); t.equal(video.crypto[0].config, 'inline:keNcG3HezSNID7LmfDa9J4lfdUL8W1F7TNJKcbuy|2^20|1:32', 'video crypto 0 config'); t.equal(video.ssrcs.length, 3, 'video got 3 ssrc lines'); // test ssrc with attr:value t.deepEqual(video.ssrcs[0], { id: 1399694169, attribute: 'foo', value: 'bar' }, 'video 1st ssrc line attr:value'); // test ssrc with attr only t.deepEqual(video.ssrcs[1], { id: 1399694169, attribute: 'baz', }, 'video 2nd ssrc line attr only'); // test ssrc with at-tr:value t.deepEqual(video.ssrcs[2], { id: 1399694169, attribute: 'foo-bar', value: 'baz' }, 'video 3rd ssrc line attr with dash'); // ICE candidates (same for both audio and video in this case) [audio.candidates, video.candidates].forEach(function (cs, i) { var str = (i === 0) ? 'audio ' : 'video '; var port = (i === 0) ? 54400 : 55400; t.equal(cs.length, 4, str + 'got 4 candidates'); t.equal(cs[0].foundation, 0, str + 'ice candidate 0 foundation'); t.equal(cs[0].component, 1, str + 'ice candidate 0 component'); t.equal(cs[0].transport, 'UDP', str + 'ice candidate 0 transport'); t.equal(cs[0].priority, 2113667327, str + 'ice candidate 0 priority'); t.equal(cs[0].ip, '203.0.113.1', str + 'ice candidate 0 ip'); t.equal(cs[0].port, port, str + 'ice candidate 0 port'); t.equal(cs[0].type, 'host', str + 'ice candidate 0 type'); t.equal(cs[1].foundation, 1, str + 'ice candidate 1 foundation'); t.equal(cs[1].component, 2, str + 'ice candidate 1 component'); t.equal(cs[1].transport, 'UDP', str + 'ice candidate 1 transport'); t.equal(cs[1].priority, 2113667326, str + 'ice candidate 1 priority'); t.equal(cs[1].ip, '203.0.113.1', str + 'ice candidate 1 ip'); t.equal(cs[1].port, port+1, str + 'ice candidate 1 port'); t.equal(cs[1].type, 'host', str + 'ice candidate 1 type'); t.equal(cs[2].foundation, 2, str + 'ice candidate 2 foundation'); t.equal(cs[2].component, 1, str + 'ice candidate 2 component'); t.equal(cs[2].transport, 'UDP', str + 'ice candidate 2 transport'); t.equal(cs[2].priority, 1686052607, str + 'ice candidate 2 priority'); t.equal(cs[2].ip, '203.0.113.1', str + 'ice candidate 2 ip'); t.equal(cs[2].port, port+2, str + 'ice candidate 2 port'); t.equal(cs[2].type, 'srflx', str + 'ice candidate 2 type'); t.equal(cs[2].raddr, '192.168.1.145', str + 'ice candidate 2 raddr'); t.equal(cs[2].rport, port+2, str + 'ice candidate 2 rport'); t.equal(cs[2].generation, 0, str + 'ice candidate 2 generation'); t.equal(cs[2]['network-id'], 3, str + 'ice candidate 2 network-id'); t.equal(cs[2]['network-cost'], (i === 0 ? 10 : undefined), str + 'ice candidate 2 network-cost'); t.equal(cs[3].foundation, 3, str + 'ice candidate 3 foundation'); t.equal(cs[3].component, 2, str + 'ice candidate 3 component'); t.equal(cs[3].transport, 'UDP', str + 'ice candidate 3 transport'); t.equal(cs[3].priority, 1686052606, str + 'ice candidate 3 priority'); t.equal(cs[3].ip, '203.0.113.1', str + 'ice candidate 3 ip'); t.equal(cs[3].port, port+3, str + 'ice candidate 3 port'); t.equal(cs[3].type, 'srflx', str + 'ice candidate 3 type'); t.equal(cs[3].raddr, '192.168.1.145', str + 'ice candidate 3 raddr'); t.equal(cs[3].rport, port+3, str + 'ice candidate 3 rport'); t.equal(cs[3].generation, 0, str + 'ice candidate 3 generation'); t.equal(cs[3]['network-id'], 3, str + 'ice candidate 3 network-id'); t.equal(cs[3]['network-cost'], (i === 0 ? 10 : undefined), str + 'ice candidate 3 network-cost'); }); t.equal(media.length, 2, 'got 2 m-lines'); }); /* * Test for an sdp that started out as something from chrome * it's since been hacked to include tests for other stuff * ignore the name */ test('hackySdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/hacky.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); t.equal(session.origin.sessionId, '3710604898417546434', 'origin sessionId'); t.ok(session.groups, 'parsing session groups'); t.equal(session.groups.length, 1, 'one grouping'); t.equal(session.groups[0].type, 'BUNDLE', 'grouping is BUNDLE'); t.equal(session.groups[0].mids, 'audio video', 'bundling audio video'); t.ok(session.msidSemantic, 'have an msid semantic'); t.equal(session.msidSemantic.semantic, 'WMS', 'webrtc semantic'); t.equal(session.msidSemantic.token, 'Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV', 'semantic token'); // verify a=rtcp:65179 IN IP4 193.84.77.194 t.equal(media[0].rtcp.port, 1, 'rtcp port'); t.equal(media[0].rtcp.netType, 'IN', 'rtcp netType'); t.equal(media[0].rtcp.ipVer, 4, 'rtcp ipVer'); t.equal(media[0].rtcp.address, '0.0.0.0', 'rtcp address'); // verify ice tcp types t.equal(media[0].candidates[0].tcptype, undefined, 'no tcptype'); t.equal(media[0].candidates[1].tcptype, 'active', 'active tcptype'); t.equal(media[0].candidates[1].transport, 'tcp', 'tcp transport'); t.equal(media[0].candidates[1].generation, 0, 'generation 0'); t.equal(media[0].candidates[1].type, 'host', 'tcp host'); t.equal(media[0].candidates[2].generation, undefined, 'no generation'); t.equal(media[0].candidates[2].type, 'host', 'tcp host'); t.equal(media[0].candidates[2].tcptype, 'active', 'active tcptype'); t.equal(media[0].candidates[3].tcptype, 'passive', 'passive tcptype'); t.equal(media[0].candidates[4].tcptype, 'so', 'so tcptype'); // raddr + rport + tcptype + generation t.equal(media[0].candidates[5].type, 'srflx', 'tcp srflx'); t.equal(media[0].candidates[5].rport, 9, 'tcp rport'); t.equal(media[0].candidates[5].raddr, '10.0.1.1', 'tcp raddr'); t.equal(media[0].candidates[5].tcptype, 'active', 'active tcptype'); t.equal(media[0].candidates[6].tcptype, 'passive', 'passive tcptype'); t.equal(media[0].candidates[6].rport, 8998, 'tcp rport'); t.equal(media[0].candidates[6].raddr, '10.0.1.1', 'tcp raddr'); t.equal(media[0].candidates[6].generation, 5, 'tcp generation'); // and verify it works without specifying the ip t.equal(media[1].rtcp.port, 12312, 'rtcp port'); t.equal(media[1].rtcp.netType, undefined, 'rtcp netType'); t.equal(media[1].rtcp.ipVer, undefined, 'rtcp ipVer'); t.equal(media[1].rtcp.address, undefined, 'rtcp address'); // verify a=rtpmap:126 telephone-event/8000 var lastRtp = media[0].rtp.length-1; t.equal(media[0].rtp[lastRtp].codec, 'telephone-event', 'dtmf codec'); t.equal(media[0].rtp[lastRtp].rate, 8000, 'dtmf rate'); t.equal(media[0].iceOptions, 'google-ice', 'ice options parsed'); t.equal(media[0].ptime, 0.125, 'audio packet duration'); t.equal(media[0].maxptime, 60, 'maxptime parsed'); t.equal(media[0].rtcpMux, 'rtcp-mux', 'rtcp-mux present'); t.equal(media[0].rtp[0].codec, 'opus', 'audio rtp 0 codec'); t.equal(media[0].rtp[0].encoding, 2, 'audio rtp 0 encoding'); t.ok(media[0].ssrcs, 'have ssrc lines'); t.equal(media[0].ssrcs.length, 4, 'got 4 ssrc lines'); var ssrcs = media[0].ssrcs; t.deepEqual(ssrcs[0], { id: 2754920552, attribute: 'cname', value: 't9YU8M1UxTF8Y1A1' }, '1st ssrc line'); t.deepEqual(ssrcs[1], { id: 2754920552, attribute: 'msid', value: 'Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlVa0' }, '2nd ssrc line'); t.deepEqual(ssrcs[2], { id: 2754920552, attribute: 'mslabel', value: 'Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV' }, '3rd ssrc line'); t.deepEqual(ssrcs[3], { id: 2754920552, attribute: 'label', value: 'Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlVa0' }, '4th ssrc line'); // verify a=sctpmap:5000 webrtc-datachannel 1024 t.ok(media[2].sctpmap, 'we have sctpmap'); t.equal(media[2].sctpmap.sctpmapNumber, 5000, 'sctpmap number is 5000'); t.equal(media[2].sctpmap.app, 'webrtc-datachannel', 'sctpmap app is webrtc-datachannel'); t.equal(media[2].sctpmap.maxMessageSize, 1024, 'sctpmap maxMessageSize is 1024'); // verify a=framerate:29.97 t.ok(media[2].framerate, 'we have framerate'); t.equal(media[2].framerate, 29.97, 'framerate is 29.97'); // verify a=label:1 t.ok(media[0].label, 'we have label'); t.equal(media[0].label, 1, 'label is 1'); }); test('iceliteSdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/icelite.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); t.equal(session.icelite, 'ice-lite', 'icelite parsed'); var rew = write(session); t.ok(rew.indexOf('a=ice-lite\r\n') >= 0, 'got ice-lite'); t.ok(rew.indexOf('m=') > rew.indexOf('a=ice-lite'), 'session level icelite'); }); test('invalidSdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/invalid.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); // verify a=rtcp:65179 IN IP4 193.84.77.194 t.equal(media[0].rtcp.port, 1, 'rtcp port'); t.equal(media[0].rtcp.netType, 'IN', 'rtcp netType'); t.equal(media[0].rtcp.ipVer, 7, 'rtcp ipVer'); t.equal(media[0].rtcp.address, 'X', 'rtcp address'); t.equal(media[0].invalid.length, 1, 'found exactly 1 invalid line'); // f= lost t.equal(media[0].invalid[0].value, 'goo:hithere', 'copied verbatim'); }); test('jssipSdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/jssip.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); var audio = media[0]; var audCands = audio.candidates; t.equal(audCands.length, 6, '6 candidates'); // testing ice optionals: t.deepEqual(audCands[0], { foundation: 1162875081, component: 1, transport: 'udp', priority: 2113937151, ip: '192.168.34.75', port: 60017, type: 'host', generation: 0, }, 'audio candidate 0' ); t.deepEqual(audCands[2], { foundation: 3289912957, component: 1, transport: 'udp', priority: 1845501695, ip: '193.84.77.194', port: 60017, type: 'srflx', raddr: '192.168.34.75', rport: 60017, generation: 0, }, 'audio candidate 2 (raddr rport)' ); t.deepEqual(audCands[4], { foundation: 198437945, component: 1, transport: 'tcp', priority: 1509957375, ip: '192.168.34.75', port: 0, type: 'host', generation: 0 }, 'audio candidate 4 (tcp)' ); }); test('jsepSdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/jsep.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length === 2, 'got media'); var video = media[1]; t.equal(video.ssrcGroups.length, 1, '1 ssrc grouping'); t.deepEqual(video.ssrcGroups[0], { semantics: 'FID', ssrcs: '1366781083 1366781084' }, 'ssrc-group' ); t.equal(video.msid, '61317484-2ed4-49d7-9eb7-1414322a7aae f30bdb4a-5db8-49b5-bcdc-e0c9a23172e0' , 'msid' ); t.ok(video.rtcpRsize, 'rtcp-rsize present'); t.ok(video.bundleOnly, 'bundle-only present'); // video contains 'a=end-of-candidates' // we want to ensure this comes after the candidate lines // so this is the only place we actually test the writer in here t.ok(video.endOfCandidates, 'have end of candidates marker'); var rewritten = write(session).split('\r\n'); var idx = rewritten.indexOf('a=end-of-candidates'); t.equal(rewritten[idx-1].slice(0, 11), 'a=candidate', 'marker after candidate'); }); test('alacSdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/alac.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); var audio = media[0]; t.equal(audio.type, 'audio', 'audio type'); t.equal(audio.protocol, 'RTP/AVP', 'audio protocol'); t.equal(audio.fmtp[0].payload, 96, 'audio fmtp 0 payload'); t.equal(audio.fmtp[0].config, '352 0 16 40 10 14 2 255 0 0 44100', 'audio fmtp 0 config'); t.equal(audio.rtp[0].payload, 96, 'audio rtp 0 payload'); t.equal(audio.rtp[0].codec, 'AppleLossless', 'audio rtp 0 codec'); t.equal(audio.rtp[0].rate, undefined, 'audio rtp 0 rate'); t.equal(audio.rtp[0].encoding, undefined, 'audio rtp 0 encoding'); }); test('onvifSdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/onvif.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); var audio = media[0]; t.equal(audio.type, 'audio', 'audio type'); t.equal(audio.port, 0, 'audio port'); t.equal(audio.protocol, 'RTP/AVP', 'audio protocol'); t.equal(audio.control, 'rtsp://example.com/onvif_camera/audio', 'audio control'); t.equal(audio.payloads, 0, 'audio payloads'); var video = media[1]; t.equal(video.type, 'video', 'video type'); t.equal(video.port, 0, 'video port'); t.equal(video.protocol, 'RTP/AVP', 'video protocol'); t.equal(video.control, 'rtsp://example.com/onvif_camera/video', 'video control'); t.equal(video.payloads, 26, 'video payloads'); var application = media[2]; t.equal(application.type, 'application', 'application type'); t.equal(application.port, 0, 'application port'); t.equal(application.protocol, 'RTP/AVP', 'application protocol'); t.equal(application.control, 'rtsp://example.com/onvif_camera/metadata', 'application control'); t.equal(application.payloads, 107, 'application payloads'); t.equal(application.direction, 'recvonly', 'application direction'); t.equal(application.rtp[0].payload, 107, 'application rtp 0 payload'); t.equal(application.rtp[0].codec, 'vnd.onvif.metadata', 'application rtp 0 codec'); t.equal(application.rtp[0].rate, 90000, 'application rtp 0 rate'); t.equal(application.rtp[0].encoding, undefined, 'application rtp 0 encoding'); }); test('ssrcSdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/ssrc.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); var video = media[1]; t.equal(video.ssrcGroups.length, 2, 'video got 2 ssrc-group lines'); var expectedSsrc = [ { semantics: 'FID', ssrcs: '3004364195 1126032854' }, { semantics: 'FEC-FR', ssrcs: '3004364195 1080772241' } ]; t.deepEqual(video.ssrcGroups, expectedSsrc, 'video ssrc-group obj'); }); test('simulcastSdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/simulcast.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); var video = media[1]; t.equal(video.type, 'video', 'video type'); // test rid lines t.equal(video.rids.length, 5, 'video got 5 rid lines'); // test rid 1 t.deepEqual(video.rids[0], { id: 1, direction: 'send', params: 'pt=97;max-width=1280;max-height=720;max-fps=30' }, 'video 1st rid line'); // test rid 2 t.deepEqual(video.rids[1], { id: 2, direction: 'send', params: 'pt=98' }, 'video 2nd rid line'); // test rid 3 t.deepEqual(video.rids[2], { id: 3, direction: 'send', params: 'pt=99' }, 'video 3rd rid line'); // test rid 4 t.deepEqual(video.rids[3], { id: 4, direction: 'send', params: 'pt=100' }, 'video 4th rid line'); // test rid 5 t.deepEqual(video.rids[4], { id: 'c', direction: 'recv', params: 'pt=97' }, 'video 5th rid line'); // test rid 1 params var rid1Params = parseParams(video.rids[0].params); t.deepEqual(rid1Params, { 'pt': 97, 'max-width': 1280, 'max-height': 720, 'max-fps': 30 }, 'video 1st rid params'); // test rid 2 params var rid2Params = parseParams(video.rids[1].params); t.deepEqual(rid2Params, { 'pt': 98 }, 'video 2nd rid params'); // test rid 3 params var rid3Params = parseParams(video.rids[2].params); t.deepEqual(rid3Params, { 'pt': 99 }, 'video 3rd rid params'); // test rid 4 params var rid4Params = parseParams(video.rids[3].params); t.deepEqual(rid4Params, { 'pt': 100 }, 'video 4th rid params'); // test rid 5 params var rid5Params = parseParams(video.rids[4].params); t.deepEqual(rid5Params, { 'pt': 97 }, 'video 5th rid params'); // test imageattr lines t.equal(video.imageattrs.length, 5, 'video got 5 imageattr lines'); // test imageattr 1 t.deepEqual(video.imageattrs[0], { pt: 97, dir1: 'send', attrs1: '[x=1280,y=720]', dir2: 'recv', attrs2: '[x=1280,y=720] [x=320,y=180] [x=160,y=90]' }, 'video 1st imageattr line'); // test imageattr 2 t.deepEqual(video.imageattrs[1], { pt: 98, dir1: 'send', attrs1: '[x=320,y=180]' }, 'video 2nd imageattr line'); // test imageattr 3 t.deepEqual(video.imageattrs[2], { pt: 99, dir1: 'send', attrs1: '[x=160,y=90]' }, 'video 3rd imageattr line'); // test imageattr 4 t.deepEqual(video.imageattrs[3], { pt: 100, dir1: 'recv', attrs1: '[x=1280,y=720] [x=320,y=180]', dir2: 'send', attrs2: '[x=1280,y=720]' }, 'video 4th imageattr line'); // test imageattr 5 t.deepEqual(video.imageattrs[4], { pt: '*', dir1: 'recv', attrs1: '*' }, 'video 5th imageattr line'); // test imageattr 1 send params var imageattr1SendParams = parseImageAttributes(video.imageattrs[0].attrs1); t.deepEqual(imageattr1SendParams, [ {'x': 1280, 'y': 720} ], 'video 1st imageattr send params'); // test imageattr 1 recv params var imageattr1RecvParams = parseImageAttributes(video.imageattrs[0].attrs2); t.deepEqual(imageattr1RecvParams, [ {'x': 1280, 'y': 720}, {'x': 320, 'y': 180}, {'x': 160, 'y': 90}, ], 'video 1st imageattr recv params'); // test imageattr 2 send params var imageattr2SendParams = parseImageAttributes(video.imageattrs[1].attrs1); t.deepEqual(imageattr2SendParams, [ {'x': 320, 'y': 180} ], 'video 2nd imageattr send params'); // test imageattr 3 send params var imageattr3SendParams = parseImageAttributes(video.imageattrs[2].attrs1); t.deepEqual(imageattr3SendParams, [ {'x': 160, 'y': 90} ], 'video 3rd imageattr send params'); // test imageattr 4 recv params var imageattr4RecvParams = parseImageAttributes(video.imageattrs[3].attrs1); t.deepEqual(imageattr4RecvParams, [ {'x': 1280, 'y': 720}, {'x': 320, 'y': 180}, ], 'video 4th imageattr recv params'); // test imageattr 4 send params var imageattr4SendParams = parseImageAttributes(video.imageattrs[3].attrs2); t.deepEqual(imageattr4SendParams, [ {'x': 1280, 'y': 720} ], 'video 4th imageattr send params'); // test imageattr 5 recv params t.equal(video.imageattrs[4].attrs1, '*', 'video 5th imageattr recv params'); // test simulcast line t.deepEqual(video.simulcast, { dir1: 'send', list1: '1,~4;2;3', dir2: 'recv', list2: 'c' }, 'video simulcast line'); // test simulcast send streams var simulcastSendStreams = parseSimulcastStreamList(video.simulcast.list1); t.deepEqual(simulcastSendStreams, [ [ {scid: 1, paused: false}, {scid: 4, paused: true} ], [ {scid: 2, paused: false} ], [ {scid: 3, paused: false} ] ], 'video simulcast send streams'); // test simulcast recv streams var simulcastRecvStreams = parseSimulcastStreamList(video.simulcast.list2); t.deepEqual(simulcastRecvStreams, [ [ {scid: 'c', paused: false} ] ], 'video simulcast recv streams'); // test simulcast version 03 line // test simulcast line t.deepEqual(video.simulcast_03, { value: 'send rid=1,4;2;3 paused=4 recv rid=c' }, 'video simulcast draft 03 line'); }); test('ST2022-6', function *(t) { var sdp = yield fs.readFile(__dirname + '/st2022-6.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); var video = media[0]; var sourceFilter = video.sourceFilter; t.equal(sourceFilter.filterMode, 'incl', 'filter-mode is "incl"'); t.equal(sourceFilter.netType, 'IN', 'nettype is "IN"'); t.equal(sourceFilter.addressTypes, 'IP4', 'address-type is "IP4"'); t.equal(sourceFilter.destAddress, '239.0.0.1', 'dest-address is "239.0.0.1"'); t.equal(sourceFilter.srcList, '192.168.20.20', 'src-list is "192.168.20.20"'); }); test('ST2110-20', function* (t) { var sdp = yield fs.readFile(__dirname + '/st2110-20.sdp', 'utf8'); var session = parse(sdp + ''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); var video = media[0]; var sourceFilter = video.sourceFilter; t.equal(sourceFilter.filterMode, 'incl', 'filter-mode is "incl"'); t.equal(sourceFilter.netType, 'IN', 'nettype is "IN"'); t.equal(sourceFilter.addressTypes, 'IP4', 'address-type is "IP4"'); t.equal(sourceFilter.destAddress, '239.100.9.10', 'dest-address is "239.100.9.10"'); t.equal(sourceFilter.srcList, '192.168.100.2', 'src-list is "192.168.100.2"'); t.equal(video.type, 'video', 'video type'); var fmtp0Params = parseParams(video.fmtp[0].config); t.deepEqual(fmtp0Params, { sampling: 'YCbCr-4:2:2', width: 1280, height: 720, interlace: undefined, exactframerate: '60000/1001', depth: 10, TCS: 'SDR', colorimetry: 'BT709', PM: '2110GPM', SSN: 'ST2110-20:2017' }, 'video 5th rid params'); }); test('SCTP-DTLS-26', function* (t) { var sdp = yield fs.readFile(__dirname + '/sctp-dtls-26.sdp', 'utf8'); var session = parse(sdp + ''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); t.equal(session.origin.sessionId, '5636137646675714991', 'origin sessionId'); t.ok(session.groups, 'parsing session groups'); t.equal(session.groups.length, 1, 'one grouping'); t.equal(session.groups[0].type, 'BUNDLE', 'grouping is BUNDLE'); t.equal(session.groups[0].mids, 'data', 'bundling data'); t.ok(session.msidSemantic, 'have an msid semantic'); t.equal(session.msidSemantic.semantic, 'WMS', 'webrtc semantic'); // verify media is data application t.equal(media[0].type, 'application', 'media type application'); t.equal(media[0].mid, 'data', 'media id pplication'); // verify protocol and ports t.equal(media[0].protocol, 'UDP/DTLS/SCTP', 'protocol is UDP/DTLS/SCTP'); t.equal(media[0].port, 9, 'the UDP port value is 9'); t.equal(media[0].sctpPort, 5000, 'the offerer/answer SCTP port value is 5000'); // verify maxMessageSize t.equal(media[0].maxMessageSize, 10000, 'maximum message size is 10000'); }); test('extmapEncryptSdp', function *(t) { var sdp = yield fs.readFile(__dirname + '/extmap-encrypt.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length > 0, 'got media'); t.equal(session.origin.username, '-', 'origin username'); t.equal(session.origin.sessionId, 20518, 'origin sessionId'); t.equal(session.origin.sessionVersion, 0, 'origin sessionVersion'); t.equal(session.origin.netType, 'IN', 'origin netType'); t.equal(session.origin.ipVer, 4, 'origin ipVer'); t.equal(session.origin.address, '203.0.113.1', 'origin address'); t.equal(session.connection.ip, '203.0.113.1', 'session connect ip'); t.equal(session.connection.version, 4, 'session connect ip ver'); var audio = media[0]; t.equal(audio.type, 'audio', 'audio type'); t.equal(audio.port, 54400, 'audio port'); t.equal(audio.protocol, 'RTP/SAVPF', 'audio protocol'); t.equal(audio.rtp[0].payload, 96, 'audio rtp 0 payload'); t.equal(audio.rtp[0].codec, 'opus', 'audio rtp 0 codec'); t.equal(audio.rtp[0].rate, 48000, 'audio rtp 0 rate'); // extmap and encrypted extmap t.deepEqual(audio.ext[0], { value: 1, direction: 'sendonly', uri: 'URI-toffset' }, 'audio extension 0'); t.deepEqual(audio.ext[1], { value: 2, uri: 'urn:ietf:params:rtp-hdrext:toffset' }, 'audio extension 1'); t.deepEqual(audio.ext[2], { value: 3, 'encrypt-uri': 'urn:ietf:params:rtp-hdrext:encrypt', uri: 'urn:ietf:params:rtp-hdrext:smpte-tc', config: '25@600/24' }, 'audio extension 2'); t.deepEqual(audio.ext[3], { value: 4, direction: 'recvonly', 'encrypt-uri': 'urn:ietf:params:rtp-hdrext:encrypt', uri: 'URI-gps-string' }, 'audio extension 3'); t.equal(media.length, 1, 'got 1 m-lines'); }); test('dante-aes67', function *(t) { var sdp = yield fs.readFile(__dirname + '/dante-aes67.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length == 1, 'got single media'); t.equal(session.origin.username, '-', 'origin username'); t.equal(session.origin.sessionId, 1423986, 'origin sessionId'); t.equal(session.origin.sessionVersion, 1423994, 'origin sessionVersion'); t.equal(session.origin.netType, 'IN', 'origin netType'); t.equal(session.origin.ipVer, 4, 'origin ipVer'); t.equal(session.origin.address, '169.254.98.63', 'origin address'); t.equal(session.name, 'AOIP44-serial-1614 : 2', 'Session Name'); t.equal(session.keywords, 'Dante', 'Keywords'); t.equal(session.connection.ip, '239.65.125.63/32', 'session connect ip'); t.equal(session.connection.version, 4, 'session connect ip ver'); var audio = media[0]; t.equal(audio.type, 'audio', 'audio type'); t.equal(audio.port, 5004, 'audio port'); t.equal(audio.protocol, 'RTP/AVP', 'audio protocol'); t.equal(audio.direction, 'recvonly', 'audio direction'); t.equal(audio.description, '2 channels: TxChan 0, TxChan 1', 'audio description'); t.equal(audio.ptime, 1, 'audio packet duration'); t.equal(audio.rtp[0].payload, 97, 'audio rtp payload type'); t.equal(audio.rtp[0].codec, 'L24', 'audio rtp codec'); t.equal(audio.rtp[0].rate, 48000, 'audio sample rate'); t.equal(audio.rtp[0].encoding, 2, 'audio channels'); }); test('bfcp', function *(t) { var sdp = yield fs.readFile(__dirname + '/bfcp.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length == 4, 'got 4 media'); t.equal(session.origin.username, '-', 'origin username'); var audio = media[0]; t.equal(audio.type, 'audio', 'audio type'); var video = media[1]; t.equal(video.type, 'video', 'main video type'); t.equal(video.direction, 'sendrecv', 'main video direction'); t.equal(video.content, 'main', 'main video content'); t.equal(video.label, 1, 'main video label'); var app = media[2]; t.equal(app.type, 'application', 'application type'); t.equal(app.port, 3238, 'application port'); t.equal(app.protocol, 'UDP/BFCP', 'bfcp protocol'); t.equal(app.payloads, '*', 'bfcp payloads'); t.equal(app.connectionType, 'new', 'connection type'); t.equal(app.bfcpFloorCtrl, 's-only', 'bfcp Floor Control'); t.equal(app.bfcpConfId, 1, 'bfcp ConfId'); t.equal(app.bfcpUserId, 1, 'bfcp UserId'); t.equal(app.bfcpFloorId.id, 1, 'bfcp FloorId'); t.equal(app.bfcpFloorId.mStream, 3, 'bfcp Floor Stream'); var video2 = media[3]; t.equal(video2.type, 'video', '2nd video type'); t.equal(video2.direction, 'sendrecv', '2nd video direction'); t.equal(video2.content, 'slides', '2nd video content'); t.equal(video2.label, 3, '2nd video label'); }); test('tcp-active', function *(t) { var sdp = yield fs.readFile(__dirname + '/tcp-active.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length == 1, 'got single media'); t.equal(session.origin.username, '-', 'origin username'); t.equal(session.origin.sessionId, 1562876543, 'origin sessionId'); t.equal(session.origin.sessionVersion, 11, 'origin sessionVersion'); t.equal(session.origin.netType, 'IN', 'origin netType'); t.equal(session.origin.ipVer, 4, 'origin ipVer'); t.equal(session.origin.address, '192.0.2.3', 'origin address'); var image = media[0]; t.equal(image.type, 'image', 'image type'); t.equal(image.port, 9, 'port'); t.equal(image.connection.version, 4, 'Connection is IPv4'); t.equal(image.connection.ip, '192.0.2.3', 'Connection address'); t.equal(image.protocol, 'TCP', 'TCP protocol'); t.equal(image.payloads, 't38', 'TCP payload'); t.equal(image.setup, 'active', 'setup active'); t.equal(image.connectionType, 'new', 'new connection'); }); test('tcp-passive', function *(t) { var sdp = yield fs.readFile(__dirname + '/tcp-passive.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length == 1, 'got single media'); t.equal(session.origin.username, '-', 'origin username'); t.equal(session.origin.sessionId, 1562876543, 'origin sessionId'); t.equal(session.origin.sessionVersion, 11, 'origin sessionVersion'); t.equal(session.origin.netType, 'IN', 'origin netType'); t.equal(session.origin.ipVer, 4, 'origin ipVer'); t.equal(session.origin.address, '192.0.2.2', 'origin address'); var image = media[0]; t.equal(image.type, 'image', 'image type'); t.equal(image.port, 54111, 'port'); t.equal(image.connection.version, 4, 'Connection is IPv4'); t.equal(image.connection.ip, '192.0.2.2', 'Connection address'); t.equal(image.protocol, 'TCP', 'TCP protocol'); t.equal(image.payloads, 't38', 'TCP payload'); t.equal(image.setup, 'passive', 'setup passive'); t.equal(image.connectionType, 'existing', 'existing connection'); }); test('mediaclk-avbtp', function *(t) { var sdp = yield fs.readFile(__dirname + '/mediaclk-avbtp.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length == 1, 'got single media'); var audio = media[0]; t.equal(audio.mediaClk.mediaClockName, 'IEEE1722', 'IEEE1722 Media Clock'); t.equal(audio.mediaClk.mediaClockValue, '38-D6-6D-8E-D2-78-13-2F', 'AVB stream ID'); }); test('mediaclk-ptp-v2-w-rate', function *(t) { var sdp = yield fs.readFile(__dirname + '/mediaclk-ptp-v2-w-rate.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length == 1, 'got single media'); var audio = media[0]; t.equal(audio.mediaClk.mediaClockName, 'direct', 'Direct Media Clock'); t.equal(audio.mediaClk.mediaClockValue, 963214424, 'offset'); t.equal(audio.mediaClk.rateNumerator, 1000, 'rate numerator'); t.equal(audio.mediaClk.rateDenominator, 1001, 'rate denominator'); }); test('mediaclk-ptp-v2', function *(t) { var sdp = yield fs.readFile(__dirname + '/mediaclk-ptp-v2.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length == 1, 'got single media'); var audio = media[0]; t.equal(audio.mediaClk.mediaClockName, 'direct', 'Direct Media Clock'); t.equal(audio.mediaClk.mediaClockValue, 963214424, 'offset'); }); test('mediaclk-rtp', function *(t) { var sdp = yield fs.readFile(__dirname + '/mediaclk-rtp.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var media = session.media; t.ok(media && media.length == 1, 'got single media'); var audio = media[0]; t.equal(audio.mediaClk.id, 'MDA6NjA6MmI6MjA6MTI6MWY=', 'Media Clock ID'); t.equal(audio.mediaClk.mediaClockName, 'sender', 'sender type'); }); test('ts-refclk-media', function *(t) { var sdp = yield fs.readFile(__dirname + '/ts-refclk-media.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var sessTsRefClocks = session.tsRefClocks; t.ok(sessTsRefClocks && sessTsRefClocks.length == 1, 'got one TS Ref Clock'); t.equal(sessTsRefClocks[0].clksrc, 'local', 'local Clock Source at Session Level'); var media = session.media; t.ok(media && media.length == 2, 'got two media'); var audio = media[0]; var audTsRefClocks = audio.tsRefClocks; t.ok(audTsRefClocks && audTsRefClocks.length == 2, 'got two audio TS Ref Clocks'); var audTsRefClock1 = audTsRefClocks[0]; t.equal(audTsRefClock1.clksrc, 'ntp', 'NTP Clock Source'); t.equal(audTsRefClock1.clksrcExt, '203.0.113.10', 'IPv4 address'); var audTsRefClock2 = audTsRefClocks[1]; t.equal(audTsRefClock2.clksrc, 'ntp', 'NTP Clock Source'); t.equal(audTsRefClock2.clksrcExt, '198.51.100.22', 'IPv4 address'); var video = media[1]; var vidTsRefClocks = video.tsRefClocks; t.ok(vidTsRefClocks && vidTsRefClocks.length == 1, 'got one video TS Ref Clocks'); t.equal(vidTsRefClocks[0].clksrc, 'ptp', 'PTP Clock Source'); t.equal(vidTsRefClocks[0].clksrcExt, 'IEEE802.1AS-2011:39-A7-94-FF-FE-07-CB-D0', 'PTP config'); }); test('ts-refclk-sess', function *(t) { var sdp = yield fs.readFile(__dirname + '/ts-refclk-sess.sdp', 'utf8'); var session = parse(sdp+''); t.ok(session, 'got session info'); var sessTsRefClocks = session.tsRefClocks; t.ok(sessTsRefClocks && sessTsRefClocks.length == 1, 'got one TS Ref Clock at Session Level'); t.equal(sessTsRefClocks[0].clksrc, 'ntp', 'NTP Clock Source'); t.equal(sessTsRefClocks[0].clksrcExt, '/traceable/', 'traceable Clock Source'); });
// 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"],function(c,g){Object.defineProperty(g,"__esModule",{value:!0});g.SwapTable=[["(",")"],[")","("],["\x3c","\x3e"],["\x3e","\x3c"],["[","]"],["]","["],["{","}"],["}","{"],["\u00ab","\u00bb"],["\u00bb","\u00ab"],["\u2039","\u203a"],["\u203a","\u2039"],["\u207d","\u207e"],["\u207e","\u207d"],["\u208d","\u208e"],["\u208e","\u208d"],["\u2264","\u2265"],["\u2265","\u2264"],["\u2329","\u232a"],["\u232a","\u2329"],["\ufe59","\ufe5a"],["\ufe5a","\ufe59"],["\ufe5b","\ufe5c"],["\ufe5c", "\ufe5b"],["\ufe5d","\ufe5e"],["\ufe5e","\ufe5d"],["\ufe64","\ufe65"],["\ufe65","\ufe64"]];g.AlefTable=["\u0622","\u0623","\u0625","\u0627"];g.LamAlefInialTableFE=["\ufef5","\ufef7","\ufef9","\ufefb"];g.LamAlefMedialTableFE=["\ufef6","\ufef8","\ufefa","\ufefc"];g.BaseForm="\u0627\u0628\u062a\u062b\u062c\u062d\u062e\u062f\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063a\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u064a\u0625\u0623\u0622\u0629\u0649\u0644\u0645\u0646\u0647\u0648\u064a\u0625\u0623\u0622\u0629\u0649\u06cc\u0626\u0624".split(""); g.IsolatedForm="\ufe8d\ufe8f\ufe95\ufe99\ufe9d\ufea1\ufea5\ufea9\ufeab\ufead\ufeaf\ufeb1\ufeb5\ufeb9\ufebd\ufec1\ufec5\ufec9\ufecd\ufed1\ufed5\ufed9\ufedd\ufee1\ufee5\ufee9\ufeed\ufef1\ufe87\ufe83\ufe81\ufe93\ufeef\ufbfc\ufe89\ufe85\ufe70\ufe72\ufe74\ufe76\ufe78\ufe7a\ufe7c\ufe7e\ufe80\ufe89\ufe85".split("");g.FinalForm="\ufe8e\ufe90\ufe96\ufe9a\ufe9e\ufea2\ufea6\ufeaa\ufeac\ufeae\ufeb0\ufeb2\ufeb6\ufeba\ufebe\ufec2\ufec6\ufeca\ufece\ufed2\ufed6\ufeda\ufede\ufee2\ufee6\ufeea\ufeee\ufef2\ufe88\ufe84\ufe82\ufe94\ufef0\ufbfd\ufe8a\ufe86\ufe70\ufe72\ufe74\ufe76\ufe78\ufe7a\ufe7c\ufe7e\ufe80\ufe8a\ufe86".split(""); g.MedialForm="\ufe8e\ufe92\ufe98\ufe9c\ufea0\ufea4\ufea8\ufeaa\ufeac\ufeae\ufeb0\ufeb4\ufeb8\ufebc\ufec0\ufec4\ufec8\ufecc\ufed0\ufed4\ufed8\ufedc\ufee0\ufee4\ufee8\ufeec\ufeee\ufef4\ufe88\ufe84\ufe82\ufe94\ufef0\ufbff\ufe8c\ufe86\ufe71\ufe72\ufe74\ufe77\ufe79\ufe7b\ufe7d\ufe7f\ufe80\ufe8c\ufe86".split("");g.InitialForm="\ufe8d\ufe91\ufe97\ufe9b\ufe9f\ufea3\ufea7\ufea9\ufeab\ufead\ufeaf\ufeb3\ufeb7\ufebb\ufebf\ufec3\ufec7\ufecb\ufecf\ufed3\ufed7\ufedb\ufedf\ufee3\ufee7\ufeeb\ufeed\ufef3\ufe87\ufe83\ufe81\ufe93\ufeef\ufbfe\ufe8b\ufe85\ufe70\ufe72\ufe74\ufe76\ufe78\ufe7a\ufe7c\ufe7e\ufe80\ufe8b\ufe85".split(""); g.StandAlonForm="\u0621\u0622\u0623\u0624\u0625\u0627\u0629\u062f\u0630\u0631\u0632\u0648\u0649".split("");g.FETo06Table="\u064b\u064b\u064c\u061f\u064d\u061f\u064e\u064e\u064f\u064f\u0650\u0650\u0651\u0651\u0652\u0652\u0621\u0622\u0622\u0623\u0623\u0624\u0624\u0625\u0625\u0626\u0626\u0626\u0626\u0627\u0627\u0628\u0628\u0628\u0628\u0629\u0629\u062a\u062a\u062a\u062a\u062b\u062b\u062b\u062b\u062c\u062c\u062c\u062c\u062d\u062d\u062d\u062d\u062e\u062e\u062e\u062e\u062f\u062f\u0630\u0630\u0631\u0631\u0632\u0632\u0633\u0633\u0633\u0633\u0634\u0634\u0634\u0634\u0635\u0635\u0635\u0635\u0636\u0636\u0636\u0636\u0637\u0637\u0637\u0637\u0638\u0638\u0638\u0638\u0639\u0639\u0639\u0639\u063a\u063a\u063a\u063a\u0641\u0641\u0641\u0641\u0642\u0642\u0642\u0642\u0643\u0643\u0643\u0643\u0644\u0644\u0644\u0644\u0645\u0645\u0645\u0645\u0646\u0646\u0646\u0646\u0647\u0647\u0647\u0647\u0648\u0648\u0649\u0649\u064a\u064a\u064a\u064a\ufef5\ufef6\ufef7\ufef8\ufef9\ufefa\ufefb\ufefc\u061f\u061f\u061f".split(""); g.ArabicAlefBetIntervalsBegine=["\u0621","\u0641"];g.ArabicAlefBetIntervalsEnd=["\u063a","\u064a"];g.impTabLtr=[[0,3,0,1,0,0,0],[0,3,0,1,2,2,0],[0,3,0,17,2,0,1],[0,3,5,5,4,1,0],[0,3,21,21,4,0,1],[0,3,5,5,4,2,0]];g.impTabRtl=[[2,0,1,1,0,1,0],[2,0,1,1,0,2,0],[2,0,2,1,3,2,0],[2,0,2,33,3,1,1]];g.UBAT_L=0;g.UBAT_R=1;g.UBAT_EN=2;g.UBAT_AN=3;g.UBAT_ON=4;g.UBAT_B=5;g.UBAT_S=6;g.UBAT_AL=7;g.UBAT_WS=8;g.UBAT_CS=9;g.UBAT_ES=10;g.UBAT_ET=11;g.UBAT_NSM=12;g.UBAT_LRE=13;g.UBAT_RLE=14;g.UBAT_PDF=15;g.UBAT_LRO=16; g.UBAT_RLO=17;g.UBAT_BN=18;g.TYPES_NAMES="UBAT_L UBAT_R UBAT_EN UBAT_AN UBAT_ON UBAT_B UBAT_S UBAT_AL UBAT_WS UBAT_CS UBAT_ES UBAT_ET UBAT_NSM UBAT_LRE UBAT_RLE UBAT_PDF UBAT_LRO UBAT_RLO UBAT_BN".split(" ");g.TBBASE=100;c=g.UBAT_L;var e=g.UBAT_R,k=g.UBAT_EN,l=g.UBAT_AN,a=g.UBAT_ON,q=g.UBAT_B,r=g.UBAT_S,b=g.UBAT_AL,m=g.UBAT_WS,n=g.UBAT_CS,p=g.UBAT_ES,h=g.UBAT_ET,d=g.UBAT_NSM,t=g.UBAT_LRE,u=g.UBAT_RLE,v=g.UBAT_PDF,w=g.UBAT_LRO,x=g.UBAT_RLO,f=g.UBAT_BN;g.MasterTable=[g.TBBASE+0,c,c,c,c,g.TBBASE+1,g.TBBASE+ 2,g.TBBASE+3,e,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,g.TBBASE+4,a,a,a,c,a,c,a,c,a,a,a,c,c,a,a,c,c,c,c,c,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,c,c,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,c,c,a,a,c,c,a,a,c,c,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a, c,c,c,g.TBBASE+5,b,b,g.TBBASE+6,g.TBBASE+7];g.UnicodeTable=[[f,f,f,f,f,f,f,f,f,r,q,r,m,q,f,f,f,f,f,f,f,f,f,f,f,f,f,f,q,q,q,r,m,a,a,h,h,h,a,a,a,a,a,p,n,p,n,n,k,k,k,k,k,k,k,k,k,k,n,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,f,f,f,f,f,f,q,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,n,a,h,h,h,h,a,a,a,a,c,a,a,f,a,a,h,h,k,k,a,c,a,a,a,k,c,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,c,c,c,c, c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,c,c,c,c,c,c,c,c],[c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,c,c,c,c,c,c,c,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,c,a,a,a,a,a,a,a,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,e,d,e,d,d,e,d,d,e,d,a,a,a,a,a,a,a,a,e,e,e,e,e,e, e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,a,a,a,a,a,e,e,e,e,e,a,a,a,a,a,a,a,a,a,a,a],[l,l,l,l,a,a,a,a,b,h,h,b,n,b,a,a,d,d,d,d,d,d,d,d,d,d,d,b,a,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,l,l,l,l,l,l,l,l,l,l,h,l,l,b,b,b,d,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b, b,b,b,b,b,b,d,d,d,d,d,d,d,l,a,d,d,d,d,d,d,b,b,d,d,a,d,d,d,d,b,b,k,k,k,k,k,k,k,k,k,k,b,b,b,b,b,b],[b,b,b,b,b,b,b,b,b,b,b,b,b,b,a,b,b,d,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,a,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,d,d,d,d,d,d,d,d,d,d,d,b,a,a,a,a,a,a,a,a,a,a,a,a,a,a,e,e,e,e,e,e,e,e,e,e, e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,d,d,d,d,d,d,d,d,d,e,e,a,a,a,a,e,a,a,a,a,a],[m,m,m,m,m,m,m,m,m,m,m,f,f,f,c,e,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,m,q,t,u,v,w,x,n,h,h,h,h,h,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,n,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,m,f,f,f,f,f,a,a,a,a,a,f,f,f,f,f,f,k,c,a,a,k,k,k,k,k,k,p,p,a,a,a,c,k,k,k,k,k,k,k,k,k,k,p,p,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,a,a,a,a,a,a,a,a,a,a, a,a,a,a,a,a,a,a,a,a,a,a,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a],[c,c,c,c,c,c,c,a,a,a,a,a,a,a,a,a,a,a,a,c,c,c,c,c,a,a,a,a,a,e,d,e,e,e,e,e,e,e,e,e,e,p,e,e,e,e,e,e,e,e,e,e,e,e,e,a,e,e,e,e,e,a,e,a,e,e,a,e,e,a,e,e,e,e,e,e,e,e,e,e,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b, b,b,b,b,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b],[d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,d,d,d,d,d,d,d,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,n,a,n,a,a,n,a,a,a,a,a,a,a,a,a,h,a,a,p,p,a,a,a,a,a,h,h,a,a,a,a,a,b,b,b,b,b,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b, b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,a,a,f],[a,a,a,h,h,h,a,a,a,a,a,p,n,p,n,n,k,k,k,k,k,k,k,k,k,k,n,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,a,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c, c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,c,c,c,c,c,c,a,a,c,c,c,c,c,c,a,a,c,c,c,c,c,c,a,a,c,c,c,a,a,a,h,h,a,a,a,h,h,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a]]});
var flag = "did_you_use_python's_[::-1]_notation?"; exports.get_data = function(req, callback) { var result = []; var s = [ "[Go, droop aloof] sides reversed, is [fool a poor dog]. I did roar again, Niagara! ... or did I?", "Help Max, Enid -- in example, H. See, slave, I demonstrate yet arts no medieval sees.", "Egad, a base tone denotes a bad age. So may Obadiah, even in Nineveh, aid a boy, Amos. Naomi, did I moan?", "Sir, I soon saw Bob was no Osiris. Poor Dan is in a droop.", "Straw? No, too stupid a fad. I put soot on warts.", "Live on, Time; emit no evil.", "No, it is opposition.", "Peel's lager on red rum did murder no regal sleep.", "Too far away, no mere clay or royal ceremony, a war afoot." ]; var rand = s[(Math.random()*s.length)|0]; var a = s[(Math.random()*s.length)|0]; while (a == rand){ a = s[(Math.random()*s.length)|0]; } a += " " + rand; //console.log(s,a); result.push(a); req.session.data = result; callback(result); }; exports.check_data = function(req, callback) { var answer = req.param("answer"); var data = req.session.data; var s = data[0]; var longest = ""; var longestOrig = ""; for(var i = s.length - 1; i >= 0; i--) { for (var j = i + 1; j < s.length; j++) { var q = s.substring(i, j); var t = q; if (q.substring(0,1).match(/[0-9a-zA-Z]+$/)){ t = q.replace(/[^A-Za-z]/gi,'').toLowerCase(); } if (t == t.split("").reverse().join("") && t.length > longest.length) { longest = t; longestOrig = q.trim(); } } } var correct = longestOrig; /*console.log("!"+longestOrig+"!"); console.log("!"+output+"!"); console.log(longestOrig == output);*/ // return longestOrig === answer; if (answer) { answer = answer.replace(/^\s+|\s+$/g,''); correct = correct.replace(/^\s+|\s+$/g,''); if (answer.toLowerCase() === correct.toLowerCase()) { callback({ status: 1, message: "Great job! Your flag is <code>" + flag + "</code>", }); return; } else { callback({ status: 0, message: "Nope, try again..." }); return; } } else { callback({ status: 0, message: "Answer cannot be empty!" }); return; } };
(function () { "use strict"; angular .module('documents') .component('scientillaDocumentAffiliations', { templateUrl: 'partials/scientilla-document-affiliations.html', controller: controller, controllerAs: 'vm', bindings: { document: "<", collapsed: '=?', highlighted: '=?' } }); controller.$inject = [ '$filter', '$scope' ]; function controller($filter, $scope) { const vm = this; vm.getAffiliationInstituteIdentifier = getAffiliationInstituteIdentifier; vm.toggleCollapse = toggleCollapse; vm.affiliationInstitutes = []; vm.$onInit = () => { if (!vm.collapsed) { vm.collapsed = false; } shortenAuthorString(); $scope.$watch('vm.collapsed', function() { shortenAuthorString(); }); }; function toggleCollapse() { vm.collapsed = !vm.collapsed; } function getAffiliationInstituteIdentifier(institute) { return vm.document.getInstituteIdentifier( vm.document.institutes.findIndex(i => i.id === institute.id) ); } function shortenAuthorString() { let limit = vm.collapsed ? vm.document.getAuthorLimit() : 0, shortAuthorString = $filter('authorsLength')(vm.document.authorsStr, limit); vm.affiliationInstitutes = []; shortAuthorString.split(/,\s?/).map(function (author, index) { const authorship = _.find(vm.document.authorships, a => a.position === index); if (authorship) { vm.affiliationInstitutes = vm.affiliationInstitutes.concat(authorship.affiliations).unique(); } }); } } }) ();
exports.config = { allScriptsTimeout: 11000, specs: [ '*.js' ], capabilities: { 'browserName': 'chrome' }, baseUrl: 'http://localhost:8080/mylibrary/', framework: 'jasmine', jasmineNodeOpts: { defaultTimeoutInterval: 30000 } };
const { resolve } = require('path') const express = require('express') const bodyParser = require('body-parser') var proxy = require('express-http-proxy') const app = express() // parse JSON bodies app.use(bodyParser.json({ type: 'application/json' })) // the index file app.get('/', (req, res) => { res.sendFile(resolve(__dirname, '../index.html')) }) // handle Perl requests app.post('/resources/cgi-bin/scrollery-cgi.pl', proxy('http://localhost:9080/resources/cgi-bin/scrollery-cgi.pl')) // expose the Express app instance module.exports = app
'use strict'; var AppDispatcher = require('../dispatchers/AppDispatcher'); var AppStore = require('../stores/AppStore'); var AppConstants = require('../constants/AppConstants'); var ServerActions = { receiveData: function(data) { AppDispatcher.handleViewAction({ actionType: AppConstants.GET_CATEGORIES, data: data }); }, receiveNewCategory(category) { AppDispatcher.handleViewAction({ actionType: AppConstants.ADD_NEW_CATEGORY, category: category }); }, receiveDeletedCategory(categoryID) { AppDispatcher.handleViewAction({ actionType: AppConstants.DELETE_CATEGORY, categoryID: categoryID }); }, receiveUpdatedComponents(categoryID, sectionID, components) { AppDispatcher.handleViewAction({ actionType: AppConstants.UPDATE_COMPONENTS, categoryID: categoryID, sectionID: sectionID, components: components }); }, receiveNewSection(categoryID, section) { AppDispatcher.handleViewAction({ actionType: AppConstants.ADD_NEW_SECTION, section: section, categoryID: categoryID }); }, receiveDeletedSection(categoryID, sectionID) { AppDispatcher.handleViewAction({ actionType: AppConstants.DELETE_SECTION, sectionID: sectionID, categoryID: categoryID }); }, receiveSection(index, data) { AppDispatcher.handleViewAction({ actionType: AppConstants.UPDATE_SECTION, index: index, data: data }); }, receiveCategory(index, data) { AppDispatcher.handleViewAction({ actionType: AppConstants.UPDATE_CATEGORY, index: index, data: data }); }, receiveSortedSectionItems: function(sectionID, items) { AppDispatcher.handleViewAction({ actionType: AppConstants.SORT_SECTION_ITEMS, sectionID: sectionID, items: items }); }, receiveSortedCategorySections: function(categoryID, sections) { AppDispatcher.handleViewAction({ actionType: AppConstants.SORT_CATEGORY_SECTIONS, categoryID: categoryID, sections: sections }); }, receiveSortedCategories: function(dragged, over) { AppDispatcher.handleViewAction({ actionType: AppConstants.SORT_CATEGORIES, dragged: dragged, over: over }); } }; module.exports = ServerActions;
function Database() { if(typeof this.mysql == "undefined") { this.init(); } } Database.prototype.init = function() { var mysql = require('mysql'); this.connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'test1234', database : 'linkbank' }); }, Database.prototype.search = function(word, socket) { console.log("search:", word); var query = this.connection.query("SELECT address, description FROM link WHERE description LIKE '%" + word + "%' OR address LIKE '%"+ word +"%'", function(err, rows, fields) { if(err) { console.log("search query failed:", err); } else { console.log("found", rows); socket.emit('search response', JSON.stringify(rows)); } }); }, Database.prototype.addlink = function(link, description, socket) { console.log("addlink:", link, description); this.connection.query("INSERT INTO link (address, description) VALUES (?, ?)", [link, description], function(err, result) { if(err) { console.log("addlink query failed:", err); socket.emit('add link response', false); } else { socket.emit('add link response', true); } }); }, Database.prototype.login = function(username, passwordhash, socket) { this.connection.query("SELECT passwordhash FROM user WHERE username = ?", [username], function(err, rows, fields) { if(err) { console.log("login query failed:", err); } else { var status = false; if(typeof rows[0] !== "undefined") { if(passwordhash == rows[0].passwordhash) { status = true; } else { status = false; } } socket.emit('login response', status); socket.authorized = status; } }); } Database.prototype.register = function(username, passwordhash, socket) { console.log("register:", username, passwordhash); var query = this.connection.query("INSERT INTO user (username, passwordhash) VALUES (?,?)", [username, passwordhash], function(err, result) { if(err) { console.log("register query failed:", err); } else { socket.emit('register response', true); socket.authorized = true; } }); } module.exports = Database;
module.exports = [ require('./deepSouth'), require('./fallsRiverMusic') // require('./gizmoBrewWorks') ];
// app/routes.js // grab the country model we just created var Country = require('./models/country'); module.exports = function (app) { //---------------------------------------------------------------------- // server routes // handle things like api calls // authentication routes // sample api route app.get('/api/countries', function (req, res) { // use mongoose to get all countries in the database Country.find(function (err, countries) { // if there is an error retrieving, send the error. // nothing after res.send(err) will execute if (err) res.send(err); // return all countries in JSON format res.json(countries); }); }); app.get('/api/countries/:id',function(req,res){ // var response = {}; Country.findById(req.params.id, function(err,data){ // This will run Mongo Query to fetch data based on ID. if(err) { res.send(err); } res.send(data); }); }); app.post('/api/countries',function(req,res){ var country = new Country(); var response = {}; country.index = req.body.index; country.name = req.body.name; country.gdi_value =req.body.gdi_value; country.gdi_group = req.body.gdi_group; country.hdi_f = req.body.hdi_f; country.hdi_m =req.body.hdi_m; country.le_f =req.body.le_f; country.le_m =req.body.le_m; country.eys_f =req.body.eys_f; country.eys_m =req.body.eys_m; country.mys_f = req.body.mys_f; country.mys_m = req.body.mys_m; country.gni_f =req.body.gni_f; country.gni_m =req.body.gni_m; country.hd_level=req.body.hd_level; country.save(function(err){ // save() will run insert() command of MongoDB. // it will add new data in collection. if(err) { response = {"error" : true,"message" : "Error adding data"}; } else { response = {"error" : false,"message" : "Data added"}; } res.json(response); }); }); app.delete('/api/countries/:id', function (req, res){ return Country.findById(req.params.id, function (err, country) { return Country.remove({_id : req.params.id},function (err) { if (!err) { console.log("removed"); return res.send(''); } else { console.log(err); } }); }); }); app.put('/api/countries',function(req,res){ var response = {}; // first find out record exists or not // if it does then update the record Country.findById(req.params.id,function(err,country){ if(err) { response = {"error" : true,"message" : "Error fetching data"}; } else { // we got data from Mongo. // change it accordingly. if(req.body.index !== undefined) { // country.index = req.body.index; } if(req.body.name !== undefined) { // country.name = req.body.name; } if(req.body.gdi_value!==undefined){ coutry.gdi_value=req.body.gdi_value; } if(req.gdi_group!==undefined){ country.gdi_group = req.body.gdi_group; } if(req.body.hdi_f!==undefined){ country.hdi_f = req.body.hdi_f; } if(req.body.hdi_m!==undefined){ country.hdi_m =req.body.hdi_m; } if(req.body.le_f!==undefined){ country.le_f =req.body.le_f; } if(req.body.le_m!==undefined){ country.le_m =req.body.le_m; } if(req.body.eys_f!==undefined){ country.eys_f =req.body.eys_f; } if(req.body.eys_m!==undefined){ country.eys_m =req.body.eys_m; } if(req.body.mys_f!==undefined){ country.mys_f = req.body.mys_f; } if(req.body.mys_m!==undefined){ country.mys_m = req.body.mys_m; } if(req.body.gni_f!==undefined){ country.gni_f =req.body.gni_f; } if(req.body.gni_m!==undefined){ country.gni_m =req.body.gni_m; } if(req.body.hd_level){ country.hd_level=req.body.hd_level; } // save the data country.save(function(err){ if(err) { response = {"error" : true,"message" : "Error updating data"}; } else { response = {"error" : false,"message" : "Data is updated for "+req.params.id}; } res.json(response); }) } }); }) // app.get('/api/countries/:name',function(req,res){ // // var response = {}; // Country.find({'name': new RegExp(req.params.name, "i")}, function(err, data) { // //Do your action here.. // // This will run Mongo Query to fetch data based on ID. // if(err) { // res.send(err); // // response = {"error" : true,"message" : "Error fetching data"}; // // } else { // // response = {"error" : false,"message" : data}; // } // res.send(data); // }); // }); // route to handle creating goes here (app.post) // route to handle delete goes here (app.delete) //---------------------------------------------------------------------- // frontend routes // route to handle all angular requests app.get('*', function (req, res) { res.sendFile('/public/index.html', { root: '.' }); }); };
'use strict' var _ = require('lodash'), CrudRoutes = require('../lib/crud-routes'), transactions = require('../services/transactions'), log = require('../lib/log'); let opts = { entity: 'transactions', service: transactions, user: true, parent: { name: 'account' }, protected: true }; let routes = CrudRoutes(opts); routes.push({ method: 'get', uri: '/user/:userid/accounts/:accountid/transactions/search/:kind/:search', protected: true, handler: (req,res,next) => { log.info('Search Transactions by ' + req.params.kind + '/' + req.params.search); return transactions.search(req.params) .then((data) => { res.send(200, data); }) .catch((err) => { let code = err.type === 'validation' ? 400 : 500; log.error('Error searching transactions: ' + err.message); res.send(400, err.message); }); } }); routes.push({ method: 'get', uri: '/user/:userid/accounts/:accountid/transactions/startdate/:startdate/enddate/:enddate', protected: true, handler: (req,res,next) => { log.info('Retrieve Transactions from ' + req.params.startdate + '-' + req.params.enddate); return transactions.search(req.params) .then((data) => { res.send(200, data); }) .catch((err) => { let code = err.type === 'validation' ? 400 : 500; log.error('Error searching transactions: ' + err.message); res.send(400, err.message); }); } }); routes.push({ method: 'get', uri: '/user/:userid/accounts/:accountid/transactions/startdate/:startdate/enddate/:enddate/:groupby', protected: true, handler: (req,res,next) => { log.info('Retrieve Transactions from ' + req.params.startdate + ' to ' + req.params.enddate); return transactions.search(req.params) .then((data) => { log.debug('Grouping by ' + req.params.groupby); let a = _.groupBy(data, req.params.groupby); res.send(200, a); }) .catch((err) => { let code = err.type === 'validation' ? 400 : 500; log.error('Error searching transactions: ' + err.message); res.send(400, err.message); }); } }); module.exports = routes;
/*Write an if statement that takes two double variables a and b and exchanges their values if the first one is greater than the second. As a result print the values a and b, separated by a space.*/ console.log('-----Problem 1. Exchange if greater-----'); function exchangeIfIsGrater (first, second){ console.log('Before exchange:', first, second); var temp; if(first > second){ temp = first; first = second; second = temp; } console.log('After exchange:', first, second); } exchangeIfIsGrater(15, 10);
'use strict'; module.exports = { type: 'error', error: { line: 1, column: 3, message: 'Unexpected character \'💩\'.', }, };
export { default } from 'ember-radical/components/rad-dropdown/content'
/* eslint-disable @typescript-eslint/no-var-requires */ const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); const webpack = require('webpack'); const { version, author, license } = require('./package.json'); module.exports = { entry: './src/index.js', output: { filename: 'toastui-vue-editor.js', path: path.resolve(__dirname, 'dist'), library: { type: 'commonjs2', }, environment: { arrowFunction: false, const: false, }, }, externals: { '@toast-ui/editor': { commonjs: '@toast-ui/editor', commonjs2: '@toast-ui/editor', }, '@toast-ui/editor/dist/toastui-editor-viewer': { commonjs: '@toast-ui/editor/dist/toastui-editor-viewer', commonjs2: '@toast-ui/editor/dist/toastui-editor-viewer', }, }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', exclude: /node_modules/, }, { test: /\.js$/, use: [ { loader: 'ts-loader', options: { transpileOnly: true, }, }, ], exclude: /node_modules/, }, ], }, plugins: [ new VueLoaderPlugin(), new webpack.BannerPlugin({ banner: [ 'TOAST UI Editor : Vue Wrapper', `@version ${version} | ${new Date().toDateString()}`, `@author ${author}`, `@license ${license}`, ].join('\n'), }), ], };
var gulp = require('gulp'); var to5 = require('gulp-6to5'); var concat = require('gulp-concat'); var order = require('gulp-order'); var watch = require('gulp-watch'); var connect = require('gulp-connect'); gulp.task('6to5', function () { return gulp.src('src/js/**/*.js') .pipe(order([ 'core/**/*.js', 'components/**/*.js', 'app/**/*.js', 'main.js' ])) .pipe(to5()) .pipe(concat('app.js')) .pipe(gulp.dest('build')) .pipe(connect.reload()); }); gulp.task('webserver', function() { connect.server({ root: 'build', livereload: true }); }); gulp.task('watch', function() { gulp.watch('src/js/**/*.js', ['6to5']); }); gulp.task('serve', ['webserver', 'watch']);
define([ 'lib/validators/moment', 'lib/validators/unequalTo' ], function () { });