code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
|---|---|---|---|---|---|
var searchData=
[
['directorio_2ecpp',['directorio.cpp',['../directorio_8cpp.html',1,'']]],
['directorio_2eh',['directorio.h',['../directorio_8h.html',1,'']]]
];
|
Baltasarq/zero
|
src/doc/search/files_64.js
|
JavaScript
|
mit
| 166
|
module.exports = function splayDepthFirst (nodes) {
return nodes.reduce((splayed, node) => (
splayed.concat([node].concat(splayDepthFirst(node.children)))
), [])
}
|
dbkaplun/webtop
|
src/splayDepthFirst.js
|
JavaScript
|
mit
| 172
|
/*!
* jQuery UI Touch Punch Improved 0.3.1
*
*
* Copyright 2013, Chris Hutchinson <chris@brushd.com>
* Original jquery-ui-touch-punch Copyright 2011, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery", "jquery.ui" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function ($) {
var pointerEnabled = window.navigator.pointerEnabled
|| window.navigator.msPointerEnabled;
// Detect touch support
$.support.touch = 'ontouchend' in document || pointerEnabled;
// Ignore browsers without touch support or mouse support
if (!$.support.touch || !$.ui.mouse) {
return;
}
var mouseProto = $.ui.mouse.prototype,
_mouseInit = mouseProto._mouseInit,
touchHandled;
// see http://stackoverflow.com/a/12714084/220825
function fixTouch(touch) {
var winPageX = window.pageXOffset,
winPageY = window.pageYOffset,
x = touch.clientX,
y = touch.clientY;
if (touch.pageY === 0 && Math.floor(y) > Math.floor(touch.pageY) || touch.pageX === 0 && Math.floor(x) > Math.floor(touch.pageX)) {
// iOS4 clientX/clientY have the value that should have been
// in pageX/pageY. While pageX/page/ have the value 0
x = x - winPageX;
y = y - winPageY;
} else if (y < (touch.pageY - winPageY) || x < (touch.pageX - winPageX)) {
// Some Android browsers have totally bogus values for clientX/Y
// when scrolling/zooming a page. Detectable since clientX/clientY
// should never be smaller than pageX/pageY minus page scroll
x = touch.pageX - winPageX;
y = touch.pageY - winPageY;
}
return {
clientX: x,
clientY: y
};
}
/**
* Simulate a mouse event based on a corresponding touch event
* @param {Object} event A touch event
* @param {String} simulatedType The corresponding mouse event
*/
function simulateMouseEvent (event, simulatedType) {
// Ignore multi-touch events
if ((!pointerEnabled && event.originalEvent.touches.length > 1) || (pointerEnabled && !event.isPrimary)) {
return;
}
var touch = pointerEnabled ? event.originalEvent : event.originalEvent.changedTouches[0],
simulatedEvent = document.createEvent('MouseEvents'),
coord = fixTouch(touch);
// Check if element is an input or a textarea
if ($(touch.target).is("input") || $(touch.target).is("textarea")) {
event.stopPropagation();
} else {
event.preventDefault();
}
// Initialize the simulated mouse event using the touch event's coordinates
simulatedEvent.initMouseEvent(
simulatedType, // type
true, // bubbles
true, // cancelable
window, // view
1, // detail
event.screenX || touch.screenX, // screenX
event.screenY || touch.screenY, // screenY
event.clientX || coord.clientX, // clientX
event.clientY || coord.clientY, // clientY
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
0, // button
null // relatedTarget
);
// Dispatch the simulated event to the target element
event.target.dispatchEvent(simulatedEvent);
}
/**
* Handle the jQuery UI widget's touchstart events
* @param {Object} event The widget element's touchstart event
*/
mouseProto._touchStart = function (event) {
var self = this;
// Ignore the event if another widget is already being handled
if (touchHandled || (!pointerEnabled && !self._mouseCapture(event.originalEvent.changedTouches[0]))) {
return;
}
// Set the flag to prevent other widgets from inheriting the touch event
touchHandled = true;
// Track movement to determine if interaction was a click
self._touchMoved = false;
// Simulate the mouseover event
simulateMouseEvent(event, 'mouseover');
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
// Simulate the mousedown event
simulateMouseEvent(event, 'mousedown');
};
/**
* Handle the jQuery UI widget's touchmove events
* @param {Object} event The document's touchmove event
*/
mouseProto._touchMove = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Interaction was not a click
this._touchMoved = true;
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
};
/**
* Handle the jQuery UI widget's touchend events
* @param {Object} event The document's touchend event
*/
mouseProto._touchEnd = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Simulate the mouseup event
simulateMouseEvent(event, 'mouseup');
// Simulate the mouseout event
simulateMouseEvent(event, 'mouseout');
// If the touch interaction did not move, it should trigger a click
if (!this._touchMoved) {
// Simulate the click event
simulateMouseEvent(event, 'click');
}
// Unset the flag to allow other widgets to inherit the touch event
touchHandled = false;
};
/**
* A duck punch of the $.ui.mouse _mouseInit method to support touch events.
* This method extends the widget with bound touch event handlers that
* translate touch events to mouse events and pass them to the widget's
* original mouse event handling methods.
*/
mouseProto._mouseInit = function () {
var self = this;
self.element.on({
'touchstart': $.proxy(self, '_touchStart'),
'touchmove': $.proxy(self, '_touchMove'),
'touchend': $.proxy(self, '_touchEnd'),
'pointerDown': $.proxy(self, '_touchStart'),
'pointerMove': $.proxy(self, '_touchMove'),
'pointerUp': $.proxy(self, '_touchEnd'),
'MSPointerDown': $.proxy(self, '_touchStart'),
'MSPointerMove': $.proxy(self, '_touchMove'),
'MSPointerUp': $.proxy(self, '_touchEnd')
});
// Call the original $.ui.mouse init method
_mouseInit.call(self);
};
}));
|
tslmy/Windows-Web
|
js/jquery.ui.touch-punch-improved.js
|
JavaScript
|
mit
| 6,025
|
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.services',
'uiGmapgoogle-maps'
]).
config(['$routeProvider', 'uiGmapGoogleMapApiProvider',function($routeProvider, uiGmapGoogleMapApiProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
uiGmapGoogleMapApiProvider.configure({
// key: 'your api key',
v: '3.20', //defaults to latest 3.X anyhow
libraries: 'weather,geometry,visualization'
});
}]);
|
CombustionBustinPyroPeople/peponi
|
public/app.js
|
JavaScript
|
mit
| 555
|
/**
* @fileoverview
* @enhanceable
* @public
*/
// GENERATED CODE -- DO NOT EDIT!
goog.provide('proto.tensorflow.test.TestEmptyMessage');
goog.require('jspb.Message');
goog.require('jspb.BinaryReader');
goog.require('jspb.BinaryWriter');
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.tensorflow.test.TestEmptyMessage = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.tensorflow.test.TestEmptyMessage, jspb.Message);
if (goog.DEBUG && !COMPILED) {
proto.tensorflow.test.TestEmptyMessage.displayName = 'proto.tensorflow.test.TestEmptyMessage';
}
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto suitable for use in Soy templates.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS.
* @param {boolean=} opt_includeInstance Whether to include the JSPB instance
* for transitional soy proto support: http://goto/soy-param-migration
* @return {!Object}
*/
proto.tensorflow.test.TestEmptyMessage.prototype.toObject = function(opt_includeInstance) {
return proto.tensorflow.test.TestEmptyMessage.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Whether to include the JSPB
* instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.tensorflow.test.TestEmptyMessage} msg The msg instance to transform.
* @return {!Object}
*/
proto.tensorflow.test.TestEmptyMessage.toObject = function(includeInstance, msg) {
var f, obj = {
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.tensorflow.test.TestEmptyMessage}
*/
proto.tensorflow.test.TestEmptyMessage.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.tensorflow.test.TestEmptyMessage;
return proto.tensorflow.test.TestEmptyMessage.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.tensorflow.test.TestEmptyMessage} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.tensorflow.test.TestEmptyMessage}
*/
proto.tensorflow.test.TestEmptyMessage.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.tensorflow.test.TestEmptyMessage.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.tensorflow.test.TestEmptyMessage.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.tensorflow.test.TestEmptyMessage} message
* @param {!jspb.BinaryWriter} writer
*/
proto.tensorflow.test.TestEmptyMessage.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
};
|
nubbel/swift-tensorflow
|
NodeGenerated/testemptymessage.js
|
JavaScript
|
mit
| 4,013
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import queryString from 'query-string';
import './graph-styles.css';
const d3 = {
...require('d3-selection'), // eslint-disable-line
...require('d3-scale'), // eslint-disable-line
...require('d3-axis'), // eslint-disable-line
...require('d3-format'), // eslint-disable-line
...require('d3-shape'), // eslint-disable-line
...require('d3-array'), // eslint-disable-line
};
const styles = theme => ({
root: {},
});
export class Graph extends Component {
static propTypes = {
classes: PropTypes.object.isRequired,
sensor: PropTypes.object,
readings: PropTypes.arrayOf(
PropTypes.shape({
timestamp: PropTypes.number.isRequired,
value: PropTypes.number.isRequired,
}),
).isRequired,
};
static defaultProps = {
sensor: null,
};
drawGraph() {
console.log('draw');
const data = this.props.readings;
// Initialization.
const container = document.querySelector('#graph-container');
container.innerHTML = '';
let width = container.clientWidth;
let height = 400;
const margin = {
top: 10,
right: 20,
bottom: 10,
left: this.props.sensor.units ? 40 + this.props.sensor.units.length * 10 : 60,
};
width = width - margin.left - margin.right;
height = height - margin.top - margin.bottom;
let i = 0;
let newText = '';
// // Apply calibration data.
const coef = {
x: 1,
y: 0,
};
const dataObject = [];
for (i = data.length - 1; i > 0; i--) {
dataObject.push({
created: data[i].timestamp,
value: data[i].value * coef.x + coef.y,
});
}
if (dataObject.length === 0) {
container.innerHTML = 'There arnt enough readings for this sensor to display anything.';
return;
}
let start = queryString.parse(location.search).start;
let end = queryString.parse(location.search).end;
if (end === undefined) {
end = Date.now();
} else {
end = new Date(parseInt(end));
}
if (start === undefined) {
start = Date.now() - 24 * 60 * 60 * 1000;
} else {
start = new Date(parseInt(start));
}
let min = dataObject[0].value;
let max = dataObject[0].value;
// Set min and max values
for (i = 0; i < dataObject.length; i++) {
if (min > dataObject[i].value) {
min = dataObject[i].value;
}
if (max < dataObject[i].value) {
max = dataObject[i].value;
}
}
// Adds margins within the graph
min = min - (max - min) * 0.05;
max = max + (max - min) * 0.05;
// Create the svg.
const newChart = d3
.select('#graph-container')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', `translate(${margin.left},${margin.bottom})`)
.classed('svg-content-responsive', true);
// Scale
const xScale = d3
.scaleTime()
.domain([new Date(start), new Date(end)])
.rangeRound([0, width]);
const yScale = d3
.scaleLinear()
.domain([min, max])
.rangeRound([height - margin.bottom, margin.top]);
// Formats text for units display
const getFormattedText = d => {
const f = d3.format('.1f');
const units = this.props.sensor.units;
return f(d) + units;
};
// TOOL-TIPS
// Tooltip container
const tooltip = newChart.append('g').style('display', 'none');
// Tooltip helper
const bisectDate = d3.bisector(d => d.created).left;
// Y-axis line for tooltip
const yLine = tooltip
.append('g')
.append('line')
.attr('class', 'tooltip-line')
.style('stroke', 'blue')
.style('stroke-dasharray', '3,3')
.style('opacity', 0.5)
.attr('y1', margin.bottom)
.attr('y2', height);
// Date text
const timeText = tooltip
.append('text')
.attr('x', 0)
.attr('y', margin.top - 5)
.attr('width', 100)
.attr('height', 100 * 0.4)
.attr('fill', 'black');
// Drag behaivors for the selection box.
// const dragStart = 0, dragStartPos = 0, dragEnd = 0;
// const drag = d3.drag()
// .on('drag', function(d,i) {
// const x0 = xScale.invert(d3.mouse(this)[0]);
// i = bisectDate(data.readings, x0, 1);
// const d0 = data.readings[i - 1],
// d1 = data.readings[i];
// d = x0 - d0.created > d1.created - x0 ? d1 : d0;
// if(xScale(d.created) > dragStartPos){
// selectionBox.attr('width', (xScale(d.created) - dragStartPos));
// } else {
// selectionBox.attr('width', ( dragStartPos - xScale(d.created)));
// selectionBox.attr('transform', 'translate(' + xScale(d.created) + ',0)' );
// }
// })
// .on('end', function(d,i){
// dragEnd = d3.mouse(this)[0];
// if(Math.abs(dragStart - dragEnd) < 10) return;
// const x0 = xScale.invert(dragStart), x1 = xScale.invert(dragEnd);
// scope.$apply(function(){
// if(x1 > x0){
// $location.search('start_date', x0.getTime());
// $location.search('end_date',x1.getTime());
// } else {
// $location.search('start_date', x1.getTime());
// $location.search('end_date',x0.getTime());
// }
// });
// });
// Update loop for tooltips.
const circleElements = [];
const textElements = [];
function mousemove() {
const x0 = xScale.invert(d3.mouse(this)[0]); // jshint ignore:line
const cross = bisectDate(dataObject, x0, 1);
const d0 = dataObject[cross - 1];
const d1 = dataObject[cross];
if (d1 === undefined) {
return;
}
const d = x0 - d0.created > d1.created - x0 ? d1 : d0;
circleElements[0].attr('transform', `translate(${xScale(d.created)},${yScale(d.value)})`);
yLine.attr('transform', `translate(${xScale(d.created)},0)`);
timeText.text(new Date(d.created));
textElements[0]
.text(getFormattedText(d.value))
.attr('transform', `translate(${xScale(d.created) + 10},${yScale(d.value) - 10})`);
}
// Selection box
const selectionBox = newChart
.append('rect')
.attr('fill', 'none')
.attr('opacity', 0.5)
.attr('x', 0)
.attr('y', margin.top)
.attr('width', 14)
.attr('height', height - margin.top);
// Hit area for selection box
newChart
.append('rect')
.attr('width', width)
.attr('height', height)
.style('fill', 'none')
.style('pointer-events', 'all')
.on('mouseover', () => {
tooltip.style('display', null);
})
.on('mouseout', () => {
tooltip.style('display', 'none');
})
.on('mousemove', mousemove)
.on('mousedown', () => {
selectionBox.attr('fill', '#b7ff64');
// dragStart = d3.mouse(this)[0];
const x0 = xScale.invert(d3.mouse(this)[0]);
const cross = bisectDate(dataObject.readings, x0, 1);
const d0 = dataObject.readings[cross - 1];
const d1 = dataObject.readings[cross];
const d = x0 - d0.created > d1.created - x0 ? d1 : d0;
selectionBox.attr('transform', `translate(${xScale(d.created)},0)`);
// dragStartPos = xScale(d.created);
});
// .call(drag);
// Y Axis
function getTic() {
const Ticks = [];
const ratio = (max - min) / 6;
for (let q = 0; q < 7; q++) {
Ticks.push(min + ratio * q);
}
return Ticks;
}
const yAxis = d3
.axisLeft(yScale)
.tickSizeInner(-width)
.tickSizeOuter(0)
.tickValues(getTic())
.tickFormat(d => {
const f = d3.format('.1f');
return `${f(d)} ${this.props.sensor.units}`;
});
newChart
.append('g')
.attr('class', 'chart-axis-shape')
.call(yAxis);
// X Axis
const xAxis = d3
.axisBottom(xScale)
.tickSizeInner(-height + margin.bottom + margin.top)
.tickSizeOuter(0)
.tickPadding(10)
.ticks(10);
newChart
.append('g')
.attr('class', 'chart-axis-shape')
.attr('transform', `translate(0,${height - margin.bottom})`)
.call(xAxis);
// Top border
newChart
.append('g')
.append('line')
.attr('class', 'chart-axis-shape')
.attr('x1', 0)
.attr('x2', width)
.attr('y1', margin.bottom)
.attr('y2', margin.bottom);
// Right border
newChart
.append('g')
.append('line')
.attr('class', 'chart-axis-shape')
.attr('x1', width)
.attr('x2', width)
.attr('y1', margin.bottom)
.attr('y2', height - margin.bottom);
// Graph lines
const lineFunction = d3
.line()
// .defined(() => {
// // TODO: add linebreak behaivor
// return true;
// })
.x(d => xScale(d.created))
.y(d => yScale(d.value));
newChart
.append('path')
.attr('d', lineFunction(dataObject))
.attr('stroke', 'rgba(45, 100, 255, 0.87)')
.attr('stroke-width', 2)
.attr('fill', 'none');
// // Tooltip circle
const newCircle = tooltip
.append('circle')
.style('fill', 'none')
.style('stroke', 'blue')
.attr('r', 4);
circleElements.push(newCircle);
// Tooltip text
newText = tooltip
.append('text')
.attr('width', 100 * 2)
.attr('height', 100 * 0.4)
.attr('fill', 'black');
textElements.push(newText);
} // End D3
componentDidMount() {
this.setState({
readings: this.props.readings,
});
this.drawGraph();
}
shouldComponentUpdate(nextProps, nextState) {
if (
this.state &&
this.state.readings &&
(nextProps.readings[0].timestamp !== this.state.readings[0].timestamp ||
nextProps.readings.length !== this.state.readings.length)
) {
this.setState({
readings: this.props.readings,
});
this.drawGraph();
}
return true;
}
render() {
return (
<div className={this.props.classes.root}>
<div id="graph-container" />
</div>
);
}
}
export default withStyles(styles)(Graph);
|
cyrillegin/Aquaponics
|
src/client/components/SensorGraph/Graph.js
|
JavaScript
|
mit
| 10,466
|
require('../common.js');
test.expect(2);
var zoneFunc = function() {
throw 133;
};
var cb = function(err) {
test.ok(err instanceof Error);
test.strictEqual(err.value, 133);
test.done();
};
zone.create(zoneFunc).catch (cb);
|
CaitlinJD/RA-Angular2Project
|
node_modules/zone/test/tests/test-callback-throw-non-error.js
|
JavaScript
|
mit
| 235
|
import { run, read, remove } from '@miljan/build'
import { compile, buildIndex } from './util/icons'
run(async () => {
const tmpl = await read('src/file.tmpl')
await remove('src/uikit')
// compile uikit icons
await compile({
tmpl,
src: '../../node_modules/uikit/src/images/icons/*.svg',
dest: 'src/uikit'
})
await buildIndex({
src: 'src/uikit/*.js',
dest: 'src/index.js'
})
})
|
vuikit/vuikit
|
packages/vuikit-icons/scripts/pull-icons.js
|
JavaScript
|
mit
| 414
|
import {step} from '../types/step';
let temp = [
{
"id": "overview",
"data": {
"x": "3000",
"y": "800",
"scale": 9
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(3000px, 1500px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) scale(10)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-1",
"slide": true,
"content": "<p style=\"text-align: center;\"> </p>\n<p style=\"text-align: center;\"> </p>\n<p style=\"text-align: center;\"> </p>\n<p style=\"text-align: center;\"> </p>\n<p style=\"text-align: center;\"> </p>\n<p style=\"text-align: center;\">你正在準備這種<strong>傳統式</strong>投影片嗎?</p>",
"data": {
"x": "-1100",
"y": -1500,
"scale": 1
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(-1100px, -1500px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) scale(1)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-2",
"slide": true,
"content": "<p style=\"text-align: center;\"> </p>\n<p style=\"text-align: center;\"> </p>\n<p style=\"text-align: center;\"> </p>\n<p style=\"text-align: center;\"> </p>\n<p style=\"text-align: center;\"> </p>\n<p style=\"text-align: center;\">或許你該給自己一點<strong>新的嘗試</strong></p>",
"data": {
"y": -1500,
"scale": 1
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(0px, -1500px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) scale(1)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-3",
"slide": true,
"content": "<p> </p>\n<p style=\"text-align: center;\"> </p>\n<p> </p>\n<p> </p>\n<p> </p>\n<h4 style=\"text-align: center;\">讓你的<strong>創意</strong>在這裡大放異彩吧!</h4>",
"data": {
"x": 1100,
"y": -1500,
"scale": 1
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(1100px, -1500px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) scale(1)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-4",
"content": "<h4 style=\"text-align: center;\"> 歡迎使用 </h4>\n<h1 style=\"text-align: center;\"><strong>[Oi]</strong></h1>\n<h6 style=\"text-align: center;\"> </h6>\n<h6 style=\"text-align: center;\"> - 創造讓人印象深刻的投影片編輯器 -</h6>",
"data": {
"y": "-300",
"scale": 4
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(0px, -300px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) scale(4)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-5",
"content": "<h6>這是一套生成 <a href=\"https://github.com/impress/impress.js/\" target=\"_blank\">impress.js</a> 的編輯器</h6>\n<p> </p>\n<p>提供你 <strong>更快速</strong>、<strong>更直覺 </strong>的方式創作</p>\n<p> </p>\n<h6>更重要的是,你 <span style=\"text-decoration: underline;\">不需要</span> 撰寫任何程式碼</h6>",
"data": {
"x": "850",
"y": "2800",
"scale": 5,
"rotate": 90,
"rotateZ": 90
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(850px, 2800px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(90deg) scale(5)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-6",
"content": "<p style=\"text-align: center;\">你只需要</p>\n<h1 style=\"text-align: center;\"><strong>專注</strong></h1>\n<p style=\"text-align: center;\"> 於你的流程設計</p>",
"data": {
"x": "3100",
"y": "1300",
"scale": 6,
"rotate": 180,
"rotateZ": 180
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(3100px, 1300px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(180deg) scale(6)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-7",
"content": "<p style=\"text-align: center;\">和<strong>想像力</strong></p>",
"data": {
"x": "2900",
"y": "1400",
"z": -3000,
"scale": 1,
"rotate": 300,
"rotateZ": 300
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(2900px, 1400px, -3000px) rotateX(0deg) rotateY(0deg) rotateZ(300deg) scale(1)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-8",
"content": "<h6>這是參考 <a href=\"http://impress.github.io/impress.js\" target=\"_blank\">impress.js Demo</a></h6>\n<h6> </h6>\n<h6>使用 <strong>[ Oi ] </strong>快速建立的範例</h6>\n<h6> </h6>\n<h6>你可以直接參考或修改</h6>\n<h6> </h6>\n<h6>但我們更<sub>期待</sub>看到<strong>你的創作</strong></h6>",
"data": {
"x": "2950",
"y": "-2200",
"scale": 6,
"rotate": 270,
"rotateZ": 270
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(2950px, -2200px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(270deg) scale(6)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-9",
"content": "<p style=\"text-align: center;\">別讓範例限制你的</p>\n<h1 style=\"text-align: center;\">想像力</h1>",
"data": {
"x": "5600",
"y": "-900",
"scale": 6
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(5600px, -900px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) scale(6)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-10",
"active": true,
"content": "<h6 style=\"text-align: center;\"> 在我們震撼你的觀眾前 </h6>\n<p> </p>\n<p style=\"text-align: center;\">先拿起紙筆準備<span style=\"color: #1583d6;\"><sup>創作</sup></span>吧!</p>\n<p style=\"text-align: center;\"> <sup><img src=\"http://rs374.pbsrc.com/albums/oo187/gamegeek2589/Gif/tumblr_lhgmxe1Pe01qbmtfl.gif~c200\" alt=\"pic by http://photobucket.com/images/wink%20gif\" width=\"97\" height=\"97\" /></sup></p>",
"data": {
"x": "6000",
"y": "1500",
"scale": 4,
"rotate": 20,
"rotateZ": 20
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(6000px, 1500px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(20deg) scale(4)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-11",
"content": "<p style=\"text-align: center;\">啊!忘了提醒你...</p>",
"data": {
"x": "5000",
"y": "2500",
"scale": 2
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(5000px, 2500px, 0px) rotateX(0deg) rotateY(0deg) rotateZ(0deg) scale(2)",
"transformStyle": "preserve-3d"
}
},
{
"id": "start-12",
"content": "<p style=\"text-align: center;\">你的創作是 <strong>3D*</strong> 的 :)</p>\n<p style=\"text-align: left;\"><span style=\"font-size: 11px;\"> 一起震撼你的觀眾吧!</span></p>",
"data": {
"x": "5350",
"y": "2700",
"z": "-200",
"scale": 2,
"rotateX": "-40",
"rotateY": "10"
},
"style": {
"0": "position",
"1": "transform",
"2": "transform-style",
"position": "absolute",
"transform": "translate(-50%, -50%) translate3d(5350px, 2700px, -200px) rotateX(-40deg) rotateY(10deg) rotateZ(0deg) scale(2)",
"transformStyle": "preserve-3d"
}
}
];
let defaultSlides = new Array();
temp.forEach((s) => {
let _step = new step(s);
defaultSlides.push(_step);
});
export const start = defaultSlides;
|
GeorgioWan/Oi
|
src/example/demo-start.js
|
JavaScript
|
mit
| 9,283
|
const {
FriendshipValidationError
} = require('../../shared/errors');
function formatFriendshipResponse(friendship) {
const clone = { ...friendship };
clone.id = clone._id;
clone.friendId = clone._friend;
clone.userId = clone._user;
delete clone._id;
delete clone._friend;
delete clone._user;
return clone;
}
function handleError(err, next) {
if (err.name === 'ValidationError') {
const error = new FriendshipValidationError();
error.errors = err.errors;
next(error);
return;
}
next(err);
}
module.exports = {
formatFriendshipResponse,
handleError
};
|
stevebrush/giftdibs-api
|
src/routes/friendships/shared.js
|
JavaScript
|
mit
| 602
|
/**
* @file EntryView 入口级别基础类
*
* @author Leo Wang(wangkemiao@baidu.com)
*/
define(function (require) {
var fc = require('fc-core');
/**
* EntryView 入口级别基础类
*/
var overrides = {};
var EntryView = fc.oo.derive(require('./BaseView'), overrides);
return EntryView;
});
|
sdgdsffdsfff/fc-view
|
src/mvc/EntryView.js
|
JavaScript
|
mit
| 332
|
import { CSSLoader, Plugins } from 'jspm-loader-css'
import vars from 'postcss-simple-vars'
import nested from 'postcss-nested'
const {fetch, bundle} = new CSSLoader([
vars,
nested,
Plugins.localByDefault,
Plugins.extractImports,
Plugins.scope,
Plugins.autoprefixer()
], __moduleName);
export {fetch, bundle};
|
josephfinlayson/react-berlin-css-modules
|
public/css.js
|
JavaScript
|
mit
| 336
|
const wallabyWebpack = require('wallaby-webpack');
const webpackConfig = {};
webpackConfig.externals = webpackConfig.externals || {};
webpackConfig.externals['react/lib/ExecutionEnvironment'] = true;
webpackConfig.externals['react/lib/ReactContext'] = true;
webpackConfig.externals['react/addons'] = true;
const wallabyPostprocessor = wallabyWebpack(webpackConfig);
module.exports = function (wallaby) {
return {
testFramework: 'jasmine',
files: [
{pattern: 'src/**/*.ts', load: false},
{pattern: 'src/**/*.tsx', load: false},
],
tests: [
{pattern: 'test/**/*.ts', load: false},
{pattern: 'test/**/*.tsx', load: false}
],
postprocessor: wallabyPostprocessor,
setup: function () {
// required to trigger test loading
window.__moduleBundler.loadTests();
}
};
};
|
OneNoteDev/OneNotePicker-JS
|
wallaby.config.js
|
JavaScript
|
mit
| 802
|
$_QE.prototype.FeatureLookable = function() {
if (this.flag_is_off(EFLAG_IS_INTERACTIVE)) {
$_QE.prototype.FeatureInteractive.call(this);
}
this.flag_set_off(EFLAG_IS_OUTLINE_GLOWABLE);
this.flag_set_off(EFLAG_IS_ENGABLE);
this.flag_set_off(EFLAG_IS_CLICKABLE);
/*__ ___ ___ ___ ___ __ __
/__` |__ | | |__ |__) /__`
.__/ |___ | | |___ | \ .__/ */
/*__ ___ ___ ___ ___ __ __
/ _` |__ | | |__ |__) /__`
\__> |___ | | |___ | \ .__/ */
};
|
utarsuno/quasar_source
|
libraries/front_end_old/inheritable_features/dynamic/interactions/feature_lookable.js
|
JavaScript
|
mit
| 530
|
function Element(tagName, selfClosing) {
this.tagName = tagName;
this.selfClosing = selfClosing || false;
this.attributes = {};
this.children = [];
this._value = '';
return this;
}
Element.prototype.text = function(value) {
if (typeof value === 'undefined') {
return this._value;
} else {
this._value = value.toString();
return this;
}
};
Element.prototype.append = function(item, selfClosing) {
var elem;
selfClosing = selfClosing || false;
if (typeof item === 'string') {
elem = new Element(item, selfClosing);
} else {
elem = item;
}
this.children.push(elem);
return elem;
};
Element.prototype.attr = function(name, value) {
if (arguments.length === 0) {
throw new Error('cannot call "Element.attr()" without arguments');
} else if (arguments.length === 1) {
if (typeof name === 'string') {
// if given a string, return the value for that attribute
return this.attributes[name];
} else if (typeof name === 'object') {
// if given an object, loop through to assign all attrs
for (var key in name) {
this.attributes[key] = name[key];
}
return this;
} else {
// throw an error on any other type of input
throw new TypeError('Element.attr() must be called with a String or Object as the first argument.');
}
} else {
this.attributes[name] = value;
return this;
}
};
Element.prototype.stringify = function(indent) {
if (typeof indent !== 'undefined') {
return tidy(this, indent);
}
var output = '<' + this.tagName;
for (var a in this.attributes) {
output += ' ' + a + '="' + this.attributes[a] + '"';
}
if (this.selfClosing) {
output += ' />';
return output;
}
output += '>';
output += this._value;
if (this.children.length === 0) {
output += '</' + this.tagName + '>';
return output;
}
for (var c = 0; c < this.children.length; c++) {
output += this.children[c].stringify();
}
output += '</' + this.tagName + '>';
return output;
};
xml.element = function(tag, sc) {
return new Element(tag, sc);
};
|
jshanley/xm-el
|
src/element.js
|
JavaScript
|
mit
| 2,004
|
import React from 'react';
import IconBase from 'react-icon-base';
export default class FaMinusCircle extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m30.1 21.4v-2.8q0-0.6-0.4-1t-1-0.5h-17.1q-0.6 0-1 0.5t-0.5 1v2.8q0 0.6 0.5 1t1 0.5h17.1q0.6 0 1-0.5t0.4-1z m7.2-1.4q0 4.7-2.3 8.6t-6.3 6.2-8.6 2.3-8.6-2.3-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3 8.6 2.3 6.3 6.2 2.3 8.6z"/></g>
</IconBase>
);
}
}
|
scampersand/sonos-front
|
app/react-icons/fa/minus-circle.js
|
JavaScript
|
mit
| 518
|
var nut = require('./nut')
var shell = require('./shell') //the shell surrounds the nut
var codec = require('levelup/lib/codec')
var merge = require('xtend')
var ReadStream = require('levelup/lib/read-stream')
var precodec = require('./codec/bytewise')
function id (e) {
return e
}
module.exports = function (db, opts) {
opts = merge(db.options, {
keyEncoding: {
encode: id,
decode: id,
buffer: true
}
}, opts)
return shell ( nut ( db, precodec, codec ), [], ReadStream, opts)
}
|
mafintosh/level-sublevel
|
bytewise.js
|
JavaScript
|
mit
| 524
|
'use strict';
module.exports = function(environment) {
let ENV = {
modulePrefix: 'dummy',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
emberTracker: {
analyticsSettings: {
LOG_PAGEVIEW: true,
LOG_EVENTS: true,
trackingId: 'UA-97028033-2',
onload: false,
afterCreate: 'console.log("test after create");'
},
},
};
if (environment === 'development') {
ENV.emberTracker.LOG_PAGEVIEW = true;
ENV.emberTracker.LOG_EVENTS = true;
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
//ENV.APP.LOG_ACTIVE_GENERATION = false;
//ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
}
if (environment === 'production') {
ENV.locationType = 'hash';
ENV.rootURL = '/ember-tracker/';
}
return ENV;
};
|
tsteuwer/ember-tracker
|
tests/dummy/config/environment.js
|
JavaScript
|
mit
| 1,523
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true }); /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
class ExpectationFailed extends Error {}exports.default = ExpectationFailed;
|
Dagers/React-Native-Differential-Updater
|
App/node_modules/jest-jasmine2/build/expectation_failed.js
|
JavaScript
|
mit
| 1,074
|
'use strict';
var wordNet = require("../src/index.js");
var wn = wordNet(null, true);
var util = require("util");
// get meronyms for finger
wn.fetchSynset("finger.n.1", function(err, synset){
synset.getMeronyms("part", function(err, data){
console.log(util.inspect(data, null, 3));
});
});
|
Planeshifter/node-wordnet-magic
|
examples/meronyms.js
|
JavaScript
|
mit
| 298
|
var db = require('mongo-start')('pages');
module.exports = function (req, res, next) {
var publishDate = new Date();
console.log(publishDate);
db.find({
deletedOn: true
}, function (err, pages) {
console.log(pages);
if(!req.xmsData) {
req.xmsData = {};
}
req.xmsData.queuedPages = pages;
next();
});
}
|
Kevnz/xms
|
lib/middleware/deletedPages.js
|
JavaScript
|
mit
| 382
|
/* Runtime Support for the Pacioli language
*
* Copyright (c) 2013-2018 Paul Griffioen
*
* 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.
*/
var Pacioli = Pacioli || {};
// -----------------------------------------------------------------------------
// 0. Interface
//
// See box.js for other interface functions
// -----------------------------------------------------------------------------
Pacioli.value = function (module, name) {
return new Pacioli.Box(Pacioli.lookupItem("u_glbl_" + module + "_" + name),
Pacioli.lookupItem("glbl_" + module + "_" + name))
}
Pacioli.fun = function (module, name) {
return new Pacioli.Box(Pacioli.lookupItem("u_glbl_" + module + "_" + name),
Pacioli.lookupItem("glbl_" + module + "_" + name))
}
Pacioli.unit = function (name1, name2) {
return new Pacioli.PowerProduct(name2 === undefined ? name1 : name1 + '$' + name2)
}
Pacioli.num = function (num, unit) {
var shape = new Pacioli.Shape ()
if (unit !== undefined) {
shape.multiplier = unit
}
return new Pacioli.Box(new Pacioli.Type("matrix", shape),
Pacioli.tagNumbers([[typeof num === "string" ? parseFloat(num) : num]], 1, 1, 1))
}
Pacioli.tuple = function (array) {
var uTuple = array.map(function (elt) {return elt.type})
var vTuple = array.map(function (elt) {return elt.value})
vTuple.kind = 'tuple'
return new Pacioli.Box(new Pacioli.Type('tuple', uTuple), vTuple)
}
Pacioli.list = function (array) {
var uList = array.length === 0 ? null : array[0].type
var vList = array.map(function (elt) {return elt.value})
vList.kind = 'list'
return new Pacioli.Box(new Pacioli.Type('list', uList), vList)
}
// -----------------------------------------------------------------------------
// 0. Functions used by generated code
// -----------------------------------------------------------------------------
Pacioli.makeIndexSet = function (name, items) {
var indexSet = {
name:name,
items: items,
index: {}
}
for (var i = 0; i < items.length; i++) {
indexSet.index[items[i]] = i
}
return indexSet
}
Pacioli.createCoordinates = function (pairs) {
var names = []
var indexSets = []
for (var i = 0 ; i < pairs.length; i++) {
names[i] = pairs[i][0]
indexSets[i] = Pacioli.lookupItem(pairs[i][1])
}
var coords = new Pacioli.Coordinates(names, indexSets);
// added coords for b_Matrix_make_matrix
return {kind: "coordinates", position: coords.position(), size: coords.size(), coords: coords}
}
Pacioli.scalarShape = function (unit) {
var result = new Pacioli.Shape();
result.multiplier = unit;
return result;
}
Pacioli.zeroNumbers = function (m, n) {
return Pacioli.tagNumbers([], m, n, 1)
}
Pacioli.oneNumbers = function (m, n) {
var numbers = Pacioli.tagNumbers([], m, n, 1)
for (var i = 0; i < m; i++) {
for (var j = 0; j < n; j++) {
Pacioli.set(numbers, i, j, 1)
}
}
return numbers;
}
Pacioli.oneMatrix = function (shape) {
return new Pacioli.Box(new Pacioli.Type("matrix", shape),
Pacioli.oneNumbers(shape.nrRows(), shape.nrColumns()))
}
Pacioli.initialMatrix = function (shape, data) {
return new Pacioli.Box(new Pacioli.Type("matrix", shape),
Pacioli.initialNumbers(shape.nrRows(), shape.nrColumns(), data))
}
Pacioli.initialNumbers = function (m, n, data) {
var numbers = Pacioli.tagNumbers([], m, n, 1)
for (var i = 0; i < data.length; i++) {
Pacioli.set(numbers, data[i][0], data[i][1], data[i][2])
}
return numbers;
}
Pacioli.conversionNumbers = function (shape) {
var numbers = Pacioli.zeroNumbers(shape.nrRows(), shape.nrColumns())
for (var i = 0; i < shape.nrRows(); i++) {
var flat = shape.unitAt(i, i).reciprocal().flat()
if (flat.isDimensionless()) {
Pacioli.set(numbers, i, i, flat.factor)
} else {
/* throw new Error("Cannot convert unit '" +
shape.findColumnUnit(i).toText() +
"' to unit '" +
shape.findRowUnit(i).toText() +
"' for entry '" +
shape.rowCoordinates(i).toText() +
"' during the construction of a matrix of type '" +
shape.toText() +
"'.") */
Pacioli.set(numbers, i, i, "unit conversion error")
}
}
return numbers
}
Pacioli.conversionMatrixType = function (shape) {
return new Pacioli.Type("matrix", shape);
}
Pacioli.printValue = function (x) {
document.body.appendChild(Pacioli.ValueDOM(x))
return x;
}
Pacioli.dimNum = function (a, b) {
return new Pacioli.DimensionedNumber(a, b);
}
// -----------------------------------------------------------------------------
// 1. The Store
// -----------------------------------------------------------------------------
Pacioli.cache = {};
Pacioli.fetchValue = function (home, name) {
return Pacioli.lookupItem("glbl_" + home + "_" + name);
}
Pacioli.bfetchValue = function (home, name) {
return Pacioli.lookupItem("b_glbl_" + home + "_" + name);
}
Pacioli.fetchIndex = function (id) {
return Pacioli.lookupItem("index_" + id);
}
Pacioli.storeIndex = function (id, index) {
Pacioli.cache["index_" + id] = index;
}
// todo: replace unit_ by sbase_
Pacioli.storeScalarBase = function (id, base) {
Pacioli.cache["unit_" + id] = base;
}
// todo: replace unit_ by sbase_
Pacioli.fetchScalarBase = function (id) {
return Pacioli.lookupItem("unit_" + id);
}
// todo: replace unit_ by sbase_
Pacioli.storeVectorBase = function (id, base) {
Pacioli.cache["unitvec_" + id] = base;
}
// todo: replace unit_ by sbase_
Pacioli.fetchVectorBase = function (id) {
return Pacioli.lookupItem("unitvec_" + id);
}
Pacioli.fetchType = function (home, name) {
alert('Who used fetchType?');
return Pacioli.lookupItem("u_glbl_" + home + "_" + name);
}
Pacioli.lookupItem = function (full) {
if (Pacioli.cache[full] == undefined) {
if (Pacioli[full]) {
Pacioli.cache[full] = Pacioli[full];
} else if (Pacioli["compute_" + full]) {
Pacioli.cache[full] = Pacioli["compute_" + full]();
} else {
throw new Error("no function found to compute Pacioli item '" + full + "'");
}
}
return Pacioli.cache[full];
}
|
pgriffel/pacioli
|
src/pacioli-js/api.js
|
JavaScript
|
mit
| 7,643
|
/**
@module ember-flexberry-designer
*/
import Controller from '@ember/controller';
import FdReadonlyProjectMixin from '../mixins/fd-readonly-project';
import FdGroupDropdown from '../mixins/fd-group-dropdown';
import { inject as service } from '@ember/service';
import { A } from '@ember/array';
import { isNone, isBlank } from '@ember/utils';
import { computed } from '@ember/object';
import moment from 'moment';
/**
The controller for the form with a log of generation.
@class FdGenerationListLogController
@extends Ember.Controller
*/
export default Controller.extend(FdReadonlyProjectMixin, FdGroupDropdown, {
/**
Service for managing the state of the sheet component.
@property fdSheetService
@type FdSheetService
*/
fdSheetService: service(),
/**
Value search input.
@property searchValue
@type String
@default ''
*/
searchValue: '',
/**
Sheet component name.
@property sheetComponentName
@type String
@default ''
*/
sheetComponentName: '',
/**
Array groups.
@property groupArray
@type Array
*/
groupArray: computed('i18n.locale', function() {
return A([
'forms.fd-generation.all-states',
'forms.fd-generation.run-caption',
'forms.fd-generation.success-caption',
'forms.fd-generation.error-caption',
'forms.fd-generation.other-caption'
]);
}),
/**
Update model for search
@method filteredModel
*/
filteredModel: computed('model', 'searchValue', function() {
let searchStr = this.get('searchValue');
let model = this.get('model');
if (isBlank(searchStr)) {
return model;
}
searchStr = searchStr.trim().toLocaleLowerCase();
let filterFunction = function(item) {
let data = moment(item.data.get('startTime')).format('DD.MM.YYYY HH:mm:ss');
if (!isNone(data) && data.toLocaleLowerCase().indexOf(searchStr) !== -1) {
return item;
}
};
let newModel = {};
for (let prop in model) {
let newdata = model[prop].filter(filterFunction);
newModel[prop] = A(newdata);
}
return newModel;
}),
init() {
this._super(...arguments);
this.set('groupValueLocale', 'forms.fd-generation.all-states');
},
actions: {
/**
This method will notify all observers that the model changed value.
@method actions.updateModel
*/
updateModel() {
this.notifyPropertyChange('model');
}
}
});
|
Flexberry/ember-flexberry-designer
|
addon/controllers/fd-generation.js
|
JavaScript
|
mit
| 2,467
|
var Client = require('../../client');
module.exports = Client.sub({
"package": require('./appdev/package')
});
|
sanjaymandadi/mozu-node-sdk
|
clients/platform/appdev.js
|
JavaScript
|
mit
| 114
|
function Bullet(x, y, r, ticks)
{
this.model = new Model(bulletModel, x, y, r, 'white');
this.speed = new Point(Math.sin(r), -Math.cos(r)).normalize(12);
this.init = function()
{
this.model.position.add(this.speed.clone().multiply(ticks + 1));
};
this.update = function()
{
this.model.position.add(this.speed);
if(this.parent &&
(this.model.position.x > w ||
this.model.position.x < 0 ||
this.model.position.y > h ||
this.model.position.y < 0))
{
this.parent.removeChild(this);
}
};
this.render = function(ctx)
{
renderModel(ctx, this.model);
};
}
|
HernanRivasAcosta/asteroids
|
web/js/bullet.js
|
JavaScript
|
mit
| 863
|
// OK - cannot affect hostname
location.href = '/foo' + document.location.search;
// NOT OK
location.href = '/' + document.location.search;
// NOT OK
location.href = '//' + document.location.search;
// NOT OK
location.href = '//foo' + document.location.search;
// NOT OK
location.href = 'https://foo' + document.location.search;
|
github/codeql
|
javascript/ql/test/query-tests/Security/CWE-601/ClientSideUrlRedirect/tst10.js
|
JavaScript
|
mit
| 333
|
// Generated by CoffeeScript 1.6.2
(function() {
var DefaultAction,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
DefaultAction = (function() {
/*
Where a route object is defined as:
{
tag: "routeTag"
route: "/route"
method: "GET|PUT|POST|DEL"
handler: RouteFn
}
*/
function DefaultAction(r) {
this.handler = __bind(this.handler, this); this.__r = r;
}
DefaultAction.prototype.handler = function(req, res, next) {
var Aux, CriscoAction,
_this = this;
CriscoAction = req.__crisco.action;
Aux = req.__crisco.aux;
return this.__r.handler(CriscoAction, Aux, function(runDefault) {
if (runDefault == null) {
runDefault = false;
}
if (runDefault) {
return console.log("There is no default action implementation. Skipping...");
} else {
return next();
}
});
};
DefaultAction.prototype.__defineGetter__('route', function() {
return this.__r.route;
});
return DefaultAction;
})();
module.exports = DefaultAction;
}).call(this);
|
classdojo/crisco
|
lib/core/domains.default/action/action.js
|
JavaScript
|
mit
| 1,202
|
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
var mem = [];
while (true) {
var arr = n.toString().split('');
n = arr.reduce(function (pre, current) {
current = parseInt(current);
return pre + current * current;
}, 0);
if (n === 1) return true;
if (mem.indexOf(n) !== -1) {
return false;
}
mem.push(n);
}
};
var eq = require('assert').equal;
eq(isHappy(19), true);
eq(isHappy(18), false);
|
zhiyelee/leetcode
|
js/happyNumber/happy_number.js
|
JavaScript
|
mit
| 480
|
// ----------------------------------------------------------------------
// Fonts
// ----------------------------------------------------------------------
module.exports = (gulp, config, kernel, $) => {
'use strict';
// Config
// ---------------------------------------------------------
// extending default config with project config
Object.assign(config.fonts = {
source: ["/" + config.fonts],
dest: "/fonts",
inputExt: "{ttf,eot,woff,woff2}",
outputExt: "{ttf,eot,woff,woff2}",
regExt: /\.(ttf|eot|woff|woff2)$/
});
// Public
// ---------------------------------------------
let clean = () => {
gulp.task("clean:fonts", () => {
$.del(kernel.setCleanStack("fonts"));
});
};
let create = () => {
gulp.task("fonts", ["clean:fonts"], () => {
gulp.src(kernel.setSourceStack("fonts", config.fonts.inputExt))
.pipe($.rename((filepath) => {
kernel.rewritePath(filepath);
}))
.pipe($.size({
showFiles: true
}))
.pipe(gulp.dest(config.destPublicDir + config.dest));
});
};
// API
// ---------------------------------------------------------
return {
clean: clean(),
create: create()
};
};
|
kreo/nixin-cli
|
tasks/_fonts.js
|
JavaScript
|
mit
| 1,391
|
var common = require('../common/common');
var subModule = require('../general/world-module');
common();
subModule.init({data : 1, page : 'world page.'});
|
soulteary/generator-lazy-demo
|
hello-world/src/js/page/world.js
|
JavaScript
|
mit
| 154
|
"use strict";
let React = require('react');
let Event = require('./event');
let Events = React.createClass({
propTypes: {
events: React.PropTypes.array
},
render: function () {
return (
<div id="events">
<h2><i className="material-icons">event</i> Life Events</h2>
<ul className="list-group">
{this.props.events.map(function (event) {
return <Event key={event.id} event={event}/>;
})}
<li className="list-group-item no-padding">
<a onClick={this.props.onAddEvent} className="btn btn-default btn-lg btn-block">
<i className="material-icons">add</i> Add A Life Event</a>
</li>
</ul>
</div>
);
}
});
module.exports = Events;
|
milianoo/miladrk.com-website
|
src/components/profile/events.js
|
JavaScript
|
mit
| 895
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M10 3H8c0 .37-.04.72-.12 1.06l1.59 1.59C9.81 4.84 10 3.94 10 3zM3 4.27l2.84 2.84C5.03 7.67 4.06 8 3 8v2c1.61 0 3.09-.55 4.27-1.46L8.7 9.97C7.14 11.24 5.16 12 3 12v2c2.71 0 5.19-.99 7.11-2.62l2.5 2.5C10.99 15.81 10 18.29 10 21h2c0-2.16.76-4.14 2.03-5.69l1.43 1.43C14.55 17.91 14 19.39 14 21h2c0-1.06.33-2.03.89-2.84L19.73 21 21 19.73 4.27 3 3 4.27zM14 3h-2c0 1.5-.37 2.91-1.02 4.16l1.46 1.46C13.42 6.98 14 5.06 14 3zm5.94 13.12c.34-.08.69-.12 1.06-.12v-2c-.94 0-1.84.19-2.66.52l1.6 1.6zm-4.56-4.56l1.46 1.46C18.09 12.37 19.5 12 21 12v-2c-2.06 0-3.98.58-5.62 1.56z" />
, 'LeakRemove');
|
kybarg/material-ui
|
packages/material-ui-icons/src/LeakRemove.js
|
JavaScript
|
mit
| 704
|
import Link from 'next/link';
import Page from '../layouts/page';
export default ({children}) => (
<Page>
Home
</Page>
);
|
jorgeherrera1/skill-matrix
|
pages/index.js
|
JavaScript
|
mit
| 131
|
/**
* 程序员工具自己的编辑器
* 可以定义组件 2.0
*/
;(function($) {
var cursor;//光标对象
var defaults = {
//自定义菜单列表
menus: [
{group:[
{type:"eraser",i:'am-icon-eraser',desc:'清除格式',init: function (editor) {
editor.find('.iutilsEditor-tools').on('click','button.eraser',function(){
console.log(cursor.html());
var selObj = getSelectText();
console.log(selObj);
syncData(editor);//同步数据
});
}}
]},
{group:[
{type:"bold",i:'am-icon-bold',desc:'粗体',init: function (editor) {
editor.find('.iutilsEditor-tools').on('click','button.bold',function() {
var $this = $(this);
var selectText = getSelectText();
if(isEleOp(selectText.trim())){
return;
}
if(toolsSelectd($this)){
if(cursor.text()==selectText){
cursor.css("font-weight","bold");
}else{
var html = cursor.html();
html = html.replace(new RegExp(selectText,"gm"),"<span style='font-weight:bold;'>"+selectText+"</span>");
cursor.html(html);
}
}else{
if(cursor.text()==selectText){
cursor.css("font-weight","");
}else{
var html = cursor.html();
html = html.replace(new RegExp("<span style='font-weight:bold;'>"+selectText+"</span>","gm"),selectText);
cursor.html(html);
}
}
syncData(editor);//同步数据
});
}},
{type:"italic",i:'am-icon-italic',desc:'斜体',init: function (editor) {
editor.find('.iutilsEditor-tools').on('click','button.italic',function() {
var $this = $(this);
var selectText = getSelectText();
if(isEleOp(selectText.trim())){
return;
}
if(toolsSelectd($this)){
if(cursor.text()==selectText){
cursor.css("font-style","italic");
}else{
var html = cursor.html();
html = html.replace(new RegExp(selectText,"gm"),"<span style='font-style:italic;'>"+selectText+"</span>");
cursor.html(html);
}
}else{
if(cursor.text()==selectText){
cursor.css("font-style","");
}else{
var html = cursor.html();
html = html.replace(new RegExp("<span style='font-style:italic;'>"+selectText+"</span>","gm"),selectText);
cursor.html(html);
}
}
syncData(editor);//同步数据
});
}},
{type:"underline",i:'am-icon-underline',desc:'下划线',init: function (editor) {
editor.find('.iutilsEditor-tools').on('click','button.underline',function() {
var $this = $(this);
var selectText = getSelectText();
if(isEleOp(selectText.trim())){
return;
}
if(toolsSelectd($this)){
if(cursor.text()==selectText){
cursor.css("text-decoration","underline");
}else{
var html = cursor.html();
html = html.replace(new RegExp(selectText,"gm"),"<span style='text-decoration:underline;'>"+selectText+"</span>");
cursor.html(html);
}
}else{
if(cursor.text()==selectText){
cursor.css("text-decoration","");
}else{
var html = cursor.html();
html = html.replace(new RegExp("<span style='text-decoration:underline;'>"+selectText+"</span>","gm"),selectText);
cursor.html(html);
}
}
syncData(editor);//同步数据
});
}},
{type:"strikethrough",i:'am-icon-strikethrough',desc:'删除线',init: function (editor) {
editor.find('.iutilsEditor-tools').on('click','button.strikethrough',function() {
var $this = $(this);
var selectText = getSelectText();
if(isEleOp(selectText.trim())){
return;
}
if(toolsSelectd($this)){
if(cursor.text()==selectText){
cursor.css("text-decoration","line-through");
}else{
var html = cursor.html();
html = html.replace(new RegExp(selectText,"gm"),"<span style='text-decoration:line-through;'>"+selectText+"</span>");
cursor.html(html);
}
}else{
if(cursor.text()==selectText){
cursor.css("text-decoration","");
}else{
var html = cursor.html();
html = html.replace(new RegExp("<span style='text-decoration:line-through;'>"+selectText+"</span>","gm"),selectText);
cursor.html(html);
}
}
syncData(editor);//同步数据
});
}}
]},
{
group:[
{type:"expand",i:'am-icon-expand',desc:'全屏',init: function (editor) {
editor.find('.iutilsEditor-tools').on('click','button.expand',function(){
var $this = $(this);
if(!$this.hasClass('active')){
$this.addClass("active");
$this.find("i").addClass("am-icon-compress").removeClass("am-icon-expand");
editor.addClass("iutilsEditor-fullscreen");
}else{
$this.removeClass("active");
editor.removeClass("iutilsEditor-fullscreen");
$this.find("i").addClass("am-icon-expand").removeClass("am-icon-compress");
}
});
}}
]
}
]
};
//对外函数
$.fn.createEditor = function (options) {
var settings = $.extend({},defaults, options);
//创建界面
var html = '<div class="iutilsEditor"><div class="iutilsEditor-tools"><div class="am-btn-toolbar">';
for(var i=0;i<settings.menus.length;i++){
var groups = settings.menus[i].group;
html += '<div class="am-btn-group am-btn-group-xs">';
for(var j=0;j<groups.length;j++){
var menu = groups[j];
if(menu.html){
html += '<div class="am-dropdown" data-am-dropdown><button type="button" class="am-btn am-btn-iutils am-dropdown-toggle '+menu.type+'" title="'+menu.desc+'"><i class="'+menu.i+'"></i></button>'+menu.html+'</div>';
}else{
html += '<button type="button" class="am-btn am-btn-iutils '+menu.type+'" title="'+menu.desc+'"><i class="'+menu.i+'"></i></button>';
}
}
html += '</div>';
}
html += '</div></div><div class="iutilsEditor-content" contenteditable="true"></div></div>';
$(html).insertAfter(this);
//隐藏本身
var $this = $(this);
$this.hide();
//编辑器对象
var editor = $this.next();
//初始化菜单绑定
for(var i=0;i<settings.menus.length;i++){
var groups = settings.menus[i].group;
for(var j=0;j<groups.length;j++){
var menu = groups[j];
menu.init && menu.init(editor);
}
}
var editorPanel = editor.find(".iutilsEditor-content");
editorPanel.on('keydown keyup',function(){
$this.val($(this).html());//同步内容
if($(this).html()=="" || $(this).html()=="<br>"){
editorPanel.html("<div><br></div>");
}
});
//初始化内容
editorPanel.html("<div><br></div>");
//监听光标所在的位置
editorPanel.on('click',function(e){
cursor = $(e.target);
});
//绑定下拉事件
$(document.body).on('click','.am-dropdown',function(){
var $this = $(this);
$($this).dropdown('open');
});
//绑定按钮状态监听
editorPanel.mouseup(function(){
var selObj = getSelectObj();
var currentEle=null;//当前元素
if(selObj!=null && selObj.baseNode!=null){
currentEle = $(selObj.baseNode.parentNode);
}
if(currentEle!=null){
var tools = editor.find('.iutilsEditor-tools');
//是否粗体
if(currentEle.css("font-weight")=="bold"){
tools.find('button.bold').addClass("active");
}else{
tools.find('button.bold').removeClass("active");
}
//是否斜体
if(currentEle.css("font-style")=="italic"){
tools.find('button.italic').addClass("active");
}else{
tools.find('button.italic').removeClass("active");
}
//是否下划线
if(currentEle.css("text-decoration")=="underline"){
tools.find('button.underline').addClass("active");
}else{
tools.find('button.underline').removeClass("active");
}
//是否删除线
if(currentEle.css("text-decoration")=="line-through"){
tools.find('button.strikethrough').addClass("active");
}else{
tools.find('button.strikethrough').removeClass("active");
}
//是否居左
if(currentEle.css("text-align")=="left"){
tools.find('button.align-left').addClass("active");
}else{
tools.find('button.align-left').removeClass("active");
}
//是否居中
if(currentEle.css("text-align")=="center"){
tools.find('button.align-center').addClass("active");
}else{
tools.find('button.align-center').removeClass("active");
}
//是否居右
if(currentEle.css("text-align")=="right"){
tools.find('button.align-right').addClass("active");
}else{
tools.find('button.align-right').removeClass("active");
}
}
});
};
//工具栏选中状态
function toolsSelectd($this){
if(!$this.hasClass('active')){
$this.addClass("active");
return true;
}else{
$this.removeClass("active");
return false;
}
}
//判断当前节点是否可以操作
function isEleOp(selectText){
if(!cursor.hasClass("iutilsEditor-content") && !cursor.hasClass("no-op") && selectText!=""){
return false;//可操作
}else{
return true;//不可操作
}
}
//同步数据
function syncData(editor){
var content = editor.find(".iutilsEditor-content");//内容对象
var textarea = editor.prev();//源码存放对象
textarea.val(content.html());//同步表单内容
}
//获取选中的对象
function getSelectObj(){
var selObj;
if (window.getSelection) {
selObj = window.getSelection();
} else if (window.document.getSelection) {
selObj = window.document.getSelection();
} else if (window.document.selection) {
selObj = window.document.selection.createRange();
}
return selObj;
}
//获取选中的文字
function getSelectText(){
var selObj=null,text=null;
if (window.getSelection) {
selObj = window.getSelection();
} else if (window.document.getSelection) {
selObj = window.document.getSelection();
} else if (window.document.selection) {
selObj = window.document.selection.createRange();
}
if(selObj!=null){
text = selObj.toString();
}
return text;
}
})(jQuery);
|
iutils/iutils-editor
|
js/iutils.editor.2.0.js
|
JavaScript
|
mit
| 14,086
|
var jsdom = require('jsdom'),
shelljs = require('shelljs'),
format = require("string-template"),
grunt = require('grunt');
var moment = require('moment');
var util = require('../util/util');
// TODO: make files in tmp dir and then move to path relativ to current working directory
module.exports = {
html: function(data, options, generatedContent, callback){
grunt.log.subhead('Processing html for: ', data.id);
grunt.log.subhead(util.constants.tabs.equals);
var dateString = moment().format("MMMM Do YYYY, h:mm:ss A zz");
var currentDir = __dirname +'/' ;
//grunt.file.copy(currentDir+ '../template/html', '.reports');
var indexPath = currentDir +'template/html/index.html';
var html = grunt.file.read(indexPath);
//console.log(shelljs.pwd());
//var window = jsdom.jsdom().parentWindow;
/* parse the html and create a dom window */
var _jsdom = require('jsdom').jsdom(html, null, {
// standard options: disable loading other assets
// or executing script tags
FetchExternalResources: false,
ProcessExternalResources: false,
MutationEvents: false,
QuerySelector: false
});
var window = _jsdom.parentWindow;
jsdom.jQueryify(window, 'http://code.jquery.com/jquery-2.1.1.js', function () {
window.$('#template-doc-title').text(options.title);
window.$('.template-overview-table-elm').remove();
window.$('#template-date').text(dateString);
generatedContent.results.forEach(function(result){
var rowTemplate = '<tr class="template-overview-table-elm {thresholdMarker}"><td><a href="#">{id}</a></td><td>{score}</td></tr>';
var row = format(rowTemplate, result);
window.$('#template-overview-table-body').append(row);
});
window.$('.jsdom').remove();
var indexFile = window.document.documentElement.outerHTML;
grunt.file.write(indexPath, indexFile);
callback(generatedContent);
});
}
};
|
lwhiteley/grunt-pagespeed-report
|
tasks/config/reporters/html.js
|
JavaScript
|
mit
| 2,012
|
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
collectCoverage: true,
collectCoverageFrom: ['src/**/*.ts', '!src/WriterT.ts'],
transform: {
'^.+\\.tsx?$': 'ts-jest'
},
testRegex: 'test',
moduleFileExtensions: ['ts', 'js'],
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100
}
},
modulePathIgnorePatterns: ['util']
}
|
gcanti/fp-ts
|
jest.config.js
|
JavaScript
|
mit
| 429
|
'use strict';
import {
NativeModules,
DeviceEventEmitter,
} from 'react-native';
const WebRTCModule = NativeModules.WebRTCModule;
import base64 from 'base64-js'
import EventTarget from 'event-target-shim'
import MessageEvent from './MessageEvent'
import RTCDataChannelEvent from './RTCDataChannelEvent'
type RTCDataChannelInit = {
ordered?: boolean;
maxPacketLifeTime?: number;
maxRetransmits?: number;
protocol?: string;
negotiated?: boolean;
id?: number;
// deprecated:
maxRetransmitTime?: number,
};
type RTCDataChannelState =
'connecting' |
'open' |
'closing' |
'closed';
const dataChannelIds = new Set();
let nextDataChannelId = 0;
const DATA_CHANNEL_EVENTS = [
'open',
'message',
'bufferedamountlow',
'close',
'error',
];
class ResourceInUse extends Error {}
class RTCDataChannel extends EventTarget(DATA_CHANNEL_EVENTS) {
binaryType: 'arraybuffer' = 'arraybuffer'; // we only support 'arraybuffer'
bufferedAmount: number = 0;
bufferedAmountLowThreshold: number = 0;
id: string;
label: string;
maxPacketLifeTime: ?number = null;
maxRetransmits: ?number = null;
negotiated: boolean = false;
ordered: boolean = true;
protocol: string = '';
readyState: RTCDataChannelState = 'connecting';
onopen: ?Function;
onmessage: ?Function;
onbufferedamountlow: ?Function;
onerror: ?Function;
onclose: ?Function;
constructor(peerConnectionId: number, label: string, options?: ?RTCDataChannelInit) {
super();
if (options && 'id' in options) {
if (typeof options.id !== 'number') {
throw new TypeError('DataChannel id must be a number: ' + options.id);
}
if (dataChannelIds.contains(options.id)) {
throw new ResourceInUse('DataChannel id already in use: ' + options.id);
}
this.id = options.id;
} else {
this.id = nextDataChannelId++;
}
dataChannelIds.add(this.id);
this.label = label;
if (options) {
this.ordered = !!options.ordered;
this.maxPacketLifeTime = options.maxPacketLifeTime;
this.maxRetransmits = options.maxRetransmits;
this.protocol = options.protocol || '';
this.negotiated = !!options.negotiated;
}
WebRTCModule.dataChannelInit(peerConnectionId, this.id, label, options);
this._registerEvents();
}
send(data: string | ArrayBuffer | ArrayBufferView) {
if (typeof data === 'string') {
WebRTCModule.dataChannelSend(this.id, data, 'text');
return;
}
if (ArrayBuffer.isView(data)) {
data = data.buffer;
}
if (!(data instanceof ArrayBuffer)) {
throw new TypeError('Data must be either string, ArrayBuffer, or ArrayBufferView');
}
WebRTCModule.dataChannelSend(this.id, base64.fromByteArray(new Uint8Array(data)), 'binary');
}
close() {
if (this.readyState === 'closing' || this.readyState === 'closed') {
return;
}
this.readyState = 'closing';
WebRTCModule.dataChannelClose(this.id);
}
_unregisterEvents() {
this._subscriptions.forEach(e => e.remove());
this._subscriptions = [];
}
_registerEvents() {
this._subscriptions = [
DeviceEventEmitter.addListener('dataChannelStateChanged', ev => {
if (ev.id !== this.id) {
return;
}
this.readyState = ev.state;
if (this.readyState === 'open') {
this.dispatchEvent(new RTCDataChannelEvent('open', {channel: this}));
} else if (this.readyState === 'close') {
this.dispatchEvent(new RTCDataChannelEvent('close', {channel: this}));
this._unregisterEvents();
}
}),
DeviceEventEmitter.addListener('dataChannelReceiveMessage', ev => {
if (ev.id !== this.id) {
return;
}
let data = ev.data;
if (ev.type === 'binary') {
data = base64.toByteArray(ev.data).buffer;
}
this.dispatchEvent(new MessageEvent('message', {data}));
}),
];
}
}
module.exports = RTCDataChannel;
|
srikanthkh/react-native-webrtc
|
RTCDataChannel.js
|
JavaScript
|
mit
| 4,006
|
// Visualize which strokes were classified
function visualizeSymbolStrokes(tag) {
var strokes = tag.getAttribute('data-strokes').split(',').map(function(item) {
return parseInt(item, 10);
});;
var svgDoc = tag.contentDocument;
console.log(strokes);
for (var i = 100 - 1; i >= 0; i--) {
var stroke = svgDoc.getElementById('stroke'+i);
//console.log(stroke);
if (stroke) {
if (strokes.indexOf(i) > -1) {
stroke.style.stroke = '#ff0000';
} else {
stroke.style.stroke = '#000000';
}
//stroke.style.fill = '#000000';
//console.log("done");
};
};
//svgDoc.getElementById('stroke'+stroke_id).style.stroke
}
|
MartinThoma/write-math
|
website/js/symbolstrokes.js
|
JavaScript
|
mit
| 760
|
goog.provide('gmf.ObjecteditinggetwmsfeatureController');
goog.provide('gmf.objecteditinggetwmsfeatureDirective');
goog.require('gmf');
goog.require('gmf.ObjectEditingQuery');
/**
* When activated, this directive registers clicks on an OL3 map and use the
* clicked coordinate to fetch a feature using the ObjectEditing query service.
* A feature returned is pushed to a collection.
*
* Example:
*
* <gmf-objecteditinggetwmsfeature
* gmf-objecteditinggetwmsfeature-active="ctrl.active"
* gmf-objecteditinggetwmsfeature-features="ctrl.features"
* gmf-objecteditinggetwmsfeature-layerinfo="ctrl.layerInfo"
* gmf-objecteditinggetwmsfeature-map="::ctrl.map">
* </gmf-objecteditinggetwmsfeature>
*
* @htmlAttribute {boolean} gmf-objecteditinggetwmsfeature-active Whether the
* directive is active or not.
* @htmlAttribute {ol.Collection} gmf-objecteditinggetwmsfeature-features
* The collection of features where to add those created by this directive.
* @htmlAttribute {gmf.ObjectEditingQuery.QueryableLayerInfo} gmf-objecteditinggetwmsfeature-layerinfo Queryable layer info.
* @htmlAttribute {ol.Map} gmf-objecteditinggetwmsfeature-map The map.
* @return {angular.Directive} The directive specs.
* @ngInject
* @ngdoc directive
* @ngname gmfObjecteditinggetwmsfeature
*/
gmf.objecteditinggetwmsfeatureDirective = function() {
return {
controller: 'GmfObjecteditinggetwmsfeatureController',
scope: {
'active': '=gmfObjecteditinggetwmsfeatureActive',
'features': '<gmfObjecteditinggetwmsfeatureFeatures',
'layerInfo': '=gmfObjecteditinggetwmsfeatureLayerinfo',
'map': '<gmfObjecteditinggetwmsfeatureMap'
},
bindToController: true,
controllerAs: 'gwfCtrl'
};
};
gmf.module.directive(
'gmfObjecteditinggetwmsfeature',
gmf.objecteditinggetwmsfeatureDirective);
/**
* @param {!angular.Scope} $scope Scope.
* @param {gmf.ObjectEditingQuery} gmfObjectEditingQuery GMF ObjectEditing
* query service.
* @constructor
* @ngInject
* @ngdoc controller
* @ngname GmfObjecteditinggetwmsfeatureController
*/
gmf.ObjecteditinggetwmsfeatureController = function($scope,
gmfObjectEditingQuery) {
// Scope properties
/**
* @type {boolean}
* @export
*/
this.active;
$scope.$watch(
function() {
return this.active;
}.bind(this),
this.handleActiveChange_.bind(this)
);
/**
* @type {ol.Collection}
* @export
*/
this.features;
/**
* @type {gmf.ObjectEditingQuery.QueryableLayerInfo}
* @export
*/
this.layerInfo;
/**
* @type {ol.Map}
* @export
*/
this.map;
// Injected properties
/**
* @type {gmf.ObjectEditingQuery}
* @private
*/
this.gmfObjectEditingQuery_ = gmfObjectEditingQuery;
};
/**
* @param {boolean} active Active.
* @private
*/
gmf.ObjecteditinggetwmsfeatureController.prototype.handleActiveChange_ = function(
active
) {
if (active) {
ol.events.listen(
this.map,
ol.MapBrowserEvent.EventType.CLICK,
this.handleMapClick_,
this
);
} else {
ol.events.unlisten(
this.map,
ol.MapBrowserEvent.EventType.CLICK,
this.handleMapClick_,
this
);
}
};
/**
* @param {ol.MapBrowserEvent} evt Event.
* @private
*/
gmf.ObjecteditinggetwmsfeatureController.prototype.handleMapClick_ = function(
evt
) {
this.gmfObjectEditingQuery_.getFeatureInfo(
this.layerInfo,
evt.coordinate,
this.map
).then(function(feature) {
if (feature) {
this.features.push(feature);
}
}.bind(this));
};
gmf.module.controller(
'GmfObjecteditinggetwmsfeatureController',
gmf.ObjecteditinggetwmsfeatureController);
|
kalbermattenm/ngeo
|
contribs/gmf/src/directives/objecteditinggetwmsfeature.js
|
JavaScript
|
mit
| 3,724
|
#!/usr/bin/env node
/**
* Module dependencies.
*/
const
reg_delmiter = /\-/ig,
under = require('underscore'),
valtree = require('valtree'),
path = require('path'),
fs = require('fs'),
util = require('util'),
tty = process.stdin.isTTY,
Templatefy = require('./templatefy'),
options = {};
under.each(under.extend(require('nomnom')
/**
* Command line options.
*/
.script("templatefy")
.help('' +
' █████████╗███████╗███╗ ███╗██████╗ ██╗ █████╗ ████████╗███████╗███████╗██╗ ██╗ \n' +
' ███╔═██╔══╝╚══════╝████╗ ████║██╔══██╗██║ ██╔══██╗╚══██╔══╝██╔════╝██╔════╝╚██╗ ██╔╝ \n' +
' ╚══╝ ██║ █████╗ ██╔████╔██║██████╔╝██║ ███████║ ██║ █████╗ █████╗ ╚████╔╝ \n' +
' ██║ ╚════╝ ██║╚██╔╝██║██╔═══╝ ██║ ██╔══██║ ██║ ██╔══╝ ██╔══╝ ╚██╔╝ \n' +
' ██║ ███████╗██║ ╚═╝ ██║██║ ███████╗██║ ██║ ██║ ███████╗██║ ██║ \n' +
' ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ \n')
.option('input', {
abbr: 'i',
help: 'Input html file or string template',
required: tty,
trasnform: function(value) {
console.log(value);
return tty ? value : process.stdin;
}
})
.option('output', {
abbr: 'o',
help: 'Output compiled JavaScript file templated'
})
.option('scope', {
abbr: 's',
flag: true,
default: false,
help: 'Enable scope function to prevent collition declarations'
})
.option('exports', {
abbr: 'e',
flag: true,
default: false,
help: 'Exports the template using commonjs module exports'
})
.option('var', {
abbr: 'r',
help: 'Store the template into a variable'
})
.option('global', {
abbr: 'g',
help: 'Store the template into a global property <global:property>'
})
.option('angular', {
abbr: 'a',
flag: true,
default: Templatefy.defaults.angular,
help: 'Enable Angular templateCache injection; for angular options use --angular-<option-name>',
transform: function(value){
return value === true ? {} : false;
}
})
.option('linter', {
abbr: 'l',
flag: true,
default: Templatefy.defaults.linter,
help: 'Enable Linter validation; for linter options use --linter-<option-name>',
transform: function(value){
return value === true ? {} : false;
}
})
.option('minify', {
abbr: 'm',
flag: true,
default: Templatefy.defaults.minify,
help: 'Enable log ouput; for log options use --minify-<option-name>',
transform: function(value){
return value === true ? {} : false;
}
})
.option('log', {
abbr: 'V',
flag: true,
default: !Templatefy.defaults.log,
help: 'Enable log trace; for log options use --log-<option-name>'
})
.option('version', {
abbr: 'v',
flag: true,
help: 'Print version and exit',
callback: function() {
return util.format("Version v%s", Templatefy.version);
}
})
.parse(), {
_input: null,
_output: null
}), function(val, key, opts) {
switch(true){
case key === '_input':
options.input = opts.input ? opts.input : 'stdin';
break;
case key === '_output':
options.output = opts.output ? opts.output : 'stdout';
break;
default:
valtree(options, key.replace(reg_delmiter, '.'), val);
break;
}
});
module.exports = Templatefy.parse(options, options.input, options.output);
|
rubeniskov/templatefy
|
lib/templatefy-cli.js
|
JavaScript
|
mit
| 4,986
|
//~ name c452
alert(c452);
//~ component c453.js
|
homobel/makebird-node
|
test/projects/large/c452.js
|
JavaScript
|
mit
| 52
|
const cheerio = require('cheerio');
const Moment = require('moment');
const Park = require('../park');
const Location = require('../location');
const sParkAPIBase = Symbol('Phantasialand API Base URL');
const sParkAccessToken = Symbol('Phantasialand Access Token');
const sLongMin = Symbol('Minimum Random Longitude');
const sLongMax = Symbol('Maximum Random Longitude');
const sLatMin = Symbol('Minimum Random Latitude');
const sLatMax = Symbol('Maximum Random Latitude');
const sCalendarURL = Symbol('Phantasialand Calendar URL');
const sLangPref = Symbol('Language Preferences');
/**
* Implements the Phantasialand API framework.
* @class
* @extends Park
*/
class Phantasialand extends Park {
/**
* Create new Phantasialand Object.
* @param {Object} [options]
* @param {String} [options.apiBase] Optional base URL for API requests
*/
constructor(options = {}) {
options.name = options.name || 'Phantasialand';
// Phantasialand Entrance coordinates
options.latitude = options.latitude || 50.798954;
options.longitude = options.longitude || 6.879314;
// park's timezone
options.timezone = 'Europe/Berlin';
super(options);
this[sParkAPIBase] = options.apiBase || 'https://api.phlsys.de/api/';
this[sParkAccessToken] = options.accessToken || 'c4BG0WOePBG81MCrEewa0biBBUnoIOhUcTqUxUnWgBXvCUpEV9OCBxaMHQhwegRu';
this[sLongMin] = options.longitudeMin || 6.878342628;
this[sLongMax] = options.longitudeMax || 6.877570152;
this[sLatMin] = options.latitudeMin || 50.800659529;
this[sLatMax] = options.latitudeMax || 50.799683077;
this[sCalendarURL] = options.calendarURL || 'https://www.phantasialand.de/en/theme-park/opening-hours/';
this[sLangPref] = options.langPref || ['en', 'de'];
}
FetchPOIData() {
const PickName = (title) => {
const n = this[sLangPref].find(lang => title[lang]);
return n !== undefined ? title[n] : title;
};
return this.HTTP({
url: `${this[sParkAPIBase]}pois?filter[where][seasons][like]=%25SUMMER%25&compact=true&access_token=auiJJnDpbIWrqt2lJBnD8nV9pcBCIprCrCxaWettkBQWAjhDAHtDxXBbiJvCzkUf`,
method: 'GET',
data: {
compact: true,
access_token: this[sParkAccessToken],
},
}).then((data) => {
const rides = {};
data.forEach((ride) => {
const location = (ride.entrance && ride.entrance.world) ? ride.entrance.world : undefined;
rides[ride.id] = {
name: PickName(ride.title),
meta: {
area: PickName(ride.area),
longitude: location ? location.lng : null,
latitude: location ? location.lat : null,
},
};
});
return Promise.resolve(rides);
});
}
GetPOIData() {
// cache POI data for 2 days
return this.Cache.Wrap('POI', () => {
return this.FetchPOIData();
}, 60 * 60 * 48);
}
FetchWaitTimes() {
return this.GetPOIData().then((poi) => {
// generate random point within Phantasialand
const RandomLocation = Location.RandomBetween(this[sLongMin], this[sLatMin], this[sLongMax], this[sLatMax]);
return this.HTTP({
url: `${this[sParkAPIBase]}signage-snapshots`,
method: 'GET',
data: {
loc: `${RandomLocation.latitude},${RandomLocation.longitude}`,
compact: true,
access_token: this[sParkAccessToken],
},
}).then((rideData) => {
rideData.forEach((ride) => {
if (poi[ride.poiId]) {
const ridePOI = poi[ride.poiId];
let waitTime = -1;
if (ride.open && ride.waitTime !== null) {
// eslint-disable-next-line prefer-destructuring
waitTime = ride.waitTime;
}
this.UpdateRide(ride.poiId, {
name: ridePOI.name,
meta: ridePOI.meta,
waitTime,
});
}
});
return Promise.resolve();
});
});
}
FetchOpeningTimes() {
return this.HTTP({
url: this[sCalendarURL],
mock: 'phantasialand_calendarHTML',
}).then((html) => {
const $ = cheerio.load(html);
const timeRegex = /(\d+%3A\d+)/g;
const calendarData = JSON.parse($('.phl-date-picker').attr('data-calendar'));
calendarData.forEach((timeseries) => {
const timesMatch = timeseries.title.match(timeRegex);
if (timesMatch !== null) {
this.Schedule.SetRange({
startDate: Moment.tz(timeseries.startDate, 'YYYY-MM-DD', this.Timezone),
endDate: Moment.tz(timeseries.endDate, 'YYYY-MM-DD', this.Timezone),
openingTime: Moment.tz(timesMatch[0].replace('%3A', ':'), 'HH:mm', this.Timezone),
closingTime: Moment.tz(timesMatch[1].replace('%3A', ':'), 'HH:mm', this.Timezone),
});
} else {
this.Schedule.SetRange({
startDate: Moment.tz(timeseries.startDate, 'YYYY-MM-DD', this.Timezone),
endDate: Moment.tz(timeseries.endDate, 'YYYY-MM-DD', this.Timezone),
openingTime: null,
closingTime: null,
type: 'Closed',
});
}
});
return Promise.resolve();
});
}
}
module.exports = Phantasialand;
|
cubehouse/themeparks
|
lib/phantasialand/phantasialand.js
|
JavaScript
|
mit
| 5,262
|
'use strict';
require('mocha');
require('co-mocha');
const chai = require('chai');
const assert = require('chai').assert;
const r = require('rethinkdbdash')({
db: process.env.MCDB || 'materialscommons',
port: process.env.MCDB_PORT || 30815
});
const backend_base = '../../../..';
const dbModelUsers = require(backend_base + '/servers/mcapi/db/model/users');
const projects = require(backend_base + '/servers/mcapi/db/model/projects');
const directories = require(backend_base + '/servers/mcapi/db/model/directories');
const base_user_id = 'thisIsAUserForTestingONLY!';
const fullname = "Test User";
const base_project_name = "Test project - test 1: ";
let random_name = function () {
let number = Math.floor(Math.random() * 10000);
return base_project_name + number;
};
let userId = "test@test.mc";
describe('Feature - projects: ', function () {
describe('Create project', function () {
it('create project and get project back', function* () {
let user = yield dbModelUsers.getUser(userId);
let project_name = random_name();
assert.isNotNull(user, "test user exists");
let attrs = {
name: project_name,
description: "This is a test project for automated testing."
};
let ret = yield projects.createProject(user, attrs);
let project = ret.val;
assert.equal(project.otype, "project");
assert.equal(project.name, project_name);
assert.equal(project.owner, user.id);
assert.equal(project.owner, userId);
assert.equal(project.users.length, 1);
assert.equal(project.users[0].user_id, userId);
});
it('create project and find project in all projects', function* () {
let user = yield dbModelUsers.getUser(userId);
let project_name = random_name();
assert.isNotNull(user, "test user exists");
let attrs = {
name: project_name,
description: "This is a test project for automated testing."
};
let ret = yield projects.createProject(user, attrs);
let project = ret.val;
assert.equal(project.name, project_name);
assert.equal(project.users[0].user_id, userId);
let project_list = yield projects.all();
let found_project = null;
project_list.forEach(function (p) {
if (p.name === project_name) {
found_project = p;
}
});
assert.isNotNull(found_project);
assert.equal(found_project.otype, "project");
assert.equal(found_project.owner, user.id);
assert.equal(found_project.owner, userId);
});
it('create project and find project by user', function* () {
let user = yield dbModelUsers.getUser(userId);
let project_name = random_name();
assert.isNotNull(user, "test user exists");
let attrs = {
name: project_name,
description: "This is a test project for automated testing."
};
let ret = yield projects.createProject(user, attrs);
let project = ret.val;
assert.equal(project.name, project_name);
assert.equal(project.users[0].user_id, userId);
let project_list = yield projects.forUser(user);
let found_project = null;
project_list.forEach(function (p) {
if (p.name === project_name) {
found_project = p;
}
});
assert.isNotNull(found_project);
assert.equal(found_project.otype, "project");
assert.equal(found_project.owner, user.id);
assert.equal(found_project.owner, userId);
assert.equal(found_project.users.length, 1);
// NOTE: field is user, here, but user_id in test above!!!
// is this the correct behaivor???
assert.equal(found_project.users[0].user_id, userId);
});
it('create project, find by user, has full set of properties', function* () {
let user = yield dbModelUsers.getUser(userId);
let project_name = random_name();
assert.isNotNull(user, "test user exists");
let attrs = {
name: project_name,
description: "This is a test project for automated testing."
};
let ret = yield projects.createProject(user, attrs);
let project = ret.val;
let project_list = yield projects.forUser(user);
let found_project = null;
project_list.forEach(function (p) {
if (p.name === project_name) {
found_project = p;
}
});
assert.isNotNull(found_project);
assert.equal(found_project.otype, "project");
assert.equal(found_project.owner, user.id);
assert.equal(found_project.owner, userId);
assert.equal(found_project.users.length, 1);
assert.equal(found_project.users[0].user_id, userId);
assert.isTrue(found_project.hasOwnProperty('processes'));
assert.isTrue(found_project.hasOwnProperty('samples'));
assert.isTrue(found_project.hasOwnProperty('files'));
assert.isTrue(found_project.hasOwnProperty('experiments'));
assert.equal(found_project.processes, 0);
assert.equal(found_project.samples, 0);
assert.equal(found_project.files, 0);
assert.equal(found_project.experiments, 0);
});
});
describe('Update project', function () {
it('create project, update name and description', function* () {
let user = yield dbModelUsers.getUser(userId);
let project_name = random_name();
assert.isNotNull(user, "test user exists");
let attrs = {
name: project_name,
description: "This is a test project for automated testing."
};
let ret = yield projects.createProject(user, attrs);
let project = ret.val;
assert.equal(project.otype, "project");
assert.equal(project.name, project_name);
assert.equal(project.owner, userId);
let top_directory = yield directories.get(project.id, 'top');
assert.equal(top_directory.otype, "directory");
assert.equal(top_directory.name, project_name);
let name = random_name();
let description = "An alternate description";
let update_attrs = {
name: name,
description: description
};
let updated_project = yield projects.update(project.id, update_attrs);
assert.equal(updated_project.otype, "project");
assert.equal(updated_project.owner, userId);
assert.equal(updated_project.name, name);
assert.equal(updated_project.description, description);
top_directory = yield directories.get(project.id, 'top');
assert.equal(top_directory.otype, "directory");
assert.equal(top_directory.name, name);
});
});
});
|
materials-commons/materialscommons.org
|
backend/tests/mcapi/Database-Level/specs/projects-spec.js
|
JavaScript
|
mit
| 7,382
|
/**
* This module defines the commands an e2e test client may execute against keystone's item edit form screen.
* When using the assertElement* commands, you may specify one of the predefined element selector properties
* by prefixing it with the '@' sign or you can specify a string representing your own element selector.
* See {@link https://github.com/keystonejs/keystone/tree/master/test/e2e/adminUI/tests/group005Item|usage example},
* {@link https://github.com/keystonejs/keystone/tree/master/test/e2e/adminUI/tests/group006Fields|usage example}
*
* @module adminUIItemScreen
*/
module.exports = {
commands: [{
/**
* Sets a default model test config object so that tests do not have to pass it in with each field level command.
* Tests can still override the default model test config object when calling any field level command.
*
* @param {Object} modelTestConfig The model test config that should be used by field level commands, if the
* command does not pass it in directly.
*/
setDefaultModelTestConfig: function (modelTestConfig) {
this.defaultModelTestConfig = modelTestConfig;
return this;
},
/**
* Asserts that the specified edit item screen element UI is visible.
*
* @param {Object} config The config spec.
* @param {string} config.element The element whose UI should be visible.
*/
assertElementIsVisible: function (config) {
if (config) {
if (config.element) {
this.expect.element(config.element).to.be.visible;
} else {
throw new Error('adminUIItemScreen:must specify an element!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified edit item screen element UI is not visible.
*
* @param {Object} config The config spec.
* @param {string} config.element The element whose UI should not be visible.
*/
assertElementIsNotVisible: function (config) {
if (config) {
if (config.element) {
this.expect.element(config.element).to.not.be.visible;
} else {
throw new Error('adminUIItemScreen:must specify an element!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified edit item screen element DOM is present.
*
* @param {Object} config The config spec.
* @param {string} config.element The element whose DOM should be present.
*/
assertElementIsPresent: function (config) {
if (config) {
if (config.element) {
this.expect.element(config.element).to.be.present;
} else {
throw new Error('adminUIItemScreen:must specify an element!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified edit item screen element DOM is not present.
*
* @param {Object} config The config spec.
* @param {string} config.element The element whose DOM should not be present.
*/
assertElementIsNotPresent: function (config) {
if (config) {
if (config.element) {
this.expect.element(config.element).to.not.be.present;
} else {
throw new Error('adminUIItemScreen:must specify an element!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified edit item screen element text equals the specified value.
*
* @param {Object} config The config spec.
* @param {string} config.element The element whose text should be compared to the input text.
* @param {String} config.text The text to compare against.
*/
assertElementTextEquals: function (config) {
if (config) {
if (config.element && config.text) {
this.expect.element(config.element).text.to.equal(config.text);
} else {
throw new Error('adminUIItemScreen:must specify an element and text!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified edit item screen element text not equals the specified value.
*
* @param {Object} config The config spec.
* @param {string} config.element The element whose text should be compared to the input text.
* @param {String} config.text The text to compare against.
*/
assertElementTextNotEquals: function (config) {
if (config) {
if (config.element && config.text) {
this.expect.element(config.element).text.to.not.equal(config.text);
} else {
throw new Error('adminUIItemScreen:must specify an element and text!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified edit item screen element text contains the specified value.
*
* @param {Object} config The config spec.
* @param {string} config.element The element whose text should contain the input text.
* @param {String} config.text The text to compare against.
*/
assertElementTextContains: function (config) {
if (config) {
if (config.element && config.text) {
this.expect.element(config.element).text.to.contain(config.text);
} else {
throw new Error('adminUIItemScreen:must specify an element and text!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified edit item screen element has the specified attribute.
*
* @param {Object} config The config spec.
* @param {string} config.element The element whose UI should be visible.
* @param {string} config.attribute The attribute that should be present in the element.
* @param {string} config.value The value that the attribute should have.
*/
assertElementHasAttribute: function (config) {
if (config) {
if (config.element && config.attribute && config.value) {
this.expect.element(config.element).to.have.attribute(config.attribute).which.contains(config.value);
} else {
throw new Error('adminUIItemScreen:must specify a config element, attribute, and value!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified item field's UI is visible in the edit item screen. This command calls into the
* assertFieldUIVisible command of the field under test, which gets passed the field.options.
*
* @param {Object} config The config spec.
* @param {array} config.fields The array of fields to assert the UI visibility on.
* @param {String} config.field.name The name of the field under test.
* @param {Object} config.field.modelTestConfig The model test config that should be used for the field under test.
* @param {Object} config.field.options Any options required by the field test object command assertFieldUIVisible.
*/
assertFieldUIVisible: function (config) {
var browser = this;
var form = this.section.form;
if (config) {
if (config.fields) {
config.fields.forEach(function (field) {
var ModelTestConfig = field.modelTestConfig || browser.defaultModelTestConfig;
if (ModelTestConfig) {
form.section.list = new ModelTestConfig({ formSelector: form.selector });
if (form.section.list) {
var fieldTestObject = form.section.list[field.name];
if (fieldTestObject) {
if (fieldTestObject.commands && 'assertFieldUIVisible' in fieldTestObject.commands) {
form.section.list[field.name].commands.assertFieldUIVisible(browser, field.options);
} else {
throw new Error('adminUIItemScreen:assertFieldUIVisible command not defined in ' + field.name + ' field test object!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldUIVisible: invalid field name!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldUIVisible: invalid field modelTestConfig!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldUIVisible: No modelTestConfig given!');
}
});
} else {
throw new Error('adminUIItemScreen:assertFieldUIVisible: Invalid fields specification!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified item field's UI is not visible in the edit item screen. This command calls into the
* assertFieldUINotVisible command of the field under test, which gets passed the field.options.
*
* @param {Object} config The config spec.
* @param {array} config.fields The array of fields to assert the UI visibility on.
* @param {String} config.field.name The name of the field under test.
* @param {Object} config.field.modelTestConfig The model test config that should be used for the field under test.
* @param {Object} config.field.options Any options required by the field test object command assertFieldUINotVisible.
*/
assertFieldUINotVisible: function (config) {
var browser = this;
var form = this.section.form;
if (config) {
if (config.fields) {
config.fields.forEach(function (field) {
var ModelTestConfig = field.modelTestConfig || browser.defaultModelTestConfig;
if (ModelTestConfig) {
form.section.list = new ModelTestConfig({ formSelector: form.selector });
if (form.section.list) {
var fieldTestObject = form.section.list[field.name];
if (fieldTestObject) {
if (fieldTestObject.commands && 'assertFieldUINotVisible' in fieldTestObject.commands) {
form.section.list[field.name].commands.assertFieldUINotVisible(browser, field.options);
} else {
throw new Error('adminUIItemScreen:assertFieldUINotVisible command not defined in ' + field.name + ' field test object!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldUINotVisible: invalid field name!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldUINotVisible: invalid field modelTestConfig!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldUINotVisible: No modelTestConfig given!');
}
});
} else {
throw new Error('adminUIItemScreen:assertFieldUINotVisible: Invalid fields specification!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified item field's DOM is present in the edit item screen. This command calls into the
* assertFieldDOMPresent command of the field under test, which gets passed the field.options.
*
* @param {Object} config The config spec.
* @param {array} config.fields The array of fields to assert the DOM presence on.
* @param {String} config.field.name The name of the field under test.
* @param {Object} config.field.modelTestConfig The model test config that should be used for the field under test.
* @param {Object} config.field.options Any options required by the field test object command assertFieldDOMPresent.
*/
assertFieldDOMPresent: function (config) {
var browser = this;
var form = this.section.form;
if (config) {
if (config.fields) {
config.fields.forEach(function (field) {
var ModelTestConfig = field.modelTestConfig || browser.defaultModelTestConfig;
if (ModelTestConfig) {
form.section.list = new ModelTestConfig({ formSelector: form.selector });
if (form.section.list) {
var fieldTestObject = form.section.list[field.name];
if (fieldTestObject) {
if (fieldTestObject.commands && 'assertFieldDOMPresent' in fieldTestObject.commands) {
form.section.list[field.name].commands.assertFieldDOMPresent(browser, field.options);
} else {
throw new Error('adminUIItemScreen:assertFieldDOMPresent command not defined in ' + field.name + ' field test object!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldDOMPresent: invalid field name!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldDOMPresent: invalid field modelTestConfig!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldDOMPresent: No modelTestConfig given!');
}
});
} else {
throw new Error('adminUIItemScreen:assertFieldDOMPresent: Invalid fields specification!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts that the specified item field's DOM is not present in the edit item screen. This command calls into the
* assertFieldDOMNotPresent command of the field under test, which gets passed the field.options.
*
* @param {Object} config The config spec.
* @param {array} config.fields The array of fields to assert the DOM presence on.
* @param {String} config.field.name The name of the field under test.
* @param {Object} config.field.modelTestConfig The model test config that should be used for the field under test.
* @param {Object} config.field.options Any options required by the field test object command assertFieldDOMNotPresent.
*/
assertFieldDOMNotPresent: function (config) {
var browser = this;
var form = this.section.form;
if (config) {
if (config.fields) {
config.fields.forEach(function (field) {
var ModelTestConfig = field.modelTestConfig || browser.defaultModelTestConfig;
if (ModelTestConfig) {
form.section.list = new ModelTestConfig({ formSelector: form.selector });
if (form.section.list) {
var fieldTestObject = form.section.list[field.name];
if (fieldTestObject) {
if (fieldTestObject.commands && 'assertFieldDOMNotPresent' in fieldTestObject.commands) {
form.section.list[field.name].commands.assertFieldDOMNotPresent(browser, field.options);
} else {
throw new Error('adminUIItemScreen:assertFieldDOMNotPresent command not defined in ' + field.name + ' field test object!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldDOMNotPresent: invalid field name!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldDOMNotPresent: invalid field modelTestConfig!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldDOMNotPresent: No modelTestConfig given!');
}
});
} else {
throw new Error('adminUIItemScreen:assertFieldDOMNotPresent: Invalid fields specification!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Clicks the specified field's click area in the edit item screen. This command calls into the
* clickFieldUI command of the field under test, which gets passed the field.input and field.options.
*
* @param {Object} config The config spec.
* @param {array} config.fields The array of fields to click on.
* @param {String} config.field.name The name of the field under test.
* @param {Object} field.click The clickable area to pass to the field test object command clickFieldUI.
* @param {Object} config.field.options Any options required by the field test object command clickFieldUI.
* @param {Object} config.field.modelTestConfig The model test config that should be used for the field under test.
*/
clickFieldUI: function (config) {
var browser = this;
var form = this.section.form;
if (config) {
if (config.fields) {
config.fields.forEach(function (field) {
var ModelTestConfig = field.modelTestConfig || browser.defaultModelTestConfig;
if (ModelTestConfig) {
form.section.list = new ModelTestConfig({ formSelector: form.selector });
if (form.section.list) {
var fieldTestObject = form.section.list[field.name];
if (fieldTestObject) {
if (fieldTestObject.commands && 'clickFieldUI' in fieldTestObject.commands) {
form.section.list[field.name].commands.clickFieldUI(browser, field.click, field.options);
} else {
throw new Error('adminUIItemScreen:clickFieldUI command not defined in ' + field.name + ' field test object!');
}
} else {
throw new Error('adminUIItemScreen:clickFieldUI: invalid field name!');
}
} else {
throw new Error('adminUIItemScreen:clickFieldUI: invalid field modelTestConfig!');
}
} else {
throw new Error('adminUIItemScreen:clickFieldUI: No modelTestConfig given!');
}
});
} else {
throw new Error('adminUIItemScreen:clickFieldUI: Invalid fields specification!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Fills the specified field's inputs in the edit item screen. This command calls into the
* fillFieldInputs command of the field under test, which gets passed the field.input and field.options.
*
* @param {Object} config The config spec.
* @param {array} config.fields The array of fields to assert the UI visibility on.
* @param {String} config.field.name The name of the field under test.
* @param {Object} field.input The input to pass to the field test object command fillFieldInputs.
* @param {Object} config.field.options Any options required by the field test object command fillFieldInputs.
* @param {Object} config.field.modelTestConfig The model test config that should be used for the field under test.
*/
fillFieldInputs: function (config) {
var browser = this;
var form = this.section.form;
if (config) {
if (config.fields) {
config.fields.forEach(function (field) {
var ModelTestConfig = field.modelTestConfig || browser.defaultModelTestConfig;
form.section.list = new ModelTestConfig({ formSelector: form.selector });
if (form.section.list) {
var fieldTestObject = form.section.list[field.name];
if (fieldTestObject) {
if (fieldTestObject.commands && 'fillFieldInputs' in fieldTestObject.commands) {
form.section.list[field.name].commands.fillFieldInputs(browser, field.input, field.options);
browser.api.pause(1000);
} else {
throw new Error('adminUIItemScreen:fillFieldInputs command not defined in ' + field.name + ' field test object!');
}
} else {
throw new Error('adminUIItemScreen:fillFieldInputs: invalid field name!');
}
} else {
throw new Error('adminUIItemScreen:fillFieldInputs: invalid field modelTestConfig!');
}
});
} else {
throw new Error('adminUIItemScreen:fillFieldInputs: Invalid fields specification!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Asserts the field's inputs in the edit item screen are as specified. This command calls into the
* assertFieldInputs command of the field under test, which gets passed the field.input and field.options.
*
* @param {Object} config The config spec.
* @param {array} config.fields The array of fields to assert the UI visibility on.
* @param {String} config.field.name The name of the field under test.
* @param {Object} field.input The input to pass to the field test object command assertFieldInputs.
* @param {Object} config.field.options Any options required by the field test object command assertFieldInputs.
* @param {Object} config.field.modelTestConfig The model test config that should be used for the field under test.
*/
assertFieldInputs: function (config) {
var browser = this;
var form = this.section.form;
if (config) {
if (config.fields) {
config.fields.forEach(function (field) {
var ModelTestConfig = field.modelTestConfig || browser.defaultModelTestConfig;
if (ModelTestConfig) {
form.section.list = new ModelTestConfig({ formSelector: form.selector });
if (form.section.list) {
var fieldTestObject = form.section.list[field.name];
if (fieldTestObject) {
if (fieldTestObject.commands && 'assertFieldInputs' in fieldTestObject.commands) {
form.section.list[field.name].commands.assertFieldInputs(browser, field.input, field.options);
} else {
throw new Error('adminUIItemScreen:assertFieldInputs command not defined in ' + field.name + ' field test object!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldInputs: invalid field name!');
}
} else {
throw new Error('adminUIItemScreen:assertFieldInputs: invalid field modelTestConfig!');
}
} else {
throw new Error('adminUIItemScreen:fillFieldInputs: invalid field modelTestConfig!');
}
});
} else {
throw new Error('adminUIItemScreen:assertFieldInputs: Invalid fields specification!');
}
} else {
throw new Error('adminUIItemScreen:invalid config specification!');
}
return this;
},
/**
* Navigates to the first relationship in the edit item form.
*
* TODO: this should be refactor to be able to navigate to any relationship!
*/
navitageToFirstRelationship: function () {
return this
.moveToElement('@firstRelationshipItemLink', 0, 0)
.click('@firstRelationshipItemLink');
},
/**
* Navigate back to the list screen from the edit item form.
*/
back: function () {
return this
.moveToElement('@listBreadcrumb', 0, 0)
.click('@listBreadcrumb');
},
/**
* Creates a new item off the edit item form.
*/
new: function () {
return this
.moveToElement('@newItemButton', 0, 0)
.click('@newItemButton');
},
/**
* Saves the edited item form.
*/
save: function () {
return this.section.form
.moveToElement('@saveButton', 0, 0)
.click('@saveButton');
},
/**
* Resets pending changes in the edit item form.
*/
reset: function () {
return this.section.form
.moveToElement('@resetButton', 0, 0)
.click('@resetButton');
},
/**
* Deletes the item being edited.
*/
delete: function () {
return this.section.form
.moveToElement('@deleteButton', 0, 0)
.click('@deleteButton');
},
}],
sections: {
form: {
selector: '.EditForm-container',
sections: {},
elements: {
//
// FORM LEVEL ELEMENTS
//
saveButton: 'button[data-button=update]',
resetButton: 'button[data-button=reset]',
deleteButton: 'button[data-button=delete]',
},
commands: [{
//
// FORM LEVEL COMMANDS
//
}],
},
},
/**
* @property {string} listBreadcrumb The element used to ID the back to list breadcrumb.
* @property {string} searchInputIcon The element used to ID the search input icon.
* @property {string} newItemButton The element used to ID the new item button.
* @property {string} flashMessage The element used to ID the success flash message.
* @property {string} flashError The element used to ID the error flash message.
* @property {string} readOnlyNameHeader The element used to ID the read-only name header.
* @property {string} editableNameHeader The element used to ID the editable name header.
* @property {string} idLabel The element used to ID the item id label.
* @property {string} idValue The element used to ID the item id value.
* @property {string} metaHeader The element used to ID the meta data header.
* @property {string} metaCreatedAtLabel The element used to ID the meta data header created-at label.
* @property {string} metaCreatedAtValue The element used to ID the meta data header created-at value.
* @property {string} metaCreatedByLabel The element used to ID the meta data header created-by label.
* @property {string} metaCreatedByValue The element used to ID the meta data header created-by value.
* @property {string} metaUpdatedAtLabel The element used to ID the meta data header updated-at label.
* @property {string} metaUpdatedAtValue The element used to ID the meta data header updated-at value.
* @property {string} metaUpdatedByLabel The element used to ID the meta data header updated-by label.
* @property {string} metaUpdatedByValue The element used to ID the meta data header updated-by value.
* @property {string} saveButton The element used to ID the save button.
* @property {string} resetButton The element used to ID the reset button.
* @property {string} resetButtonText The element used to ID the reset button text.
* @property {string} deleteButton The element used to ID the delete button.
* @property {string} deleteButtonText The element used to ID the delete button text.
* @property {string} firstRelationshipItemLink The element used to ID the first relationship item link.
*/
elements: {
//
// PAGE LEVEL ELEMENTS
//
listBreadcrumb: 'a[data-e2e-editform-header-back="true"]',
searchInputIcon: '[data-e2e-search-icon]',
newItemButton: '.Toolbar__section button[data-e2e-item-create-button="true"]',
flashMessage: 'div[data-alert-type="success"]',
flashError: 'div[data-alert-type="danger"]',
readOnlyNameHeader: '.EditForm__name-field h2',
editableNameHeader: '.EditForm__name-field input[class*="item-name-field"',
idLabel: '.EditForm__key-or-id span[class="EditForm__key-or-id__label"]',
idValue: '.EditForm__key-or-id span[class="EditForm__key-or-id__field"]',
metaHeader: '.EditForm-container h3[class="form-heading"]',
metaCreatedAtLabel: '.EditForm-container div[for="createdAt"] label[for="createdAt"]',
metaCreatedAtValue: '.EditForm-container div[for="createdAt"] span',
metaCreatedByLabel: '.EditForm-container div[for="createdBy"] label[for="createdBy"]',
metaCreatedByValue: '.EditForm-container div[for="createdBy"] span',
metaUpdatedAtLabel: '.EditForm-container div[for="updatedAt"] label[for="updatedAt"]',
metaUpdatedAtValue: '.EditForm-container div[for="updatedAt"] span',
metaUpdatedByLabel: '.EditForm-container div[for="updatedBy"] label[for="updatedBy"]',
metaUpdatedByValue: '.EditForm-container div[for="updatedBy"] span',
saveButton: '.EditForm-container button[data-button=update]',
resetButton: '.EditForm-container button[data-button=reset]',
resetButtonText: '.EditForm-container button[data-button=reset] span',
deleteButton: '.EditForm-container button[data-button=delete]',
deleteButtonText: '.EditForm-container button[data-button=delete] span',
// TODO: refactor this so that any relationship itrem link can be used
firstRelationshipItemLink: 'div.Relationships > div > div > div > table > tbody > tr > td > a',
},
defaultModelTestConfig: null,
};
|
keystonejs/keystone-nightwatch-e2e
|
lib/src/pageObjects/adminUIItemScreen.js
|
JavaScript
|
mit
| 26,946
|
'use strict';
const gulp = require('gulp');
const uglify = require('gulp-uglify');
let sass = require('gulp-sass');
gulp.task('sass', function() {
return gulp.src('./front/scss/index.scss')
.pipe(sass.sync())
.pipe(gulp.dest('./public/css'))
})
gulp.task('copy', function() {
return gulp.src('./front/simditor.css')
.pipe(gulp.dest('./public/css'))
})
gulp.task('sass-watch', function() {
return gulp.watch('./front/scss/*.scss', ['sass'])
});
gulp.task('default', ['copy', 'sass', 'sass-watch'])
|
struCoder/pngOrPdfHtml
|
gulpfile.js
|
JavaScript
|
mit
| 519
|
let passport = require('passport')
let nodeifyit = require('nodeifyit')
let User = require('../models/user')
let util = require('util')
let LocalStrategy = require('passport-local').Strategy
let FacebookStrategy = require('passport-facebook').Strategy
let GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
let TwitterStrategy = require('passport-twitter').Strategy
require('songbird')
function useExternalPassportStrategy(OauthStrategy, config, field) {
config.passReqToCallback = true
console.log('configuring....' + field)
// 1. Load user from store
// 2. If req.user exists, we're authorizing (connecting an account)
// 2a. Ensure it's not associated with another account
// 2b. Link account
// 3. If not, we're authenticating (logging in)
// 3a. If user exists, we're logging in via the 3rd party account
// 3b. Otherwise create a user associated with the 3rd party account
async function authCB(req, token, tokenSecret, account) {
let idField = field + '.id'
let query = {}
query[idField] = account.id
console.log('query-->' + JSON.stringify(query))
let dbUser = await User.promise.findOne({query})
let user = req.user
//User is authenticated locally
if (user) {
if (dbUser && (dbUser.id !== user.id)) {
console.log('account associated to some other user - ' + dbUser.id)
return [false, {message: "account associated to some other user"}]
}
} else {
if(dbUser) {
//Logged in using social account
user = dbUser
} else {
//Creating the account for social login
user = new User()
}
}
user[field].id = account.id
user[field].token = token
user[field].tokenSecret = tokenSecret
if(field === 'twitter') {
user[field].username = account.username
} else {
user[field].email = account.emails[0].value
}
user[field].name = account.displayName
try{
return await user.save()
}catch(excep){
console.log(util.inspect(excep))
return [false, {message: excep.message}]
}
}
passport.use(field, new OauthStrategy(config, nodeifyit(authCB, {spread: true})))
}
function configure(config) {
// Required for session support / persistent login sessions
passport.serializeUser(nodeifyit(async (user) => user._id))
passport.deserializeUser(nodeifyit(async (id) => {
return await User.promise.findById(id)
}))
useExternalPassportStrategy(FacebookStrategy, config.facebookAuth, 'facebook')
useExternalPassportStrategy(GoogleStrategy, config.googleAuth, 'google')
useExternalPassportStrategy(TwitterStrategy, config.twitterAuth, 'twitter')
passport.use(new LocalStrategy({
usernameField: 'email',
failureFlash: true
}, nodeifyit(async (email, password) => {
let regExQuery
let regExp = new RegExp(email, "i")
regExQuery = {'local.email': {$regex: regExp}}
let user = await User.promise.findOne(regExQuery)
if(!user) {
return [false, {message: 'Invalid username or password'}]
}
if(!await user.validatePassword(password)) {
return [false, {message: 'Invalid password'}]
}
return user
}, {spread: true})))
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passReqToCallback: true
}, nodeifyit(async (req, email, password) => {
let emailRegExp = new RegExp(email, "i")
let emailRegExQuery = {'local.email': {$regex: emailRegExp}}
if(!email.indexOf('@')){
return [false, {message: 'The email is invalid'}]
}
if(await User.promise.findOne(emailRegExQuery)){
return [false, {message: 'The email is already taken'}]
}
let user
if(req.user) {
user = req.user
} else {
user = new User()
}
user.local.email = email
user.local.password = password
try {
return await user.save()
} catch (e) {
console.log('Validation error', e)
return [false, {message: e.message}]
}
}, {spread: true})))
return passport
}
module.exports = {passport, configure}
|
vasupalanisamy/nodejs-socialfeed
|
app/middlewares/passport.js
|
JavaScript
|
mit
| 4,156
|
/* global ranTransition, noTransitionsYet */
import Ember from 'ember';
import startApp from '../helpers/start-app';
import { injectTransitionSpies,
classFound,
clickWithoutWaiting } from '../helpers/integration';
var App;
module('Acceptance: Demos', {
setup: function() {
App = startApp();
// Conceptually, integration tests shouldn't be digging around in
// the container. But animations are slippery, and it's easier to
// just spy on them to make sure they're being run than to try to
// observe their behavior more directly.
injectTransitionSpies(App);
},
teardown: function() {
Ember.run(App, 'destroy');
}
});
test('visit every link in sidebar', function() {
var lastRouteName = 'modal-documentation.component';
expect(1);
function navigateForward() {
var forward = find('.nav-link.forward a');
if (forward.length > 0) {
click('.nav-link.forward a');
andThen(navigateForward);
} else {
equal(currentRouteName(), lastRouteName);
}
}
visit('/');
andThen(navigateForward);
});
test('liquid outlet demo', function() {
visit('/helpers/liquid-outlet');
andThen(function(){
equal(currentRouteName(), 'helpers-documentation.liquid-outlet.index');
equal(find('.demo-container a').text(), 'Click me!');
noTransitionsYet();
});
click('.demo-container a');
andThen(function(){
equal(currentRouteName(), 'helpers-documentation.liquid-outlet.other');
equal(find('.demo-container a').text(), 'Go back!');
ranTransition('toLeft');
});
click('.demo-container a');
andThen(function(){
equal(currentRouteName(), 'helpers-documentation.liquid-outlet.index');
equal(find('.demo-container a').text(), 'Click me!');
ranTransition('toRight');
});
});
test('liquid with demo', function() {
visit('/helpers/liquid-with');
andThen(function(){
ok(/\b1\b/.test(find('.demo-container').text()), 'Has 1');
noTransitionsYet();
});
click('.demo-container button');
andThen(function(){
ranTransition('rotateBelow');
ok(/\b2\b/.test(find('.demo-container').text()), 'Has 2');
});
});
test('liquid bind demo', function() {
var first, second, self = this;
function clock() {
var m = /(\d\d)\s*:\s*(\d\d)\s*:\s*(\d\d)/.exec($('#liquid-bind-demo').text());
ok(m, "Read the clock");
return parseInt(m[3]);
}
visit('/helpers/liquid-bind');
andThen(function(){
first = clock();
});
click('#force-tick');
andThen(function(){
second = clock();
notEqual(first, second, "clock readings differ, " + first + ", " + second);
ranTransition('toUp');
});
});
test('liquid if demo', function() {
visit('/helpers/liquid-if');
andThen(function(){
noTransitionsYet();
equal(find('#liquid-box-demo input[type=checkbox]').length, 1, "found checkbox");
equal(find('#liquid-box-demo input[type=text]').length, 0, "no text input");
find('select').val('car').trigger('change');
});
andThen(function(){
ranTransition('toLeft');
equal(find('#liquid-box-demo input[type=checkbox]').length, 0, "no more checkbox");
equal(find('#liquid-box-demo input[type=text]').length, 1, "has text input");
find('select').val('bike').trigger('change');
});
andThen(function(){
ranTransition('crossFade');
});
});
test('interruption demo, normal transition', function() {
visit('/transitions/primitives');
andThen(function(){
noTransitionsYet();
classFound('one');
clickWithoutWaiting('#interrupted-fade-demo a', 'Two');
});
andThen(function(){
ranTransition('fade');
classFound('two');
});
});
test('interruption demo, early interruption', function() {
visit('/transitions/primitives');
andThen(function(){
classFound('one');
clickWithoutWaiting('#interrupted-fade-demo a', 'Two');
Ember.run.later(function(){
clickWithoutWaiting('#interrupted-fade-demo a', 'Three');
}, 300);
});
andThen(function(){
classFound('three');
});
});
test('interruption demo, late interruption', function() {
visit('/transitions/primitives');
andThen(function(){
classFound('one');
clickWithoutWaiting('#interrupted-fade-demo a', 'Two');
Ember.run.later(function(){
classFound('two');
clickWithoutWaiting('#interrupted-fade-demo a', 'Three');
}, 120);
});
andThen(function(){
classFound('three');
});
});
test('modal demo', function() {
visit('/modals');
click('#basic-modal-demo button');
andThen(function(){
findWithAssert('.hello-modal');
click('.hello-modal button.change');
});
andThen(function(){
ok(find('.hello-modal').text().match(/Hello/), "Salutation has changed");
});
andThen(function(){
click('.hello-modal button.done');
});
andThen(function(){
equal(find('.hello-modal').length, 0, "dismissed hello-modal");
});
});
test('warn-popup - dismiss with overlay', function() {
visit('/modals?warn=1');
andThen(function(){
findWithAssert('#warn-popup');
click('.lf-overlay');
});
andThen(function(){
equal(find('#warn-popup').length, 0, "dismissed popup");
});
});
test('warn-popup - dismiss with url', function() {
visit('/modals?warn=1');
andThen(function(){
findWithAssert('#warn-popup');
visit('/');
});
andThen(function(){
equal(find('#warn-popup').length, 0, "dismissed popup");
});
});
|
stefanpenner/liquid-fire
|
tests/acceptance/demos-test.js
|
JavaScript
|
mit
| 5,395
|
import pollsReducer from '../../../../lib/modules/comments/reducers/polls';
const actionFile = '../lib/modules/comments/actions/doClearPollComments';
const commentsFixture = require('../../../fixtures/comments.json');
describe('Clear poll comments', () => {
/**
* getInstance method
*/
function getInstance(promise) {
return proxyquire.noCallThru().load(actionFile, {
'../../../utils/fetch/ApiFetch': { get: () => promise }
}).default;
}
describe('call api with poll ID', () => {
let action;
const actionToDispatch = getInstance(
Promise.resolve({
comments: commentsFixture.slice(0, 2)
})
);
before(async () => {
const store = mockStore({});
action = await store.dispatch(actionToDispatch({ pollId: 1 }));
});
it('validate action', () => {
expect(action.type).to.equal('CLEAR_POLL_COMMENTS');
expect(action.payload.pollId).to.equal(1);
});
it('validate polls reducer', () => {
const statePollsReducer = pollsReducer(undefined, action);
expect(statePollsReducer).to.deep.equal({});
});
});
});
|
gonetcats/betaseries-api-redux-sdk
|
tests/modules/comments/actions/doClearPollComments.spec.js
|
JavaScript
|
mit
| 1,122
|
(function($) {
module("slider: options");
test('setAttributes', function() {
var values = $('#slider').slider("option", "values");
equals(values.join(','), ['25','50','75'].join(','), 'Array property');
var disabled = $('#slider').slider("option", "disabled");
equals(disabled, true, 'Boolean property');
var step = $('#slider').slider("option", "step");
equals(step, 25, 'Number property');
var orientation = $('#slider').slider("option", "orientation");
equals(orientation, 'vertical', 'String property');
});
})(jQuery);
|
davecowart/jquery-ui-unobtrusive
|
tests/unit/slider/slider_attributes.js
|
JavaScript
|
mit
| 550
|
$(document).ready(function() {
$("#submit").click(function() {
var nume = $("input[name='firstname']").val();
var prenume = $("input[name='lastname']").val();
var cnp = $("input[name='codnumeric']").val();
var sex = $("option:selected").val();
var stare = $("input[name='starecivila']").val();
var telefon = $("input[name='numartelefon']").val();
var email = $("input[name='adresaemail']").val();
var adresa = $("input[name='adresa']").val();
var localitate = $("input[name='localitate']").val();
var judet = $("input[name='judet']").val();
var tara = $("input[name='tara']").val();
$.getJSON("db/data.json", function(data) {
var corect = false;
for(var i=0; i<data.length; i++) {
if(nume == data[i].nume && prenume == data[i].prenume && cnp == data[i].cnp &&
sex == data[i].sex && stare == data[i].stare && telefon == data[i].telefon &&
email == data[i].email && adresa == data[i].adresa && localitate == data[i].localitate &&
judet == data[i].judet && tara == data[i].tara) {
corect = true;
break;
}
}
if(corect) {
location.href = "bilete.html";
} else {
$(":input").css("border", "1px solid red")
$(".error").show();
//$(".invalid").show();
}
})
});
});
function hideError() {
$('.error').hide();
//$('.invalid').hide();
$(":input").css("border", "1px solid green")
};
|
edmondpr/Transport
|
app/js/datepersonale.js
|
JavaScript
|
mit
| 1,373
|
/**
* Task for loading timer data and then parsing it in some fashion.
*/
module.exports = function(grunt) {
var crushJSON = require('./lib/crush-json'),
moment = require('moment');
function convertDate(date) {
try {
return Date.parse(date);
} catch (ex) {
grunt.log.error("Unable to parse time \"" + date + "\": " + ex);
}
}
/**
* Given an input timer definition, converts any fields as necessary (basically
* parse the start/end dates if they're strings and convert them to UNIX-style
* time-stamps).
*/
function convertTimer(timer) {
if (grunt.util.kindOf(timer['start']) === 'string') {
timer['start'] = convertDate(timer['start']);
}
if (grunt.util.kindOf(timer['end']) === 'string') {
timer['end'] = convertDate(timer['end']);
}
}
/**
* The set of fields the timer cares about and that should survive
* JSON-crushing. Note that this does NOT include the "subtimers" field as
* that's only valid on the top-level field.
*/
var TIMER_FIELDS = {
"start": true,
"end": true,
"name": true,
"type": true,
"showDuration": true,
"popover": true
};
/**
* Strips any field out of the timer that isn't used by the actual timer code.
*/
function stripIgnoredFields(timer, allowSubtimer) {
if (arguments.length < 2)
allowSubtimer = true;
// We want to pull the keys and delete them while iterating over them, so:
var keys = Object.keys(timer);
keys.forEach(function(key) {
if (!(key in TIMER_FIELDS)) {
if (key === 'subtimers' && allowSubtimer) {
// We actually want to recurse into this.
if (grunt.util.kindOf(timer['subtimers']) === 'array') {
timer['subtimers'].forEach(function(subtimer) {
// Subtimers aren't allowed on subtimers. You can only nest once.
stripIgnoredFields(subtimer, false);
});
}
return;
}
// Otherwise, delete it.
delete timer[key];
}
});
}
function parseTimers(timers, filename, oldest) {
var json = grunt.file.readJSON(filename);
// Fairly simple: just merge the timer data as necessary.
var ts;
if (grunt.util.kindOf(json) === 'array') {
ts = json;
} else if (grunt.util.kindOf(json['timers']) === 'array') {
ts = json['timers'];
} else {
grunt.log.error("No timer data in " + filename);
return;
}
ts.forEach(function(t) {
convertTimer(t);
if (grunt.util.kindOf(t['subtimers']) === 'array') {
t['subtimers'].forEach(function(subtimer) {
convertTimer(subtimer);
});
}
// Exclude timers that are too old:
if ('end' in t && t['end'] > oldest) {
// Most timers have an end...
timers.push(t);
} else {
// ...but if it doesn't, base it on the start.
if ('start' in t && t['start'] > oldest) {
timers.push(t);
}
}
});
}
grunt.registerMultiTask('parsetimers', 'Parses timer data', function() {
var options = this.options({
sort: true,
stripUnusedFields: true,
crush: true,
oldest: moment.duration(1, 'day')
});
if (moment.isDuration(options['oldest']))
options['oldest'] = options['oldest'].asMilliseconds();
this.files.forEach(function(file) {
if (file.src.length < 1) {
grunt.log.error("No input files for " + file.dest);
} else {
var timers = [], oldest = new Date().getTime() - options['oldest'];
file.src.forEach(function(src) {
parseTimers(timers, src, oldest);
});
if (options['sort']) {
// Sort the timers by start time before writing them. Earlier timers
// should be higher on the list.
timers.sort(function(a,b) {
var d = a['start'] - b['start'];
if (d != 0)
return d;
// Sort by title instead.
if ('title' in a && 'title' in b) {
return a['title'] < b['title'] ? -1 : (a['title'] == b['title'] ? 0 : 1);
} else {
// Otherwise, sort by the name field.
return a['name'] < b['name'] ? -1 : (a['name'] == b['name'] ? 0 : 1);
}
});
}
if (options['stripUnusedFields']) {
timers.forEach(function(timer) {
stripIgnoredFields(timer);
});
}
grunt.file.write(file.dest, options['crush'] ?
crushJSON({ timers: timers }) :
JSON.stringify({ timers: timers }, null, 2));
grunt.log.ok("Wrote " + timers.length + " " +
grunt.util.pluralize(timers.length, "timer/timers") +" to " + file.dest);
}
});
});
};
|
khoa002/ffxiv-js-timer
|
tasks/parse-timer-task.js
|
JavaScript
|
mit
| 4,519
|
/**
* Copyright 2016 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright 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
*
* @flow
*/
'use strict'
/**
* The states were interested in
*/
const {
LOGGED_IN,
LOGGED_OUT,
} = require('../lib/constants').default
import type {Action} from '../actions/types'
export type State = {
isLoggedIn: boolean,
// User Instance
id: ? string,
username: ? string,
loginType: ? string,
email: ? string,
updatedAt: ? Date,
uniqueId: ?string;
}
const initialState = {
isLoggedIn: false,
// User Instance
id: null,
username: null,
loginType: null,
email: null,
updatedAt: null,
uniqueId: null,
}
function user(state: State = initialState, action: Action): State {
switch (action.type) {
case LOGGED_IN: {
let {id, username, loginType, email, updatedAt, uniqueId} = action.payload
return {
isLoggedIn: true,
id, username, loginType, email, updatedAt, uniqueId
}
}
case LOGGED_OUT: {
return initialState
}
}
return state
}
export default user;
|
sidkarwal/politicl-wb-app
|
src/reducers/user.js
|
JavaScript
|
mit
| 2,029
|
/* global it */
var proxyquire = require('proxyquire').noCallThru();
var assert = require('assert');
var File = require('vinyl');
it('should run npm command', function (done) {
delete require.cache[require.resolve('./')];
proxyquire('./', { 'gulp-start-process': function (cmd) {
assert.equal(cmd, 'npm install');
done();
} });
var start = require('./');
start().end(new File({
path: '/some/dir/package.json'
}));
});
it('should run bower command', function (done) {
delete require.cache[require.resolve('./')];
proxyquire('./', { 'gulp-start-process': function (cmd) {
assert.equal(cmd, 'bower install');
done();
} });
var start = require('./');
start().end(new File({
path: '/some/dir/bower.json'
}));
});
it('should support custom commands', function (done) {
delete require.cache[require.resolve('./')];
proxyquire('./', { 'gulp-start-process': function (cmd) {
assert.equal(cmd, 'lol');
done();
} });
var start = require('./');
start([{ match: /\.json$/, cmd: 'lol' }]).end(new File({
path: '/some/dir/bower.json'
}));
});
it('should throw on invalid argument', function () {
assert.throws(function () { require('./')('lol'); });
});
|
sbarnabas/gowhere
|
node_modules/gulp-start/test.js
|
JavaScript
|
mit
| 1,295
|
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import cssModules from 'react-css-modules'
import styles from './SearchInput.module.scss'
class SearchInput extends PureComponent {
static porpTypes = {
onSearch: PropTypes.func.isRequired
}
state = {
query: ''
}
handleKeyUp = (e) => {
if (e.keyCode !== 13) return
this.props.onSearch(this.state.query)
}
render() {
return (
<div styleName="search-input">
<input
type="search"
placeholder="搜点什么"
value={this.state.query}
onChange={e => this.setState({ query: e.target.value.trim() })}
onKeyUp={this.handleKeyUp}
/>
<i
className="iconfont icon-icon_search_"
onClick={e => this.props.onSearch(this.state.query)}
styleName="search-icon"
/>
</div>
)
}
}
export default cssModules(SearchInput, styles)
|
imuntil/React
|
L/my-app/src/containers/SearchInput.js
|
JavaScript
|
mit
| 953
|
version https://git-lfs.github.com/spec/v1
oid sha256:cb6f42a953a0707ace6e80ee2b6529288bd34654262580cc54f6f7674c3450ee
size 5123
|
yogeshsaroya/new-cdnjs
|
ajax/libs/angular-smart-table/1.4.7/smart-table.min.js
|
JavaScript
|
mit
| 129
|
/**
* Provides Form and input features.
*
* @module furnace
* @submodule furnace-forms
*/
import Ember from 'ember';
import Control from './abstract';
/**
* Input control component
*
* @class Input
* @namespace Furnace.Forms.Components
* @extends Furnace.Forms.Components.Abstract
*/
export default Control.extend({
defaultLayoutName: 'forms/view',
value:Ember.computed.alias('control.value'),
});
|
ember-furnace/ember-cli-furnace-forms
|
addon/components/view.js
|
JavaScript
|
mit
| 416
|
/**
* Created by Virginia on 5/4/2014.
*/
'use strict';
var gulp = require('gulp'),
templateCache = require('gulp-angular-templatecache'),
handleErrors = require('../util/handleErrors');
gulp.task('templates', function () {
gulp.src(['./src/**/**.tpl.html'])
.on('error', handleErrors)
.pipe(templateCache({module: 'templatesCache', standalone: true}))
.pipe(gulp.dest('./builds/development/js/'))
});
|
virginc/HomeDashboard
|
gulp/tasks/templates.js
|
JavaScript
|
mit
| 428
|
class LibA{
constructor(){
console.log('LibA constructed');
}
}
export default LibA;
|
justinwilaby/grunt-jspm-builder
|
test/libs/LibA.js
|
JavaScript
|
mit
| 88
|
import {run} from "../fill-stateless"
import find from "./dom/find-stateless"
import {rafBounceIds, _cprops, doc} from './constants'
import mag from "./mag"
import magInit from "./mag-init"
mag._handler = function(idOrNode, mod, dprops) {
return magInit(idOrNode, mod, dprops, run, find)
}
export {_cprops, rafBounceIds, doc}
export default mag
|
magnumjs/mag.js
|
src/core/mag-stateless.js
|
JavaScript
|
mit
| 352
|
var mongodb = require('./mongodb');
var Schema = mongodb.Schema;
var fakeDataSchema = new Schema({
id : Number,
name : String,
city : String,
state : String,
country : String,
company : String,
favoriteNumber : Number
});
var fakeData = mongodb.model("fakeData", fakeDataSchema);
var fakeDataDAO = function(){};
//±£´æÐÅÏ¢
fakeDataDAO.prototype.save = function(obj, callback) {
var instance = new fakeData(obj);
instance.save(function(err){
callback(err);
});
};
//»ñÈ¡ÁбíÐÅÏ¢
fakeDataDAO.prototype.getFakeDataList = function(query, callback) {
fakeData.find(query, '-_id -__v', {}, callback);
};
//»ñÈ¡µ¥ÌõÐÅÏ¢
fakeDataDAO.prototype.getFakeData = function(query, callback) {
fakeData.findOne(query, '-_id -__v', {}, function(err, res){
if (err) {
console.log(err.message);
}
//console.log(res);
return res;
});
};
module.exports = new fakeDataDAO();
|
shenzhenlong1203/react
|
models/fakeData.js
|
JavaScript
|
mit
| 963
|
import config from '../config';
import changed from 'gulp-changed';
import gulp from 'gulp';
import gulpif from 'gulp-if';
import imagemin from 'gulp-imagemin';
import browserSync from 'browser-sync';
gulp.task('images', function() {
return gulp.src(config.images.src)
.pipe(changed(config.images.dest)) // Ignore unchanged files
// .pipe(gulpif(global.isProd, imagemin())) // Optimize
.pipe(gulp.dest(config.images.dest))
.pipe(browserSync.stream());
});
|
underwoodarturo/troy
|
gulp/tasks/images.js
|
JavaScript
|
mit
| 500
|
// Load all the controllers within this directory and all subdirectories.
// Controller files must be named *_controller.js.
import { Application } from 'stimulus';
import { definitionsFromContext } from 'stimulus/webpack-helpers';
const application = Application.start();
const context = require.context('controllers', true, /_controller\.js$/);
application.load(definitionsFromContext(context));
|
christopherstyles/bookmark-manager
|
app/javascript/controllers/index.js
|
JavaScript
|
mit
| 400
|
'use strict';
angular.module('myApp.view2', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/view2', {
templateUrl: 'view2/view2.html',
controller: 'View2Ctrl'
});
}])
.controller('View2Ctrl', [function ($scope, $filter, moment, uiCalendarConfig) {
}]);
|
anilgmaipady/angular-ui-calendar
|
app/view2/view2.js
|
JavaScript
|
mit
| 355
|
import Vue from 'vue';
import Framework7 from 'framework7';
import Framework7Vue from 'framework7-vue';
import Framework7Icons from 'framework7-icons/css/framework7-icons.css';
import Framework7Theme from 'framework7/dist/css/framework7.ios.min.css';
import Framework7ThemeColors from 'framework7/dist/css/framework7.ios.colors.min.css';
import AppStyles from './css/app.css';
import Routes from './routes';
import App from './app';
import { store } from './store'
Vue.use(Framework7Vue);
new Vue({
el: '#app',
template: '<app/>',
store,
framework7: {
root: '#app',
routes: Routes,
},
components: {
app: App,
},
});
|
osmansafak/themoviedbapp
|
src/main.js
|
JavaScript
|
mit
| 646
|
// Base16 Porple
// Scheme: Niek den Breeje (https://github.com/AuditeMarlow)
var color_scheme = {
'base00': '#292c36',
'base01': '#333344',
'base02': '#474160',
'base03': '#65568a',
'base04': '#b8b8b8',
'base05': '#d8d8d8',
'base06': '#e8e8e8',
'base07': '#f8f8f8',
'base08': '#f84547',
'base09': '#d28e5d',
'base0A': '#efa16b',
'base0B': '#95c76f',
'base0C': '#64878f',
'base0D': '#8485ce',
'base0E': '#b74989',
'base0F': '#986841',
};
term_.prefs_.set('background-color', color_scheme.base00);
term_.prefs_.set('foreground-color', color_scheme.base05);
term_.prefs_.set('cursor-color', "rgba(216, 216, 216, 0.5)");
term_.prefs_.set('color-palette-overrides',
[color_scheme.base00,
color_scheme.base08,
color_scheme.base0B,
color_scheme.base0A,
color_scheme.base0D,
color_scheme.base0E,
color_scheme.base0C,
color_scheme.base05,
color_scheme.base03,
color_scheme.base08,
color_scheme.base0B,
color_scheme.base0A,
color_scheme.base0D,
color_scheme.base0E,
color_scheme.base0C,
color_scheme.base07,
color_scheme.base09,
color_scheme.base0F,
color_scheme.base01,
color_scheme.base02,
color_scheme.base04,
color_scheme.base06]);
|
philj56/base16-crosh
|
colors/base16-porple.js
|
JavaScript
|
mit
| 1,787
|
$(function () {
$('#container').highcharts({
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
plotOptions: {
series: {
stickyTracking: false
}
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}, {
data: [144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2]
}]
});
});
|
Oxyless/highcharts-export-image
|
lib/highcharts.com/samples/highcharts/plotoptions/series-stickytracking-false/demo.js
|
JavaScript
|
mit
| 548
|
// Vectorizer.
// -----------
// A tiny library for making your live easier when dealing with SVG.
// Copyright © 2012 - 2014 client IO (http://client.io)
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else {
// Browser globals.
root.Vectorizer = root.V = factory();
}
}(this, function() {
// Well, if SVG is not supported, this library is useless.
var SVGsupported = !!(window.SVGAngle || document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1'));
// XML namespaces.
var ns = {
xmlns: 'http://www.w3.org/2000/svg',
xlink: 'http://www.w3.org/1999/xlink'
};
// SVG version.
var SVGversion = '1.1';
// A function returning a unique identifier for this client session with every call.
var idCounter = 0;
function uniqueId() {
var id = ++idCounter + '';
return 'v-' + id;
}
// Create SVG element.
// -------------------
function createElement(el, attrs, children) {
if (!el) return undefined;
// If `el` is an object, it is probably a native SVG element. Wrap it to VElement.
if (typeof el === 'object') {
return new VElement(el);
}
attrs = attrs || {};
// If `el` is a `'svg'` or `'SVG'` string, create a new SVG canvas.
if (el.toLowerCase() === 'svg') {
attrs.xmlns = ns.xmlns;
attrs['xmlns:xlink'] = ns.xlink;
attrs.version = SVGversion;
} else if (el[0] === '<') {
// Create element from an SVG string.
// Allows constructs of type: `document.appendChild(Vectorizer('<rect></rect>').node)`.
var svg = '<svg xmlns="' + ns.xmlns + '" xmlns:xlink="' + ns.xlink + '" version="' + SVGversion + '">' + el + '</svg>';
var parser = new DOMParser();
parser.async = false;
var svgDoc = parser.parseFromString(svg, 'text/xml').documentElement;
// Note that `createElement()` might also return an array should the SVG string passed as
// the first argument contain more then one root element.
if (svgDoc.childNodes.length > 1) {
// Map child nodes to `VElement`s.
var ret = [];
for (var i = 0, len = svgDoc.childNodes.length; i < len; i++) {
var childNode = svgDoc.childNodes[i];
ret.push(new VElement(document.importNode(childNode, true)));
}
return ret;
}
return new VElement(document.importNode(svgDoc.firstChild, true));
}
el = document.createElementNS(ns.xmlns, el);
// Set attributes.
for (var key in attrs) {
setAttribute(el, key, attrs[key]);
}
// Normalize `children` array.
if (Object.prototype.toString.call(children) != '[object Array]') children = [children];
// Append children if they are specified.
var i = 0, len = (children[0] && children.length) || 0, child;
for (; i < len; i++) {
child = children[i];
el.appendChild(child instanceof VElement ? child.node : child);
}
return new VElement(el);
}
function setAttribute(el, name, value) {
if (name.indexOf(':') > -1) {
// Attribute names can be namespaced. E.g. `image` elements
// have a `xlink:href` attribute to set the source of the image.
var combinedKey = name.split(':');
el.setAttributeNS(ns[combinedKey[0]], combinedKey[1], value);
} else if (name === 'id') {
el.id = value;
} else {
el.setAttribute(name, value);
}
}
function parseTransformString(transform) {
var translate,
rotate,
scale;
if (transform) {
var separator = /[ ,]+/;
var translateMatch = transform.match(/translate\((.*)\)/);
if (translateMatch) {
translate = translateMatch[1].split(separator);
}
var rotateMatch = transform.match(/rotate\((.*)\)/);
if (rotateMatch) {
rotate = rotateMatch[1].split(separator);
}
var scaleMatch = transform.match(/scale\((.*)\)/);
if (scaleMatch) {
scale = scaleMatch[1].split(separator);
}
}
var sx = (scale && scale[0]) ? parseFloat(scale[0]) : 1;
return {
translate: {
tx: (translate && translate[0]) ? parseInt(translate[0], 10) : 0,
ty: (translate && translate[1]) ? parseInt(translate[1], 10) : 0
},
rotate: {
angle: (rotate && rotate[0]) ? parseInt(rotate[0], 10) : 0,
cx: (rotate && rotate[1]) ? parseInt(rotate[1], 10) : undefined,
cy: (rotate && rotate[2]) ? parseInt(rotate[2], 10) : undefined
},
scale: {
sx: sx,
sy: (scale && scale[1]) ? parseFloat(scale[1]) : sx
}
};
}
// Matrix decomposition.
// ---------------------
function deltaTransformPoint(matrix, point) {
var dx = point.x * matrix.a + point.y * matrix.c + 0;
var dy = point.x * matrix.b + point.y * matrix.d + 0;
return { x: dx, y: dy };
}
function decomposeMatrix(matrix) {
// @see https://gist.github.com/2052247
// calculate delta transform point
var px = deltaTransformPoint(matrix, { x: 0, y: 1 });
var py = deltaTransformPoint(matrix, { x: 1, y: 0 });
// calculate skew
var skewX = ((180 / Math.PI) * Math.atan2(px.y, px.x) - 90);
var skewY = ((180 / Math.PI) * Math.atan2(py.y, py.x));
return {
translateX: matrix.e,
translateY: matrix.f,
scaleX: Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b),
scaleY: Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d),
skewX: skewX,
skewY: skewY,
rotation: skewX // rotation is the same as skew x
};
}
// VElement.
// ---------
function VElement(el) {
this.node = el;
if (!this.node.id) {
this.node.id = uniqueId();
}
}
// VElement public API.
// --------------------
VElement.prototype = {
translate: function(tx, ty, opt) {
opt = opt || {};
ty = ty || 0;
var transformAttr = this.attr('transform') || '',
transform = parseTransformString(transformAttr);
// Is it a getter?
if (typeof tx === 'undefined') {
return transform.translate;
}
transformAttr = transformAttr.replace(/translate\([^\)]*\)/g, '').trim();
var newTx = opt.absolute ? tx : transform.translate.tx + tx,
newTy = opt.absolute ? ty : transform.translate.ty + ty,
newTranslate = 'translate(' + newTx + ',' + newTy + ')';
// Note that `translate()` is always the first transformation. This is
// usually the desired case.
this.attr('transform', (newTranslate + ' ' + transformAttr).trim());
return this;
},
rotate: function(angle, cx, cy, opt) {
opt = opt || {};
var transformAttr = this.attr('transform') || '',
transform = parseTransformString(transformAttr);
// Is it a getter?
if (typeof angle === 'undefined') {
return transform.rotate;
}
transformAttr = transformAttr.replace(/rotate\([^\)]*\)/g, '').trim();
angle %= 360;
var newAngle = opt.absolute ? angle: transform.rotate.angle + angle,
newOrigin = (cx !== undefined && cy !== undefined) ? ',' + cx + ',' + cy : '',
newRotate = 'rotate(' + newAngle + newOrigin + ')';
this.attr('transform', (transformAttr + ' ' + newRotate).trim());
return this;
},
// Note that `scale` as the only transformation does not combine with previous values.
scale: function(sx, sy) {
sy = (typeof sy === 'undefined') ? sx : sy;
var transformAttr = this.attr('transform') || '',
transform = parseTransformString(transformAttr);
// Is it a getter?
if (typeof sx === 'undefined') {
return transform.scale;
}
transformAttr = transformAttr.replace(/scale\([^\)]*\)/g, '').trim();
var newScale = 'scale(' + sx + ',' + sy + ')';
this.attr('transform', (transformAttr + ' ' + newScale).trim());
return this;
},
// Get SVGRect that contains coordinates and dimension of the real bounding box,
// i.e. after transformations are applied.
// If `target` is specified, bounding box will be computed relatively to `target` element.
bbox: function(withoutTransformations, target) {
// If the element is not in the live DOM, it does not have a bounding box defined and
// so fall back to 'zero' dimension element.
if (!this.node.ownerSVGElement) return { x: 0, y: 0, width: 0, height: 0 };
var box;
try {
box = this.node.getBBox();
// Opera returns infinite values in some cases.
// Note that Infinity | 0 produces 0 as opposed to Infinity || 0.
// We also have to create new object as the standard says that you can't
// modify the attributes of a bbox.
box = { x: box.x | 0, y: box.y | 0, width: box.width | 0, height: box.height | 0};
} catch (e) {
// Fallback for IE.
box = {
x: this.node.clientLeft,
y: this.node.clientTop,
width: this.node.clientWidth,
height: this.node.clientHeight
};
}
if (withoutTransformations) {
return box;
}
var matrix = this.node.getTransformToElement(target || this.node.ownerSVGElement);
var corners = [];
var point = this.node.ownerSVGElement.createSVGPoint();
point.x = box.x;
point.y = box.y;
corners.push(point.matrixTransform(matrix));
point.x = box.x + box.width;
point.y = box.y;
corners.push(point.matrixTransform(matrix));
point.x = box.x + box.width;
point.y = box.y + box.height;
corners.push(point.matrixTransform(matrix));
point.x = box.x;
point.y = box.y + box.height;
corners.push(point.matrixTransform(matrix));
var minX = corners[0].x;
var maxX = minX;
var minY = corners[0].y;
var maxY = minY;
for (var i = 1, len = corners.length; i < len; i++) {
var x = corners[i].x;
var y = corners[i].y;
if (x < minX) {
minX = x;
} else if (x > maxX) {
maxX = x;
}
if (y < minY) {
minY = y;
} else if (y > maxY) {
maxY = y;
}
}
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY
};
},
text: function(content, opt) {
opt = opt || {};
var lines = content.split('\n');
var i = 0;
var tspan;
// `alignment-baseline` does not work in Firefox.
// Setting `dominant-baseline` on the `<text>` element doesn't work in IE9.
// In order to have the 0,0 coordinate of the `<text>` element (or the first `<tspan>`)
// in the top left corner we translate the `<text>` element by `0.8em`.
// See `http://www.w3.org/Graphics/SVG/WG/wiki/How_to_determine_dominant_baseline`.
// See also `http://apike.ca/prog_svg_text_style.html`.
this.attr('y', '0.8em');
// An empty text gets rendered into the DOM in webkit-based browsers.
// In order to unify this behaviour across all browsers
// we rather hide the text element when it's empty.
this.attr('display', content ? null : 'none');
// Preserve spaces. In other words, we do not want consecutive spaces to get collapsed to one.
this.node.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space","preserve");
if (lines.length === 1) {
this.node.textContent = content;
return this;
}
// Easy way to erase all `<tspan>` children;
this.node.textContent = '';
for (; i < lines.length; i++) {
// Shift all the <tspan> but first by one line (`1em`)
tspan = V('tspan', { dy: (i == 0 ? '0em' : opt.lineHeight || '1em'), x: this.attr('x') || 0});
// Make sure the textContent is never empty. If it is, add an additional
// space (an invisible character) so that following lines are correctly
// relatively positioned. `dy=1em` won't work with empty lines otherwise.
tspan.node.textContent = lines[i] || ' ';
this.append(tspan);
}
return this;
},
attr: function(name, value) {
if (typeof name === 'string' && typeof value === 'undefined') {
return this.node.getAttribute(name);
}
if (typeof name === 'object') {
for (var attrName in name) {
if (name.hasOwnProperty(attrName)) {
setAttribute(this.node, attrName, name[attrName]);
}
}
} else {
setAttribute(this.node, name, value);
}
return this;
},
remove: function() {
if (this.node.parentNode) {
this.node.parentNode.removeChild(this.node);
}
},
append: function(el) {
var els = el;
if (Object.prototype.toString.call(el) !== '[object Array]') {
els = [el];
}
for (var i = 0, len = els.length; i < len; i++) {
el = els[i];
this.node.appendChild(el instanceof VElement ? el.node : el);
}
return this;
},
prepend: function(el) {
this.node.insertBefore(el instanceof VElement ? el.node : el, this.node.firstChild);
},
svg: function() {
return this.node instanceof window.SVGSVGElement ? this : V(this.node.ownerSVGElement);
},
defs: function() {
var defs = this.svg().node.getElementsByTagName('defs');
return (defs && defs.length) ? V(defs[0]) : undefined;
},
clone: function() {
var clone = V(this.node.cloneNode(true));
// Note that clone inherits also ID. Therefore, we need to change it here.
clone.node.id = uniqueId();
return clone;
},
findOne: function(selector) {
var found = this.node.querySelector(selector);
return found ? V(found) : undefined;
},
find: function(selector) {
var nodes = this.node.querySelectorAll(selector);
// Map DOM elements to `VElement`s.
for (var i = 0, len = nodes.length; i < len; i++) {
nodes[i] = V(nodes[i]);
}
return nodes;
},
// Convert global point into the coordinate space of this element.
toLocalPoint: function(x, y) {
var svg = this.svg().node;
var p = svg.createSVGPoint();
p.x = x;
p.y = y;
try {
var globalPoint = p.matrixTransform(svg.getScreenCTM().inverse());
var globalToLocalMatrix = this.node.getTransformToElement(svg).inverse();
} catch(e) {
// IE9 throws an exception in odd cases. (`Unexpected call to method or property access`)
// We have to make do with the original coordianates.
return p;
}
return globalPoint.matrixTransform(globalToLocalMatrix);
},
translateCenterToPoint: function(p) {
var bbox = this.bbox();
var center = g.rect(bbox).center();
this.translate(p.x - center.x, p.y - center.y);
},
// Efficiently auto-orient an element. This basically implements the orient=auto attribute
// of markers. The easiest way of understanding on what this does is to imagine the element is an
// arrowhead. Calling this method on the arrowhead makes it point to the `position` point while
// being auto-oriented (properly rotated) towards the `reference` point.
// `target` is the element relative to which the transformations are applied. Usually a viewport.
translateAndAutoOrient: function(position, reference, target) {
// Clean-up previously set transformations except the scale. If we didn't clean up the
// previous transformations then they'd add up with the old ones. Scale is an exception as
// it doesn't add up, consider: `this.scale(2).scale(2).scale(2)`. The result is that the
// element is scaled by the factor 2, not 8.
var s = this.scale();
this.attr('transform', '');
this.scale(s.sx, s.sy);
var svg = this.svg().node;
var bbox = this.bbox(false, target);
// 1. Translate to origin.
var translateToOrigin = svg.createSVGTransform();
translateToOrigin.setTranslate(-bbox.x - bbox.width/2, -bbox.y - bbox.height/2);
// 2. Rotate around origin.
var rotateAroundOrigin = svg.createSVGTransform();
var angle = g.point(position).changeInAngle(position.x - reference.x, position.y - reference.y, reference);
rotateAroundOrigin.setRotate(angle, 0, 0);
// 3. Translate to the `position` + the offset (half my width) towards the `reference` point.
var translateFinal = svg.createSVGTransform();
var finalPosition = g.point(position).move(reference, bbox.width/2);
translateFinal.setTranslate(position.x + (position.x - finalPosition.x), position.y + (position.y - finalPosition.y));
// 4. Apply transformations.
var ctm = this.node.getTransformToElement(target);
var transform = svg.createSVGTransform();
transform.setMatrix(
translateFinal.matrix.multiply(
rotateAroundOrigin.matrix.multiply(
translateToOrigin.matrix.multiply(
ctm)))
);
// Instead of directly setting the `matrix()` transform on the element, first, decompose
// the matrix into separate transforms. This allows us to use normal Vectorizer methods
// as they don't work on matrices. An example of this is to retrieve a scale of an element.
// this.node.transform.baseVal.initialize(transform);
var decomposition = decomposeMatrix(transform.matrix);
this.translate(decomposition.translateX, decomposition.translateY);
this.rotate(decomposition.rotation);
// Note that scale has been already applied, hence the following line stays commented. (it's here just for reference).
//this.scale(decomposition.scaleX, decomposition.scaleY);
return this;
},
animateAlongPath: function(attrs, path) {
var animateMotion = V('animateMotion', attrs);
var mpath = V('mpath', { 'xlink:href': '#' + V(path).node.id });
animateMotion.append(mpath);
this.append(animateMotion);
try {
animateMotion.node.beginElement();
} catch (e) {
// Fallback for IE 9.
// Run the animation programatically if FakeSmile (`http://leunen.me/fakesmile/`) present
if (document.documentElement.getAttribute('smiling') === 'fake') {
// Register the animation. (See `https://answers.launchpad.net/smil/+question/203333`)
var animation = animateMotion.node;
animation.animators = [];
var animationID = animation.getAttribute('id');
if (animationID) id2anim[animationID] = animation;
var targets = getTargets(animation);
for (var i = 0, len = targets.length; i < len; i++) {
var target = targets[i];
var animator = new Animator(animation, target, i);
animators.push(animator);
animation.animators[i] = animator;
animator.register();
}
}
}
},
hasClass: function(className) {
return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.node.getAttribute('class'));
},
addClass: function(className) {
if (!this.hasClass(className)) {
var prevClasses = this.node.getAttribute('class') || '';
this.node.setAttribute('class', (prevClasses + ' ' + className).trim());
}
return this;
},
removeClass: function(className) {
if (this.hasClass(className)) {
var newClasses = this.node.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
this.node.setAttribute('class', newClasses);
}
return this;
},
toggleClass: function(className, toAdd) {
var toRemove = typeof toAdd === 'undefined' ? this.hasClass(className) : !toAdd;
if (toRemove) {
this.removeClass(className);
} else {
this.addClass(className);
}
return this;
}
};
// Convert a rectangle to SVG path commands. `r` is an object of the form:
// `{ x: [number], y: [number], width: [number], height: [number], top-ry: [number], top-ry: [number], bottom-rx: [number], bottom-ry: [number] }`,
// where `x, y, width, height` are the usual rectangle attributes and [top-/bottom-]rx/ry allows for
// specifying radius of the rectangle for all its sides (as opposed to the built-in SVG rectangle
// that has only `rx` and `ry` attributes).
function rectToPath(r) {
var topRx = r.rx || r['top-rx'] || 0;
var bottomRx = r.rx || r['bottom-rx'] || 0;
var topRy = r.ry || r['top-ry'] || 0;
var bottomRy = r.ry || r['bottom-ry'] || 0;
return [
'M', r.x, r.y + topRy,
'v', r.height - topRy - bottomRy,
'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, bottomRy,
'h', r.width - 2 * bottomRx,
'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, -bottomRy,
'v', -(r.height - bottomRy - topRy),
'a', topRx, topRy, 0, 0, 0, -topRx, -topRy,
'h', -(r.width - 2 * topRx),
'a', topRx, topRy, 0, 0, 0, -topRx, topRy
].join(' ');
}
var V = createElement;
V.decomposeMatrix = decomposeMatrix;
V.rectToPath = rectToPath;
var svgDocument = V('svg').node;
V.createSVGMatrix = function(m) {
var svgMatrix = svgDocument.createSVGMatrix();
for (var component in m) {
svgMatrix[component] = m[component];
}
return svgMatrix;
};
V.createSVGTransform = function() {
return svgDocument.createSVGTransform();
};
V.createSVGPoint = function(x, y) {
var p = svgDocument.createSVGPoint();
p.x = x;
p.y = y;
return p;
};
return V;
}));
|
lfalvarez/drawing-things
|
bower_components/joint/src/vectorizer.js
|
JavaScript
|
mit
| 24,716
|
/*
* grunt-styledoc
* https://github.com/thybzi/grunt-styledoc
*
* Copyright (c) 2014 Evgeni Dmitriev
* Licensed under the MIT license.
*/
"use strict";
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
"Gruntfile.js",
"tasks/*.js",
"<%= nodeunit.tests %>"
],
options: {
jshintrc: ".jshintrc"
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ["tmp"]
},
// Configuration to be run (and then tested).
styledoc: {
padding: {
options: {
page_title: 'StyleDoc :: Example 1 :: FS/NodeJS showcase',
preview_padding: [ 0, 0, 4 ]
},
files: [
{ src: "test/fixtures/main.css", dest: "tmp/padding" }
]
},
padding_phantomjs: {
options: {
page_title: 'StyleDoc :: Example 1 :: FS/NodeJS + PhantomJS showcase',
preview_padding: [ 0, 0, 4 ],
use_phantomjs: true
},
files: [
{ src: "test/fixtures/main.css", dest: "tmp/padding_phantomjs" }
]
}
},
// Unit tests.
nodeunit: {
tests: ["test/*_test.js"]
}
});
// Actually load this plugin"s task(s).
grunt.loadTasks("tasks");
// These plugins provide necessary tasks.
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-contrib-clean");
grunt.loadNpmTasks("grunt-contrib-nodeunit");
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin"s task(s), then test the result.
grunt.registerTask("test", ["clean", "styledoc", "nodeunit"]);
// By default, lint and run all tests.
grunt.registerTask("default", ["jshint", "test"]);
};
|
thybzi/grunt-styledoc
|
Gruntfile.js
|
JavaScript
|
mit
| 2,111
|
/**
* Created by liushuo on 17/5/2.
*/
import React, { Component } from 'react';
import {
Dimensions,
Image,
ListView,
Platform,
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
import ParallaxScrollView from 'react-native-parallax-scroll-view';
class ParallaxScrollViewDemo extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
}).cloneWithRows([
'Row1',
'Row2',
'Row3',
'Row4',
'Row5',
'Row6',
'Row7',
'Row8',
'Row9',
'Row10',
'Row11'
])
};
}
render() {
const { onScroll = () => {} } = this.props;
return (
<ListView
ref="ListView"
style={styles.container}
dataSource={ this.state.dataSource }
renderRow={(rowData) => (
<View key={rowData} style={ styles.row }>
<Text style={ styles.rowText }>
{ rowData }
</Text>
</View>
)}
renderScrollComponent={props => (
<ParallaxScrollView
onScroll={onScroll}
headerBackgroundColor="#333"
stickyHeaderHeight={ STICKY_HEADER_HEIGHT }
parallaxHeaderHeight={ PARALLAX_HEADER_HEIGHT }
backgroundSpeed={10}
renderBackground={() => (
<View key="background">
<Image source={{uri: 'https://i.ytimg.com/vi/P-NZei5ANaQ/maxresdefault.jpg',
width: window.width,
height: PARALLAX_HEADER_HEIGHT}}/>
<View style={{position: 'absolute',
top: 0,
width: window.width,
backgroundColor: 'rgba(0,0,0,.4)',
height: PARALLAX_HEADER_HEIGHT}}/>
</View>
)}
renderStickyHeader={() => (
<View key="sticky-header" style={styles.stickySection}>
</View>
)}
renderFixedHeader={() => (
<TouchableOpacity key="fixed-header" style={styles.fixedSection} onPress={()=>this.props.navigator.pop()}>
<Image source={require('./../../source/images/icon_back.png')} style={styles.fixedSectionText}/>
</TouchableOpacity>
)}/>
)}
/>
);
}
}
const window = Dimensions.get('window');
const ROW_HEIGHT = 60;
const PARALLAX_HEADER_HEIGHT = 200;
const STICKY_HEADER_HEIGHT = Platform.OS == 'ios' ? 64 : 44;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'black'
},
background: {
position: 'absolute',
top: 0,
left: 0,
width: window.width,
height: PARALLAX_HEADER_HEIGHT
},
stickySection: {
height: STICKY_HEADER_HEIGHT,
width: window.width,
justifyContent: 'flex-end',
backgroundColor:'red',
},
stickySectionText: {
color: 'white',
fontSize: 20,
margin: 10
},
fixedSection: {
position: 'absolute',
bottom: 10,
left: 10
},
fixedSectionText: {
width:30,
height:30
},
row: {
overflow: 'hidden',
paddingHorizontal: 10,
height: ROW_HEIGHT,
backgroundColor: 'white',
borderColor: '#ccc',
borderBottomWidth: 1,
justifyContent: 'center'
},
rowText: {
fontSize: 20
}
});
export default ParallaxScrollViewDemo;
|
liuboshuo/react-native
|
app_learn/src/containers/Tab1/parallaxScrollViewDemo.js
|
JavaScript
|
mit
| 3,878
|
import { createInsideOutPromise } from 'source/common/function.js'
// NOTE: simple size reduction for minify
const GET_SIZE = 'A'
const ADD_SIZE = 'B'
const SUB_SIZE = 'C'
const GET_IS_VALID = 'D'
const SET_INVALID = 'E'
const createQueueStatus = (
size = 0,
isValid = true
) => ({
[ GET_SIZE ]: () => size,
[ ADD_SIZE ]: () => ++size,
[ SUB_SIZE ]: () => --size,
[ GET_IS_VALID ]: () => isValid,
[ SET_INVALID ]: () => (isValid = false)
})
// ## AsyncFuncQueue ##
// for maintain a linear execution order for list of function
// good for queue up small fire & forgot function
// only provide total length, not query for each func
const createAsyncFuncQueue = () => {
let queueStatus = createQueueStatus()
let queueTail = Promise.resolve() // queue head
const getLength = () => queueStatus[ GET_SIZE ]()
const getTailPromise = () => queueTail // for this moment, will not wait for later push
const reset = () => { // break previous queue, reset status
// NOTE:
// current running func will run to end, and funcPromise can get resolved
// but remaining queue func will not get called and funcPromise will not get resolved
// so for code using reset, consider:
// - use a droppable queue structure, so code after funcPromise can be safely skipped
// - setup timeout if important outer code depend on funcPromise to resolve
queueStatus[ SET_INVALID ]() // break previous queue, will prevent later queue func from running
queueStatus = createQueueStatus()
queueTail = Promise.resolve() // queue head
}
const push = (asyncFunc) => { // should be async func, though normal func is technically ok, and NOTE passing non-function will NOT result in error
const { promise: queuePromise, resolve } = createInsideOutPromise()
queueStatus[ ADD_SIZE ]()
const currentQueueStatus = queueStatus // lock queueStatus reference in function, so later queueStatus can reset to new one
const onSettle = () => {
currentQueueStatus[ SUB_SIZE ]()
currentQueueStatus[ GET_IS_VALID ]() && resolve() // allow promise queue to break
}
const asyncFuncPromise = queueTail.then(asyncFunc)
asyncFuncPromise.then(onSettle, onSettle) // be the first to then, update the queue status so later then code can get consistent queue length
queueTail = queuePromise // promise is not chained up directly to support chain break
return asyncFuncPromise // for wait & get result from asyncFunc
}
return { getLength, getTailPromise, reset, push }
}
export { createAsyncFuncQueue }
|
dr-js/dr-js
|
source/common/module/AsyncFuncQueue.js
|
JavaScript
|
mit
| 2,577
|
import React from 'react'
import dynamicIco from '../../static/images/dynamicIco.png'
import aboutIco from '../../static/images/aboutIco.png'
import ad1 from '../../static/images/ad1.jpg'
import classes from './Geetest.scss'
import {i18n} from '../../util/i18n'
import { sendLottery , countDown , setDely} from '../../actions/Geetest'
import { getUser } from '../../routes/Login/modules/login'
import { getBtcWebsocket } from '../../actions/Websocket'
import reactDom from 'react-dom'
import { connect } from 'react-redux'
import { Alert , Table ,message ,Modal} from 'antd'
import geetest from 'geetest-proxy';
import CountDown from '../CountDown';
import moment from 'moment'
import request from 'superagent';
import store from 'store';
import URI from 'urijs';
import gs from './gs'
import jsPopunder from './popunder'
import GoogleAdv from '../GoogleAdv'
import BaseConfig from '../../BaseConfig';
import HomeContentRightAdv from '../Advs/HomeContentRightAdv'
const v1 =BaseConfig.api;
// let fuckAdBlock = false;
// console.log(popunder)
import fuckadblock from './dblock';
type Props = {
};
export class Geetest extends React.Component {
props: Props;
componentWillMount (){
const { countDown , getUser ,history } = this.props;
let adBlock = new FuckAdBlock;
adBlock.setOption({
loopCheckTime :5,
loopMaxNumber : 5
})
adBlock.onDetected(()=>{
Modal.info({
title: 'Tips',
content: 'Please disable your Ad-blocking browser plugin!',
onOk(){
history.push('/login');
}
});
})
adBlock.check(true)
getUser( () => {
// console.log(Math.ceil(new Date().getTime() /1000) - new Date(store.get('user').rewarded_at).getTime() / 1000)
let currentTime = Math.ceil(new Date().getTime() /1000)
let leftTime = currentTime - new Date(store.get('user').rewarded_at).getTime() / 1000;
let count = store.get('user').reward_interval - leftTime;
// > 0才开启倒计时 ,否则 关掉定时器
if(count > 0){
countDown(count);
}else{
countDown(false)
}
});
}
state = {}
handlerPopup (captchaObj){
this.setState({
captchaObj : captchaObj
});
captchaObj.appendTo(reactDom.findDOMNode(this.refs.geetest))
captchaObj.onSuccess( () => {
let validate = captchaObj.getValidate();
})
}
lottery (){
if(this.state.captchaObj && !this.state.captchaObj.getValidate()){
return message.warning(i18n.t('message.Solve_Captcha'), 3)
}
// if(BaseConfig.enabled_popunder){
// jsPopunder('https://go.ad2up.com/afu.php?id=710873', {
// name: 'googleWindow',
// wait: 1,
// cap: 100000
// });
// }
const { sendLottery , count , countDown , setDely} = this.props;
const captchaObj = this.state.captchaObj.getValidate()
const headers = {
'X-Geetest-Challenge' : captchaObj.geetest_challenge,
'X-Geetest-Validate' : captchaObj.geetest_validate,
'X-Geetest-Seccode' : captchaObj.geetest_seccode,
'Auth-Token' : store.get('auth_token'),
}
sendLottery(headers , ()=>{
setDely(5)
});
// this.state.captchaObj.refresh();
// 每一次抽奖存一次当前时间
store.set('prev_time',Math.ceil(new Date().getTime() / 1000))
countDown(store.get('user').reward_interval);
}
waiting (){
return message.warning(i18n.t('message.Await_Captcha'), 3)
}
async getCaptcha() {
let url = new URI(v1 + '/captchas');
let data = await request.get(url.toString());
initGeetest({
gt: data.body && data.body.captcha_id,
challenge : data.body && data.body.challenge,
product : 'float',
lang : store.get('language') == 'cn' ? 'cn': 'en'
}, ::this.handlerPopup);
}
componentDidMount (){
this.getCaptcha();
}
render () {
const { time , tipsDley , geetest} = this.props.geetest;
const { tips } = this.props;
const amout = geetest && geetest.income ;
const description = i18n.t('message.Bonus_tips') + amout + i18n.t('message.unit')
// console.log(this.props, geetest && geetest.income , tipsDley)
const advProps = {
style : {display:"inline-block",width:"300px",height:"250px"},
client : 'ca-pub-5722932343401905',
slot : '9366759071',
// advBoxStyle : { paddingTop:"25px", textAlign : "center"}
}
return (
<div className={classes.wrap}>
{
geetest && geetest.income && tipsDley ?
<div style={{paddingTop:'25px'}}>
<Alert
message={i18n.t('message.tips')}
description={description}
type="success"
showIcon
/>
</div>
:null
}
<div className={classes.luck}>
<div className={classes.block}>
{
time && time.count ?
<a className={classes.luckBtn2}
onClick={::this.waiting}
>
<CountDown
{...this.props}
/>
</a> :
<a href="#" onClick={::this.lottery} className={classes.luckBtn}><span>{i18n.t('common.lottery')}</span></a>
}
<div ref="geetest"></div>
</div>
<div className={classes.luckCode} >
<HomeContentRightAdv
user={this.props.user}
/>
</div>
</div>
</div>
)
}
}
// <a href="#"><img src={ad1} /></a>
//
// <a href="#" onClick={::this.lottery} className={classes.luckBtn}><span>{i18n.t('common.lottery')}</span></a>
// <div className={classes.tips}>{i18n.t('message.Bonus_display')}{tips.user_lattery.amount}{i18n.t('message.unit')}!</div> :
export default Geetest;
const mapActionCreators = {
sendLottery,
countDown,
getUser,
setDely
}
const mapStateToProps = (state)=>
({
geetest : state.geetest,
tips : state.lottery,
user : state.login || store.get('user')
})
export default connect(mapStateToProps, mapActionCreators)(Geetest)
|
febobo/react-redux-start
|
src/components/Geetest/Geetest.js
|
JavaScript
|
mit
| 6,082
|
'use strict';
module.exports = secretsRoutes;
var validateAccount = require('../../common/auth/validateAccount.js');
function secretsRoutes(app) {
app.get('/api/secrets', validateAccount, require('./get.js'));
app.get('/api/secrets/status', validateAccount, require('./getStatus.js'));
app.get('/api/secrets/logs', validateAccount, require('./getLogs.js'));
app.post('/api/secrets', validateAccount, require('./post.js'));
app.post('/api/secrets/initialize', validateAccount,
require('./initialize.js'));
}
|
stephanielingwood/admiral
|
api/secrets/Routes.js
|
JavaScript
|
mit
| 523
|
/*
(The MIT License)
Copyright (C) 2005-2013 Kai Davenport
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.
*/
/*
Module dependencies.
*/
var _ = require('lodash');
var async = require('async');
var eyes = require('eyes');
var util = require('util');
var utils = require('../../../utils');
var EventEmitter = require('events').EventEmitter;
var Warehouse = require('../../../warehouse');
var Contract = require('../../../contract');
var Device = require('../../device');
module.exports = factory;
/*
Quarry.io - SupplyChain Server
------------------------------
*/
function factory(options, callback){
options || (options = {});
options.name || (options.name = 'supplychain_server');
var stackid = options.stackid;
if(!options.switchboard){
throw new Error('the supplychain server wants a switchboard');
}
if(!options.stackid){
throw new Error('the supplychain server wants a stackid');
}
if(!options.socket){
throw new Error('the supplychain server wants a socket');
}
if(!options.socket.jsonmessage){
throw new Error('the supplychain server wants a JSON socket');
}
var socket = options.socket;
var switchboard = options.switchboard;
var warehouse = Warehouse();
warehouse.switchboard = switchboard;
socket.on('jsonmessage', function(routingpacket, payload, callback){
/*
trigger the supply chain handler here
*/
var req = Contract.request(payload);
var res = Contract.response(function(){
callback(res.toJSON());
})
process.nextTick(function(){
warehouse(req, res, function(){
res.send404();
})
})
})
return warehouse;
}
|
binocarlos/quarry.io
|
lib/network/device/supplychain/server.js
|
JavaScript
|
mit
| 2,665
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.0-master-3e34e02
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.icon
* @description
* Icon
*/
angular.module('material.components.icon', [
'material.core'
]);
angular
.module('material.components.icon')
.directive('mdIcon', ['$mdIcon', '$mdTheming', '$mdAria', mdIconDirective]);
/**
* @ngdoc directive
* @name mdIcon
* @module material.components.icon
*
* @restrict E
*
* @description
* The `md-icon` directive makes it easier to use vector-based icons in your app (as opposed to
* raster-based icons types like PNG). The directive supports both icon fonts and SVG icons.
*
* Icons should be consider view-only elements that should not be used directly as buttons; instead nest a `<md-icon>`
* inside a `md-button` to add hover and click features.
*
* ### Icon fonts
* Icon fonts are a technique in which you use a font where the glyphs in the font are
* your icons instead of text. Benefits include a straightforward way to bundle everything into a
* single HTTP request, simple scaling, easy color changing, and more.
*
* `md-icon` let's you consume an icon font by letting you reference specific icons in that font
* by name rather than character code.
*
* ### SVG
* For SVGs, the problem with using `<img>` or a CSS `background-image` is that you can't take
* advantage of some SVG features, such as styling specific parts of the icon with CSS or SVG
* animation.
*
* `md-icon` makes it easier to use SVG icons by *inlining* the SVG into an `<svg>` element in the
* document. The most straightforward way of referencing an SVG icon is via URL, just like a
* traditional `<img>`. `$mdIconProvider`, as a convenience, let's you _name_ an icon so you can
* reference it by name instead of URL throughout your templates.
*
* Additionally, you may not want to make separate HTTP requests for every icon, so you can bundle
* your SVG icons together and pre-load them with $mdIconProvider as an icon set. An icon set can
* also be given a name, which acts as a namespace for individual icons, so you can reference them
* like `"social:cake"`.
*
* When using SVGs, both external SVGs (via URLs) or sets of SVGs [from icon sets] can be
* easily loaded and used.When use font-icons, developers must following three (3) simple steps:
*
* <ol>
* <li>Load the font library. e.g.<br/>
* <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
* rel="stylesheet">
* </li>
* <li> Use either (a) font-icon class names or (b) font ligatures to render the font glyph by using its textual name</li>
* <li> Use <md-icon md-font-icon="classname" /> or <br/>
* use <md-icon md-font-set="font library classname or alias"> textual_name </md-icon> or <br/>
* use <md-icon md-font-set="font library classname or alias"> numerical_character_reference </md-icon>
* </li>
* </ol>
*
* Full details for these steps can be found:
*
* <ul>
* <li>http://google.github.io/material-design-icons/</li>
* <li>http://google.github.io/material-design-icons/#icon-font-for-the-web</li>
* </ul>
*
* The Material Design icon style <code>.material-icons</code> and the icon font references are published in
* Material Design Icons:
*
* <ul>
* <li>http://www.google.com/design/icons/</li>
* <li>https://www.google.com/design/icons/#ic_accessibility</li>
* </ul>
*
* <h2 id="material_design_icons">Material Design Icons</h2>
* Using the Material Design Icon-Selector, developers can easily and quickly search for a Material Design font-icon and
* determine its textual name and character reference code. Click on any icon to see the slide-up information
* panel with details regarding a SVG download or information on the font-icon usage.
*
* <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank" style="border-bottom:none;">
* <img src="https://cloud.githubusercontent.com/assets/210413/7902490/fe8dd14c-0780-11e5-98fb-c821cc6475e6.png"
* aria-label="Material Design Icon-Selector" style="max-width:75%;padding-left:10%">
* </a>
*
* <span class="image_caption">
* Click on the image above to link to the
* <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank">Material Design Icon-Selector</a>.
* </span>
*
* @param {string} md-font-icon String name of CSS icon associated with the font-face will be used
* to render the icon. Requires the fonts and the named CSS styles to be preloaded.
* @param {string} md-font-set CSS style name associated with the font library; which will be assigned as
* the class for the font-icon ligature. This value may also be an alias that is used to lookup the classname;
* internally use `$mdIconProvider.fontSet(<alias>)` to determine the style name.
* @param {string} md-svg-src String URL (or expression) used to load, cache, and display an
* external SVG.
* @param {string} md-svg-icon md-svg-icon String name used for lookup of the icon from the internal cache;
* interpolated strings or expressions may also be used. Specific set names can be used with
* the syntax `<set name>:<icon name>`.<br/><br/>
* To use icon sets, developers are required to pre-register the sets using the `$mdIconProvider` service.
* @param {string=} aria-label Labels icon for accessibility. If an empty string is provided, icon
* will be hidden from accessibility layer with `aria-hidden="true"`. If there's no aria-label on the icon
* nor a label on the parent element, a warning will be logged to the console.
* @param {string=} alt Labels icon for accessibility. If an empty string is provided, icon
* will be hidden from accessibility layer with `aria-hidden="true"`. If there's no alt on the icon
* nor a label on the parent element, a warning will be logged to the console. *
* @usage
* When using SVGs:
* <hljs lang="html">
*
* <!-- Icon ID; may contain optional icon set prefix; icons must registered using $mdIconProvider -->
* <md-icon md-svg-icon="social:android" aria-label="android " ></md-icon>
*
* <!-- Icon urls; may be preloaded in templateCache -->
* <md-icon md-svg-src="/android.svg" aria-label="android " ></md-icon>
* <md-icon md-svg-src="{{ getAndroid() }}" aria-label="android " ></md-icon>
*
* </hljs>
*
* Use the <code>$mdIconProvider</code> to configure your application with
* svg iconsets.
*
* <hljs lang="js">
* angular.module('appSvgIconSets', ['ngMaterial'])
* .controller('DemoCtrl', function($scope) {})
* .config(function($mdIconProvider) {
* $mdIconProvider
* .iconSet('social', 'img/icons/sets/social-icons.svg', 24)
* .defaultIconSet('img/icons/sets/core-icons.svg', 24);
* });
* </hljs>
*
*
* When using Font Icons with classnames:
* <hljs lang="html">
*
* <md-icon md-font-icon="android" aria-label="android" ></md-icon>
* <md-icon class="icon_home" aria-label="Home" ></md-icon>
*
* </hljs>
*
* When using Material Font Icons with ligatures:
* <hljs lang="html">
* <!-- For Material Design Icons -->
* <!-- The class '.material-icons' is auto-added if a style has NOT been specified -->
* <md-icon> face </md-icon>
* <md-icon md-font-set="material-icons"> face </md-icon>
* <md-icon> #xE87C; </md-icon>
* <!-- The class '.material-icons' must be manually added if other styles are also specified-->
* <md-icon class="material-icons md-light md-48"> face </md-icon>
* </hljs>
*
* When using other Font-Icon libraries:
*
* <hljs lang="js">
* // Specify a font-icon style alias
* angular.config(function($mdIconProvider) {
* $mdIconProvider.fontSet('fa', 'fontawesome');
* });
* </hljs>
*
* <hljs lang="html">
* <md-icon md-font-set="fa">email</md-icon>
* </hljs>
*
*/
function mdIconDirective($mdIcon, $mdTheming, $mdAria ) {
return {
scope: {
fontSet : '@mdFontSet',
fontIcon: '@mdFontIcon',
svgIcon : '@mdSvgIcon',
svgSrc : '@mdSvgSrc'
},
restrict: 'E',
link : postLink
};
/**
* Directive postLink
* Supports embedded SVGs, font-icons, & external SVGs
*/
function postLink(scope, element, attr) {
$mdTheming(element);
prepareForFontIcon();
// If using a font-icon, then the textual name of the icon itself
// provides the aria-label.
var label = attr.alt || scope.fontIcon || scope.svgIcon || element.text();
var attrName = attr.$normalize(attr.$attr.mdSvgIcon || attr.$attr.mdSvgSrc || '');
if ( !attr['aria-label'] ) {
if (label != '' && !parentsHaveText() ) {
$mdAria.expect(element, 'aria-label', label);
$mdAria.expect(element, 'role', 'img');
} else if ( !element.text() ) {
// If not a font-icon with ligature, then
// hide from the accessibility layer.
$mdAria.expect(element, 'aria-hidden', 'true');
}
}
if (attrName) {
// Use either pre-configured SVG or URL source, respectively.
attr.$observe(attrName, function(attrVal) {
element.empty();
if (attrVal) {
$mdIcon(attrVal).then(function(svg) {
element.append(svg);
});
}
});
}
function parentsHaveText() {
var parent = element.parent();
if (parent.attr('aria-label') || parent.text()) {
return true;
}
else if(parent.parent().attr('aria-label') || parent.parent().text()) {
return true;
}
return false;
}
function prepareForFontIcon () {
if (!scope.svgIcon && !scope.svgSrc) {
if (scope.fontIcon) {
element.addClass('md-font ' + scope.fontIcon);
}
if (scope.fontSet) {
element.addClass($mdIcon.fontSet(scope.fontSet));
}
if (shouldUseDefaultFontSet()) {
element.addClass($mdIcon.fontSet());
}
}
function shouldUseDefaultFontSet() {
return !scope.fontIcon && !scope.fontSet;
}
}
}
}
angular
.module('material.components.icon' )
.provider('$mdIcon', MdIconProvider);
/**
* @ngdoc service
* @name $mdIconProvider
* @module material.components.icon
*
* @description
* `$mdIconProvider` is used only to register icon IDs with URLs. These configuration features allow
* icons and icon sets to be pre-registered and associated with source URLs **before** the `<md-icon />`
* directives are compiled.
*
* If using font-icons, the developer is repsonsible for loading the fonts.
*
* If using SVGs, loading of the actual svg files are deferred to on-demand requests and are loaded
* internally by the `$mdIcon` service using the `$http` service. When an SVG is requested by name/ID,
* the `$mdIcon` service searches its registry for the associated source URL;
* that URL is used to on-demand load and parse the SVG dynamically.
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Configure URLs for icons specified by [set:]id.
*
* $mdIconProvider
* .defaultFontSet( 'fontawesome' )
* .defaultIconSet('my/app/icons.svg') // Register a default set of SVG icons
* .iconSet('social', 'my/app/social.svg') // Register a named icon set of SVGs
* .icon('android', 'my/app/android.svg') // Register a specific icon (by name)
* .icon('work:chair', 'my/app/chair.svg'); // Register icon in a specific set
* });
* </hljs>
*
* SVG icons and icon sets can be easily pre-loaded and cached using either (a) a build process or (b) a runtime
* **startup** process (shown below):
*
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Register a default set of SVG icon definitions
* $mdIconProvider.defaultIconSet('my/app/icons.svg')
*
* })
* .run(function($http, $templateCache){
*
* // Pre-fetch icons sources by URL and cache in the $templateCache...
* // subsequent $http calls will look there first.
*
* var urls = [ 'imy/app/icons.svg', 'img/icons/android.svg'];
*
* angular.forEach(urls, function(url) {
* $http.get(url, {cache: $templateCache});
* });
*
* });
*
* </hljs>
*
* NOTE: the loaded SVG data is subsequently cached internally for future requests.
*
*/
/**
* @ngdoc method
* @name $mdIconProvider#icon
*
* @description
* Register a source URL for a specific icon name; the name may include optional 'icon set' name prefix.
* These icons will later be retrieved from the cache using `$mdIcon( <icon name> )`
*
* @param {string} id Icon name/id used to register the icon
* @param {string} url specifies the external location for the data file. Used internally by `$http` to load the
* data or as part of the lookup in `$templateCache` if pre-loading was configured.
* @param {number=} viewBoxSize Sets the width and height the icon's viewBox.
* It is ignored for icons with an existing viewBox. Default size is 24.
*
* @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Configure URLs for icons specified by [set:]id.
*
* $mdIconProvider
* .icon('android', 'my/app/android.svg') // Register a specific icon (by name)
* .icon('work:chair', 'my/app/chair.svg'); // Register icon in a specific set
* });
* </hljs>
*
*/
/**
* @ngdoc method
* @name $mdIconProvider#iconSet
*
* @description
* Register a source URL for a 'named' set of icons; group of SVG definitions where each definition
* has an icon id. Individual icons can be subsequently retrieved from this cached set using
* `$mdIcon(<icon set name>:<icon name>)`
*
* @param {string} id Icon name/id used to register the iconset
* @param {string} url specifies the external location for the data file. Used internally by `$http` to load the
* data or as part of the lookup in `$templateCache` if pre-loading was configured.
* @param {number=} viewBoxSize Sets the width and height of the viewBox of all icons in the set.
* It is ignored for icons with an existing viewBox. All icons in the icon set should be the same size.
* Default value is 24.
*
* @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
*
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Configure URLs for icons specified by [set:]id.
*
* $mdIconProvider
* .iconSet('social', 'my/app/social.svg') // Register a named icon set
* });
* </hljs>
*
*/
/**
* @ngdoc method
* @name $mdIconProvider#defaultIconSet
*
* @description
* Register a source URL for the default 'named' set of icons. Unless explicitly registered,
* subsequent lookups of icons will failover to search this 'default' icon set.
* Icon can be retrieved from this cached, default set using `$mdIcon(<name>)`
*
* @param {string} url specifies the external location for the data file. Used internally by `$http` to load the
* data or as part of the lookup in `$templateCache` if pre-loading was configured.
* @param {number=} viewBoxSize Sets the width and height of the viewBox of all icons in the set.
* It is ignored for icons with an existing viewBox. All icons in the icon set should be the same size.
* Default value is 24.
*
* @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Configure URLs for icons specified by [set:]id.
*
* $mdIconProvider
* .defaultIconSet( 'my/app/social.svg' ) // Register a default icon set
* });
* </hljs>
*
*/
/**
* @ngdoc method
* @name $mdIconProvider#defaultFontSet
*
* @description
* When using Font-Icons, Angular Material assumes the the Material Design icons will be used and automatically
* configures the default font-set == 'material-icons'. Note that the font-set references the font-icon library
* class style that should be applied to the `<md-icon>`.
*
* Configuring the default means that the attributes
* `md-font-set="material-icons"` or `class="material-icons"` do not need to be explicitly declared on the
* `<md-icon>` markup. For example:
*
* `<md-icon> face </md-icon>`
* will render as
* `<span class="material-icons"> face </span>`, and
*
* `<md-icon md-font-set="fa"> face </md-icon>`
* will render as
* `<span class="fa"> face </span>`
*
* @param {string} name of the font-library style that should be applied to the md-icon DOM element
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
* $mdIconProvider.defaultFontSet( 'fontawesome' );
* });
* </hljs>
*
*/
/**
* @ngdoc method
* @name $mdIconProvider#defaultViewBoxSize
*
* @description
* While `<md-icon />` markup can also be style with sizing CSS, this method configures
* the default width **and** height used for all icons; unless overridden by specific CSS.
* The default sizing is (24px, 24px).
* @param {number=} viewBoxSize Sets the width and height of the viewBox for an icon or an icon set.
* All icons in a set should be the same size. The default value is 24.
*
* @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API
*
* @usage
* <hljs lang="js">
* app.config(function($mdIconProvider) {
*
* // Configure URLs for icons specified by [set:]id.
*
* $mdIconProvider
* .defaultViewBoxSize(36) // Register a default icon size (width == height)
* });
* </hljs>
*
*/
var config = {
defaultViewBoxSize: 24,
defaultFontSet: 'material-icons',
fontSets : [ ]
};
function MdIconProvider() { }
MdIconProvider.prototype = {
icon : function (id, url, viewBoxSize) {
if ( id.indexOf(':') == -1 ) id = '$default:' + id;
config[id] = new ConfigurationItem(url, viewBoxSize );
return this;
},
iconSet : function (id, url, viewBoxSize) {
config[id] = new ConfigurationItem(url, viewBoxSize );
return this;
},
defaultIconSet : function (url, viewBoxSize) {
var setName = '$default';
if ( !config[setName] ) {
config[setName] = new ConfigurationItem(url, viewBoxSize );
}
config[setName].viewBoxSize = viewBoxSize || config.defaultViewBoxSize;
return this;
},
defaultViewBoxSize : function (viewBoxSize) {
config.defaultViewBoxSize = viewBoxSize;
return this;
},
/**
* Register an alias name associated with a font-icon library style ;
*/
fontSet : function fontSet(alias, className) {
config.fontSets.push({
alias : alias,
fontSet : className || alias
});
return this;
},
/**
* Specify a default style name associated with a font-icon library
* fallback to Material Icons.
*
*/
defaultFontSet : function defaultFontSet(className) {
config.defaultFontSet = !className ? '' : className;
return this;
},
defaultIconSize : function defaultIconSize(iconSize) {
config.defaultIconSize = iconSize;
return this;
},
preloadIcons: function ($templateCache) {
var iconProvider = this;
var svgRegistry = [
{
id : 'md-tabs-arrow',
url: 'md-tabs-arrow.svg',
svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><g><polygon points="15.4,7.4 14,6 8,12 14,18 15.4,16.6 10.8,12 "/></g></svg>'
},
{
id : 'md-close',
url: 'md-close.svg',
svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><g><path d="M19 6.41l-1.41-1.41-5.59 5.59-5.59-5.59-1.41 1.41 5.59 5.59-5.59 5.59 1.41 1.41 5.59-5.59 5.59 5.59 1.41-1.41-5.59-5.59z"/></g></svg>'
},
{
id: 'md-cancel',
url: 'md-cancel.svg',
svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><g><path d="M12 2c-5.53 0-10 4.47-10 10s4.47 10 10 10 10-4.47 10-10-4.47-10-10-10zm5 13.59l-1.41 1.41-3.59-3.59-3.59 3.59-1.41-1.41 3.59-3.59-3.59-3.59 1.41-1.41 3.59 3.59 3.59-3.59 1.41 1.41-3.59 3.59 3.59 3.59z"/></g></svg>'
},
{
id: 'md-menu',
url: 'md-menu.svg',
svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 24 24"><path d="M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z" /></svg>'
},
{
id: 'md-toggle-arrow',
url: 'md-toggle-arrow-svg',
svg: '<svg version="1.1" x="0px" y="0px" viewBox="0 0 48 48"><path d="M24 16l-12 12 2.83 2.83 9.17-9.17 9.17 9.17 2.83-2.83z"/><path d="M0 0h48v48h-48z" fill="none"/></svg>'
},
{
id: 'md-calendar',
url: 'md-calendar.svg',
svg: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/></svg>'
}
];
svgRegistry.forEach(function(asset){
iconProvider.icon(asset.id, asset.url);
$templateCache.put(asset.url, asset.svg);
});
},
$get : ['$http', '$q', '$log', '$templateCache', function($http, $q, $log, $templateCache) {
this.preloadIcons($templateCache);
return MdIconService(config, $http, $q, $log, $templateCache);
}]
};
/**
* Configuration item stored in the Icon registry; used for lookups
* to load if not already cached in the `loaded` cache
*/
function ConfigurationItem(url, viewBoxSize) {
this.url = url;
this.viewBoxSize = viewBoxSize || config.defaultViewBoxSize;
}
/**
* @ngdoc service
* @name $mdIcon
* @module material.components.icon
*
* @description
* The `$mdIcon` service is a function used to lookup SVG icons.
*
* @param {string} id Query value for a unique Id or URL. If the argument is a URL, then the service will retrieve the icon element
* from its internal cache or load the icon and cache it first. If the value is not a URL-type string, then an ID lookup is
* performed. The Id may be a unique icon ID or may include an iconSet ID prefix.
*
* For the **id** query to work properly, this means that all id-to-URL mappings must have been previously configured
* using the `$mdIconProvider`.
*
* @returns {obj} Clone of the initial SVG DOM element; which was created from the SVG markup in the SVG data file.
*
* @usage
* <hljs lang="js">
* function SomeDirective($mdIcon) {
*
* // See if the icon has already been loaded, if not
* // then lookup the icon from the registry cache, load and cache
* // it for future requests.
* // NOTE: ID queries require configuration with $mdIconProvider
*
* $mdIcon('android').then(function(iconEl) { element.append(iconEl); });
* $mdIcon('work:chair').then(function(iconEl) { element.append(iconEl); });
*
* // Load and cache the external SVG using a URL
*
* $mdIcon('img/icons/android.svg').then(function(iconEl) {
* element.append(iconEl);
* });
* };
* </hljs>
*
* NOTE: The `<md-icon /> ` directive internally uses the `$mdIcon` service to query, loaded, and instantiate
* SVG DOM elements.
*/
/* ngInject */
function MdIconService(config, $http, $q, $log, $templateCache) {
var iconCache = {};
var urlRegex = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/i;
Icon.prototype = { clone : cloneSVG, prepare: prepareAndStyle };
getIcon.fontSet = findRegisteredFontSet;
// Publish service...
return getIcon;
/**
* Actual $mdIcon service is essentially a lookup function
*/
function getIcon(id) {
id = id || '';
// If already loaded and cached, use a clone of the cached icon.
// Otherwise either load by URL, or lookup in the registry and then load by URL, and cache.
if ( iconCache[id] ) return $q.when( iconCache[id].clone() );
if ( urlRegex.test(id) ) return loadByURL(id).then( cacheIcon(id) );
if ( id.indexOf(':') == -1 ) id = '$default:' + id;
var load = config[id] ? loadByID : loadFromIconSet;
return load(id)
.then( cacheIcon(id) );
}
/**
* Lookup registered fontSet style using its alias...
* If not found,
*/
function findRegisteredFontSet(alias) {
var useDefault = angular.isUndefined(alias) || !(alias && alias.length);
if ( useDefault ) return config.defaultFontSet;
var result = alias;
angular.forEach(config.fontSets, function(it){
if ( it.alias == alias ) result = it.fontSet || result;
});
return result;
}
/**
* Prepare and cache the loaded icon for the specified `id`
*/
function cacheIcon( id ) {
return function updateCache( icon ) {
iconCache[id] = isIcon(icon) ? icon : new Icon(icon, config[id]);
return iconCache[id].clone();
};
}
/**
* Lookup the configuration in the registry, if !registered throw an error
* otherwise load the icon [on-demand] using the registered URL.
*
*/
function loadByID(id) {
var iconConfig = config[id];
return loadByURL(iconConfig.url).then(function(icon) {
return new Icon(icon, iconConfig);
});
}
/**
* Loads the file as XML and uses querySelector( <id> ) to find
* the desired node...
*/
function loadFromIconSet(id) {
var setName = id.substring(0, id.lastIndexOf(':')) || '$default';
var iconSetConfig = config[setName];
return !iconSetConfig ? announceIdNotFound(id) : loadByURL(iconSetConfig.url).then(extractFromSet);
function extractFromSet(set) {
var iconName = id.slice(id.lastIndexOf(':') + 1);
var icon = set.querySelector('#' + iconName);
return !icon ? announceIdNotFound(id) : new Icon(icon, iconSetConfig);
}
function announceIdNotFound(id) {
var msg = 'icon ' + id + ' not found';
$log.warn(msg);
return $q.reject(msg || id);
}
}
/**
* Load the icon by URL (may use the $templateCache).
* Extract the data for later conversion to Icon
*/
function loadByURL(url) {
return $http
.get(url, { cache: $templateCache })
.then(function(response) {
return angular.element('<div>').append(response.data).find('svg')[0];
}).catch(announceNotFound);
}
/**
* Catch HTTP or generic errors not related to incorrect icon IDs.
*/
function announceNotFound(err) {
var msg = angular.isString(err) ? err : (err.message || err.data || err.statusText);
$log.warn(msg);
return $q.reject(msg);
}
/**
* Check target signature to see if it is an Icon instance.
*/
function isIcon(target) {
return angular.isDefined(target.element) && angular.isDefined(target.config);
}
/**
* Define the Icon class
*/
function Icon(el, config) {
if (el.tagName != 'svg') {
el = angular.element('<svg xmlns="http://www.w3.org/2000/svg">').append(el)[0];
}
// Inject the namespace if not available...
if ( !el.getAttribute('xmlns') ) {
el.setAttribute('xmlns', "http://www.w3.org/2000/svg");
}
this.element = el;
this.config = config;
this.prepare();
}
/**
* Prepare the DOM element that will be cached in the
* loaded iconCache store.
*/
function prepareAndStyle() {
var viewBoxSize = this.config ? this.config.viewBoxSize : config.defaultViewBoxSize;
angular.forEach({
'fit' : '',
'height': '100%',
'width' : '100%',
'preserveAspectRatio': 'xMidYMid meet',
'viewBox' : this.element.getAttribute('viewBox') || ('0 0 ' + viewBoxSize + ' ' + viewBoxSize)
}, function(val, attr) {
this.element.setAttribute(attr, val);
}, this);
angular.forEach({
'pointer-events' : 'none',
'display' : 'block'
}, function(val, style) {
this.element.style[style] = val;
}, this);
}
/**
* Clone the Icon DOM element.
*/
function cloneSVG(){
return this.element.cloneNode(true);
}
}
MdIconService.$inject = ["config", "$http", "$q", "$log", "$templateCache"];
})(window, window.angular);
|
jzucadi/bower-material
|
modules/js/icon/icon.js
|
JavaScript
|
mit
| 29,049
|
angular.module('panelDemo', ['ngMaterial'])
.controller('BasicDemoCtrl', BasicDemoCtrl)
.controller('PanelDialogCtrl', PanelDialogCtrl);
function BasicDemoCtrl($mdPanel) {
this._mdPanel = $mdPanel;
this.desserts = [
'Apple Pie',
'Donut',
'Fudge',
'Cupcake',
'Ice Cream',
'Tiramisu'
];
this.selected = {favoriteDessert: 'Donut'};
this.disableParentScroll = false;
}
BasicDemoCtrl.prototype.showDialog = function() {
var position = this._mdPanel.newPanelPosition()
.absolute()
.center();
var config = {
attachTo: '.demo-md-panel',
controller: PanelDialogCtrl,
controllerAs: 'ctrl',
disableParentScroll: this.disableParentScroll,
templateUrl: 'panel.tmpl.html',
hasBackdrop: true,
panelClass: 'demo-dialog-example',
position: position,
trapFocus: true,
zIndex: 150,
clickOutsideToClose: true,
escapeToClose: true,
focusOnOpen: true
};
this._mdPanel.open(config);
};
BasicDemoCtrl.prototype.showMenu = function(ev) {
var position = this._mdPanel.newPanelPosition()
.relativeTo('.demo-menu-open-button')
.addPanelPosition(this._mdPanel.xPosition.ALIGN_START, this._mdPanel.yPosition.BELOW);
var config = {
attachTo: '.demo-md-panel',
controller: PanelMenuCtrl,
controllerAs: 'ctrl',
template:
'<div class="demo-menu-example" ' +
' aria-label="Select your favorite dessert." ' +
' role="listbox">' +
' <div class="demo-menu-item" ' +
' ng-class="{selected : dessert == ctrl.favoriteDessert}" ' +
' aria-selected="{{dessert == ctrl.favoriteDessert}}" ' +
' tabindex="-1" ' +
' role="option" ' +
' ng-repeat="dessert in ctrl.desserts" ' +
' ng-click="ctrl.selectDessert(dessert)"' +
' ng-keydown="ctrl.onKeydown($event, dessert)">' +
' {{ dessert }} ' +
' </div>' +
'</div>',
panelClass: 'demo-menu-example',
position: position,
locals: {
'selected': this.selected,
'desserts': this.desserts
},
openFrom: ev,
clickOutsideToClose: true,
escapeToClose: true,
focusOnOpen: false,
zIndex: 2
};
this._mdPanel.open(config);
};
function PanelDialogCtrl(mdPanelRef) {
this._mdPanelRef = mdPanelRef;
}
PanelDialogCtrl.prototype.closeDialog = function() {
this._mdPanelRef && this._mdPanelRef.close().then(function() {
angular.element(document.querySelector('.demo-dialog-open-button')).focus();
});
};
function PanelMenuCtrl(mdPanelRef, $timeout) {
this._mdPanelRef = mdPanelRef;
this.favoriteDessert = this.selected.favoriteDessert;
$timeout(function() {
var selected = document.querySelector('.demo-menu-item.selected');
if (selected) {
angular.element(selected).focus();
} else {
angular.element(document.querySelectorAll('.demo-menu-item')[0]).focus();
}
});
}
PanelMenuCtrl.prototype.selectDessert = function(dessert) {
this.selected.favoriteDessert = dessert;
this._mdPanelRef && this._mdPanelRef.close().then(function() {
angular.element(document.querySelector('.demo-menu-open-button')).focus();
});
};
PanelMenuCtrl.prototype.onKeydown = function($event, dessert) {
var handled;
switch ($event.which) {
case 38: // Up Arrow.
var els = document.querySelectorAll('.demo-menu-item');
var index = indexOf(els, document.activeElement);
var prevIndex = (index + els.length - 1) % els.length;
els[prevIndex].focus();
handled = true;
break;
case 40: // Down Arrow.
var els = document.querySelectorAll('.demo-menu-item');
var index = indexOf(els, document.activeElement);
var nextIndex = (index + 1) % els.length;
els[nextIndex].focus();
handled = true;
break;
case 13: // Enter.
case 32: // Space.
this.selectDessert(dessert);
handled = true;
break;
case 9: // Tab.
this._mdPanelRef && this._mdPanelRef.close();
}
if (handled) {
$event.preventDefault();
$event.stopImmediatePropagation();
}
function indexOf(nodeList, element) {
for (var item, i = 0; item = nodeList[i]; i++) {
if (item === element) {
return i;
}
}
return -1;
}
};
|
ErinCoughlan/material
|
src/components/panel/demoBasicUsage/script.js
|
JavaScript
|
mit
| 4,335
|
// Karma configuration
// Generated on Sun May 03 2015 14:02:57 GMT+0200 (W. Europe Daylight Time)
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'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/lodash/lodash.js',
'src/js/bootstrap.js',
'src/js/**/*.js',
'test/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['story'],
// web server port
port: 9876,
// 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
});
};
|
patbuergin/angular-widget-grid
|
karma.conf.js
|
JavaScript
|
mit
| 1,790
|
var Qb,Rb="",Sb,Tb=[{type:"a",shift:65248,start:65,end:90},{type:"a",shift:65248,start:97,end:122},{type:"n",shift:65248,start:48,end:57},{type:"p",shift:65248,start:33,end:47},{type:"p",shift:65248,start:58,end:64},{type:"p",shift:65248,start:91,end:96},{type:"p",shift:65248,start:123,end:126}],Ub,Vb=/[\u0020-\u00A5]|[\uFF61-\uFF9F][\uff9e\uff9f]?/g,Wb=/[\u3000-\u301C]|[\u301A-\u30FC]|[\uFF01-\uFF60]|[\uFFE0-\uFFE6]/g,Xb="\uff61\uff64\uff62\uff63\u00a5\u00a2\u00a3",Yb="\u3002\u3001\u300c\u300d\uffe5\uffe0\uffe1",
Zb=/[\u30ab\u30ad\u30af\u30b1\u30b3\u30b5\u30b7\u30b9\u30bb\u30bd\u30bf\u30c1\u30c4\u30c6\u30c8\u30cf\u30d2\u30d5\u30d8\u30db]/,$b=/[\u30cf\u30d2\u30d5\u30d8\u30db\u30f2]/,ac="\uff71\uff72\uff73\uff74\uff75\uff67\uff68\uff69\uff6a\uff6b\uff76\uff77\uff78\uff79\uff7a\uff7b\uff7c\uff7d\uff7e\uff7f\uff80\uff81\uff82\uff6f\uff83\uff84\uff85\uff86\uff87\uff88\uff89\uff8a\uff8b\uff8c\uff8d\uff8e\uff8f\uff90\uff91\uff92\uff93\uff94\uff6c\uff95\uff6d\uff96\uff6e\uff97\uff98\uff99\uff9a\uff9b\uff9c\uff66\uff9d\uff70\uff65",
bc="\u30a2\u30a4\u30a6\u30a8\u30aa\u30a1\u30a3\u30a5\u30a7\u30a9\u30ab\u30ad\u30af\u30b1\u30b3\u30b5\u30b7\u30b9\u30bb\u30bd\u30bf\u30c1\u30c4\u30c3\u30c6\u30c8\u30ca\u30cb\u30cc\u30cd\u30ce\u30cf\u30d2\u30d5\u30d8\u30db\u30de\u30df\u30e0\u30e1\u30e2\u30e4\u30e3\u30e6\u30e5\u30e8\u30e7\u30e9\u30ea\u30eb\u30ec\u30ed\u30ef\u30f2\u30f3\u30fc\u30fb";
function cc(a,b,c,d){Ub||dc();var e=H(b).join(""),g=Ub[d];e=e.replace(/all/,"").replace(/(\w)lphabet|umbers?|atakana|paces?|unctuation/g,"$1");return a.replace(c,function(f){return g[f]&&(!e||e.has(g[f].type))?g[f].to:f})}
function dc(){var a;Ub={zenkaku:{},hankaku:{}};Tb.forEach(function(b){N(b.start,b.end,function(c){$(b.type,u.fromCharCode(c),u.fromCharCode(c+b.shift))})});bc.each(function(b,c){a=ac.charAt(c);$("k",a,b);b.match(Zb)&&$("k",a+"\uff9e",b.shift(1));b.match($b)&&$("k",a+"\uff9f",b.shift(2))});Yb.each(function(b,c){$("p",Xb.charAt(c),b)});$("k","\uff73\uff9e","\u30f4");$("k","\uff66\uff9e","\u30fa");$("s"," ","\u3000")}function $(a,b,c){Ub.zenkaku[b]={type:a,to:c};Ub.hankaku[c]={type:a,to:b}}
function ec(){Qb={};I(Sb,function(a,b){b.split("").forEach(function(c){Qb[c]=a});Rb+=b});Rb=s("["+Rb+"]","g")}
Sb={A:"A\u24b6\uff21\u00c0\u00c1\u00c2\u1ea6\u1ea4\u1eaa\u1ea8\u00c3\u0100\u0102\u1eb0\u1eae\u1eb4\u1eb2\u0226\u01e0\u00c4\u01de\u1ea2\u00c5\u01fa\u01cd\u0200\u0202\u1ea0\u1eac\u1eb6\u1e00\u0104\u023a\u2c6f",B:"B\u24b7\uff22\u1e02\u1e04\u1e06\u0243\u0182\u0181",C:"C\u24b8\uff23\u0106\u0108\u010a\u010c\u00c7\u1e08\u0187\u023b\ua73e",D:"D\u24b9\uff24\u1e0a\u010e\u1e0c\u1e10\u1e12\u1e0e\u0110\u018b\u018a\u0189\ua779",E:"E\u24ba\uff25\u00c8\u00c9\u00ca\u1ec0\u1ebe\u1ec4\u1ec2\u1ebc\u0112\u1e14\u1e16\u0114\u0116\u00cb\u1eba\u011a\u0204\u0206\u1eb8\u1ec6\u0228\u1e1c\u0118\u1e18\u1e1a\u0190\u018e",
F:"F\u24bb\uff26\u1e1e\u0191\ua77b",G:"G\u24bc\uff27\u01f4\u011c\u1e20\u011e\u0120\u01e6\u0122\u01e4\u0193\ua7a0\ua77d\ua77e",H:"H\u24bd\uff28\u0124\u1e22\u1e26\u021e\u1e24\u1e28\u1e2a\u0126\u2c67\u2c75\ua78d",I:"I\u24be\uff29\u00cc\u00cd\u00ce\u0128\u012a\u012c\u0130\u00cf\u1e2e\u1ec8\u01cf\u0208\u020a\u1eca\u012e\u1e2c\u0197",J:"J\u24bf\uff2a\u0134\u0248",K:"K\u24c0\uff2b\u1e30\u01e8\u1e32\u0136\u1e34\u0198\u2c69\ua740\ua742\ua744\ua7a2",L:"L\u24c1\uff2c\u013f\u0139\u013d\u1e36\u1e38\u013b\u1e3c\u1e3a\u0141\u023d\u2c62\u2c60\ua748\ua746\ua780",
M:"M\u24c2\uff2d\u1e3e\u1e40\u1e42\u2c6e\u019c",N:"N\u24c3\uff2e\u01f8\u0143\u00d1\u1e44\u0147\u1e46\u0145\u1e4a\u1e48\u0220\u019d\ua790\ua7a4",O:"O\u24c4\uff2f\u00d2\u00d3\u00d4\u1ed2\u1ed0\u1ed6\u1ed4\u00d5\u1e4c\u022c\u1e4e\u014c\u1e50\u1e52\u014e\u022e\u0230\u00d6\u022a\u1ece\u0150\u01d1\u020c\u020e\u01a0\u1edc\u1eda\u1ee0\u1ede\u1ee2\u1ecc\u1ed8\u01ea\u01ec\u00d8\u01fe\u0186\u019f\ua74a\ua74c",P:"P\u24c5\uff30\u1e54\u1e56\u01a4\u2c63\ua750\ua752\ua754",Q:"Q\u24c6\uff31\ua756\ua758\u024a",R:"R\u24c7\uff32\u0154\u1e58\u0158\u0210\u0212\u1e5a\u1e5c\u0156\u1e5e\u024c\u2c64\ua75a\ua7a6\ua782",
S:"S\u24c8\uff33\u1e9e\u015a\u1e64\u015c\u1e60\u0160\u1e66\u1e62\u1e68\u0218\u015e\u2c7e\ua7a8\ua784",T:"T\u24c9\uff34\u1e6a\u0164\u1e6c\u021a\u0162\u1e70\u1e6e\u0166\u01ac\u01ae\u023e\ua786",U:"U\u24ca\uff35\u00d9\u00da\u00db\u0168\u1e78\u016a\u1e7a\u016c\u00dc\u01db\u01d7\u01d5\u01d9\u1ee6\u016e\u0170\u01d3\u0214\u0216\u01af\u1eea\u1ee8\u1eee\u1eec\u1ef0\u1ee4\u1e72\u0172\u1e76\u1e74\u0244",V:"V\u24cb\uff36\u1e7c\u1e7e\u01b2\ua75e\u0245",W:"W\u24cc\uff37\u1e80\u1e82\u0174\u1e86\u1e84\u1e88\u2c72",
X:"X\u24cd\uff38\u1e8a\u1e8c",Y:"Y\u24ce\uff39\u1ef2\u00dd\u0176\u1ef8\u0232\u1e8e\u0178\u1ef6\u1ef4\u01b3\u024e\u1efe",Z:"Z\u24cf\uff3a\u0179\u1e90\u017b\u017d\u1e92\u1e94\u01b5\u0224\u2c7f\u2c6b\ua762",a:"a\u24d0\uff41\u1e9a\u00e0\u00e1\u00e2\u1ea7\u1ea5\u1eab\u1ea9\u00e3\u0101\u0103\u1eb1\u1eaf\u1eb5\u1eb3\u0227\u01e1\u00e4\u01df\u1ea3\u00e5\u01fb\u01ce\u0201\u0203\u1ea1\u1ead\u1eb7\u1e01\u0105\u2c65\u0250",b:"b\u24d1\uff42\u1e03\u1e05\u1e07\u0180\u0183\u0253",c:"c\u24d2\uff43\u0107\u0109\u010b\u010d\u00e7\u1e09\u0188\u023c\ua73f\u2184",
d:"d\u24d3\uff44\u1e0b\u010f\u1e0d\u1e11\u1e13\u1e0f\u0111\u018c\u0256\u0257\ua77a",e:"e\u24d4\uff45\u00e8\u00e9\u00ea\u1ec1\u1ebf\u1ec5\u1ec3\u1ebd\u0113\u1e15\u1e17\u0115\u0117\u00eb\u1ebb\u011b\u0205\u0207\u1eb9\u1ec7\u0229\u1e1d\u0119\u1e19\u1e1b\u0247\u025b\u01dd",f:"f\u24d5\uff46\u1e1f\u0192\ua77c",g:"g\u24d6\uff47\u01f5\u011d\u1e21\u011f\u0121\u01e7\u0123\u01e5\u0260\ua7a1\u1d79\ua77f",h:"h\u24d7\uff48\u0125\u1e23\u1e27\u021f\u1e25\u1e29\u1e2b\u1e96\u0127\u2c68\u2c76\u0265",i:"i\u24d8\uff49\u00ec\u00ed\u00ee\u0129\u012b\u012d\u00ef\u1e2f\u1ec9\u01d0\u0209\u020b\u1ecb\u012f\u1e2d\u0268\u0131",
j:"j\u24d9\uff4a\u0135\u01f0\u0249",k:"k\u24da\uff4b\u1e31\u01e9\u1e33\u0137\u1e35\u0199\u2c6a\ua741\ua743\ua745\ua7a3",l:"l\u24db\uff4c\u0140\u013a\u013e\u1e37\u1e39\u013c\u1e3d\u1e3b\u017f\u0142\u019a\u026b\u2c61\ua749\ua781\ua747",m:"m\u24dc\uff4d\u1e3f\u1e41\u1e43\u0271\u026f",n:"n\u24dd\uff4e\u01f9\u0144\u00f1\u1e45\u0148\u1e47\u0146\u1e4b\u1e49\u019e\u0272\u0149\ua791\ua7a5",o:"o\u24de\uff4f\u00f2\u00f3\u00f4\u1ed3\u1ed1\u1ed7\u1ed5\u00f5\u1e4d\u022d\u1e4f\u014d\u1e51\u1e53\u014f\u022f\u0231\u00f6\u022b\u1ecf\u0151\u01d2\u020d\u020f\u01a1\u1edd\u1edb\u1ee1\u1edf\u1ee3\u1ecd\u1ed9\u01eb\u01ed\u00f8\u01ff\u0254\ua74b\ua74d\u0275",
p:"p\u24df\uff50\u1e55\u1e57\u01a5\u1d7d\ua751\ua753\ua755",q:"q\u24e0\uff51\u024b\ua757\ua759",r:"r\u24e1\uff52\u0155\u1e59\u0159\u0211\u0213\u1e5b\u1e5d\u0157\u1e5f\u024d\u027d\ua75b\ua7a7\ua783",s:"s\u24e2\uff53\u015b\u1e65\u015d\u1e61\u0161\u1e67\u1e63\u1e69\u0219\u015f\u023f\ua7a9\ua785\u1e9b",t:"t\u24e3\uff54\u1e6b\u1e97\u0165\u1e6d\u021b\u0163\u1e71\u1e6f\u0167\u01ad\u0288\u2c66\ua787",u:"u\u24e4\uff55\u00f9\u00fa\u00fb\u0169\u1e79\u016b\u1e7b\u016d\u00fc\u01dc\u01d8\u01d6\u01da\u1ee7\u016f\u0171\u01d4\u0215\u0217\u01b0\u1eeb\u1ee9\u1eef\u1eed\u1ef1\u1ee5\u1e73\u0173\u1e77\u1e75\u0289",
v:"v\u24e5\uff56\u1e7d\u1e7f\u028b\ua75f\u028c",w:"w\u24e6\uff57\u1e81\u1e83\u0175\u1e87\u1e85\u1e98\u1e89\u2c73",x:"x\u24e7\uff58\u1e8b\u1e8d",y:"y\u24e8\uff59\u1ef3\u00fd\u0177\u1ef9\u0233\u1e8f\u00ff\u1ef7\u1e99\u1ef5\u01b4\u024f\u1eff",z:"z\u24e9\uff5a\u017a\u1e91\u017c\u017e\u1e93\u1e95\u01b6\u0225\u0240\u2c6c\ua763",AA:"\ua732",AE:"\u00c6\u01fc\u01e2",AO:"\ua734",AU:"\ua736",AV:"\ua738\ua73a",AY:"\ua73c",DZ:"\u01f1\u01c4",Dz:"\u01f2\u01c5",LJ:"\u01c7",Lj:"\u01c8",NJ:"\u01ca",Nj:"\u01cb",OI:"\u01a2",
OO:"\ua74e",OU:"\u0222",TZ:"\ua728",VY:"\ua760",aa:"\ua733",ae:"\u00e6\u01fd\u01e3",ao:"\ua735",au:"\ua737",av:"\ua739\ua73b",ay:"\ua73d",dz:"\u01f3\u01c6",hv:"\u0195",lj:"\u01c9",nj:"\u01cc",oi:"\u01a3",ou:"\u0223",oo:"\ua74f",ss:"\u00df",tz:"\ua729",vy:"\ua761"};
G(u,j,m,{normalize:function(){Qb||ec();return this.replace(Rb,function(a){return Qb[a]})},hankaku:function(){return cc(this,arguments,Wb,"hankaku")},zenkaku:function(){return cc(this,arguments,Vb,"zenkaku")},hiragana:function(a){var b=this;if(a!==m)b=b.zenkaku("k");return b.replace(/[\u30A1-\u30F6]/g,function(c){return c.shift(-96)})},katakana:function(){return this.replace(/[\u3041-\u3096]/g,function(a){return a.shift(96)})}});
[{ca:["Arabic"],source:"\u0600-\u06ff"},{ca:["Cyrillic"],source:"\u0400-\u04ff"},{ca:["Devanagari"],source:"\u0900-\u097f"},{ca:["Greek"],source:"\u0370-\u03ff"},{ca:["Hangul"],source:"\uac00-\ud7af\u1100-\u11ff"},{ca:["Han","Kanji"],source:"\u4e00-\u9fff\uf900-\ufaff"},{ca:["Hebrew"],source:"\u0590-\u05ff"},{ca:["Hiragana"],source:"\u3040-\u309f\u30fb-\u30fc"},{ca:["Kana"],source:"\u3040-\u30ff\uff61-\uff9f"},{ca:["Katakana"],source:"\u30a0-\u30ff\uff61-\uff9f"},{ca:["Latin"],source:"\u0001-\u0080-\u00ff\u0100-\u017f\u0180-\u024f"},
{ca:["Thai"],source:"\u0e00-\u0e7f"}].forEach(function(a){var b=s("^["+a.source+"\\s]+$"),c=s("["+a.source+"]");a.ca.forEach(function(d){ia(u.prototype,"is"+d,function(){return b.test(this.trim())});ia(u.prototype,"has"+d,function(){return c.test(this)})})});
|
sunnywz/weather
|
node_modules/sugar/release/1.3/precompiled/minified/language.js
|
JavaScript
|
mit
| 8,884
|
import { RelationLoader } from "../query-builder/RelationLoader";
/**
* Wraps entities and creates getters/setters for their relations
* to be able to lazily load relations when accessing these relations.
*/
var LazyRelationsWrapper = /** @class */ (function () {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
function LazyRelationsWrapper(connection) {
this.connection = connection;
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Wraps given entity and creates getters/setters for its given relation
* to be able to lazily load data when accessing these relation.
*/
LazyRelationsWrapper.prototype.wrap = function (object, relation) {
var relationLoader = new RelationLoader(this.connection);
var dataIndex = "__" + relation.propertyName + "__"; // in what property of the entity loaded data will be stored
var promiseIndex = "__promise_" + relation.propertyName + "__"; // in what property of the entity loading promise will be stored
var resolveIndex = "__has_" + relation.propertyName + "__"; // indicates if relation data already was loaded or not, we need this flag if loaded data is empty
Object.defineProperty(object, relation.propertyName, {
get: function () {
var _this = this;
if (this[resolveIndex] === true)
return Promise.resolve(this[dataIndex]);
if (this[promiseIndex])
return this[promiseIndex];
// nothing is loaded yet, load relation data and save it in the model once they are loaded
this[promiseIndex] = relationLoader.load(relation, this).then(function (result) {
_this[dataIndex] = result;
_this[resolveIndex] = true;
delete _this[promiseIndex];
return _this[dataIndex];
}); // .catch((err: any) => { throw err; });
return this[promiseIndex];
},
set: function (promise) {
var _this = this;
if (promise instanceof Promise) {
promise.then(function (result) {
_this[dataIndex] = result;
_this[resolveIndex] = true;
});
}
else {
this[dataIndex] = promise;
this[resolveIndex] = true;
}
},
configurable: true
});
};
return LazyRelationsWrapper;
}());
export { LazyRelationsWrapper };
//# sourceMappingURL=LazyRelationsWrapper.js.map
|
JacksonLee2019/CS341-VolunteerSchedule
|
node_modules/typeorm/browser/lazy-loading/LazyRelationsWrapper.js
|
JavaScript
|
mit
| 2,929
|
'use strict';
// Production specific configuration
// =================================
module.exports = {
// Server IP
ip: process.env.OPENSHIFT_NODEJS_IP ||
process.env.IP ||
undefined,
// Server port
port: process.env.OPENSHIFT_NODEJS_PORT ||
process.env.PORT ||
8080,
// MongoDB connection options
mongo: {
uri: process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
process.env.OPENSHIFT_MONGODB_DB_URL +
process.env.OPENSHIFT_APP_NAME ||
'mongodb://localhost/circleci'
}
};
|
rafagomes/poc-circle-ci
|
server/config/environment/production.js
|
JavaScript
|
mit
| 588
|
var anna = require('../../..');
anna.discard(['la','el','las','los','de','en','mi','del']);
var categorias = require('./categorias.json');
var productos = require('./productos.json');
categorias.forEach(function (categoria) {
anna.add(categoria);
});
productos.forEach(function (producto) {
anna.add(producto);
});
console.dir(anna.search(process.argv[2]));
|
ajlopez/Annalisa
|
samples/preciosa/data/busca.js
|
JavaScript
|
mit
| 372
|
// sector-model.js - A mongoose model
//
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const sector = new mongooseClient.Schema({
name: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
return mongooseClient.model('sector', sector);
};
|
codefornigeria/project-tame-api
|
src/models/sector.model.js
|
JavaScript
|
mit
| 458
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
* Copyright (C) 2013, 2014 Apple Inc. All rights reserved.
* Copyright (C) 2014 University of Washington. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
// DO NOT EDIT THIS FILE. It is automatically generated from Inspector-iOS-6.0.json
// by the script: Source/JavaScriptCore/inspector/scripts/generate-inspector-protocol-bindings.py
// Inspector.
InspectorBackend.registerInspectorDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Inspector");
InspectorBackend.registerEvent("Inspector.evaluateForTestInFrontend", ["testCallId", "script"]);
InspectorBackend.registerEvent("Inspector.inspect", ["object", "hints"]);
InspectorBackend.registerEvent("Inspector.didCreateWorker", ["id", "url", "isShared"]);
InspectorBackend.registerEvent("Inspector.didDestroyWorker", ["id"]);
InspectorBackend.registerCommand("Inspector.enable", [], []);
InspectorBackend.registerCommand("Inspector.disable", [], []);
// Page.
InspectorBackend.registerPageDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Page");
InspectorBackend.registerEnum("Page.ResourceType", { Document: "Document", Stylesheet: "Stylesheet", Image: "Image", Font: "Font", Script: "Script", XHR: "XHR", WebSocket: "WebSocket", Other: "Other" });
InspectorBackend.registerEvent("Page.domContentEventFired", ["timestamp"]);
InspectorBackend.registerEvent("Page.loadEventFired", ["timestamp"]);
InspectorBackend.registerEvent("Page.frameNavigated", ["frame"]);
InspectorBackend.registerEvent("Page.frameDetached", ["frameId"]);
InspectorBackend.registerCommand("Page.enable", [], []);
InspectorBackend.registerCommand("Page.disable", [], []);
InspectorBackend.registerCommand("Page.addScriptToEvaluateOnLoad", [{ "name": "scriptSource", "type": "string", "optional": false }], ["identifier"]);
InspectorBackend.registerCommand("Page.removeScriptToEvaluateOnLoad", [{ "name": "identifier", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("Page.reload", [{ "name": "ignoreCache", "type": "boolean", "optional": true }, { "name": "scriptToEvaluateOnLoad", "type": "string", "optional": true }], []);
InspectorBackend.registerCommand("Page.navigate", [{ "name": "url", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("Page.getCookies", [], ["cookies", "cookiesString"]);
InspectorBackend.registerCommand("Page.deleteCookie", [{ "name": "cookieName", "type": "string", "optional": false }, { "name": "domain", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("Page.getResourceTree", [], ["frameTree"]);
InspectorBackend.registerCommand("Page.getResourceContent", [{ "name": "frameId", "type": "string", "optional": false }, { "name": "url", "type": "string", "optional": false }], ["content", "base64Encoded"]);
InspectorBackend.registerCommand("Page.searchInResource", [{ "name": "frameId", "type": "string", "optional": false }, { "name": "url", "type": "string", "optional": false }, { "name": "query", "type": "string", "optional": false }, { "name": "caseSensitive", "type": "boolean", "optional": true }, { "name": "isRegex", "type": "boolean", "optional": true }], ["result"]);
InspectorBackend.registerCommand("Page.searchInResources", [{ "name": "text", "type": "string", "optional": false }, { "name": "caseSensitive", "type": "boolean", "optional": true }, { "name": "isRegex", "type": "boolean", "optional": true }], ["result"]);
InspectorBackend.registerCommand("Page.setDocumentContent", [{ "name": "frameId", "type": "string", "optional": false }, { "name": "html", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("Page.setShowPaintRects", [{ "name": "result", "type": "boolean", "optional": false }], []);
InspectorBackend.registerCommand("Page.getScriptExecutionStatus", [], ["result"]);
InspectorBackend.registerCommand("Page.setScriptExecutionDisabled", [{ "name": "value", "type": "boolean", "optional": false }], []);
// Runtime.
InspectorBackend.registerEnum("Runtime.RemoteObjectType", { Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean" });
InspectorBackend.registerEnum("Runtime.RemoteObjectSubtype", { Array: "array", Null: "null", Node: "node", Regexp: "regexp", Date: "date" });
InspectorBackend.registerCommand("Runtime.evaluate", [{ "name": "expression", "type": "string", "optional": false }, { "name": "objectGroup", "type": "string", "optional": true }, { "name": "includeCommandLineAPI", "type": "boolean", "optional": true }, { "name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true }, { "name": "frameId", "type": "string", "optional": true }, { "name": "returnByValue", "type": "boolean", "optional": true }], ["result", "wasThrown"]);
InspectorBackend.registerCommand("Runtime.callFunctionOn", [{ "name": "objectId", "type": "string", "optional": false }, { "name": "functionDeclaration", "type": "string", "optional": false }, { "name": "arguments", "type": "object", "optional": true }, { "name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true }, { "name": "returnByValue", "type": "boolean", "optional": true }], ["result", "wasThrown"]);
InspectorBackend.registerCommand("Runtime.getProperties", [{ "name": "objectId", "type": "string", "optional": false }, { "name": "ownProperties", "type": "boolean", "optional": true }], ["result"]);
InspectorBackend.registerCommand("Runtime.releaseObject", [{ "name": "objectId", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("Runtime.releaseObjectGroup", [{ "name": "objectGroup", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("Runtime.run", [], []);
// Console.
InspectorBackend.registerConsoleDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Console");
InspectorBackend.registerEnum("Console.ConsoleMessageSource", { HTML: "html", XML: "xml", Javascript: "javascript", Network: "network", ConsoleAPI: "console-api", Other: "other" });
InspectorBackend.registerEnum("Console.ConsoleMessageLevel", { Tip: "tip", Log: "log", Warning: "warning", Error: "error", Debug: "debug" });
InspectorBackend.registerEnum("Console.ConsoleMessageType", { Log: "log", Dir: "dir", DirXML: "dirxml", Trace: "trace", StartGroup: "startGroup", StartGroupCollapsed: "startGroupCollapsed", EndGroup: "endGroup", Assert: "assert" });
InspectorBackend.registerEvent("Console.messageAdded", ["message"]);
InspectorBackend.registerEvent("Console.messageRepeatCountUpdated", ["count"]);
InspectorBackend.registerEvent("Console.messagesCleared", []);
InspectorBackend.registerCommand("Console.enable", [], []);
InspectorBackend.registerCommand("Console.disable", [], []);
InspectorBackend.registerCommand("Console.clearMessages", [], []);
InspectorBackend.registerCommand("Console.setMonitoringXHREnabled", [{ "name": "enabled", "type": "boolean", "optional": false }], []);
InspectorBackend.registerCommand("Console.addInspectedNode", [{ "name": "nodeId", "type": "number", "optional": false }], []);
// Network.
InspectorBackend.registerNetworkDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Network");
InspectorBackend.registerEnum("Network.InitiatorType", { Parser: "parser", Script: "script", Other: "other" });
InspectorBackend.registerEvent("Network.requestWillBeSent", ["requestId", "frameId", "loaderId", "documentURL", "request", "timestamp", "initiator", "redirectResponse"]);
InspectorBackend.registerEvent("Network.requestServedFromCache", ["requestId"]);
InspectorBackend.registerEvent("Network.responseReceived", ["requestId", "frameId", "loaderId", "timestamp", "type", "response"]);
InspectorBackend.registerEvent("Network.dataReceived", ["requestId", "timestamp", "dataLength", "encodedDataLength"]);
InspectorBackend.registerEvent("Network.loadingFinished", ["requestId", "timestamp"]);
InspectorBackend.registerEvent("Network.loadingFailed", ["requestId", "timestamp", "errorText", "canceled"]);
InspectorBackend.registerEvent("Network.requestServedFromMemoryCache", ["requestId", "frameId", "loaderId", "documentURL", "timestamp", "initiator", "resource"]);
InspectorBackend.registerEvent("Network.webSocketWillSendHandshakeRequest", ["requestId", "timestamp", "request"]);
InspectorBackend.registerEvent("Network.webSocketHandshakeResponseReceived", ["requestId", "timestamp", "response"]);
InspectorBackend.registerEvent("Network.webSocketCreated", ["requestId", "url"]);
InspectorBackend.registerEvent("Network.webSocketClosed", ["requestId", "timestamp"]);
InspectorBackend.registerEvent("Network.webSocketFrameReceived", ["requestId", "timestamp", "response"]);
InspectorBackend.registerEvent("Network.webSocketFrameError", ["requestId", "timestamp", "errorMessage"]);
InspectorBackend.registerEvent("Network.webSocketFrameSent", ["requestId", "timestamp", "response"]);
InspectorBackend.registerCommand("Network.enable", [], []);
InspectorBackend.registerCommand("Network.disable", [], []);
InspectorBackend.registerCommand("Network.setExtraHTTPHeaders", [{ "name": "headers", "type": "object", "optional": false }], []);
InspectorBackend.registerCommand("Network.getResponseBody", [{ "name": "requestId", "type": "string", "optional": false }], ["body", "base64Encoded"]);
InspectorBackend.registerCommand("Network.canClearBrowserCache", [], ["result"]);
InspectorBackend.registerCommand("Network.clearBrowserCache", [], []);
InspectorBackend.registerCommand("Network.canClearBrowserCookies", [], ["result"]);
InspectorBackend.registerCommand("Network.clearBrowserCookies", [], []);
InspectorBackend.registerCommand("Network.setCacheDisabled", [{ "name": "cacheDisabled", "type": "boolean", "optional": false }], []);
// Database.
InspectorBackend.registerDatabaseDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Database");
InspectorBackend.registerEvent("Database.addDatabase", ["database"]);
InspectorBackend.registerEvent("Database.sqlTransactionSucceeded", ["transactionId", "columnNames", "values"]);
InspectorBackend.registerEvent("Database.sqlTransactionFailed", ["transactionId", "sqlError"]);
InspectorBackend.registerCommand("Database.enable", [], []);
InspectorBackend.registerCommand("Database.disable", [], []);
InspectorBackend.registerCommand("Database.getDatabaseTableNames", [{ "name": "databaseId", "type": "string", "optional": false }], ["tableNames"]);
InspectorBackend.registerCommand("Database.executeSQL", [{ "name": "databaseId", "type": "string", "optional": false }, { "name": "query", "type": "string", "optional": false }], ["success", "transactionId"]);
// DOMStorage.
InspectorBackend.registerDOMStorageDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "DOMStorage");
InspectorBackend.registerEvent("DOMStorage.addDOMStorage", ["storage"]);
InspectorBackend.registerEvent("DOMStorage.updateDOMStorage", ["storageId"]);
InspectorBackend.registerCommand("DOMStorage.enable", [], []);
InspectorBackend.registerCommand("DOMStorage.disable", [], []);
InspectorBackend.registerCommand("DOMStorage.getDOMStorageEntries", [{ "name": "storageId", "type": "string", "optional": false }], ["entries"]);
InspectorBackend.registerCommand("DOMStorage.setDOMStorageItem", [{ "name": "storageId", "type": "string", "optional": false }, { "name": "key", "type": "string", "optional": false }, { "name": "value", "type": "string", "optional": false }], ["success"]);
InspectorBackend.registerCommand("DOMStorage.removeDOMStorageItem", [{ "name": "storageId", "type": "string", "optional": false }, { "name": "key", "type": "string", "optional": false }], ["success"]);
// ApplicationCache.
InspectorBackend.registerApplicationCacheDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "ApplicationCache");
InspectorBackend.registerEvent("ApplicationCache.applicationCacheStatusUpdated", ["frameId", "manifestURL", "status"]);
InspectorBackend.registerEvent("ApplicationCache.networkStateUpdated", ["isNowOnline"]);
InspectorBackend.registerCommand("ApplicationCache.getFramesWithManifests", [], ["frameIds"]);
InspectorBackend.registerCommand("ApplicationCache.enable", [], []);
InspectorBackend.registerCommand("ApplicationCache.getManifestForFrame", [{ "name": "frameId", "type": "string", "optional": false }], ["manifestURL"]);
InspectorBackend.registerCommand("ApplicationCache.getApplicationCacheForFrame", [{ "name": "frameId", "type": "string", "optional": false }], ["applicationCache"]);
// DOM.
InspectorBackend.registerDOMDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "DOM");
InspectorBackend.registerEvent("DOM.documentUpdated", []);
InspectorBackend.registerEvent("DOM.setChildNodes", ["parentId", "nodes"]);
InspectorBackend.registerEvent("DOM.attributeModified", ["nodeId", "name", "value"]);
InspectorBackend.registerEvent("DOM.attributeRemoved", ["nodeId", "name"]);
InspectorBackend.registerEvent("DOM.inlineStyleInvalidated", ["nodeIds"]);
InspectorBackend.registerEvent("DOM.characterDataModified", ["nodeId", "characterData"]);
InspectorBackend.registerEvent("DOM.childNodeCountUpdated", ["nodeId", "childNodeCount"]);
InspectorBackend.registerEvent("DOM.childNodeInserted", ["parentNodeId", "previousNodeId", "node"]);
InspectorBackend.registerEvent("DOM.childNodeRemoved", ["parentNodeId", "nodeId"]);
InspectorBackend.registerEvent("DOM.shadowRootPushed", ["hostId", "root"]);
InspectorBackend.registerEvent("DOM.shadowRootPopped", ["hostId", "rootId"]);
InspectorBackend.registerCommand("DOM.getDocument", [], ["root"]);
InspectorBackend.registerCommand("DOM.requestChildNodes", [{ "name": "nodeId", "type": "number", "optional": false }], []);
InspectorBackend.registerCommand("DOM.querySelector", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "selector", "type": "string", "optional": false }], ["nodeId"]);
InspectorBackend.registerCommand("DOM.querySelectorAll", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "selector", "type": "string", "optional": false }], ["nodeIds"]);
InspectorBackend.registerCommand("DOM.setNodeName", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "name", "type": "string", "optional": false }], ["nodeId"]);
InspectorBackend.registerCommand("DOM.setNodeValue", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "value", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOM.removeNode", [{ "name": "nodeId", "type": "number", "optional": false }], []);
InspectorBackend.registerCommand("DOM.setAttributeValue", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "name", "type": "string", "optional": false }, { "name": "value", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOM.setAttributesAsText", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "text", "type": "string", "optional": false }, { "name": "name", "type": "string", "optional": true }], []);
InspectorBackend.registerCommand("DOM.removeAttribute", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "name", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOM.getEventListenersForNode", [{ "name": "nodeId", "type": "number", "optional": false }], ["listeners"]);
InspectorBackend.registerCommand("DOM.getOuterHTML", [{ "name": "nodeId", "type": "number", "optional": false }], ["outerHTML"]);
InspectorBackend.registerCommand("DOM.setOuterHTML", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "outerHTML", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOM.performSearch", [{ "name": "query", "type": "string", "optional": false }], ["searchId", "resultCount"]);
InspectorBackend.registerCommand("DOM.getSearchResults", [{ "name": "searchId", "type": "string", "optional": false }, { "name": "fromIndex", "type": "number", "optional": false }, { "name": "toIndex", "type": "number", "optional": false }], ["nodeIds"]);
InspectorBackend.registerCommand("DOM.discardSearchResults", [{ "name": "searchId", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOM.requestNode", [{ "name": "objectId", "type": "string", "optional": false }], ["nodeId"]);
InspectorBackend.registerCommand("DOM.setInspectModeEnabled", [{ "name": "enabled", "type": "boolean", "optional": false }, { "name": "highlightConfig", "type": "object", "optional": true }], []);
InspectorBackend.registerCommand("DOM.highlightRect", [{ "name": "x", "type": "number", "optional": false }, { "name": "y", "type": "number", "optional": false }, { "name": "width", "type": "number", "optional": false }, { "name": "height", "type": "number", "optional": false }, { "name": "color", "type": "object", "optional": true }, { "name": "outlineColor", "type": "object", "optional": true }], []);
InspectorBackend.registerCommand("DOM.highlightNode", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "highlightConfig", "type": "object", "optional": false }], []);
InspectorBackend.registerCommand("DOM.hideHighlight", [], []);
InspectorBackend.registerCommand("DOM.highlightFrame", [{ "name": "frameId", "type": "string", "optional": false }, { "name": "contentColor", "type": "object", "optional": true }, { "name": "contentOutlineColor", "type": "object", "optional": true }], []);
InspectorBackend.registerCommand("DOM.pushNodeByPathToFrontend", [{ "name": "path", "type": "string", "optional": false }], ["nodeId"]);
InspectorBackend.registerCommand("DOM.resolveNode", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "objectGroup", "type": "string", "optional": true }], ["object"]);
InspectorBackend.registerCommand("DOM.getAttributes", [{ "name": "nodeId", "type": "number", "optional": false }], ["attributes"]);
InspectorBackend.registerCommand("DOM.moveTo", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "targetNodeId", "type": "number", "optional": false }, { "name": "insertBeforeNodeId", "type": "number", "optional": true }], ["nodeId"]);
InspectorBackend.registerCommand("DOM.setTouchEmulationEnabled", [{ "name": "enabled", "type": "boolean", "optional": false }], []);
InspectorBackend.registerCommand("DOM.undo", [], []);
InspectorBackend.registerCommand("DOM.redo", [], []);
InspectorBackend.registerCommand("DOM.markUndoableState", [], []);
// CSS.
InspectorBackend.registerCSSDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "CSS");
InspectorBackend.registerEnum("CSS.CSSRuleOrigin", { User: "user", UserAgent: "user-agent", Inspector: "inspector", Regular: "regular" });
InspectorBackend.registerEnum("CSS.CSSPropertyStatus", { Active: "active", Inactive: "inactive", Disabled: "disabled", Style: "style" });
InspectorBackend.registerEnum("CSS.CSSMediaSource", { MediaRule: "mediaRule", ImportRule: "importRule", LinkedSheet: "linkedSheet", InlineSheet: "inlineSheet" });
InspectorBackend.registerEvent("CSS.mediaQueryResultChanged", []);
InspectorBackend.registerEvent("CSS.styleSheetChanged", ["styleSheetId"]);
InspectorBackend.registerCommand("CSS.enable", [], []);
InspectorBackend.registerCommand("CSS.disable", [], []);
InspectorBackend.registerCommand("CSS.getMatchedStylesForNode", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "forcedPseudoClasses", "type": "object", "optional": true }, { "name": "includePseudo", "type": "boolean", "optional": true }, { "name": "includeInherited", "type": "boolean", "optional": true }], ["matchedCSSRules", "pseudoElements", "inherited"]);
InspectorBackend.registerCommand("CSS.getInlineStylesForNode", [{ "name": "nodeId", "type": "number", "optional": false }], ["inlineStyle", "attributesStyle"]);
InspectorBackend.registerCommand("CSS.getComputedStyleForNode", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "forcedPseudoClasses", "type": "object", "optional": true }], ["computedStyle"]);
InspectorBackend.registerCommand("CSS.getAllStyleSheets", [], ["headers"]);
InspectorBackend.registerCommand("CSS.getStyleSheet", [{ "name": "styleSheetId", "type": "string", "optional": false }], ["styleSheet"]);
InspectorBackend.registerCommand("CSS.getStyleSheetText", [{ "name": "styleSheetId", "type": "string", "optional": false }], ["text"]);
InspectorBackend.registerCommand("CSS.setStyleSheetText", [{ "name": "styleSheetId", "type": "string", "optional": false }, { "name": "text", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("CSS.setPropertyText", [{ "name": "styleId", "type": "object", "optional": false }, { "name": "propertyIndex", "type": "number", "optional": false }, { "name": "text", "type": "string", "optional": false }, { "name": "overwrite", "type": "boolean", "optional": false }], ["style"]);
InspectorBackend.registerCommand("CSS.toggleProperty", [{ "name": "styleId", "type": "object", "optional": false }, { "name": "propertyIndex", "type": "number", "optional": false }, { "name": "disable", "type": "boolean", "optional": false }], ["style"]);
InspectorBackend.registerCommand("CSS.setRuleSelector", [{ "name": "ruleId", "type": "object", "optional": false }, { "name": "selector", "type": "string", "optional": false }], ["rule"]);
InspectorBackend.registerCommand("CSS.addRule", [{ "name": "contextNodeId", "type": "number", "optional": false }, { "name": "selector", "type": "string", "optional": false }], ["rule"]);
InspectorBackend.registerCommand("CSS.getSupportedCSSProperties", [], ["cssProperties"]);
InspectorBackend.registerCommand("CSS.startSelectorProfiler", [], []);
InspectorBackend.registerCommand("CSS.stopSelectorProfiler", [], ["profile"]);
// Timeline.
InspectorBackend.registerTimelineDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Timeline");
InspectorBackend.registerEnum("Timeline.EventType", { EventDispatch: "EventDispatch", Layout: "Layout", RecalculateStyles: "RecalculateStyles", Paint: "Paint", ParseHTML: "ParseHTML", TimerInstall: "TimerInstall", TimerRemove: "TimerRemove", TimerFire: "TimerFire", EvaluateScript: "EvaluateScript", MarkLoad: "MarkLoad", MarkDOMContent: "MarkDOMContent", TimeStamp: "TimeStamp", ScheduleResourceRequest: "ScheduleResourceRequest", ResourceSendRequest: "ResourceSendRequest", ResourceReceiveResponse: "ResourceReceiveResponse", ResourceReceivedData: "ResourceReceivedData", ResourceFinish: "ResourceFinish", XHRReadyStateChange: "XHRReadyStateChange", XHRLoad: "XHRLoad", FunctionCall: "FunctionCall", GCEvent: "GCEvent", RequestAnimationFrame: "RequestAnimationFrame", CancelAnimationFrame: "CancelAnimationFrame", FireAnimationFrame: "FireAnimationFrame" });
InspectorBackend.registerEvent("Timeline.eventRecorded", ["record"]);
InspectorBackend.registerCommand("Timeline.start", [{ "name": "maxCallStackDepth", "type": "number", "optional": true }], []);
InspectorBackend.registerCommand("Timeline.stop", [], []);
// Debugger.
InspectorBackend.registerDebuggerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Debugger");
InspectorBackend.registerEnum("Debugger.ScopeType", { Global: "global", Local: "local", With: "with", Closure: "closure", Catch: "catch" });
InspectorBackend.registerEvent("Debugger.globalObjectCleared", []);
InspectorBackend.registerEvent("Debugger.scriptParsed", ["scriptId", "url", "startLine", "startColumn", "endLine", "endColumn", "isContentScript", "sourceMapURL"]);
InspectorBackend.registerEvent("Debugger.scriptFailedToParse", ["url", "scriptSource", "startLine", "errorLine", "errorMessage"]);
InspectorBackend.registerEvent("Debugger.breakpointResolved", ["breakpointId", "location"]);
InspectorBackend.registerEvent("Debugger.paused", ["callFrames", "reason", "data"]);
InspectorBackend.registerEvent("Debugger.resumed", []);
InspectorBackend.registerCommand("Debugger.supportsNativeBreakpoints", [], ["result"]);
InspectorBackend.registerCommand("Debugger.enable", [], []);
InspectorBackend.registerCommand("Debugger.disable", [], []);
InspectorBackend.registerCommand("Debugger.setBreakpointsActive", [{ "name": "active", "type": "boolean", "optional": false }], []);
InspectorBackend.registerCommand("Debugger.setBreakpointByUrl", [{ "name": "lineNumber", "type": "number", "optional": false }, { "name": "url", "type": "string", "optional": true }, { "name": "urlRegex", "type": "string", "optional": true }, { "name": "columnNumber", "type": "number", "optional": true }, { "name": "condition", "type": "string", "optional": true }], ["breakpointId", "locations"]);
InspectorBackend.registerCommand("Debugger.setBreakpoint", [{ "name": "location", "type": "object", "optional": false }, { "name": "condition", "type": "string", "optional": true }], ["breakpointId", "actualLocation"]);
InspectorBackend.registerCommand("Debugger.removeBreakpoint", [{ "name": "breakpointId", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("Debugger.continueToLocation", [{ "name": "location", "type": "object", "optional": false }], []);
InspectorBackend.registerCommand("Debugger.stepOver", [], []);
InspectorBackend.registerCommand("Debugger.stepInto", [], []);
InspectorBackend.registerCommand("Debugger.stepOut", [], []);
InspectorBackend.registerCommand("Debugger.pause", [], []);
InspectorBackend.registerCommand("Debugger.resume", [], []);
InspectorBackend.registerCommand("Debugger.searchInContent", [{ "name": "scriptId", "type": "string", "optional": false }, { "name": "query", "type": "string", "optional": false }, { "name": "caseSensitive", "type": "boolean", "optional": true }, { "name": "isRegex", "type": "boolean", "optional": true }], ["result"]);
InspectorBackend.registerCommand("Debugger.getScriptSource", [{ "name": "scriptId", "type": "string", "optional": false }], ["scriptSource"]);
InspectorBackend.registerCommand("Debugger.getFunctionDetails", [{ "name": "functionId", "type": "string", "optional": false }], ["details"]);
InspectorBackend.registerCommand("Debugger.setPauseOnExceptions", [{ "name": "state", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("Debugger.evaluateOnCallFrame", [{ "name": "callFrameId", "type": "string", "optional": false }, { "name": "expression", "type": "string", "optional": false }, { "name": "objectGroup", "type": "string", "optional": true }, { "name": "includeCommandLineAPI", "type": "boolean", "optional": true }, { "name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true }, { "name": "returnByValue", "type": "boolean", "optional": true }], ["result", "wasThrown"]);
// DOMDebugger.
InspectorBackend.registerEnum("DOMDebugger.DOMBreakpointType", { SubtreeModified: "subtree-modified", AttributeModified: "attribute-modified", NodeRemoved: "node-removed" });
InspectorBackend.registerCommand("DOMDebugger.setDOMBreakpoint", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "type", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOMDebugger.removeDOMBreakpoint", [{ "name": "nodeId", "type": "number", "optional": false }, { "name": "type", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOMDebugger.setEventListenerBreakpoint", [{ "name": "eventName", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOMDebugger.removeEventListenerBreakpoint", [{ "name": "eventName", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOMDebugger.setInstrumentationBreakpoint", [{ "name": "eventName", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOMDebugger.removeInstrumentationBreakpoint", [{ "name": "eventName", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOMDebugger.setXHRBreakpoint", [{ "name": "url", "type": "string", "optional": false }], []);
InspectorBackend.registerCommand("DOMDebugger.removeXHRBreakpoint", [{ "name": "url", "type": "string", "optional": false }], []);
// Profiler.
InspectorBackend.registerProfilerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Profiler");
InspectorBackend.registerEnum("Profiler.ProfileHeaderTypeId", { CPU: "CPU" });
InspectorBackend.registerEvent("Profiler.addProfileHeader", ["header"]);
InspectorBackend.registerEvent("Profiler.setRecordingProfile", ["isProfiling"]);
InspectorBackend.registerEvent("Profiler.resetProfiles", []);
InspectorBackend.registerCommand("Profiler.enable", [], []);
InspectorBackend.registerCommand("Profiler.disable", [], []);
InspectorBackend.registerCommand("Profiler.start", [], []);
InspectorBackend.registerCommand("Profiler.stop", [], []);
InspectorBackend.registerCommand("Profiler.getProfileHeaders", [], ["headers"]);
InspectorBackend.registerCommand("Profiler.getProfile", [{ "name": "type", "type": "string", "optional": false }, { "name": "uid", "type": "number", "optional": false }], ["profile"]);
InspectorBackend.registerCommand("Profiler.removeProfile", [{ "name": "type", "type": "string", "optional": false }, { "name": "uid", "type": "number", "optional": false }], []);
InspectorBackend.registerCommand("Profiler.clearProfiles", [], []);
// Worker.
InspectorBackend.registerWorkerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Worker");
InspectorBackend.registerEvent("Worker.workerCreated", ["workerId", "url", "inspectorConnected"]);
InspectorBackend.registerEvent("Worker.workerTerminated", ["workerId"]);
InspectorBackend.registerEvent("Worker.dispatchMessageFromWorker", ["workerId", "message"]);
InspectorBackend.registerEvent("Worker.disconnectedFromWorker", []);
InspectorBackend.registerCommand("Worker.setWorkerInspectionEnabled", [{ "name": "value", "type": "boolean", "optional": false }], []);
InspectorBackend.registerCommand("Worker.sendMessageToWorker", [{ "name": "workerId", "type": "number", "optional": false }, { "name": "message", "type": "object", "optional": false }], []);
InspectorBackend.registerCommand("Worker.connectToWorker", [{ "name": "workerId", "type": "number", "optional": false }], []);
InspectorBackend.registerCommand("Worker.disconnectFromWorker", [{ "name": "workerId", "type": "number", "optional": false }], []);
InspectorBackend.registerCommand("Worker.setAutoconnectToWorkers", [{ "name": "value", "type": "boolean", "optional": false }], []);
|
artygus/webkit-webinspector
|
lib/WebInspectorUI/v8/Protocol/Legacy/6.0/InspectorWebBackendCommands.js
|
JavaScript
|
mit
| 31,875
|
/* jshint undef: true, node: true, esnext: true, eqeqeq: true */
'use strict';
/**
* This is a toy example to test our led server.
* It is rendering a random color at a random index.
*/
const request = require('request');
const LED_SERVER_DEFAULT_URL = 'http://localhost:3000';
const NUMBER_OF_LEDS = 32;
let leds = [
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0
];
request
.get(LED_SERVER_DEFAULT_URL + '/clear')
.on('response', res => { console.log('Clear: ' + res.statusCode); });
// Loop every 0.1 sec:
let interval = setInterval(() => {
// Pick a random LED and a random color and set it
let randomIndex = Math.floor(Math.random() * NUMBER_OF_LEDS);
let randomColour = Math.floor(Math.random() * 0xffffff);
leds[randomIndex] = randomColour;
console.log('Rendering colour ' + randomColour + ' at index ' + randomIndex);
// Contact the server and pass the array of LEDs
request
.post({url: LED_SERVER_DEFAULT_URL + '/display', body: {leds: leds}, json: true })
.on('response', res => { console.log('Response status: ' + res.statusCode); });
}, 100);
// After 10 secondes, stop.
setTimeout(() => {
console.log('Stop!');
clearInterval(interval);
}, 10000);
|
Kylir/node-unicorn
|
examples/toy-example.js
|
JavaScript
|
mit
| 1,271
|
/* eslint-disable require-yield */
//BEGIN-SNIPPET svg-snippet.js
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import moveSVG from 'ember-animated/motions/move-svg';
import { parallel } from 'ember-animated';
function generateBubbles() {
let list = [];
for (let id = 0; id < 10; id++) {
list.push({
id,
x: Math.floor(Math.random() * 100),
y: Math.floor(Math.random() * 100),
radius: Math.floor(Math.random() * 50),
});
}
return list;
}
export default class SvgExample extends Component {
@tracked bubbles = generateBubbles();
*moveThem({ keptSprites }) {
keptSprites.forEach(
parallel(
moveSVG.property('cx'),
moveSVG.property('cy'),
moveSVG.property('r'),
),
);
}
@action move() {
this.bubbles = generateBubbles();
}
}
//END-SNIPPET
|
ember-animation/ember-animated
|
docs/app/pods/components/svg-example/component.js
|
JavaScript
|
mit
| 920
|
var experiments = require("../experiments/__index");
var log = (typeof console !== "undefined" && typeof console.log === "function") ?
function() { return console.log.apply(console, arguments); }: function(){};
var browserSupported = typeof document !== "undefined" &&
document.querySelectorAll && Array.prototype.forEach;
if (!browserSupported)
{
log("[Mutagen] browser not supported");
} else {
for (var name in experiments) {
var experiment = experiments[name];
var variation = 0;
try {
if (typeof experiment.chooseVariation === "function") {
variation = experiment.chooseVariation();
} else if (experiment.gacx) {
variation = cxApi.chooseVariation(experiment.id);
}
} catch (err) {
log("[Mutagen] error choosing variation, experiment: " + name);
continue;
}
var variate = experiment.variations && experiment.variations[variation];
if (typeof variate !== "function") continue;
log("[Mutagen] experiment: " + name + ", variation: " + variation);
try {
variate(experiment);
log("[Mutagen] applied");
} catch (error) {
log("[Mutagen] error while applying experiment: " + name + ", variation: " + variation);
log(error);
log(error.stack);
}
}
}
|
benjamine/mutagen
|
src/browser.js
|
JavaScript
|
mit
| 1,214
|
Object.defineProperty(PIXI.Point.prototype, "th", {
get: function () {
if (this.x === this._xthcache &&
this.y === this._ythcache)
return this._thcache
this._xthcache = this.x
this._ythcache = this.y
this._thcache = Math.atan2(-1 * this.y, this.x)
if (this._thcache < 0)
this._thcache += 2 * Math.PI
return this._thcache
},
set: function (th) {
//make update atomic from pov of r
var r = this.r
this.x = r * Math.cos(th)
this.y = -1 * r * Math.sin(th)
}
})
Object.defineProperty(PIXI.Point.prototype, "r", {
get: function () {
if (this.x === this._xrcache &&
this.y === this._yrcache)
return this._rcache
this._xrcache = this.x
this._yrcache = this.y
this._rcache = Math.sqrt(this.x * this.x + this.y * this.y)
return this._rcache
},
set: function (r) {
//make update atomic from pov of th
var th = this.th
this.x = r * Math.cos(th)
this.y = -1 * r * Math.sin(th)
}
})
|
jfmatt/stealth-whale
|
src/point.js
|
JavaScript
|
mit
| 1,220
|
module.exports = function (grunt) {
grunt.initConfig({
uglify: {
default: {
options: {
preserveComments: 'some',
sourceMap: 'dist/datetime-factory.min.map',
sourceMappingURL: 'dist/datetime-factory.min.map'
},
files: {
'dist/datetime-factory.min.js': 'dist/datetime-factory.js'
}
}
},
browserify: {
main: {
src: 'index.js',
dest: 'dist/datetime-factory.js',
options: {
browserifyOptions: {
standalone: 'datetimeFactory'
}
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-browserify');
grunt.registerTask('default', ['browserify', 'uglify']);
};
|
sguimont/datetime-factory
|
Gruntfile.js
|
JavaScript
|
mit
| 763
|
// Open the dashboard (or prompt login) when the leaf bar button is tapped.
OF.barButtonTouch = function() {
OF.trackEvent('game_channel', 'denied_of');
OF.sendAction('deniedOpenFeint');
};
|
AYastrebov/SixCorners
|
Resources/OFResources_iPhone_Portrait.bundle/webui.bundle/javascripts/enable_feint.js
|
JavaScript
|
mit
| 193
|
'use strict';
var assert = require('chai').assert,
sinon = require('sinon'),
proxyquire = require('proxyquire').noCallThru();
var jsonschemaMock = {
validate: function () { return; }
},
req = {
body: {}
},
res = {
status: function () {
return this;
},
send: function () {
return;
}
},
schemaDefinition = {},
schemaValidation,
sandbox,
statusSpy,
sendSpy,
nextSpy;
describe('schema-validation', function () {
beforeEach(function () {
schemaValidation = proxyquire('../../utils/schema-validation.js', {
'jsonschema': jsonschemaMock
});
sandbox = sinon.sandbox.create();
statusSpy = sandbox.spy(res, 'status'),
sendSpy = sandbox.spy(res, 'send'),
nextSpy = sandbox.spy();
});
afterEach(function () {
sandbox.restore();
});
describe('validate()', function () {
it('should return 400 and not execute the "next" callback if there is any validation error', function () {
sandbox.stub(jsonschemaMock, 'validate', function () {
return {
errors: [{
stack: 'instance requires username'
}]
}
});
schemaValidation.validate(schemaDefinition)(req, res, nextSpy);
assert(statusSpy.calledOnce);
assert(statusSpy.calledWith(400));
assert(sendSpy.calledOnce);
assert.isFalse(nextSpy.calledOnce);
});
it('should execute the "next" callback if there are no validation errors', function () {
var nextSpy = sandbox.spy();
sandbox.stub(jsonschemaMock, 'validate', function () {
return {
errors: []
}
});
schemaValidation.validate(schemaDefinition)(req, res, nextSpy);
assert(nextSpy.calledOnce);
});
});
});
|
pabloorellana/auth-spike
|
test/utils/schema-validation.spec.js
|
JavaScript
|
mit
| 2,057
|
/**
* This jQuery plugin will be the javascript hub for all contentNodeField actions of the MMCmfContentBundle
*/
(function ($) {
/**
*
* @param $contentNode
* @param $options
*/
var mmCmfContentStructureEditor = function ($contentNodes, $options) {
var $this = this;
this.contentNodes = $contentNodes;
this.settings = $options;
this.modalParent = $('body');
this.initiateDragula($('.ContentNodeChildren.draggable'));
$(this.contentNodes).each(function (key, _contentNode) {
$contentNode = $(_contentNode);
if (!$contentNode.data('mmCmfContentStructureEditor')) {
$this.appendSettingsMenu($contentNode);
$contentNode.data('mmCmfContentStructureEditor', $this);
}
});
if (typeof $.fn.tooltip != "undefined")
$('.ContentNode-settings').tooltip({html: true, placement: 'auto top'});
};
mmCmfContentStructureEditor.prototype.isGridable = function ($contentNode) {
var $this = this;
return ($this.settings.not_gridable_classes.indexOf($contentNode.data('cmf-class')) === -1);
};
/**
* creates CmfContentNode settings gui
*/
mmCmfContentStructureEditor.prototype.appendSettingsMenu = function ($contentNode) {
var $this = this;
var $settings = this.settings;
/**
* append to inner box div
*/
var $box = this.generateSettingsBox($contentNode);
var $boxInner = $('<div class="inner" />');
/**
* checks if the current contentNode
*/
if ($this.isGridable($contentNode)) {
for (var i in $settings.gridSizes) {
var $selectBox = this.generateColumnSelect($contentNode, $settings.gridSizes[i], $settings.gridCount);
$boxInner.append($selectBox);
}
}
/**
* bind change event
*/
$boxInner.on('change', 'select', function (e) {
e.preventDefault();
$this.onChangeGridsystem($contentNode, $boxInner, $box);
});
/**
* append position switch widget
*/
var $posSwitch = this.generatePositionSwitchControls($contentNode);
$boxInner.append($posSwitch);
/**
* append inner controlls to main menu
*/
$box.append($boxInner);
$contentNode.append($box);
};
mmCmfContentStructureEditor.prototype.onChangeGridsystem = function ($contentNode, $boxInner, $box) {
$box.parent().removeClass(function (index, css) {
return (css.match(/col-[a-z0-9\-]*/g) || []).join(' ');
});
$boxInner.find('select').each(function () {
$box.parent().addClass($(this).val());
});
var $fieldName = 'classes';
var $value = $contentNode.attr('class');
var $cmfId = $contentNode.data('cmf-id');
var $cmfForbiddenClasses = $contentNode.data('cmf-css-generated-classes') +
" " + this.settings.highlightClass +
" " + this.settings.hoverClass;
var $cmfForbiddenClassesArray = $cmfForbiddenClasses.split(" ");
for (var i = 0; i < $cmfForbiddenClassesArray.length; i++) {
$value = $value.replace($cmfForbiddenClassesArray[i], '');
}
$(document).trigger('updated.MMCmfContentFieldEditor',
{
value: $value.trim(),
name: $fieldName,
'cmf-id': $cmfId
}
);
};
/**
* Returns gui elemets which lets the user move the position of the current ContentNode
*
* @returns {*|HTMLElement}
*/
mmCmfContentStructureEditor.prototype.generatePositionSwitchControls = function ($contentNode) {
var $this = this;
/**
* manual position switcher
*/
var $posiswitch = $('<div class="posiswitch"><div class="upper"><i class="fa fa-chevron-up"></i></div><div class="downer"><i class="fa fa-chevron-down"></i></div></div>');
/**
* bind events
*/
$posiswitch.on('click', '.upper , .downer', function (e) {
e.preventDefault();
var $ele = $(this);
if ($ele.hasClass('upper')) {
if ($contentNode.prev().hasClass('ContentNode'))
$contentNode.prev().before($contentNode);
}
if ($ele.hasClass('downer')) {
if ($contentNode.next().hasClass('ContentNode'))
$contentNode.next().after($contentNode);
}
$this.refreshPositions($contentNode);
});
return $posiswitch;
};
/**
* Returns Grid-System-Size selectbox which lets the user change the grid size based on the viewport
*
* @returns {*|HTMLElement}
*/
mmCmfContentStructureEditor.prototype.generateColumnSelect = function ($contentNode, $gridSize, $gridCount) {
var $select = $('<select />').data('grid-size', $gridSize);
$select.append('<option></option>');
for (var i = 1; i <= $gridCount; i++) {
var $colClass = 'col-' + $gridSize + '-' + i;
var $option = $('<option value="' + $colClass + '">' + i + '</option>');
if ($contentNode.hasClass($colClass))
$option.attr('selected', 'selected');
$select.append($option);
}
var $selectContainer = $('<div class="select-container select-container-' + $gridSize + '" />');
$selectContainer.append('<label class="icon-' + $gridSize.toLowerCase() + '"><span>' + $gridSize.toUpperCase() + '</span></label>');
$selectContainer.append($select);
return $selectContainer;
};
/**
* loads the contentNode Modal
*
* @param $url
* @param __callback
*/
mmCmfContentStructureEditor.prototype.loadSettingsForm = function ($url, __callback) {
var $this = this;
if ($url != "")
$.ajax({
'url': $url,
'method': 'GET',
'data': {'root_node': $this.settings.root_node},
'success': function (request) {
var $modal = $(request)
.modal()
.on('hidden.bs.modal', function () {
console.log('modalClose.settingsForm.MMCmfContentFieldEditor', $(this).remove());
$(this).remove();
$(document).trigger('modalClose.settingsForm.MMCmfContentFieldEditor', {});
});
$this.modalParent.append($modal);
mmFormFieldhandler.init();
if (typeof __callback == "function")
__callback(request, $modal, $this.modalParent);
$(document).trigger('modalOpen.settingsForm.MMCmfContentFieldEditor');
}
});
};
/**
* Returns the CMF-Settings DOM-Element which lets the user control some ContentNode attributes
*
* @returns {*|HTMLElement}
*/
mmCmfContentStructureEditor.prototype.generateSettingsBox = function ($contentNode) {
var $this = this;
var $title = $contentNode.data('cmf-tooltip');
var $div = $('<div class="ContentNode-settings" data-toggle="tooltip" title="' + $title + '">' +
'<b class="ContentNode-settings-arrows"><i class="fa fa-arrows"></i></b>' +
'<br>' +
'</div>');
$div.on('click', 'b.ContentNode-settings-arrows', function (e) {
e.preventDefault();
$(this).parent().toggleClass('open');
$(this).parent().parent().toggleClass($this.settings.highlightClass);
});
// append settings simple form opener
var $gearButton = $('<b class="ContentNode-settings-gear"><i class="fa fa-gear"></i></b>');
$gearButton.click(function (e) {
e.preventDefault();
var $route = $contentNode.data('cmf-simple-form');
$this.loadSettingsForm($route);
});
$div.prepend($gearButton);
/**
*
* append add-children-button simple form opener
*
*/
var $addButton = $('<b class="ContentNode-settings-plus"><i class="fa fa-plus"></i></b>');
$addButton.click(function (e) {
e.preventDefault();
var $route = $contentNode.data('cmf-add-child-form');
$this.loadSettingsForm($route, function (request, $modal, $modalParent) {
console.log('a.contentNodeType', $modal, $modal.find('a.contentNodeType'));
$modal.on('click', 'a.contentNodeType', function (e) {
e.preventDefault();
$this.loadSettingsForm($(this).attr('href'));
$modal.modal('hide');
});
});
});
$div.prepend($addButton);
return $div;
};
/**
* Load Parents of given ContentNodes and initiates Dragula on it
*
* @param $elements
*/
mmCmfContentStructureEditor.prototype.initiateDragula = function ($elements) {
var $this = this;
/**
* declaration of draggable Container should be more complex in the future
* @type {*|jQuery|HTMLElement}
*/
var $draggableContainers = new Array();
var $draggableContainersObjects = $elements;
$draggableContainersObjects.each(function (k, v) {
$draggableContainers.push(v);
});
var $draguala = dragula($draggableContainers, {
ignoreInputTextSelection: true,
disableDragAndDrop: true,
moves: function (el, source, handle, sibling) {
if (!($(el).hasClass('ContentNode') ))
return false;
return true;
},
accepts: function (el, target, source, sibling) {
if (!($(el).hasClass('ContentNode') || $(el).hasClass('ParagraphContentNode')))
return false;
return true; // elements can be dropped in any of the `containers` by default
}
});
$draguala.on('drag', function (el, source) {
});
$draguala.on('dragend', function (el) {
$this.refreshPositions(el);
});
};
/**
* refreshs siblings of changed ContentNode
*
* @param $contentNode
*/
mmCmfContentStructureEditor.prototype.refreshPositions = function ($contentNode) {
var $this = this;
$($contentNode).parent().children('.ContentNode').each(function (i) {
var $contentNodeInner = $(this);
var prefIndex = $contentNodeInner.attr('data-cmf-position');
if (i != prefIndex) {
$contentNodeInner.attr('data-cmf-position', i);
$this.onObjectPositionChanged($contentNodeInner, i);
}
});
};
/**
* triggers update functions to the MainController
*
* @param $contentNode
* @param $value
*/
mmCmfContentStructureEditor.prototype.onObjectPositionChanged = function ($contentNode, $value) {
var $cmfId = $contentNode.data('cmf-id');
$(document).trigger('updated.MMCmfContentFieldEditor',
{
value: $value,
name: 'position',
'cmf-id': $cmfId
}
);
};
/**
* bootstrap jquery plugin
*
* @param options
*/
$.fn.mmCmfContentStructureEditor = function (options) {
// Establish our default settings
var settings = $.extend({
// mmCmfContentStructureEditor
gridCount: 12,
gridSizes: ['xs', 'sm', 'md', 'lg'],
highlightClass: 'ContentNode-highlighted',
hoverClass: 'hover',
root_node: null,
not_gridable_classes: []
}, options);
new mmCmfContentStructureEditor(this, settings);
};
}(jQuery));
|
Mandarin-Medien/MMCmfContentBundle
|
Resources/public/js/mmCmfContentStructureEditor.js
|
JavaScript
|
mit
| 12,250
|
import * as Scrivito from 'scrivito'
Scrivito.provideEditingConfig('LineChartWidget', {
title: 'Line Chart',
attributes: {
type: {
title: 'Line Chart Type',
description: 'Default: Simple Line Chart',
values: [
{ value: 'dashed', title: 'Dashed Lines' },
{ value: 'withRefLines', title: 'With Reference Line' },
{ value: 'vertical', title: 'Vertical' }
]
},
label1: {
title: 'Value for label 1'
},
label2: {
title: 'Value for label 2'
},
items: {
title: 'Line Values'
}
},
properties: [
'type',
'label1',
'label2',
'items'
]
})
|
capriosa/capriosa.github.io
|
src/Widgets/LineChartWidget/LineChartWidgetEditingConfig.js
|
JavaScript
|
mit
| 655
|
angular.module("mdl")
.directive("mdlProgressDefault",function ProgressDefaultDirective(){
var stl=angular.element('<style id="mdlProgressDefault">\n\
</style>\n\
');
function applyStyle(_style){
var style=document.querySelectorAll("style#"+_style.id);
if(style.length==0){
try{
document.body.appendChild(_style);
}catch(err){
setTimeout(function(){applyStyle(_style)},1000);
}
}
}
applyStyle(stl[0]);
return {
priority: 1,
restrict: 'E',
transclude: {
},
template:'\
<!-- Simple MDL Progress Bar -->\
<div id="p1" class="mdl-progress mdl-js-progress"></div>\
<script>\
document.querySelector(\'#p1\').addEventListener(\'mdl-componentupgraded\', function() {\
this.MaterialProgress.setProgress(44);\
});\
</script>\
\
',
compile:function(tElm,tAttrs,transclude){
console.debug("ProgressDefault-compile",tElm.html())
return {
pre:function(scope, elm, attrs,ctrl,transcludeFn){
console.debug("ProgressDefault-pre",elm.html(),(transcludeFn(scope)));
},
post:function(scope, elm, attrs,ctrl,transcludeFn){
console.debug("ProgressDefault-post",elm.html(),(transcludeFn(scope)));
}
}
}
}
})
|
alfu32/angular-mdl
|
src/progress/ProgressDefault.js
|
JavaScript
|
mit
| 1,202
|
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
clean: {
build: {
files: [{
dot: true,
src: [
'build/*'
]
}]
},
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'src/*.js'
]
},
useminPrepare: {
options: {
dest: 'build'
},
html: ['src/*.html']
},
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: 'src',
dest: 'build/',
src: 'manifest.webapp'
},{
expand: true,
dot: true,
cwd: 'src',
dest: 'build/',
src: 'css/**',
},{
expand: true,
dot: true,
cwd: 'src',
dest: 'build/',
src: 'images/**',
},{
expand: true,
dot: true,
cwd: 'src',
dest: 'build/',
src: 'js/**',
},{
expand: true,
dot: true,
cwd: 'src',
dest: 'build/',
src: 'views/**',
}]
}
},
usemin: {
options: {
dirs: ['build'],
basedir: 'build',
},
html: ['build/*.html']
},
compress: {
main: {
options : {
archive : "deployment/kursrs.zip"
},
files : [
{ expand: true, src : "**/*", cwd : "build/" }
]
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-usemin');
grunt.loadNpmTasks('grunt-contrib-compress');
// Build task(s).
grunt.registerTask('build', ['clean', 'jshint', 'useminPrepare', /*'concat', 'uglify',*/ 'copy', 'usemin', 'compress']);
};
|
ivandejanovic/kursrs
|
Gruntfile.js
|
JavaScript
|
mit
| 2,109
|
"use strict"
var blessed = require("blessed");
var git = require("./git/cli");
class Delete {
constructor(app) {
this.app = app;
this.modal = blessed.box({
height: 6,
width: 75,
left: "center",
top: "center",
border: {
type: "line"
}
});
this.textbox = blessed.textbox({
height: 3,
top: 0,
inputOnFocus: true,
border: {
type: "line"
}
});
this.modal.append(this.textbox);
this.hint = blessed.box({
height: 1,
bottom: 0,
left: "top",
tags: true,
content: "{red-fg}Confirm deletion?{/red-fg} Type y to confirm"
});
this.modal.append(this.hint);
this.modal.hide();
this.textbox.key("escape", () => this.app.back());
this.textbox.key("enter", () => {
var v = this.textbox.getValue();
if (v == "y") {
git.removeFile(this.filePath);
}
this.app.back();
});
this.app.container.append(this.modal);
}
show(file) {
this.filePath = file;
this.modal.show();
this.textbox.setValue("");
this.textbox.focus();
}
hide() {
this.modal.hide();
}
}
module.exports = Delete;
|
erickzanardo/git-cutlass
|
lib/delete-file.js
|
JavaScript
|
mit
| 1,197
|
ScalaJS.impls.scala_Product20$class__productArity__Lscala_Product20__I = (function($$this) {
return 20
});
ScalaJS.impls.scala_Product20$class__productElement__Lscala_Product20__I__O = (function($$this, n) {
var x1 = n;
switch (x1) {
case 0:
{
return $$this.$$und1__O();
break
};
case 1:
{
return $$this.$$und2__O();
break
};
case 2:
{
return $$this.$$und3__O();
break
};
case 3:
{
return $$this.$$und4__O();
break
};
case 4:
{
return $$this.$$und5__O();
break
};
case 5:
{
return $$this.$$und6__O();
break
};
case 6:
{
return $$this.$$und7__O();
break
};
case 7:
{
return $$this.$$und8__O();
break
};
case 8:
{
return $$this.$$und9__O();
break
};
case 9:
{
return $$this.$$und10__O();
break
};
case 10:
{
return $$this.$$und11__O();
break
};
case 11:
{
return $$this.$$und12__O();
break
};
case 12:
{
return $$this.$$und13__O();
break
};
case 13:
{
return $$this.$$und14__O();
break
};
case 14:
{
return $$this.$$und15__O();
break
};
case 15:
{
return $$this.$$und16__O();
break
};
case 16:
{
return $$this.$$und17__O();
break
};
case 17:
{
return $$this.$$und18__O();
break
};
case 18:
{
return $$this.$$und19__O();
break
};
case 19:
{
return $$this.$$und20__O();
break
};
default:
throw new ScalaJS.c.java_lang_IndexOutOfBoundsException().init___T(ScalaJS.objectToString(ScalaJS.bI(n)));
}
});
ScalaJS.impls.scala_Product20$class__$init$__Lscala_Product20__V = (function($$this) {
/*<skip>*/
});
//@ sourceMappingURL=Product20$class.js.map
|
ignaciocases/hermeneumatics
|
node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/Product20$class.js
|
JavaScript
|
mit
| 2,103
|
'use strict';
angular.module('core').controller('HomeController', ['$scope', 'Authentication', 'Articles',
function ($scope, Authentication, Articles) {
// This provides Authentication context.
$scope.authentication = Authentication;
// Find a list of Articles
$scope.find = function () {
$scope.articles = Articles.query();
};
}
]);
|
ldlharper/bath-squash-league
|
modules/core/client/controllers/home.client.controller.js
|
JavaScript
|
mit
| 365
|
// Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
return str.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/[\s+_+]/gi, '-').toLowerCase();
}
spinalCase('thisIsSpinalTap');
|
wavymav/fCC_Work_Repo
|
Intermediate_Algorithm_Scripting/Spinal_Tap_Case.js
|
JavaScript
|
mit
| 329
|
'use strict';
const _ = require('lodash'),
getProtectedServerCalls = require('../../protectedServerStubby/getProtectedServerCalls.js');
require('chai').should();
module.exports = () => {
this.Then(/^strajah does not forward it to the protected server$/, done => {
const protectedPath = this.getValue('requestPath');
getProtectedServerCalls((error, response, body) => {
_.difference(_.map(body.items, performedCall => {
return performedCall.uri
}), protectedPath).should.deep.equal([]);
done();
});
});
};
|
strajah/strajah
|
acceptance-tests/lib/steps/reverseProxy/thenStrajahDoesNotForwardItToTheProtectedServer.js
|
JavaScript
|
mit
| 598
|
require('dotenv').config();
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 index = require('./routes/index');
var receipts = require('./routes/receipts');
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('/', index);
app.use('/receipts', receipts);
// 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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
Ramp-Receipts/Ramp
|
app.js
|
JavaScript
|
mit
| 1,297
|
// All symbols in the `Modi` script as per Unicode v8.0.0:
[
'\uD805\uDE00',
'\uD805\uDE01',
'\uD805\uDE02',
'\uD805\uDE03',
'\uD805\uDE04',
'\uD805\uDE05',
'\uD805\uDE06',
'\uD805\uDE07',
'\uD805\uDE08',
'\uD805\uDE09',
'\uD805\uDE0A',
'\uD805\uDE0B',
'\uD805\uDE0C',
'\uD805\uDE0D',
'\uD805\uDE0E',
'\uD805\uDE0F',
'\uD805\uDE10',
'\uD805\uDE11',
'\uD805\uDE12',
'\uD805\uDE13',
'\uD805\uDE14',
'\uD805\uDE15',
'\uD805\uDE16',
'\uD805\uDE17',
'\uD805\uDE18',
'\uD805\uDE19',
'\uD805\uDE1A',
'\uD805\uDE1B',
'\uD805\uDE1C',
'\uD805\uDE1D',
'\uD805\uDE1E',
'\uD805\uDE1F',
'\uD805\uDE20',
'\uD805\uDE21',
'\uD805\uDE22',
'\uD805\uDE23',
'\uD805\uDE24',
'\uD805\uDE25',
'\uD805\uDE26',
'\uD805\uDE27',
'\uD805\uDE28',
'\uD805\uDE29',
'\uD805\uDE2A',
'\uD805\uDE2B',
'\uD805\uDE2C',
'\uD805\uDE2D',
'\uD805\uDE2E',
'\uD805\uDE2F',
'\uD805\uDE30',
'\uD805\uDE31',
'\uD805\uDE32',
'\uD805\uDE33',
'\uD805\uDE34',
'\uD805\uDE35',
'\uD805\uDE36',
'\uD805\uDE37',
'\uD805\uDE38',
'\uD805\uDE39',
'\uD805\uDE3A',
'\uD805\uDE3B',
'\uD805\uDE3C',
'\uD805\uDE3D',
'\uD805\uDE3E',
'\uD805\uDE3F',
'\uD805\uDE40',
'\uD805\uDE41',
'\uD805\uDE42',
'\uD805\uDE43',
'\uD805\uDE44',
'\uD805\uDE50',
'\uD805\uDE51',
'\uD805\uDE52',
'\uD805\uDE53',
'\uD805\uDE54',
'\uD805\uDE55',
'\uD805\uDE56',
'\uD805\uDE57',
'\uD805\uDE58',
'\uD805\uDE59'
];
|
mathiasbynens/unicode-data
|
8.0.0/scripts/Modi-symbols.js
|
JavaScript
|
mit
| 1,405
|