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
define("ace/snippets/r",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = "snippet #!\n\ #!/usr/bin/env Rscript\n\ \n\ # includes\n\ snippet lib\n\ library(${1:package})\n\ snippet req\n\ require(${1:package})\n\ snippet source\n\ source('${1:file}')\n\ \n\ # conditionals\n\ snippet if\n\ if (${1:condition}) {\n\ ${2:code}\n\ }\n\ snippet el\n\ else {\n\ ${1:code}\n\ }\n\ snippet ei\n\ else if (${1:condition}) {\n\ ${2:code}\n\ }\n\ \n\ # functions\n\ snippet fun\n\ ${1:name} = function (${2:variables}) {\n\ ${3:code}\n\ }\n\ snippet ret\n\ return(${1:code})\n\ \n\ # dataframes, lists, etc\n\ snippet df\n\ ${1:name}[${2:rows}, ${3:cols}]\n\ snippet c\n\ c(${1:items})\n\ snippet li\n\ list(${1:items})\n\ snippet mat\n\ matrix(${1:data}, nrow=${2:rows}, ncol=${3:cols})\n\ \n\ # apply functions\n\ snippet apply\n\ apply(${1:array}, ${2:margin}, ${3:function})\n\ snippet lapply\n\ lapply(${1:list}, ${2:function})\n\ snippet sapply\n\ lapply(${1:list}, ${2:function})\n\ snippet vapply\n\ vapply(${1:list}, ${2:function}, ${3:type})\n\ snippet mapply\n\ mapply(${1:function}, ${2:...})\n\ snippet tapply\n\ tapply(${1:vector}, ${2:index}, ${3:function})\n\ snippet rapply\n\ rapply(${1:list}, ${2:function})\n\ \n\ # plyr functions\n\ snippet dd\n\ ddply(${1:frame}, ${2:variables}, ${3:function})\n\ snippet dl\n\ dlply(${1:frame}, ${2:variables}, ${3:function})\n\ snippet da\n\ daply(${1:frame}, ${2:variables}, ${3:function})\n\ snippet d_\n\ d_ply(${1:frame}, ${2:variables}, ${3:function})\n\ \n\ snippet ad\n\ adply(${1:array}, ${2:margin}, ${3:function})\n\ snippet al\n\ alply(${1:array}, ${2:margin}, ${3:function})\n\ snippet aa\n\ aaply(${1:array}, ${2:margin}, ${3:function})\n\ snippet a_\n\ a_ply(${1:array}, ${2:margin}, ${3:function})\n\ \n\ snippet ld\n\ ldply(${1:list}, ${2:function})\n\ snippet ll\n\ llply(${1:list}, ${2:function})\n\ snippet la\n\ laply(${1:list}, ${2:function})\n\ snippet l_\n\ l_ply(${1:list}, ${2:function})\n\ \n\ snippet md\n\ mdply(${1:matrix}, ${2:function})\n\ snippet ml\n\ mlply(${1:matrix}, ${2:function})\n\ snippet ma\n\ maply(${1:matrix}, ${2:function})\n\ snippet m_\n\ m_ply(${1:matrix}, ${2:function})\n\ \n\ # plot functions\n\ snippet pl\n\ plot(${1:x}, ${2:y})\n\ snippet ggp\n\ ggplot(${1:data}, aes(${2:aesthetics}))\n\ snippet img\n\ ${1:(jpeg,bmp,png,tiff)}(filename=\"${2:filename}\", width=${3}, height=${4}, unit=\"${5}\")\n\ ${6:plot}\n\ dev.off()\n\ \n\ # statistical test functions\n\ snippet fis\n\ fisher.test(${1:x}, ${2:y})\n\ snippet chi\n\ chisq.test(${1:x}, ${2:y})\n\ snippet tt\n\ t.test(${1:x}, ${2:y})\n\ snippet wil\n\ wilcox.test(${1:x}, ${2:y})\n\ snippet cor\n\ cor.test(${1:x}, ${2:y})\n\ snippet fte\n\ var.test(${1:x}, ${2:y})\n\ snippet kvt \n\ kv.test(${1:x}, ${2:y})\n\ "; exports.scope = "r"; });
ChamGeeks/GetAroundChamonix
www/lib/ngCordova/demo/www/lib/ace-builds/src/snippets/r.js
JavaScript
gpl-2.0
2,916
YUI.add('dd-drag', function(Y) { /** * The Drag & Drop Utility allows you to create a draggable interface efficiently, buffering you from browser-level abnormalities and enabling you to focus on the interesting logic surrounding your particular implementation. This component enables you to create a variety of standard draggable objects with just a few lines of code and then, using its extensive API, add your own specific implementation logic. * @module dd * @submodule dd-drag */ /** * This class provides the ability to drag a Node. * @class Drag * @extends Base * @constructor */ var DDM = Y.DD.DDM, NODE = 'node', DRAG_NODE = 'dragNode', OFFSET_HEIGHT = 'offsetHeight', OFFSET_WIDTH = 'offsetWidth', MOUSE_UP = 'mouseup', MOUSE_DOWN = 'mousedown', DRAG_START = 'dragstart', /** * @event drag:mouseDown * @description Handles the mousedown DOM event, checks to see if you have a valid handle then starts the drag timers. * @preventable _handleMouseDown * @param {Event} ev The mousedown event. * @bubbles DDM * @type Event.Custom */ EV_MOUSE_DOWN = 'drag:mouseDown', /** * @event drag:afterMouseDown * @description Fires after the mousedown event has been cleared. * @param {Event} ev The mousedown event. * @bubbles DDM * @type Event.Custom */ EV_AFTER_MOUSE_DOWN = 'drag:afterMouseDown', /** * @event drag:removeHandle * @description Fires after a handle is removed. * @bubbles DDM * @type Event.Custom */ EV_REMOVE_HANDLE = 'drag:removeHandle', /** * @event drag:addHandle * @description Fires after a handle is added. * @bubbles DDM * @type Event.Custom */ EV_ADD_HANDLE = 'drag:addHandle', /** * @event drag:removeInvalid * @description Fires after an invalid selector is removed. * @bubbles DDM * @type Event.Custom */ EV_REMOVE_INVALID = 'drag:removeInvalid', /** * @event drag:addInvalid * @description Fires after an invalid selector is added. * @bubbles DDM * @type Event.Custom */ EV_ADD_INVALID = 'drag:addInvalid', /** * @event drag:start * @description Fires at the start of a drag operation. * @bubbles DDM * @type Event.Custom */ EV_START = 'drag:start', /** * @event drag:end * @description Fires at the end of a drag operation. * @bubbles DDM * @type Event.Custom */ EV_END = 'drag:end', /** * @event drag:drag * @description Fires every mousemove during a drag operation. * @bubbles DDM * @type Event.Custom */ EV_DRAG = 'drag:drag'; /** * @event drag:over * @description Fires when this node is over a Drop Target. (Fired from dd-drop) * @bubbles DDM * @type Event.Custom */ /** * @event drag:enter * @description Fires when this node enters a Drop Target. (Fired from dd-drop) * @bubbles DDM * @type Event.Custom */ /** * @event drag:exit * @description Fires when this node exits a Drop Target. (Fired from dd-drop) * @bubbles DDM * @type Event.Custom */ /** * @event drag:drophit * @description Fires when this node is dropped on a valid Drop Target. (Fired from dd-ddm-drop) * @bubbles DDM * @type Event.Custom */ /** * @event drag:dropmiss * @description Fires when this node is dropped on an invalid Drop Target. (Fired from dd-ddm-drop) * @bubbles DDM * @type Event.Custom */ var Drag = function() { Drag.superclass.constructor.apply(this, arguments); DDM._regDrag(this); }; Drag.NAME = 'drag'; Drag.ATTRS = { /** * @attribute node * @description Y.Node instanace to use as the element to initiate a drag operation * @type Node */ node: { set: function(node) { var n = Y.get(node); if (!n) { Y.fail('DD.Drag: Invalid Node Given: ' + node); } else { n = n.item(0); } return n; } }, /** * @attribute dragNode * @description Y.Node instanace to use as the draggable element, defaults to node * @type Node */ dragNode: { set: function(node) { var n = Y.Node.get(node); if (!n) { Y.fail('DD.Drag: Invalid dragNode Given: ' + node); } return n; } }, /** * @attribute offsetNode * @description Offset the drag element by the difference in cursor position: default true * @type Boolean */ offsetNode: { value: true }, /** * @attribute clickPixelThresh * @description The number of pixels to move to start a drag operation, default is 3. * @type Number */ clickPixelThresh: { value: DDM.get('clickPixelThresh') }, /** * @attribute clickTimeThresh * @description The number of milliseconds a mousedown has to pass to start a drag operation, default is 1000. * @type Number */ clickTimeThresh: { value: DDM.get('clickTimeThresh') }, /** * @attribute lock * @description Set to lock this drag element so that it can't be dragged: default false. * @type Boolean */ lock: { value: false, set: function(lock) { if (lock) { this.get(NODE).addClass(DDM.CSS_PREFIX + '-locked'); } else { this.get(NODE).removeClass(DDM.CSS_PREFIX + '-locked'); } } }, /** * @attribute data * @description A payload holder to store arbitrary data about this drag object, can be used to store any value. * @type Mixed */ data: { value: false }, /** * @attribute move * @description If this is false, the drag element will not move with the cursor: default true. Can be used to "resize" the element. * @type Boolean */ move: { value: true }, /** * @attribute useShim * @description Use the protective shim on all drag operations: default true. Only works with dd-ddm, not dd-ddm-base. * @type Boolean */ useShim: { value: true }, /** * @attribute activeHandle * @description This config option is set by Drag to inform you of which handle fired the drag event (in the case that there are several handles): default false. * @type Node */ activeHandle: { value: false }, /** * @attribute primaryButtonOnly * @description By default a drag operation will only begin if the mousedown occurred with the primary mouse button. Setting this to false will allow for all mousedown events to trigger a drag. * @type Boolean */ primaryButtonOnly: { value: true }, /** * @attribute dragging * @description This attribute is not meant to be used by the implementor, it is meant to be used as an Event tracker so you can listen for it to change. * @type Boolean */ dragging: { value: false }, parent: { value: false }, /** * @attribute target * @description This attribute only works if the dd-drop module has been loaded. It will make this node a drop target as well as draggable. * @type Boolean */ target: { value: false, set: function(config) { this._handleTarget(config); } }, /** * @attribute dragMode * @description This attribute only works if the dd-drop module is active. It will set the dragMode (point, intersect, strict) of this Drag instance. * @type String */ dragMode: { value: null, set: function(mode) { return DDM._setDragMode(mode); } }, /** * @attribute groups * @description Array of groups to add this drag into. * @type Array */ groups: { value: ['default'], get: function() { if (!this._groups) { this._groups = {}; } var ret = []; Y.each(this._groups, function(v, k) { ret[ret.length] = k; }); return ret; }, set: function(g) { this._groups = {}; Y.each(g, function(v, k) { this._groups[v] = true; }, this); } }, /** * @attribute handles * @description Array of valid handles to add. Adding something here will set all handles, even if previously added with addHandle * @type Array */ handles: { value: null, set: function(g) { if (g) { this._handles = {}; Y.each(g, function(v, k) { this._handles[v] = true; }, this); } else { this._handles = null; } return g; } }, /** * @attribute bubbles * @description Controls the default bubble parent for this Drag instance. Default: Y.DD.DDM. Set to false to disable bubbling. * @type Object */ bubbles: { writeOnce: true, value: Y.DD.DDM } }; Y.extend(Drag, Y.Base, { /** * @method addToGroup * @description Add this Drag instance to a group, this should be used for on-the-fly group additions. * @param {String} g The group to add this Drag Instance to. * @return {Self} * @chainable */ addToGroup: function(g) { this._groups[g] = true; DDM._activateTargets(); return this; }, /** * @method removeFromGroup * @description Remove this Drag instance from a group, this should be used for on-the-fly group removals. * @param {String} g The group to remove this Drag Instance from. * @return {Self} * @chainable */ removeFromGroup: function(g) { delete this._groups[g]; DDM._activateTargets(); return this; }, /** * @property target * @description This will be a reference to the Drop instance associated with this drag if the target: true config attribute is set.. * @type {Object} */ target: null, /** * @private * @method _handleTarget * @description Attribute handler for the target config attribute. * @param {Boolean/Object} * @return {Boolean/Object} */ _handleTarget: function(config) { if (Y.DD.Drop) { if (config === false) { if (this.target) { DDM._unregTarget(this.target); this.target = null; } return false; } else { if (!Y.Lang.isObject(config)) { config = {}; } config.bubbles = this.get('bubbles'); config.node = this.get(NODE); this.target = new Y.DD.Drop(config); } } else { return false; } }, /** * @private * @property _groups * @description Storage Array for the groups this drag belongs to. * @type {Array} */ _groups: null, /** * @private * @method _createEvents * @description This method creates all the events for this Event Target and publishes them so we get Event Bubbling. */ _createEvents: function() { this.publish(EV_MOUSE_DOWN, { defaultFn: this._handleMouseDown, queuable: true, emitFacade: true, bubbles: true }); var ev = [ EV_AFTER_MOUSE_DOWN, EV_REMOVE_HANDLE, EV_ADD_HANDLE, EV_REMOVE_INVALID, EV_ADD_INVALID, EV_START, EV_END, EV_DRAG, 'drag:drophit', 'drag:dropmiss', 'drag:over', 'drag:enter', 'drag:exit' ]; Y.each(ev, function(v, k) { this.publish(v, { type: v, emitFacade: true, bubbles: true, preventable: false, queuable: true }); }, this); if (this.get('bubbles')) { this.addTarget(this.get('bubbles')); } }, /** * @private * @property _ev_md * @description A private reference to the mousedown DOM event * @type {Event} */ _ev_md: null, /** * @private * @property _startTime * @description The getTime of the mousedown event. Not used, just here in case someone wants/needs to use it. * @type Date */ _startTime: null, /** * @private * @property _endTime * @description The getTime of the mouseup event. Not used, just here in case someone wants/needs to use it. * @type Date */ _endTime: null, /** * @private * @property _handles * @description A private hash of the valid drag handles * @type {Object} */ _handles: null, /** * @private * @property _invalids * @description A private hash of the invalid selector strings * @type {Object} */ _invalids: null, /** * @private * @property _invalidsDefault * @description A private hash of the default invalid selector strings: {'textarea': true, 'input': true, 'a': true, 'button': true} * @type {Object} */ _invalidsDefault: {'textarea': true, 'input': true, 'a': true, 'button': true}, /** * @private * @property _dragThreshMet * @description Private flag to see if the drag threshhold was met * @type {Boolean} */ _dragThreshMet: null, /** * @private * @property _fromTimeout * @description Flag to determine if the drag operation came from a timeout * @type {Boolean} */ _fromTimeout: null, /** * @private * @property _clickTimeout * @description Holder for the setTimeout call * @type {Boolean} */ _clickTimeout: null, /** * @property deltaXY * @description The offset of the mouse position to the element's position * @type {Array} */ deltaXY: null, /** * @property startXY * @description The initial mouse position * @type {Array} */ startXY: null, /** * @property nodeXY * @description The initial element position * @type {Array} */ nodeXY: null, /** * @property lastXY * @description The position of the element as it's moving (for offset calculations) * @type {Array} */ lastXY: null, realXY: null, /** * @property mouseXY * @description The XY coords of the mousemove * @type {Array} */ mouseXY: null, /** * @property region * @description A region object associated with this drag, used for checking regions while dragging. * @type Object */ region: null, /** * @private * @method _handleMouseUp * @description Handler for the mouseup DOM event * @param {Event} */ _handleMouseUp: function(ev) { this._fixIEMouseUp(); if (DDM.activeDrag) { DDM._end(); } }, /** * @private * @method _fixDragStart * @description The function we use as the ondragstart handler when we start a drag in Internet Explorer. This keeps IE from blowing up on images as drag handles. */ _fixDragStart: function(e) { e.preventDefault(); }, /** * @private * @method _ieSelectFix * @description The function we use as the onselectstart handler when we start a drag in Internet Explorer */ _ieSelectFix: function() { return false; }, /** * @private * @property _ieSelectBack * @description We will hold a copy of the current "onselectstart" method on this property, and reset it after we are done using it. */ _ieSelectBack: null, /** * @private * @method _fixIEMouseDown * @description This method copies the onselectstart listner on the document to the _ieSelectFix property */ _fixIEMouseDown: function() { if (Y.UA.ie) { this._ieSelectBack = Y.config.doc.body.onselectstart; Y.config.doc.body.onselectstart = this._ieSelectFix; } }, /** * @private * @method _fixIEMouseUp * @description This method copies the _ieSelectFix property back to the onselectstart listner on the document. */ _fixIEMouseUp: function() { if (Y.UA.ie) { Y.config.doc.body.onselectstart = this._ieSelectBack; } }, /** * @private * @method _handleMouseDownEvent * @description Handler for the mousedown DOM event * @param {Event} */ _handleMouseDownEvent: function(ev) { this.fire(EV_MOUSE_DOWN, { ev: ev }); }, /** * @private * @method _handleMouseDown * @description Handler for the mousedown DOM event * @param {Event} */ _handleMouseDown: function(e) { var ev = e.ev; this._dragThreshMet = false; this._ev_md = ev; if (this.get('primaryButtonOnly') && ev.button > 1) { return false; } if (this.validClick(ev)) { this._fixIEMouseDown(); ev.halt(); this._setStartPosition([ev.pageX, ev.pageY]); DDM.activeDrag = this; var self = this; this._clickTimeout = setTimeout(function() { self._timeoutCheck.call(self); }, this.get('clickTimeThresh')); } this.fire(EV_AFTER_MOUSE_DOWN, { ev: ev }); }, /** * @method validClick * @description Method first checks to see if we have handles, if so it validates the click against the handle. Then if it finds a valid handle, it checks it against the invalid handles list. Returns true if a good handle was used, false otherwise. * @param {Event} * @return {Boolean} */ validClick: function(ev) { var r = false, tar = ev.target, hTest = null; if (this._handles) { Y.each(this._handles, function(i, n) { if (Y.Lang.isString(n)) { //Am I this or am I inside this if (tar.test(n + ', ' + n + ' *') && !hTest) { hTest = n; r = true; } } }); } else { if (this.get(NODE).contains(tar) || this.get(NODE).compareTo(tar)) { r = true; } } if (r) { if (this._invalids) { Y.each(this._invalids, function(i, n) { if (Y.Lang.isString(n)) { //Am I this or am I inside this if (tar.test(n + ', ' + n + ' *')) { r = false; } } }); } } if (r) { if (hTest) { var els = ev.currentTarget.queryAll(hTest), set = false; els.each(function(n, i) { if ((n.contains(tar) || n.compareTo(tar)) && !set) { set = true; this.set('activeHandle', els.item(i)); } }, this); } else { this.set('activeHandle', this.get(NODE)); } } return r; }, /** * @private * @method _setStartPosition * @description Sets the current position of the Element and calculates the offset * @param {Array} xy The XY coords to set the position to. */ _setStartPosition: function(xy) { this.startXY = xy; this.nodeXY = this.get(NODE).getXY(); this.lastXY = this.nodeXY; this.realXY = this.nodeXY; if (this.get('offsetNode')) { this.deltaXY = [(this.startXY[0] - this.nodeXY[0]), (this.startXY[1] - this.nodeXY[1])]; } else { this.deltaXY = [0, 0]; } }, /** * @private * @method _timeoutCheck * @description The method passed to setTimeout to determine if the clickTimeThreshold was met. */ _timeoutCheck: function() { if (!this.get('lock')) { this._fromTimeout = true; this._dragThreshMet = true; this.start(); this._moveNode([this._ev_md.pageX, this._ev_md.pageY], true); } }, /** * @method removeHandle * @description Remove a Selector added by addHandle * @param {String} str The selector for the handle to be removed. * @return {Self} * @chainable */ removeHandle: function(str) { if (this._handles[str]) { delete this._handles[str]; this.fire(EV_REMOVE_HANDLE, { handle: str }); } return this; }, /** * @method addHandle * @description Add a handle to a drag element. Drag only initiates when a mousedown happens on this element. * @param {String} str The selector to test for a valid handle. Must be a child of the element. * @return {Self} * @chainable */ addHandle: function(str) { if (!this._handles) { this._handles = {}; } if (Y.Lang.isString(str)) { this._handles[str] = true; this.fire(EV_ADD_HANDLE, { handle: str }); } return this; }, /** * @method removeInvalid * @description Remove an invalid handle added by addInvalid * @param {String} str The invalid handle to remove from the internal list. * @return {Self} * @chainable */ removeInvalid: function(str) { if (this._invalids[str]) { this._invalids[str] = null; delete this._invalids[str]; this.fire(EV_REMOVE_INVALID, { handle: str }); } return this; }, /** * @method addInvalid * @description Add a selector string to test the handle against. If the test passes the drag operation will not continue. * @param {String} str The selector to test against to determine if this is an invalid drag handle. * @return {Self} * @chainable */ addInvalid: function(str) { if (Y.Lang.isString(str)) { this._invalids[str] = true; this.fire(EV_ADD_INVALID, { handle: str }); } else { } return this; }, /** * @private * @method initializer * @description Internal init handler */ initializer: function() { //TODO give the node instance a copy of this object //Not supported in PR1 due to Y.Node.get calling a new under the hood. //this.get(NODE).dd = this; if (!this.get(NODE).get('id')) { var id = Y.stamp(this.get(NODE)); this.get(NODE).set('id', id); } this._invalids = Y.clone(this._invalidsDefault, true); this._createEvents(); if (!this.get(DRAG_NODE)) { this.set(DRAG_NODE, this.get(NODE)); } this._prep(); this._dragThreshMet = false; }, /** * @private * @method _prep * @description Attach event listners and add classname */ _prep: function() { var node = this.get(NODE); node.addClass(DDM.CSS_PREFIX + '-draggable'); node.on(MOUSE_DOWN, this._handleMouseDownEvent, this, true); node.on(MOUSE_UP, this._handleMouseUp, this, true); node.on(DRAG_START, this._fixDragStart, this, true); }, /** * @private * @method _unprep * @description Detach event listners and remove classname */ _unprep: function() { var node = this.get(NODE); node.removeClass(DDM.CSS_PREFIX + '-draggable'); node.detach(MOUSE_DOWN, this._handleMouseDownEvent, this, true); node.detach(MOUSE_UP, this._handleMouseUp, this, true); node.detach(DRAG_START, this._fixDragStart, this, true); }, /** * @method start * @description Starts the drag operation * @return {Self} * @chainable */ start: function() { if (!this.get('lock') && !this.get('dragging')) { this.set('dragging', true); DDM._start(this.deltaXY, [this.get(NODE).get(OFFSET_HEIGHT), this.get(NODE).get(OFFSET_WIDTH)]); this.get(NODE).addClass(DDM.CSS_PREFIX + '-dragging'); this.fire(EV_START, { pageX: this.nodeXY[0], pageY: this.nodeXY[1] }); this.get(DRAG_NODE).on(MOUSE_UP, this._handleMouseUp, this, true); var xy = this.nodeXY; this._startTime = (new Date()).getTime(); this.region = { '0': xy[0], '1': xy[1], area: 0, top: xy[1], right: xy[0] + this.get(NODE).get(OFFSET_WIDTH), bottom: xy[1] + this.get(NODE).get(OFFSET_HEIGHT), left: xy[0] }; } return this; }, /** * @method end * @description Ends the drag operation * @return {Self} * @chainable */ end: function() { this._endTime = (new Date()).getTime(); clearTimeout(this._clickTimeout); this._dragThreshMet = false; this._fromTimeout = false; if (!this.get('lock') && this.get('dragging')) { this.fire(EV_END, { pageX: this.lastXY[0], pageY: this.lastXY[1] }); } this.get(NODE).removeClass(DDM.CSS_PREFIX + '-dragging'); this.set('dragging', false); this.deltaXY = [0, 0]; this.get(DRAG_NODE).detach(MOUSE_UP, this._handleMouseUp, this, true); return this; }, /** * @private * @method _align * @description Calculates the offsets and set's the XY that the element will move to. * @param {Array} xy The xy coords to align with. * @return Array * @type {Array} */ _align: function(xy) { return [xy[0] - this.deltaXY[0], xy[1] - this.deltaXY[1]]; }, /** * @private * @method _moveNode * @description This method performs the actual element move. * @param {Array} eXY The XY to move the element to, usually comes from the mousemove DOM event. * @param {Boolean} noFire If true, the drag:drag event will not fire. */ _moveNode: function(eXY, noFire) { var xy = this._align(eXY), diffXY = [], diffXY2 = []; //This will probably kill your machine ;) diffXY[0] = (xy[0] - this.lastXY[0]); diffXY[1] = (xy[1] - this.lastXY[1]); diffXY2[0] = (xy[0] - this.nodeXY[0]); diffXY2[1] = (xy[1] - this.nodeXY[1]); if (this.get('move')) { if (Y.UA.opera) { this.get(DRAG_NODE).setXY(xy); } else { DDM.setXY(this.get(DRAG_NODE), diffXY); } this.realXY = xy; } this.region = { '0': xy[0], '1': xy[1], area: 0, top: xy[1], right: xy[0] + this.get(DRAG_NODE).get(OFFSET_WIDTH), bottom: xy[1] + this.get(DRAG_NODE).get(OFFSET_HEIGHT), left: xy[0] }; var startXY = this.nodeXY; if (!noFire) { this.fire(EV_DRAG, { pageX: xy[0], pageY: xy[1], info: { start: startXY, xy: xy, delta: diffXY, offset: diffXY2 } }); } this.lastXY = xy; }, /** * @private * @method _move * @description Fired from DragDropMgr (DDM) on mousemove. * @param {Event} ev The mousemove DOM event */ _move: function(ev) { if (this.get('lock')) { return false; } else { this.mouseXY = [ev.pageX, ev.pageY]; if (!this._dragThreshMet) { var diffX = Math.abs(this.startXY[0] - ev.pageX); var diffY = Math.abs(this.startXY[1] - ev.pageY); if (diffX > this.get('clickPixelThresh') || diffY > this.get('clickPixelThresh')) { this._dragThreshMet = true; this.start(); this._moveNode([ev.pageX, ev.pageY]); } } else { clearTimeout(this._clickTimeout); this._moveNode([ev.pageX, ev.pageY]); } } }, /** * @method stopDrag * @description Method will forcefully stop a drag operation. For example calling this from inside an ESC keypress handler will stop this drag. * @return {Self} * @chainable */ stopDrag: function() { if (this.get('dragging')) { DDM._end(); } return this; }, /** * @private * @method destructor * @description Lifecycle destructor, unreg the drag from the DDM and remove listeners */ destructor: function() { DDM._unregDrag(this); this._unprep(); if (this.target) { this.target.destroy(); } } }); Y.namespace('DD'); Y.DD.Drag = Drag; }, '@VERSION@' ,{requires:['dd-ddm-base'], skinnable:false});
kiwi89/cdnjs
ajax/libs/yui/3.0.0pr2/dd/dd-drag.js
JavaScript
mit
33,361
/*! * TableSorter 2.3.1 - Client-side table sorting with ease! * @requires jQuery v1.2.6+ * * Copyright (c) 2007 Christian Bach * Examples and docs at: http://tablesorter.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * @type jQuery * @name tablesorter * @cat Plugins/Tablesorter * @author Christian Bach/christian.bach@polyester.se * @contributor Rob Garrison/https://github.com/Mottie/tablesorter */ !(function($) { $.extend({ tablesorter: new function() { this.version = "2.3.1"; var parsers = [], widgets = []; this.defaults = { // appearance widthFixed : false, // functionality cancelSelection : true, // prevent text selection in the header dateFormat : "mmddyyyy", // other options: "ddmmyyy" or "yyyymmdd" sortMultiSortKey : "shiftKey", // key used to select additional columns usNumberFormat : true, // false for German "1.234.567,89" or French "1 234 567,89" delayInit : false, // if false, the parsed table contents will not update until the first sort. // sort options headers : {}, // set sorter, string, empty, locked order, sortInitialOrder, filter, etc. ignoreCase : true, // ignore case while sorting sortForce : null, // column(s) first sorted; always applied sortList : [], // Initial sort order; applied initially; updated when manually sorted sortAppend : null, // column(s) sorted last; always applied sortInitialOrder : "asc", // sort direction on first click sortLocaleCompare: false, // replace equivalent character (accented characters) sortReset : false, // third click on the header will reset column to default - unsorted sortRestart : false, // restart sort to "sortInitialOrder" when clicking on previously unsorted columns emptyTo : "bottom", // sort empty cell to bottom, top, none, zero stringTo : "max", // sort strings in numerical column as max, min, top, bottom, zero textExtraction : "simple", // text extraction method/function - function(node, table, cellIndex){} textSorter : null, // use custom text sorter - function(a,b){ return a.sort(b); } // basic sort // widget options widgetOptions : { zebra : [ "even", "odd" ] // zebra widget alternating row class names }, // callbacks initialized : null, // function(table){}, onRenderHeader : null, // function(index){}, // css class names tableClass : 'tablesorter', cssAsc : "tablesorter-headerSortUp", cssChildRow : "expand-child", cssDesc : "tablesorter-headerSortDown", cssHeader : "tablesorter-header", cssInfoBlock : "tablesorter-infoOnly", // don't sort tbody with this class name // selectors selectorHeaders : '> thead th', selectorRemove : "tr.remove-me", // advanced debug : false, // Internal variables headerList: [], empties: {}, strings: {}, parsers: [], widgets: [] // deprecated; but retained for backwards compatibility // widgetZebra: { css: ["even", "odd"] } }; /* debuging utils */ function log(s) { if (typeof console !== "undefined" && typeof console.log !== "undefined") { console.log(s); } else { alert(s); } } function benchmark(s, d) { log(s + " (" + (new Date().getTime() - d.getTime()) + "ms)"); } this.benchmark = benchmark; this.hasInitialized = false; function getElementText(table, node, cellIndex) { var text = "", t = table.config.textExtraction; if (!node) { return ""; } if (t === "simple") { text = $(node).text(); } else { if (typeof(t) === "function") { text = t(node, table, cellIndex); } else if (typeof(t) === "object" && t.hasOwnProperty(cellIndex)) { text = t[cellIndex](node, table, cellIndex); } else { text = $(node).text(); } } return text; } /* parsers utils */ function getParserById(name) { var i, l = parsers.length; for (i = 0; i < l; i++) { if (parsers[i].id.toLowerCase() === (name.toString()).toLowerCase()) { return parsers[i]; } } return false; } function detectParserForColumn(table, rows, rowIndex, cellIndex) { var i, l = parsers.length, node = false, nodeValue = '', keepLooking = true; while (nodeValue === '' && keepLooking) { rowIndex++; if (rows[rowIndex]) { node = rows[rowIndex].cells[cellIndex]; nodeValue = $.trim(getElementText(table, node, cellIndex)); if (table.config.debug) { log('Checking if value was empty on row ' + rowIndex + ', column:' + cellIndex + ": " + nodeValue); } } else { keepLooking = false; } } for (i = 1; i < l; i++) { if (parsers[i].is(nodeValue, table, node)) { return parsers[i]; } } // 0 is always the generic parser (text) return parsers[0]; } function buildParserCache(table, $headers) { if (table.tBodies.length === 0) { return; } // In the case of empty tables var c = table.config, rows = table.tBodies[0].rows, ts = $.tablesorter, list, l, i, h, m, ch, cl, p, parsersDebug = ""; if (rows[0]) { list = []; l = rows[0].cells.length; for (i = 0; i < l; i++) { h = $headers.filter(':not([colspan])[data-column="'+i+'"]:last'); ch = c.headers[i]; // get column parser p = getParserById( ts.getData(h, ch, 'sorter') ); // empty cells behaviour - keeping emptyToBottom for backwards compatibility. c.empties[i] = ts.getData(h, ch, 'empty') || c.emptyTo || (c.emptyToBottom ? 'bottom' : 'top' ); // text strings behaviour in numerical sorts c.strings[i] = ts.getData(h, ch, 'string') || c.stringTo || 'max'; if (!p) { p = detectParserForColumn(table, rows, -1, i); } if (c.debug) { parsersDebug += "column:" + i + "; parser:" + p.id + "; string:" + c.strings[i] + '; empty: ' + c.empties[i] + "\n"; } list.push(p); } } if (c.debug) { log(parsersDebug); } return list; } /* utils */ function buildRegex(){ var a, acc = '[', t = $.tablesorter, reg = t.characterEquivalents; t.characterRegexArray = {}; for (a in reg) { if (typeof a === 'string') { acc += reg[a]; t.characterRegexArray[a] = new RegExp('[' + reg[a] + ']', 'g'); } } t.characterRegex = new RegExp(acc + ']'); } function buildCache(table) { var b = table.tBodies, tc = table.config, totalRows, totalCells, parsers = tc.parsers, t, i, j, k, c, cols, cacheTime; tc.cache = {}; if (tc.debug) { cacheTime = new Date(); } for (k = 0; k < b.length; k++) { tc.cache[k] = { row: [], normalized: [] }; // ignore tbodies with class name from css.cssInfoBlock if (!$(b[k]).hasClass(tc.cssInfoBlock)) { totalRows = (b[k] && b[k].rows.length) || 0; totalCells = (b[k].rows[0] && b[k].rows[0].cells.length) || 0; for (i = 0; i < totalRows; ++i) { /** Add the table data to main data array */ c = $(b[k].rows[i]); cols = []; // if this is a child row, add it to the last row's children and continue to the next row if (c.hasClass(tc.cssChildRow)) { tc.cache[k].row[tc.cache[k].row.length - 1] = tc.cache[k].row[tc.cache[k].row.length - 1].add(c); // go to the next for loop continue; } tc.cache[k].row.push(c); for (j = 0; j < totalCells; ++j) { t = $.trim(getElementText(table, c[0].cells[j], j)); // allow parsing if the string is empty, previously parsing would change it to zero, // in case the parser needs to extract data from the table cell attributes cols.push( parsers[j].format(t, table, c[0].cells[j], j) ); } cols.push(tc.cache[k].normalized.length); // add position for rowCache tc.cache[k].normalized.push(cols); } } } if (tc.debug) { benchmark("Building cache for " + totalRows + " rows", cacheTime); } } function getWidgetById(name) { var i, w, l = widgets.length; for (i = 0; i < l; i++) { w = widgets[i]; if (w && w.hasOwnProperty('id') && w.id.toLowerCase() === name.toLowerCase()) { return w; } } } function applyWidget(table, init) { var c = table.config.widgets, i, w, l = c.length; for (i = 0; i < l; i++) { w = getWidgetById(c[i]); if ( w ) { if (init && w.hasOwnProperty('init')) { w.init(table, widgets, w); } else if (!init && w.hasOwnProperty('format')) { w.format(table); } } } } function appendToTable(table) { var c = table.config, b = table.tBodies, rows = [], r, n, totalRows, checkCell, f, i, j, k, l, pos, appendTime; if (c.debug) { appendTime = new Date(); } for (k = 0; k < b.length; k++) { if (!$(b[k]).hasClass(c.cssInfoBlock)){ f = document.createDocumentFragment(); r = c.cache[k].row; n = c.cache[k].normalized; totalRows = n.length; checkCell = totalRows ? (n[0].length - 1) : 0; for (i = 0; i < totalRows; i++) { pos = n[i][checkCell]; rows.push(r[pos]); // removeRows used by the pager plugin if (!c.appender || !c.removeRows) { l = r[pos].length; for (j = 0; j < l; j++) { f.appendChild(r[pos][j]); } } } table.tBodies[k].appendChild(f); } } if (c.appender) { c.appender(table, rows); } if (c.debug) { benchmark("Rebuilt table", appendTime); } // apply table widgets applyWidget(table); // trigger sortend $(table).trigger("sortEnd", table); } // from: // http://www.javascripttoolbox.com/lib/table/examples.php // http://www.javascripttoolbox.com/temp/table_cellindex.html function computeTableHeaderCellIndexes(t) { var matrix = [], lookup = {}, trs = $(t).find('thead:eq(0) tr'), i, j, k, l, c, cells, rowIndex, cellId, rowSpan, colSpan, firstAvailCol, matrixrow; for (i = 0; i < trs.length; i++) { cells = trs[i].cells; for (j = 0; j < cells.length; j++) { c = cells[j]; rowIndex = c.parentNode.rowIndex; cellId = rowIndex + "-" + c.cellIndex; rowSpan = c.rowSpan || 1; colSpan = c.colSpan || 1; if (typeof(matrix[rowIndex]) === "undefined") { matrix[rowIndex] = []; } // Find first available column in the first row for (k = 0; k < matrix[rowIndex].length + 1; k++) { if (typeof(matrix[rowIndex][k]) === "undefined") { firstAvailCol = k; break; } } lookup[cellId] = firstAvailCol; // add data-column $(c).attr({ 'data-column' : firstAvailCol }); // 'data-row' : rowIndex for (k = rowIndex; k < rowIndex + rowSpan; k++) { if (typeof(matrix[k]) === "undefined") { matrix[k] = []; } matrixrow = matrix[k]; for (l = firstAvailCol; l < firstAvailCol + colSpan; l++) { matrixrow[l] = "x"; } } } } return lookup; } function formatSortingOrder(v) { // look for "d" in "desc" order; return true return (/^d/i.test(v) || v === 1); } function buildHeaders(table) { var meta = ($.metadata) ? true : false, header_index = computeTableHeaderCellIndexes(table), ch, $t, $th, lock, time, $tableHeaders, c = table.config, ts = $.tablesorter; c.headerList = []; if (c.debug) { time = new Date(); } $tableHeaders = $(c.selectorHeaders, table) .wrapInner("<div class='tablesorter-header-inner' />") .each(function(index) { $t = $(this); ch = c.headers[index]; this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex]; this.order = formatSortingOrder( ts.getData($t, ch, 'sortInitialOrder') || c.sortInitialOrder ) ? [1,0,2] : [0,1,2]; this.count = -1; // set to -1 because clicking on the header automatically adds one if (ts.getData($t, ch, 'sorter') === 'false') { this.sortDisabled = true; } this.lockedOrder = false; lock = ts.getData($t, ch, 'lockedOrder') || false; if (typeof(lock) !== 'undefined' && lock !== false) { this.order = this.lockedOrder = formatSortingOrder(lock) ? [1,1,1] : [0,0,0]; } if (!this.sortDisabled) { $th = $t.addClass(c.cssHeader); if (c.onRenderHeader) { c.onRenderHeader.apply($th, [index]); } } // add cell to headerList c.headerList[index] = this; $t.parent().addClass(c.cssHeader); }); if (c.debug) { benchmark("Built headers", time); log($tableHeaders); } return $tableHeaders; } function isValueInArray(v, a) { var i, l = a.length; for (i = 0; i < l; i++) { if (a[i][0] === v) { return true; } } return false; } function setHeadersCss(table, $headers, list) { var f, h = [], i, j, l, css = [table.config.cssDesc, table.config.cssAsc]; // remove all header information $headers .removeClass(css.join(' ')) .each(function() { if (!this.sortDisabled) { h[this.column] = $(this); } }); l = list.length; for (i = 0; i < l; i++) { if (list[i][1] === 2) { continue; } // direction = 2 means reset! h[list[i][0]].addClass(css[list[i][1]]); // multicolumn sorting updating f = $headers.filter('[data-column="' + list[i][0] + '"]'); if (l > 1 && f.length) { for (j = 0; j < f.length; j++) { if (!f[j].sortDisabled) { $(f[j]).addClass(css[list[i][1]]); } } } } } function fixColumnWidth(table) { if (table.config.widthFixed) { var colgroup = $('<colgroup>'); $("tr:first td", table.tBodies[0]).each(function() { colgroup.append($('<col>').css('width', $(this).width())); }); $(table).prepend(colgroup); } } function updateHeaderSortCount(table, sortList) { var i, s, o, c = table.config, l = sortList.length; for (i = 0; i < l; i++) { s = sortList[i]; o = c.headerList[s[0]]; o.count = s[1] % (c.sortReset ? 3 : 2); } } function getCachedSortType(parsers, i) { return (parsers) ? parsers[i].type : ''; } /* sorting methods - reverted sorting method back to version 2.0.3 */ function multisort(table, sortList) { var dynamicExp, col, mx = 0, dir = 0, tc = table.config, l = sortList.length, bl = table.tBodies.length, sortTime, i, j, k, c, cache, lc, s, e, order, orgOrderCol; if (tc.debug) { sortTime = new Date(); } for (k = 0; k < bl; k++) { dynamicExp = "var sortWrapper = function(a,b) {"; cache = tc.cache[k]; lc = cache.normalized.length; for (i = 0; i < l; i++) { c = sortList[i][0]; order = sortList[i][1]; // fallback to natural sort since it is more robust s = /n/i.test(getCachedSortType(tc.parsers, c)) ? "Numeric" : "Text"; s += order === 0 ? "" : "Desc"; e = "e" + i; // get max column value (ignore sign) if (/Numeric/.test(s) && tc.strings[c]) { for (j = 0; j < lc; j++) { col = Math.abs(parseFloat(cache.normalized[j][c])); mx = Math.max( mx, isNaN(col) ? 0 : col ); } // sort strings in numerical columns if (typeof(tc.string[tc.strings[c]]) === 'boolean') { dir = (order === 0 ? 1 : -1) * (tc.string[tc.strings[c]] ? -1 : 1); } else { dir = (tc.strings[c]) ? tc.string[tc.strings[c]] || 0 : 0; } } dynamicExp += "var " + e + " = sort" + s + "(table, a[" + c + "],b[" + c + "]," + c + "," + mx + "," + dir + "); "; dynamicExp += "if (" + e + ") { return " + e + "; } "; dynamicExp += "else { "; } // if value is the same keep orignal order orgOrderCol = (cache.normalized && cache.normalized[0]) ? cache.normalized[0].length - 1 : 0; dynamicExp += "return a[" + orgOrderCol + "]-b[" + orgOrderCol + "];"; for (i=0; i < l; i++) { dynamicExp += "}; "; } dynamicExp += "return 0; "; dynamicExp += "}; "; eval(dynamicExp); cache.normalized.sort(sortWrapper); // sort using eval expression } if (tc.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order+ " time", sortTime); } } // Natural sort - https://github.com/overset/javascript-natural-sort function sortText(table, a, b, col) { if (a === b) { return 0; } var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ], r = $.tablesorter.regex, xN, xD, yN, yD, xF, yF, i, mx; if (a === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? -1 : 1) : -e || -1; } if (b === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? 1 : -1) : e || 1; } if (typeof c.textSorter === 'function') { return c.textSorter(a, b); } // chunk/tokenize xN = a.replace(r[0], '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'); yN = b.replace(r[0], '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'); // numeric, hex or date detection xD = parseInt(a.match(r[2])) || (xN.length !== 1 && a.match(r[1]) && Date.parse(a)); yD = parseInt(b.match(r[2])) || (xD && b.match(r[1]) && Date.parse(b)) || null; // first try and sort Hex codes or Dates if (yD) { if ( xD < yD ) { return -1; } if ( xD > yD ) { return 1; } } mx = Math.max(xN.length, yN.length); // natural sorting through split numeric strings and default strings for (i = 0; i < mx; i++) { // find floats not starting with '0', string or 0 if not defined (Clint Priest) xF = (!(xN[i] || '').match(r[3]) && parseFloat(xN[i])) || xN[i] || 0; yF = (!(yN[i] || '').match(r[3]) && parseFloat(yN[i])) || yN[i] || 0; // handle numeric vs string comparison - number < string - (Kyle Adams) if (isNaN(xF) !== isNaN(yF)) { return (isNaN(xF)) ? 1 : -1; } // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' if (typeof xF !== typeof yF) { xF += ''; yF += ''; } if (xF < yF) { return -1; } if (xF > yF) { return 1; } } return 0; } function sortTextDesc(table, a, b, col) { if (a === b) { return 0; } var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? -1 : 1) : e || 1; } if (b === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? 1 : -1) : -e || -1; } if (typeof c.textSorter === 'function') { return c.textSorter(b, a); } return sortText(table, b, a); } // return text string value by adding up ascii value // so the text is somewhat sorted when using a digital sort // this is NOT an alphanumeric sort function getTextValue(a, mx, d) { if (mx) { // make sure the text value is greater than the max numerical value (mx) var i, l = a.length, n = mx + d; for (i = 0; i < l; i++) { n += a.charCodeAt(i); } return d * n; } return 0; } function sortNumeric(table, a, b, col, mx, d) { if (a === b) { return 0; } var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? -1 : 1) : -e || -1; } if (b === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? 1 : -1) : e || 1; } if (isNaN(a)) { a = getTextValue(a, mx, d); } if (isNaN(b)) { b = getTextValue(b, mx, d); } return a - b; } function sortNumericDesc(table, a, b, col, mx, d) { if (a === b) { return 0; } var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? -1 : 1) : e || 1; } if (b === '' && e !== 0) { return (typeof(e) === 'boolean') ? (e ? 1 : -1) : -e || -1; } if (isNaN(a)) { a = getTextValue(a, mx, d); } if (isNaN(b)) { b = getTextValue(b, mx, d); } return b - a; } /* public methods */ this.construct = function(settings) { return this.each(function() { // if no thead or tbody quit. if (!this.tHead || this.tBodies.length === 0) { return; } // declare var $headers, $cell, totalRows, $this, config, c, i, j, k, a, s, o, m = $.metadata; // new blank config object this.config = {}; // merge and extend. c = config = $.extend(true, this.config, $.tablesorter.defaults, settings); // store common expression for speed $this = $(this).addClass(c.tableClass); // save the settings where they read $.data(this, "tablesorter", c); // build up character equivalent cross-reference buildRegex(); // digit sort text location; keeping max+/- for backwards compatibility c.string = { 'max': 1, 'min': -1, 'max+': 1, 'max-': -1, 'zero': 0, 'none': 0, 'null': 0, 'top': true, 'bottom': false }; // build headers $headers = buildHeaders(this); // try to auto detect column type, and store in tables config c.parsers = buildParserCache(this, $headers); // build the cache for the tbody cells // delayInit will delay building the cache until the user starts a sort if (!c.delayInit) { buildCache(this); } // fixate columns if the users supplies the fixedWidth option fixColumnWidth(this); // apply event handling to headers // this is to big, perhaps break it out? $headers .click(function(e) { if (c.delayInit && !c.cache) { buildCache($this[0]); } if (!this.sortDisabled) { // Only call sortStart if sorting is enabled. $this.trigger("sortStart", $this[0]); // store exp, for speed $cell = $(this); k = !e[c.sortMultiSortKey]; // get current column sort order this.count = (this.count + 1) % (c.sortReset ? 3 : 2); // reset all sorts on non-current column - issue #30 if (c.sortRestart) { i = this; $headers.each(function() { // only reset counts on columns that weren't just clicked on and if not included in a multisort if (this !== i && (k || !$(this).is('.' + c.cssDesc + ',.' + c.cssAsc))) { this.count = -1; } }); } // get current column index i = this.column; // user only wants to sort on one column if (k) { // flush the sort list c.sortList = []; if (c.sortForce !== null) { a = c.sortForce; for (j = 0; j < a.length; j++) { if (a[j][0] !== i) { c.sortList.push(a[j]); } } } // add column to sort list o = this.order[this.count]; if (o < 2) { c.sortList.push([i, o]); // add other columns if header spans across multiple if (this.colSpan > 1) { for (j = 1; j < this.colSpan; j++) { c.sortList.push([i+j, o]); } } } // multi column sorting } else { // the user has clicked on an already sorted column. if (isValueInArray(i, c.sortList)) { // reverse the sorting direction for all tables. for (j = 0; j < c.sortList.length; j++) { s = c.sortList[j]; o = c.headerList[s[0]]; if (s[0] === i) { s[1] = o.order[o.count]; if (s[1] === 2) { c.sortList.splice(j,1); o.count = -1; } } } } else { // add column to sort list array o = this.order[this.count]; if (o < 2) { c.sortList.push([i, o]); // add other columns if header spans across multiple if (this.colSpan > 1) { for (j = 1; j < this.colSpan; j++) { c.sortList.push([i+j, o]); } } } } } if (c.sortAppend !== null) { a = c.sortAppend; for (j = 0; j < a.length; j++) { if (a[j][0] !== i) { c.sortList.push(a[j]); } } } // sortBegin event triggered immediately before the sort $this.trigger("sortBegin", $this[0]); // set css for headers setHeadersCss($this[0], $headers, c.sortList); appendToTable($this[0], multisort($this[0], c.sortList)); // stop normal event by returning false return false; } // cancel selection }) .mousedown(function() { if (c.cancelSelection) { this.onselectstart = function() { return false; }; return false; } }); // apply easy methods that trigger binded events $this .bind("update", function(e, resort) { // remove rows/elements before update $(c.selectorRemove, this).remove(); // rebuild parsers. c.parsers = buildParserCache(this, $headers); // rebuild the cache map buildCache(this); if (resort !== false) { $(this).trigger("sorton", [c.sortList]); } }) .bind("updateCell", function(e, cell, resort) { // get position from the dom. var t = this, pos = [(cell.parentNode.rowIndex - 1), cell.cellIndex], // update cache - format: function(s, table, cell, cellIndex) tbdy = $(this).find('tbody').index( $(cell).closest('tbody') ); t.config.cache[tbdy].normalized[pos[0]][pos[1]] = c.parsers[pos[1]].format( getElementText(t, cell, pos[1]), t, cell, pos[1] ); if (resort !== false) { $(this).trigger("sorton", [c.sortList]); } }) .bind("addRows", function(e, $row, resort) { var i, rows = $row.filter('tr').length, dat = [], l = $row[0].cells.length, t = this, tbdy = $(this).find('tbody').index( $row.closest('tbody') ); // add each row for (i = 0; i < rows; i++) { // add each cell for (j = 0; j < l; j++) { dat[j] = c.parsers[j].format( getElementText(t, $row[i].cells[j], j), t, $row[i].cells[j], j ); } // add the row index to the end dat.push(c.cache[tbdy].row.length); // update cache c.cache[tbdy].row.push([$row[i]]); c.cache[tbdy].normalized.push(dat); dat = []; } // resort using current settings if (resort !== false) { $(this).trigger("sorton", [c.sortList]); } }) .bind("sorton", function(e, list) { $(this).trigger("sortStart", this); // update and store the sortlist c.sortList = list; // update header count index updateHeaderSortCount(this, c.sortList); // set css for headers setHeadersCss(this, $headers, c.sortList); // sort the table and append it to the dom appendToTable(this, multisort(this, c.sortList)); }) .bind("appendCache", function() { appendToTable(this); }) .bind("applyWidgetId", function(e, id) { getWidgetById(id).format(this); }) .bind("applyWidgets", function() { // apply widgets applyWidget(this); }); // get sort list from jQuery data or metadata if ($this.data() && typeof $this.data().sortlist !== 'undefined') { c.sortList = $this.data().sortlist; } else if (m && ($this.metadata() && $this.metadata().sortlist)) { c.sortList = $this.metadata().sortlist; } // apply widget init code applyWidget(this, true); // if user has supplied a sort list to constructor. if (c.sortList.length > 0) { $this.trigger("sorton", [c.sortList]); } else { // apply widget format applyWidget(this); } // initialized this.hasInitialized = true; $this.trigger('tablesorter-initialized', this); if (typeof c.initialized === 'function') { c.initialized(this); } }); }; this.addParser = function(parser) { var i, l = parsers.length, a = true; for (i = 0; i < l; i++) { if (parsers[i].id.toLowerCase() === parser.id.toLowerCase()) { a = false; } } if (a) { parsers.push(parser); } }; this.addWidget = function(widget) { widgets.push(widget); }; this.formatFloat = function(s, table) { if (typeof(s) !== 'string' || s === '') { return s; } if (table.config.usNumberFormat !== false) { // US Format - 1,234,567.89 -> 1234567.89 s = s.replace(/,/g,''); } else { // German Format = 1.234.567,89 -> 1234567.89 // French Format = 1 234 567,89 -> 1234567.89 s = s.replace(/[\s|\.]/g,'').replace(/,/g,'.'); } if(/^\s*\([.\d]+\)/.test(s)) { s = s.replace(/^\s*\(/,'-').replace(/\)/,''); } var i = parseFloat(s); // return the text instead of zero return isNaN(i) ? $.trim(s) : i; }; this.isDigit = function(s) { // replace all unwanted chars and match. return (/^[\-+(]?\d*[)]?$/).test($.trim(s.replace(/[,.'\s]/g, ''))); }; // regex used in natural sort this.regex = [ /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi, // chunk/tokenize numbers & letters /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, //date /^0x[0-9a-f]+$/i, // hex /^0/ // leading zeros ]; // used when replacing accented characters during sorting this.characterEquivalents = { "a" : "\u00e1\u00e0\u00e2\u00e3\u00e4", // áàâãä "A" : "\u00c1\u00c0\u00c2\u00c3\u00c4", // ÁÀÂÃÄ "c" : "\u00e7", // ç "C" : "\u00c7", // Ç "e" : "\u00e9\u00e8\u00ea\u00eb", // éèêë "E" : "\u00c9\u00c8\u00ca\u00cb", // ÉÈÊË "i" : "\u00ed\u00ec\u0130\u00ee\u00ef", // íìİîï "I" : "\u00cd\u00cc\u0130\u00ce\u00cf", // ÍÌİÎÏ "o" : "\u00f3\u00f2\u00f4\u00f5\u00f6", // óòôõö "O" : "\u00d3\u00d2\u00d4\u00d5\u00d6", // ÓÒÔÕÖ "S" : "\u00df", // ß "u" : "\u00fa\u00f9\u00fb\u00fc", // úùûü "U" : "\u00da\u00d9\u00db\u00dc" // ÚÙÛÜ }; this.replaceAccents = function(s) { if (this.characterRegex.test(s)) { var a, eq = this.characterEquivalents; for (a in eq) { if (typeof a === 'string') { s = s.replace( this.characterRegexArray[a], a ); } } } return s; }; // get sorter, string, empty, etc options for each column from // metadata, header option or header class name ("sorter-false") // priority = jQuery data > meta > headers option > header class name this.getData = function(h, ch, key) { var val = '', m = $.metadata ? h.metadata() : false, cl = h.attr('class') || ''; if (h.data() && typeof h.data(key) !== 'undefined'){ val += h.data(key); } else if (m && typeof m[key] !== 'undefined') { val += m[key]; } else if (ch && typeof ch[key] !== 'undefined') { val += ch[key]; } else if (cl && cl.match(key + '-')) { // include sorter class name "sorter-text", etc val = cl.match( new RegExp(key + '-(\\w+)') )[1] || ''; } return $.trim(val); }; this.clearTableBody = function(table) { $(table.tBodies).filter(':not(.' + table.config.cssInfoBlock + ')').empty(); }; } })(); // make shortcut var ts = $.tablesorter; // extend plugin scope $.fn.extend({ tablesorter: ts.construct }); // add default parsers ts.addParser({ id: "text", is: function(s, table, node) { return true; }, format: function(s, table, cell, cellIndex) { var c = table.config; s = $.trim( c.ignoreCase ? s.toLocaleLowerCase() : s ); return c.sortLocaleCompare ? ts.replaceAccents(s) : s; }, type: "text" }); ts.addParser({ id: "currency", is: function(s) { return (/^\(?[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]/).test(s); // #$ $%"?. }, format: function(s, table) { return ts.formatFloat(s.replace(/[^\w,. \-()]/g, ""), table); }, type: "numeric" }); ts.addParser({ id: "ipAddress", is: function(s) { return (/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/).test(s); }, format: function(s, table) { var i, item, a = s.split("."), r = "", l = a.length; for (i = 0; i < l; i++) { item = a[i]; if (item.length === 2) { r += "0" + item; } else { r += item; } } return ts.formatFloat(r, table); }, type: "numeric" }); ts.addParser({ id: "url", is: function(s) { return (/^(https?|ftp|file):\/\/$/).test(s); }, format: function(s) { return $.trim(s.replace(/(https?|ftp|file):\/\//, '')); }, type: "text" }); ts.addParser({ id: "isoDate", is: function(s) { return (/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/).test(s); }, format: function(s, table) { return ts.formatFloat((s !== "") ? (new Date(s.replace(/-/g, "/")).getTime() || "") : "", table); }, type: "numeric" }); ts.addParser({ id: "percent", is: function(s) { return (/\%\)?$/).test($.trim(s)); }, format: function(s, table) { return ts.formatFloat(s.replace(/%/g, ""), table); }, type: "numeric" }); ts.addParser({ id: "usLongDate", is: function(s) { return s.match(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/); }, format: function(s, table) { return ts.formatFloat( (new Date(s).getTime() || ''), table); }, type: "numeric" }); ts.addParser({ id: "shortDate", // "mmddyyyy", "ddmmyyyy" or "yyyymmdd" is: function(s) { // testing for ####-####-#### - so it's not perfect return (/\d{1,4}[\/\-\,\.\s+]\d{1,4}[\/\-\.\,\s+]\d{1,4}/).test(s); }, format: function(s, table, cell, cellIndex) { var c = table.config, format = ts.getData($(cell), c.headers[cellIndex], 'dateFormat') || c.dateFormat; s = s.replace(/\s+/g," ").replace(/[\-|\.|\,]/g, "/"); if (format === "mmddyyyy") { s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$1/$2"); } else if (format === "ddmmyyyy") { s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$2/$1"); } else if (format === "yyyymmdd") { s = s.replace(/(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/, "$1/$2/$3"); } return ts.formatFloat( (new Date(s).getTime() || ''), table); }, type: "numeric" }); ts.addParser({ id: "time", is: function(s) { return (/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/).test(s); }, format: function(s, table) { return ts.formatFloat( (new Date("2000/01/01 " + s).getTime() || ''), table); }, type: "numeric" }); ts.addParser({ id: "digit", is: function(s) { return ts.isDigit(s); }, format: function(s, table) { return ts.formatFloat(s.replace(/[^\w,. \-()]/g, ""), table); }, type: "numeric" }); ts.addParser({ id: "metadata", is: function(s) { return false; }, format: function(s, table, cell) { var c = table.config, p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName; return $(cell).metadata()[p]; }, type: "numeric" }); // add default widgets ts.addWidget({ id: "zebra", format: function(table) { var $tr, $r, row, even, time, k, c = table.config, child = c.cssChildRow, b = $(table).children('tbody:not(' + c.cssInfoBlock + ')'), css = [ "even", "odd" ]; // maintain backwards compatibility css = c.widgetZebra && c.hasOwnProperty('css') ? c.widgetZebra.css : (c.widgetOptions && c.widgetOptions.hasOwnProperty('zebra')) ? c.widgetOptions.zebra : css; if (c.debug) { time = new Date(); } for (k = 0; k < b.length; k++ ) { row = 0; // loop through the visible rows $tr = $(b[k]).children('tr:visible'); if ($tr.length > 1) { $tr.each(function() { $r = $(this); // style children rows the same way the parent row was styled if (!$r.hasClass(child)) { row++; } even = (row % 2 === 0); $r .removeClass(css[even ? 1 : 0]) .addClass(css[even ? 0 : 1]); }); } } if (c.debug) { ts.benchmark("Applying Zebra widget", time); } } }); })(jQuery);
2947721120/cdnjs
ajax/libs/jquery.tablesorter/2.3.1/js/jquery.tablesorter.js
JavaScript
mit
36,308
var inst = require("../index").getInstance(); inst.applyConfig({ debug: true, filter: "debug" }); module.exports = inst.use("arraylist-filter");
berkmancenter/spectacle
web/js/app/editor/node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/arraylist-filter/debug.js
JavaScript
gpl-2.0
145
var baseUniq = require('./_baseUniq'); /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } module.exports = uniqWith;
grshane/monthofmud
web/themes/custom/mom/node_modules/table/node_modules/lodash/uniqWith.js
JavaScript
mit
893
(function(){ "use strict"; try { new Image(); } catch(e){ window.Image = function(){ return document.createElement('img'); }; } setTimeout(function(){ var sel = 'picture, img[srcset]'; webshims.addReady(function(context, insertedElement){ if(context == document || !window.picturefill){return;} if(context.querySelector(sel) || insertedElement.filter(sel).length){ window.picturefill(); } }); }); })(); /*! Picturefill - v2.0.0-beta - 2014-05-02 * http://scottjehl.github.io/picturefill * Copyright (c) 2014 https://github.com/scottjehl/picturefill/blob/master/Authors.txt; Licensed MIT */ /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license */ window.matchMedia || (window.matchMedia = function() { "use strict"; // For browsers that support matchMedium api such as IE 9 and webkit var styleMedia = (window.styleMedia || window.media); // For those that don't support matchMedium if (!styleMedia) { var style = document.createElement('style'), script = document.getElementsByTagName('script')[0], info = null; style.type = 'text/css'; style.id = 'matchmediajs-test'; script.parentNode.insertBefore(style, script); // 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle; styleMedia = { matchMedium: function(media) { var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }'; // 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers if (style.styleSheet) { style.styleSheet.cssText = text; } else { style.textContent = text; } // Test if media query is true or false return info.width === '1px'; } }; } return function(media) { return { matches: styleMedia.matchMedium(media || 'all'), media: media || 'all' }; }; }()); /*! Picturefill - Responsive Images that work today. * Author: Scott Jehl, Filament Group, 2012 ( new proposal implemented by Shawn Jansepar ) * License: MIT/GPLv2 * Spec: http://picture.responsiveimages.org/ */ (function( w, doc ) { // Enable strict mode "use strict"; // If picture is supported, well, that's awesome. Let's get outta here... if( w.HTMLPictureElement ){ return; } // HTML shim|v it for old IE (IE9 will still need the HTML video tag workaround) doc.createElement( "picture" ); // local object for method references and testing exposure var pf = {}; // namespace pf.ns = "picturefill"; // srcset support test pf.srcsetSupported = new w.Image().srcset !== undefined; // just a string trim workaround pf.trim = function( str ){ return str.trim ? str.trim() : str.replace( /^\s+|\s+$/g, "" ); }; // just a string endsWith workaround pf.endsWith = function( str, suffix ){ return str.endsWith ? str.endsWith( suffix ) : str.indexOf( suffix, str.length - suffix.length ) !== -1; }; /** * Shortcut method for matchMedia ( for easy overriding in tests ) */ pf.matchesMedia = function( media ) { return w.matchMedia && w.matchMedia( media ).matches; }; /** * Shortcut method for `devicePixelRatio` ( for easy overriding in tests ) */ pf.getDpr = function() { return ( w.devicePixelRatio || 1 ); }; /** * Get width in css pixel value from a "length" value * http://dev.w3.org/csswg/css-values-3/#length-value */ pf.getWidthFromLength = function( length ) { // If no length was specified, or it is 0, default to `100vw` (per the spec). length = length && parseFloat( length ) > 0 ? length : "100vw"; /** * If length is specified in `vw` units, use `%` instead since the div we’re measuring * is injected at the top of the document. * * TODO: maybe we should put this behind a feature test for `vw`? */ length = length.replace( "vw", "%" ); // Create a cached element for getting length value widths if( !pf.lengthEl ){ pf.lengthEl = doc.createElement( "div" ); doc.documentElement.insertBefore( pf.lengthEl, doc.documentElement.firstChild ); } // Positioning styles help prevent padding/margin/width on `html` from throwing calculations off. pf.lengthEl.style.cssText = "position: absolute; left: 0; width: " + length + ";"; // Using offsetWidth to get width from CSS return pf.lengthEl.offsetWidth; }; // container of supported mime types that one might need to qualify before using pf.types = {}; // test svg support pf.types[ "image/svg+xml" ] = doc.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1'); // test webp support, only when the markup calls for it pf.types[ "image/webp" ] = function(){ // based on Modernizr's lossless img-webp test // note: asynchronous var img = new w.Image(), type = "image/webp"; img.onerror = function(){ pf.types[ type ] = false; picturefill(); }; img.onload = function(){ pf.types[ type ] = img.width === 1; picturefill(); }; img.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA='; }; /** * Takes a source element and checks if its type attribute is present and if so, supported * Note: for type tests that require a async logic, * you can define them as a function that'll run only if that type needs to be tested. Just make the test function call picturefill again when it is complete. * see the async webp test above for example */ pf.verifyTypeSupport = function( source ){ var type = source.getAttribute( "type" ); // if type attribute exists, return test result, otherwise return true if( type === null || type === "" ){ return true; } else { // if the type test is a function, run it and return "pending" status. The function will rerun picturefill on pending elements once finished. if( typeof( pf.types[ type ] ) === "function" ){ pf.types[ type ](); return "pending"; } else { return pf.types[ type ]; } } }; /** * Parses an individual `size` and returns the length, and optional media query */ pf.parseSize = function( sourceSizeStr ) { var match = /(\([^)]+\))?\s*(.+)/g.exec( sourceSizeStr ); return { media: match && match[1], length: match && match[2] }; }; /** * Takes a string of sizes and returns the width in pixels as a number */ pf.findWidthFromSourceSize = function( sourceSizeListStr ) { // Split up source size list, ie ( max-width: 30em ) 100%, ( max-width: 50em ) 50%, 33% // or (min-width:30em) calc(30% - 15px) var sourceSizeList = pf.trim( sourceSizeListStr ).split( /\s*,\s*/ ), winningLength; for ( var i=0, len=sourceSizeList.length; i < len; i++ ) { // Match <media-condition>? length, ie ( min-width: 50em ) 100% var sourceSize = sourceSizeList[ i ], // Split "( min-width: 50em ) 100%" into separate strings parsedSize = pf.parseSize( sourceSize ), length = parsedSize.length, media = parsedSize.media; if ( !length ) { continue; } if ( !media || pf.matchesMedia( media ) ) { // if there is no media query or it matches, choose this as our winning length // and end algorithm winningLength = length; break; } } // pass the length to a method that can properly determine length // in pixels based on these formats: http://dev.w3.org/csswg/css-values-3/#length-value return pf.getWidthFromLength( winningLength ); }; /** * Takes a srcset in the form of url/ * ex. "images/pic-medium.png 1x, images/pic-medium-2x.png 2x" or * "images/pic-medium.png 400w, images/pic-medium-2x.png 800w" or * "images/pic-small.png" * Get an array of image candidates in the form of * {url: "/foo/bar.png", resolution: 1} * where resolution is http://dev.w3.org/csswg/css-values-3/#resolution-value * If sizes is specified, resolution is calculated */ pf.getCandidatesFromSourceSet = function( srcset, sizes ) { var candidates = pf.trim( srcset ).split( /,\s+/ ), widthInCssPixels = sizes ? pf.findWidthFromSourceSize( sizes ) : "100%", formattedCandidates = []; for ( var i = 0, len = candidates.length; i < len; i++ ) { var candidate = candidates[ i ], candidateArr = candidate.split( /\s+/ ), sizeDescriptor = candidateArr[ 1 ], resolution; if ( sizeDescriptor && ( sizeDescriptor.slice( -1 ) === "w" || sizeDescriptor.slice( -1 ) === "x" ) ) { sizeDescriptor = sizeDescriptor.slice( 0, -1 ); } if ( sizes ) { // get the dpr by taking the length / width in css pixels resolution = parseFloat( ( parseInt( sizeDescriptor, 10 ) / widthInCssPixels ) ); } else { // get the dpr by grabbing the value of Nx resolution = sizeDescriptor ? parseFloat( sizeDescriptor, 10 ) : 1; } var formattedCandidate = { url: candidateArr[ 0 ], resolution: resolution }; formattedCandidates.push( formattedCandidate ); } return formattedCandidates; }; /* * if it's an img element and it has a srcset property, * we need to remove the attribute so we can manipulate src * (the property's existence infers native srcset support, and a srcset-supporting browser will prioritize srcset's value over our winning picture candidate) * this moves srcset's value to memory for later use and removes the attr */ pf.dodgeSrcset = function( img ){ if( img.srcset ){ img[ pf.ns ].srcset = img.srcset; img.removeAttribute( "srcset" ); } }; /* * Accept a source or img element and process its srcset and sizes attrs */ pf.processSourceSet = function( el ) { var srcset = el.getAttribute( "srcset" ), sizes = el.getAttribute( "sizes" ), candidates = []; // if it's an img element, use the cached srcset property (defined or not) if( el.nodeName.toUpperCase() === "IMG" && el[ pf.ns ] && el[ pf.ns ].srcset ){ srcset = el[ pf.ns ].srcset; } if( srcset ) { candidates = pf.getCandidatesFromSourceSet( srcset, sizes ); } return candidates; }; pf.applyBestCandidate = function( candidates, picImg ) { var candidate, length, bestCandidate; candidates.sort( pf.ascendingSort ); length = candidates.length; bestCandidate = candidates[ length - 1 ]; for ( var l=0; l < length; l++ ) { candidate = candidates[ l ]; if ( candidate.resolution >= pf.getDpr() ) { bestCandidate = candidate; break; } } if ( !pf.endsWith( picImg.src, bestCandidate.url ) ) { picImg.src = bestCandidate.url; // currentSrc attribute and property to match // http://picture.responsiveimages.org/#the-img-element picImg.currentSrc = picImg.src; } }; pf.ascendingSort = function( a, b ) { return a.resolution - b.resolution; }; /* * In IE9, <source> elements get removed if they aren"t children of * video elements. Thus, we conditionally wrap source elements * using <!--[if IE 9]><video style="display: none;"><![endif]--> * and must account for that here by moving those source elements * back into the picture element. */ pf.removeVideoShim = function( picture ){ var videos = picture.getElementsByTagName( "video" ); if ( videos.length ) { var video = videos[ 0 ], vsources = video.getElementsByTagName( "source" ); while ( vsources.length ) { picture.insertBefore( vsources[ 0 ], video ); } // Remove the video element once we're finished removing its children video.parentNode.removeChild( video ); } }; /* * Find all picture elements and, * in browsers that don't natively support srcset, find all img elements * with srcset attrs that don't have picture parents */ pf.getAllElements = function() { var pictures = doc.getElementsByTagName( "picture" ), elems = [], imgs = doc.getElementsByTagName( "img" ); for ( var h = 0, len = pictures.length + imgs.length; h < len; h++ ) { if ( h < pictures.length ){ elems[ h ] = pictures[ h ]; } else { var currImg = imgs[ h - pictures.length ]; if ( currImg.parentNode.nodeName.toUpperCase() !== "PICTURE" && ( ( pf.srcsetSupported && currImg.getAttribute( "sizes" ) ) || currImg.getAttribute( "srcset" ) !== null ) ) { elems.push( currImg ); } } } return elems; }; pf.getMatch = function( picture ) { var sources = picture.childNodes, match; // Go through each child, and if they have media queries, evaluate them for ( var j=0, slen = sources.length; j < slen; j++ ) { var source = sources[ j ]; // ignore non-element nodes if( source.nodeType !== 1 ){ continue; } // Hitting an `img` element stops the search for `sources`. // If no previous `source` matches, the `img` itself is evaluated later. if( source.nodeName.toUpperCase() === "IMG" ) { return match; } // ignore non-`source` nodes if( source.nodeName.toUpperCase() !== "SOURCE" ){ continue; } var media = source.getAttribute( "media" ); // if source does not have a srcset attribute, skip if ( !source.getAttribute( "srcset" ) ) { continue; } // if there"s no media specified, OR w.matchMedia is supported if( ( !media || pf.matchesMedia( media ) ) ){ var typeSupported = pf.verifyTypeSupport( source ); if( typeSupported === true ){ match = source; break; } else if( typeSupported === "pending" ){ return false; } } } return match; }; function picturefill( options ) { var elements, element, elemType, firstMatch, candidates, picImg; options = options || {}; elements = options.elements || pf.getAllElements(); // Loop through all elements for ( var i=0, plen = elements.length; i < plen; i++ ) { element = elements[ i ]; elemType = element.nodeName.toUpperCase(); firstMatch = undefined; candidates = undefined; picImg = undefined; // expando for caching data on the img if( !element[ pf.ns ] ){ element[ pf.ns ] = {}; } // if the element has already been evaluated, skip it // unless `options.force` is set to true ( this, for example, // is set to true when running `picturefill` on `resize` ). if ( !options.reevaluate && element[ pf.ns ].evaluated ) { continue; } // if element is a picture element if( elemType === "PICTURE" ){ // IE9 video workaround pf.removeVideoShim( element ); // return the first match which might undefined // returns false if there is a pending source // TODO the return type here is brutal, cleanup firstMatch = pf.getMatch( element ); // if any sources are pending in this picture due to async type test(s) // remove the evaluated attr and skip for now ( the pending test will // rerun picturefill on this element when complete) if( firstMatch === false ) { continue; } // Find any existing img element in the picture element picImg = element.getElementsByTagName( "img" )[ 0 ]; } else { // if it's an img element firstMatch = undefined; picImg = element; } if( picImg ) { // expando for caching data on the img if( !picImg[ pf.ns ] ){ picImg[ pf.ns ] = {}; } // Cache and remove `srcset` if present and we’re going to be doing `sizes`/`picture` polyfilling to it. if( picImg.srcset && ( elemType === "PICTURE" || picImg.getAttribute( "sizes" ) ) ){ pf.dodgeSrcset( picImg ); } if ( firstMatch ) { candidates = pf.processSourceSet( firstMatch ); pf.applyBestCandidate( candidates, picImg ); } else { // No sources matched, so we’re down to processing the inner `img` as a source. candidates = pf.processSourceSet( picImg ); if( picImg.srcset === undefined || picImg.getAttribute( "sizes" ) ) { // Either `srcset` is completely unsupported, or we need to polyfill `sizes` functionality. pf.applyBestCandidate( candidates, picImg ); } // Else, resolution-only `srcset` is supported natively. } // set evaluated to true to avoid unnecessary reparsing element[ pf.ns ].evaluated = true; } } } /** * Sets up picture polyfill by polling the document and running * the polyfill every 250ms until the document is ready. * Also attaches picturefill on resize */ function runPicturefill() { picturefill(); var intervalId = setInterval( function(){ // When the document has finished loading, stop checking for new images // https://github.com/ded/domready/blob/master/ready.js#L15 w.picturefill(); if ( /^loaded|^i|^c/.test( doc.readyState ) ) { clearInterval( intervalId ); return; } }, 250 ); if( w.addEventListener ){ var resizeThrottle; w.addEventListener( "resize", function() { w.clearTimeout( resizeThrottle ); resizeThrottle = w.setTimeout( function(){ picturefill({ reevaluate: true }); }, 60 ); }, false ); } } runPicturefill(); /* expose methods for testing */ picturefill._ = pf; /* expose picturefill */ if ( typeof module === "object" && typeof module.exports === "object" ){ // CommonJS, just export module.exports = picturefill; } else if( typeof define === "object" && define.amd ){ // AMD support define( function(){ return picturefill; } ); } else if( typeof w === "object" ){ // If no AMD and we are in the browser, attach to window w.picturefill = picturefill; } } )( this, this.document );
x112358/cdnjs
ajax/libs/webshim/1.13.0/dev/shims/picture.js
JavaScript
mit
17,443
// Generated by CoffeeScript 1.4.0 var Adapter, __hasProp = {}.hasOwnProperty, __slice = [].slice; Adapter = (function() { var dataValues, lastDataId; function Adapter() {} Adapter.prototype.name = "native"; Adapter.prototype.domReady = function(callback) { var add, doc, done, init, poll, pre, rem, root, top, win, _ref; done = false; top = true; win = window; doc = document; if ((_ref = doc.readyState) === "complete" || _ref === "loaded") { return callback(); } root = doc.documentElement; add = (doc.addEventListener ? "addEventListener" : "attachEvent"); rem = (doc.addEventListener ? "removeEventListener" : "detachEvent"); pre = (doc.addEventListener ? "" : "on"); init = function(e) { if (e.type === "readystatechange" && doc.readyState !== "complete") { return; } (e.type === "load" ? win : doc)[rem](pre + e.type, init, false); if (!done) { done = true; return callback(); } }; poll = function() { try { root.doScroll("left"); } catch (e) { setTimeout(poll, 50); return; } return init("poll"); }; if (doc.readyState !== "complete") { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch (_error) {} if (top) { poll(); } } doc[add](pre + "DOMContentLoaded", init, false); doc[add](pre + "readystatechange", init, false); return win[add](pre + "load", init, false); } }; Adapter.prototype.create = function(htmlString) { var div; div = document.createElement("div"); div.innerHTML = htmlString; return this.wrap(div.childNodes); }; Adapter.prototype.wrap = function(element) { var el; if (!element) { element = []; } else if (element instanceof NodeList) { element = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = element.length; _i < _len; _i++) { el = element[_i]; _results.push(el); } return _results; })(); } else if (!(element instanceof Array)) { element = [element]; } return element; }; Adapter.prototype.unwrap = function(element) { return this.wrap(element)[0]; }; Adapter.prototype.tagName = function(element) { return this.unwrap(element).tagName; }; Adapter.prototype.attr = function(element, attr, value) { if (arguments.length === 3) { return this.unwrap(element).setAttribute(attr, value); } else { return this.unwrap(element).getAttribute(attr); } }; lastDataId = 0; dataValues = {}; Adapter.prototype.data = function(element, name, value) { var dataId; dataId = this.attr(element, "data-id"); if (!dataId) { dataId = ++lastDataId; this.attr(element, "data-id", dataId); dataValues[dataId] = {}; } if (arguments.length === 3) { return dataValues[dataId][name] = value; } else { value = dataValues[dataId][name]; if (value != null) { return value; } value = this.attr(element, "data-" + (Opentip.prototype.dasherize(name))); if (value) { dataValues[dataId][name] = value; } return value; } }; Adapter.prototype.find = function(element, selector) { return this.unwrap(element).querySelector(selector); }; Adapter.prototype.findAll = function(element, selector) { return this.unwrap(element).querySelectorAll(selector); }; Adapter.prototype.update = function(element, content, escape) { element = this.unwrap(element); if (escape) { element.innerHTML = ""; return element.appendChild(document.createTextNode(content)); } else { return element.innerHTML = content; } }; Adapter.prototype.append = function(element, child) { var unwrappedChild, unwrappedElement; unwrappedChild = this.unwrap(child); unwrappedElement = this.unwrap(element); return unwrappedElement.appendChild(unwrappedChild); }; Adapter.prototype.addClass = function(element, className) { return this.unwrap(element).classList.add(className); }; Adapter.prototype.removeClass = function(element, className) { return this.unwrap(element).classList.remove(className); }; Adapter.prototype.css = function(element, properties) { var key, value, _results; element = this.unwrap(this.wrap(element)); _results = []; for (key in properties) { if (!__hasProp.call(properties, key)) continue; value = properties[key]; _results.push(element.style[key] = value); } return _results; }; Adapter.prototype.dimensions = function(element) { var dimensions, revert; element = this.unwrap(this.wrap(element)); dimensions = { width: element.offsetWidth, height: element.offsetHeight }; if (!(dimensions.width && dimensions.height)) { revert = { position: element.style.position || '', visibility: element.style.visibility || '', display: element.style.display || '' }; this.css(element, { position: "absolute", visibility: "hidden", display: "block" }); dimensions = { width: element.offsetWidth, height: element.offsetHeight }; this.css(element, revert); } return dimensions; }; Adapter.prototype.scrollOffset = function() { return [window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop]; }; Adapter.prototype.viewportDimensions = function() { return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }; }; Adapter.prototype.mousePosition = function(e) { var pos; pos = { x: 0, y: 0 }; if (e == null) { e = window.event; } if (e == null) { return; } try { if (e.pageX || e.pageY) { pos.x = e.pageX; pos.y = e.pageY; } else if (e.clientX || e.clientY) { pos.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; pos.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } } catch (e) { } return pos; }; Adapter.prototype.offset = function(element) { var offset; element = this.unwrap(element); offset = { top: element.offsetTop, left: element.offsetLeft }; while (element = element.offsetParent) { offset.top += element.offsetTop; offset.left += element.offsetLeft; if (element !== document.body) { offset.top -= element.scrollTop; offset.left -= element.scrollLeft; } } return offset; }; Adapter.prototype.observe = function(element, eventName, observer) { return this.unwrap(element).addEventListener(eventName, observer, false); }; Adapter.prototype.stopObserving = function(element, eventName, observer) { return this.unwrap(element).removeEventListener(eventName, observer, false); }; Adapter.prototype.ajax = function(options) { var request, _ref, _ref1; if (options.url == null) { throw new Error("No url provided"); } if (window.XMLHttpRequest) { request = new XMLHttpRequest; } else if (window.ActiveXObject) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } if (!request) { throw new Error("Can't create XMLHttpRequest"); } request.onreadystatechange = function() { if (request.readyState === 4) { try { if (request.status === 200) { if (typeof options.onSuccess === "function") { options.onSuccess(request.responseText); } } else { if (typeof options.onError === "function") { options.onError("Server responded with status " + request.status); } } } catch (e) { if (typeof options.onError === "function") { options.onError(e.message); } } return typeof options.onComplete === "function" ? options.onComplete() : void 0; } }; request.open((_ref = (_ref1 = options.method) != null ? _ref1.toUpperCase() : void 0) != null ? _ref : "GET", options.url); return request.send(); }; Adapter.prototype.clone = function(object) { var key, newObject, val; newObject = {}; for (key in object) { if (!__hasProp.call(object, key)) continue; val = object[key]; newObject[key] = val; } return newObject; }; Adapter.prototype.extend = function() { var key, source, sources, target, val, _i, _len; target = arguments[0], sources = 2 <= arguments.length ? __slice.call(arguments, 1) : []; for (_i = 0, _len = sources.length; _i < _len; _i++) { source = sources[_i]; for (key in source) { if (!__hasProp.call(source, key)) continue; val = source[key]; target[key] = val; } } return target; }; return Adapter; })(); Opentip.addAdapter(new Adapter);
maruilian11/cdnjs
ajax/libs/opentip/2.3.0/lib/adapter.native.js
JavaScript
mit
9,433
/* * /MathJax/localization/cs/HelpDialog.js * * Copyright (c) 2009-2013 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.Localization.addTranslation("cs","HelpDialog",{version:"2.3",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/cs/HelpDialog.js");
IoTPPT/IoTPPT.github.io
密码学_files/mathjax-local/localization/cs/HelpDialog.js
JavaScript
mit
838
/* YUI 3.17.1 (build 0eb5a52) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("template-base",function(e,t){function n(t,n){this.defaults=n,this.engine=t||e.Template.Micro,this.engine||e.error("No template engine loaded.")}n._registry={},n.register=function(e,t){return n._registry[e]=t,t},n.get=function(e){return n._registry[e]},n.render=function(t,r,i){var s=n._registry[t],o="";return s?o=s(r,i):e.error('Unregistered template: "'+t+'"'),o},n.prototype={compile:function(t,n){return n=n?e.merge(this.defaults,n):this.defaults,this.engine.compile(t,n)},precompile:function(t,n){return n=n?e.merge(this.defaults,n):this.defaults,this.engine.precompile(t,n)},render:function(t,n,r){return r=r?e.merge(this.defaults,r):this.defaults,this.engine.render?this.engine.render(t,n,r):this.engine.compile(t,r)(n,r)},revive:function(t,n){return n=n?e.merge(this.defaults,n):this.defaults,this.engine.revive?this.engine.revive(t,n):t}},e.Template=e.Template?e.mix(n,e.Template):n},"3.17.1",{requires:["yui-base"]});
schoren/cdnjs
ajax/libs/yui/3.17.1/template-base/template-base-min.js
JavaScript
mit
1,082
/* eslint-disable no-use-before-define, max-lines, no-useless-concat, prefer-template */ const noStyleFn = (styles, value) => value; function tryStringify(arg) { try { return JSON.stringify(arg).replace(/\\n/g, '\n'); } catch (_) { return '[Circular]'; } } const sameRawFormattedValue = value => ({ stringValue: value, formattedValue: value }); function internalFormatValue(value, styleFn, styles, { padding, depth, maxDepth, objects }) { const typeofValue = typeof value; if (!styles) { if (value == null) { styles = ['cyan']; } else { switch (typeofValue) { case 'boolean': styles = ['green']; break; case 'number': styles = ['yellow']; break; case 'string': styles = ['orange']; break; case 'date': styles = ['magenta']; break; } } } let stringValue; if (value === null) { stringValue = 'null'; } else if (value === undefined) { stringValue = 'undefined'; } else if (typeofValue === 'boolean') { stringValue = value.toString(); } else if (value.constructor === Object) { if (depth >= maxDepth) { stringValue = '{Object...}'; } else { return internalFormatObject( value, styleFn, undefined, { padding, depth: depth + 1, maxDepth, objects }, ); } } else if (Array.isArray(value)) { if (depth >= maxDepth) { stringValue = '[Array...]'; } else { return internalFormatArray(value, styleFn, { padding, depth: depth + 1, maxDepth, objects }); } } else if (value instanceof Error) { const stack = value.stack; stringValue = stack.startsWith(value.message) ? stack : `${value.message}\n${stack}`; } else if (value instanceof Map || value instanceof WeakMap) { const name = value.constructor.name; if (depth >= maxDepth) { stringValue = `{${name}...}`; } else { return internalFormatMap( name, value, styleFn, { padding, depth: depth + 1, maxDepth, objects }, ); } } else if (value instanceof Set || value instanceof WeakSet) { const name = value.constructor.name; if (depth >= maxDepth) { stringValue = `{${name}...}`; } else { return internalFormatSet( name, value, styleFn, { padding, depth: depth + 1, maxDepth, objects }, ); } } else { stringValue = tryStringify(value); } const formattedValue = styleFn(styles, stringValue); return { stringValue, formattedValue, }; } const separator = ','; const internalFormatKey = (key, styleFn) => { if (!key) return { stringKey: '', formattedKey: '' }; return { stringKey: `${key}: `, formattedKey: styleFn(['gray-light', 'bold'], `${key}:`) + ' ', }; }; const internalFormatMapKey = (key, styleFn, internalFormatParams) => { const { stringValue, formattedValue } = internalFormatValue(key, noStyleFn, undefined, internalFormatParams); return { stringKey: stringValue + ' => ', formattedKey: styleFn(['gray-light', 'bold'], `${formattedValue}:`) + ' ', }; }; const internalFormatIterator = ( values, styleFn, objectStyles, { padding, depth, maxDepth, objects }, { prefix, suffix, prefixSuffixSpace = ' ', formatKey = internalFormatKey }, ) => { let breakLine = false; const formattedSeparator = () => styleFn(['gray'], separator); const valuesMaxIndex = values.length - 1; values = values.map(({ key, value }, index) => { const nextDepth = depth + 1; const internalFormatParams = { padding, depth: nextDepth, maxDepth, objects }; // key must be formatted before value (browser-formatter needs order) const { stringKey, formattedKey } = formatKey(key, styleFn, internalFormatParams); let { stringValue, formattedValue } = internalFormatValue( value, styleFn, key && objectStyles && objectStyles[key], internalFormatParams, ); if (stringValue && (stringValue.length > 80 || stringValue.indexOf('\n') !== -1)) { breakLine = true; stringValue = stringValue.replace(/\n/g, `\n${padding}`); formattedValue = formattedValue.replace(/\n/g, `\n${padding}`); } return { stringValue: stringKey + stringValue + (index === valuesMaxIndex ? '' : separator), // eslint-disable-next-line no-useless-concat formattedValue: formattedKey + formattedValue + (index === valuesMaxIndex ? '' : formattedSeparator()), // note: we need to format the separator for each values for browser-formatter }; }); return { stringValue: prefix + values .map(breakLine ? v => `\n${padding}${v.stringValue}` : fv => fv.stringValue) .join(breakLine ? '\n' : ' ') + suffix, // eslint-disable-next-line prefer-template formattedValue: `${prefix}${breakLine ? '' : prefixSuffixSpace}` + values.map(breakLine ? v => `\n${padding}${v.formattedValue}` : v => v.formattedValue) .join(breakLine ? '' : ' ') + `${breakLine ? ',\n' : prefixSuffixSpace}${suffix}`, }; }; function internalFormatObject( object, styleFn, objectStyles, { padding, depth, maxDepth, objects }, ) { if (objects.has(object)) { return sameRawFormattedValue('{Circular Object}'); } const keys = Object.keys(object); if (keys.length === 0) { return sameRawFormattedValue('{}'); } objects.add(object); const result = internalFormatIterator( keys.map(key => ({ key, value: object[key] })), styleFn, objectStyles, { padding, depth, maxDepth, objects }, { prefix: '{', suffix: '}' }, ); objects.delete(object); return result; } function internalFormatMap( name, map, styleFn, { padding, depth, maxDepth, objects }, ) { if (objects.has(map)) { return sameRawFormattedValue(`{Circular ${name}`); } const keys = Array.from(map.keys()); if (keys.length === 0) { return sameRawFormattedValue(`${name} {}`); } objects.add(map); const result = internalFormatIterator( keys.map(key => ({ key, value: map.get(key) })), styleFn, undefined, { padding, depth, maxDepth, objects }, { prefix: `${name} {`, suffix: '}', formatKey: internalFormatMapKey }, ); objects.delete(map); return result; } function internalFormatArray(array, styleFn, { padding, depth, maxDepth, objects }) { if (objects.has(array)) { return sameRawFormattedValue('{Circular Array}'); } if (array.length === 0) { return sameRawFormattedValue('[]'); } objects.add(array); const result = internalFormatIterator( array.map(value => ({ key: undefined, value })), styleFn, undefined, { padding, depth, maxDepth, objects }, { prefix: '[', suffix: ']', prefixSuffixSpace: '' }, ); objects.delete(array); return result; } function internalFormatSet( name, set, styleFn, { padding, depth, maxDepth, objects }, ) { if (objects.has(set)) { return sameRawFormattedValue(`{Circular ${name}`); } const values = Array.from(set.values()); if (values.length === 0) { return sameRawFormattedValue(`${name} []`); } objects.add(set); const result = internalFormatIterator( values.map(value => ({ key: undefined, value })), styleFn, undefined, { padding, depth, maxDepth, objects }, { prefix: `${name} [`, suffix: ']' }, ); objects.delete(set); return result; } export default function formatObject(object, styleFn, objectStyles, { padding = ' ', maxDepth = 10, } = {}) { const { formattedValue: result } = internalFormatObject( object, styleFn, objectStyles, { padding, maxDepth, depth: 0, objects: new Set() }, ); if (result === '{}') { return ''; } return result; }
nightingalejs/nightingale-formatter
src/formatObject.js
JavaScript
isc
7,810
/* 315 RPL_ENDOFWHO "<name> :End of WHO list" - The RPL_WHOREPLY and RPL_ENDOFWHO pair are used to answer a WHO message. The RPL_WHOREPLY is only sent if there is an appropriate match to the WHO query. If there is a list of parameters supplied with a WHO message, a RPL_ENDOFWHO MUST be sent after processing each list item with <name> being the item. */
burninggarden/pirc
tests/RFC2812/5._Replies/5.1_Command_responses/RPL_ENDOFWHO.js
JavaScript
isc
457
2:1 warning type String found, string is standard 3:1 warning type Number found, number is standard 4:1 warning type Number found, number is standard 5:1 warning type Number found, number is standard 6:1 warning @memberof reference to notfound not found 9:1 warning could not determine @name for hierarchy 10:1 warning type String found, string is standard ⚠ 8 warnings
odub/documentation
test/fixture/lint/lint.output.js
JavaScript
isc
442
'use strict' const iq = require('../iq-caller') const {xml, plugin} = require('@xmpp/plugin') const NS_TIME = 'urn:xmpp:time' module.exports = plugin( 'time-caller', { get(...args) { return this.query(...args).then(res => { return { tzo: res.getChildText('tzo'), utc: res.getChildText('utc'), } }) }, query(...args) { return this.plugins['iq-caller'].get( xml('time', {xmlns: NS_TIME}), ...args ) }, }, [iq] )
ggozad/node-xmpp
packages/plugins/time/caller.js
JavaScript
isc
513
module.exports = { env: { mocha: true, node: true }, extends: 'standard' }
tu4mo/teg
.eslintrc.js
JavaScript
isc
89
var path = require('path') var assert = require('assert') var stat = require('./stat') var exists = require('./exists') var readFile = require('./readFile') var writeFile = require('./writeFile') var name = require('../path/name') var segments = require('../path/segments') var eachAsync = require('../async/iterate').map var randHex = require('../random/randHex') var rename = require('../text/placeholders') // THIS STILL NEEDS WORK!! // optional rename function or parent path segment instead of randHex. // better error handling and preserving timestamps // what if you are copying dir to dir??? didn't handle that case! function copy (files, dest, opts, cb) { var defaults = {flatten: false, noclobber: false} if (typeof opts === 'function') { cb = opts opts = defaults } else { opts = opts || defaults } files = Array.isArray(files) ? files : [files] eachAsync(files, function (file, key, done) { readFile(file, function (err, data) { assert.ifError(err) var method var filepath var destination if (opts.flatten) method = 'last' else method = 'fromFirst' filepath = segments[method](file) || file destination = path.resolve(dest, filepath) if (opts.noclobber && exists(destination)) { if (stat(destination).content === stat(file).content) { return done(null, file) } else { var fn = rename()(':dest/:file:vers:ext') destination = fn({ dest : name.dir(destination), file : name.file(destination), ext : name.ext(destination), vers : '-' + randHex(4) }) } } writeFile(destination, data, function (err) { assert.ifError(err) done(null, file) }) }) }, function (err, res) { assert.ifError(err) cb(res) }) } function copySync (files, dest) { files = Array.isArray(files) ? files : [files] files.forEach(function (file) { var destFile = path.resolve(dest, segments.fromFirst(file)) var content = readFile(file) writeFile(destFile, content) }) } module.exports = copy module.exports.sync = copySync
akileez/toolz
src/file/copy.js
JavaScript
isc
2,201
/* * Lynx Project * Started August 2013 * ------------------------------------------------------ * This file is covered under the LynxJS Game Library * License. Please read license.txt for more information * on usage of this library. * ------------------------------------------------------ * Component Name: KeyboardEvents * Author: Cosrnos * Description: Keyboard Event Tracker */ // Please note that this tracks events across the page, // not just across the canvas since Lynx supports multiple // canvas positions. (function buildComponent_KeyboardEvents() { var name = "KeyboardEvents"; var auth = "Cosrnos"; var desc = "Simple keyboard event tracker."; var build = function () { var keyboard = []; this.KeyState = { UP: 0, DOWN: 1, HELD: 2 }; this.Key = function (pKeyString) { return parseKeyString(pKeyString); }; var keyMap = { BACKSPACE: 0, TAB: 9, RETURN: 13, SHIFT: 16, CTRL: 17, ALT: 18, CAPSLOCK: 20, ESCAPE: 29, SPACE: 32, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 //More Keys soon? }; function parseKey(pKeyCode) { var ret = String.fromCharCode(pKeyCode); for (var key in keyMap) //Special Character { if (keyMap.hasOwnProperty(key)) { if (keyMap[key] == pKeyCode) { ret = key; } } } return ret; } function parseKeyString(pKeyString) { pKeyString = pKeyString.toUpperCase(); if (pKeyString.length == 1) { return (pKeyString.charCodeAt(0) - 32).toUpperCase(); } if (keyMap.hasOwnProperty(pKeyString)) { return keyMap[pKeyString].toUpperCase(); } return -1; } //Event Listeners window.addEventListener("keydown", (function (event) { event = event || window.event; var keyCode = event.keyCode; var keyName = parseKey(keyCode); if (!keyboard[keyCode]) { keyboard[keyCode] = this.KeyState.UP; } if (keyboard[keyCode] == this.KeyState.DOWN) { keyboard[keyCode] = this.KeyState.HELD; } if (keyboard[keyCode] == this.KeyState.UP) { keyboard[keyCode] = this.KeyState.DOWN; } if (keyboard[keyCode] == this.KeyState.DOWN) { Lynx.Emit("Keyboard.Press." + keyName, this); } if (keyboard[keyCode] == this.KeyState.HELD) { Lynx.Emit("Keyboard.Hold." + keyName); } //event.preventDefault(); }).bind(this), false); window.addEventListener("keyup", (function (event) { event = event || window.event; var keyCode = event.keyCode; var keyName = parseKey(keyCode); keyboard[keyCode] = this.KeyState.UP; Lynx.Emit("Keyboard.Release." + keyName); //event.preventDefault(); }).bind(this), false); }; new Lynx.Component(name, auth, desc, build); })();
Cosrnos/LynxJS
old/components/KeyboardEvents.js
JavaScript
isc
2,741
function xconcat () { var len = arguments.length var i = -1 var target = [] while (++i < len) { target[i] = arguments[i] } return target } module.exports = xconcat
akileez/toolz
src/array/xcat.js
JavaScript
isc
183
'use strict' const {encode, decode} = require('./lib/b64') const plugin = require('@xmpp/plugin') const xml = require('@xmpp/xml') const streamFeatures = require('../stream-features') const {XMPPError} = require('@xmpp/connection') const SASLFactory = require('saslmechanisms') const NS = 'urn:ietf:params:xml:ns:xmpp-sasl' class SASLError extends XMPPError { constructor(...args) { super(...args) this.name = 'SASLError' } } function match(features) { return features.getChild('mechanisms', NS) } function getMechanismNames(features) { return features.getChild('mechanisms', NS).children.map(el => el.text()) } module.exports = plugin( 'sasl', { start() { this.SASL = new SASLFactory() this.streamFeature = { name: 'sasl', priority: 1000, match, restart: true, run: (entity, features) => { return this.gotFeatures(features) }, } this.plugins['stream-features'].add(this.streamFeature) }, stop() { delete this.SASL this.plugins['stream-features'].remove(this.streamFeature) delete this.streamFeature delete this.mech }, use(...args) { this.SASL.use(...args) }, gotFeatures(features) { const offered = getMechanismNames(features) const usable = this.getUsableMechanisms(offered) // FIXME const available = this.getAvailableMechanisms() return Promise.resolve(this.getMechanism(usable)).then(mech => { this.mech = mech return this.handleMechanism(mech, features) }) }, handleMechanism(mech, features) { this.entity._status('authenticate') if (mech === 'ANONYMOUS') { return this.authenticate(mech, {}, features) } return this.entity.delegate( 'authenticate', (username, password) => { return this.authenticate(mech, {username, password}, features) }, mech ) }, getAvailableMechanisms() { return this.SASL._mechs.map(({name}) => name) }, getUsableMechanisms(mechs) { const supported = this.getAvailableMechanisms() return mechs.filter(mech => { return supported.indexOf(mech) > -1 }) }, getMechanism(usable) { return usable[0] // FIXME prefer SHA-1, ... maybe order usable, available, ... by preferred? }, findMechanism(name) { return this.SASL.create([name]) }, authenticate(mechname, credentials) { const mech = this.findMechanism(mechname) if (!mech) { return Promise.reject(new Error('no compatible mechanism')) } const {domain} = this.entity.options const creds = Object.assign( { username: null, password: null, server: domain, host: domain, realm: domain, serviceType: 'xmpp', serviceName: domain, }, credentials ) this.entity._status('authenticating') return new Promise((resolve, reject) => { const handler = element => { if (element.attrs.xmlns !== NS) { return } if (element.name === 'challenge') { mech.challenge(decode(element.text())) const resp = mech.response(creds) this.entity.send( xml( 'response', {xmlns: NS, mechanism: mech.name}, typeof resp === 'string' ? encode(resp) : '' ) ) return } if (element.name === 'failure') { reject( new SASLError( element.children[0].name, element.getChildText('text') || '', element ) ) } else if (element.name === 'success') { resolve() this.entity._status('authenticated') } this.entity.removeListener('nonza', handler) } this.entity.on('nonza', handler) if (mech.clientFirst) { this.entity.send( xml( 'auth', {xmlns: NS, mechanism: mech.name}, encode(mech.response(creds)) ) ) } }) }, }, [streamFeatures] )
ggozad/node-xmpp
packages/plugins/sasl/index.js
JavaScript
isc
4,307
'use strict'; let EventEmitter = require('events').EventEmitter; let AgentError = require('./error').AgentError; /** * Factory for container instances. Container is identified by an id, 3rd param contains options * container was created with. */ module.exports = function Container(id, agent, options) { let self = Object.create(EventEmitter.prototype); self.options = options; self.id = id; // wait for a container to exit function waitContainer(fn) { agent.post(`/containers/${id}/wait`, (err, res, body) => { if (err) fn(err); else if (res.statusCode !== 200) fn(Oops(res)); else fn(null, {exitCode: body.StatusCode}); }); } // start the container, running the command passed in on `#create()` self.start = function(done) { agent.post({url: `/containers/${id}/start`, json: true}, (err, res) => { if (err) done(err); if (res.statusCode !== 204) done(AgentError(res)); else { self.emit('start', self); // setup wait. request blocks until the container stops. note that if the system dies // while this is ongoing, we will never receive the exit code for this operation. // It's therefore not a smart idea to rely on the 'exit' event for anything critical. waitContainer((err, data) => { if (err) self.emit('error', err, self); else { self.exitCode = data.exitCode; self.emit('exit', self); } }); // don't wait for container to exit - just call back immediately done(null, self); } }); } return self; }
joerx/proto-ci
app/modules/docker/container.js
JavaScript
isc
1,614
require("lodash.times");
renke/auto-install-webpack-plugin
test/some_directory/another_module.js
JavaScript
isc
24
// Hier jouw code // d3.select("main").append("p").text("whoaaaaa");
CMDA/Frontend-3
src/wg2_oefening_domManipulatie/domManip.js
JavaScript
isc
69
"use strict"; const Viridine = require("./lib/viridine"), server = new Viridine(), exitHandler = signal => { server.gc(true); process.exit(1); }; process.on("SIGINT", () => exitHandler("SIGINT")); process.on("SIGHUP", () => exitHandler("SIGHUP")); process.on("SIGTERM", () => exitHandler("SIGTERM")); process.on("SIGQUIT", () => exitHandler("SIGQUIT"));
jextious/viridine
index.js
JavaScript
isc
363
var frmData; //wBagId //date //sMaterial //wMaterialId //wShift //wShiftUserId //wCheckedBy //wOperator //MachineNo frmData = Bind({ oData: GetNewData() }, { // 'oData.wMaterialId': '#spnMatrlId', 'oData.sType': 'input[name="rbtnOwn"]', //'oData.sMaterial': '#txtMaterial', 'oData.MachineNo': '#txtMachNo', 'oData.wShift': ".shft", 'oData.wShiftUserId': ".shftIch", 'oData.wCheckedBy': ".chkd", 'oData.wOperator': ".optr" }); function GetNewData() { return { wMaterialId: -1, sType: "Raw", sMaterial: "", MachineNo: "", wShift: -1, wShiftUserId: -1, wCheckedBy: -1, wOperator: -1 }; } $(document).ready(function () { $("input[name='rbtnOwn']").click(function () { GetMaterialData(this.value); }); GetMaterialData("Raw"); }); function Save() { oValidator.validate(); if (frmData.oData.wMaterialId == -1) { notie.alert(2, 'Select Material !', 2); return; } if ($(".shft").val() == null) { notie.alert(2, 'Select Shift !', 2); return; } if ($(".shftIch").val() == null) { notie.alert(2, 'Select Shift Incharge !', 2); return; } if ($(".optr").val() == null) { notie.alert(2, 'Select Operator !', 2); return; } if ($(".chkd").val() == null) { notie.alert(2, 'Select User !', 2); return; } if (!oValidator.hasErrors()) { GetDataAsync('RawMtrIssue.aspx/SaveEntry', function (response) { notie.alert(1, 'Saved !', 2); New(); GetAllData(); }, function () { }, "{'sData':'" + JSON.stringify(frmData.oData) + "'}"); } } function GetAllData() { GetMaterialData(frmData.oData.sType); } function UpdateEntry(oRow) { GetDataAsync('RawMtrIssue.aspx/LoadSingleData', function (response) { oRow = JSON.parse(response.d); frmData.oData = oRow; DisableSave(); }, function () { HideWaitCursor(); }, "{'sId' :'" + oRow.wBagId + "'}" ); } function EnableSave() { $("#btnSave").removeAttr('disabled'); $("#btnUpdate").attr('disabled', 'disabled'); $("#btnDelete").attr('disabled', 'disabled'); $("#btnNew").attr('disabled', 'disabled'); } function DisableSave() { $("#btnSave").attr('disabled', 'disabled'); //$("#btnUpdate").removeAttr('disabled'); //$("#btnDelete").removeAttr('disabled'); //$("#btnNew").removeAttr('disabled'); } function New() { frmData.oData = GetNewData(); EnableSave(); } function Update() { oValidator.validate(); if (!oValidator.hasErrors()) { if ($("#ddlBrand").val() == "") { notie.alert(2, 'Enter Brand Name !', 2); return; } else { frmData.oData.BrandName = $("#ddlBrand").text(); frmData.oData.BrandId = $("#ddlBrand").val(); } if ($("#ddlSuplier").val() == "") { notie.alert(2, 'Enter Supplier Name !', 2); return; } else frmData.oData.wSupplierId = $("#ddlSuplier").val(); frmData.oData.CheckBy = $(".ddlchkBy").val(); GetDataAsync('RawMtrIssue.aspx/UpdateEntry', function (response) { notie.alert(4, 'Updated !', 2); GetAllData(); }, function () { }, "{'sData':'" + JSON.stringify(frmData.oData) + "'}"); } } function Delete() { GetDataAsync('RawMtrIssue.aspx/DeleteEntry', function (response) { notie.alert(1, 'Deleted !', 2); GetAllData(); }, function () { }, "{'sData':'" + JSON.stringify(frmData.oData) + "'}"); } /*Material grid added and modal popup removed*/ function GetMaterialData(sType) { GetDataAsync('MaterialPopUp.aspx/LoadData', function (response) { if (response.d != null) { formatGridData(sType, response.d); } }, function () { }, "{'sType':'" + sType + "'}"); } function formatGridData(sType, oData) { var colNames = [], colModel = [], caption = "Materials"; if (sType == "Raw") { colNames = ['Date', 'ID', 'Name', 'Grade', 'Weight', 'Type', 'bagNo']; colModel = [ { name: 'wDateTime', index: 'wDateTime', formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "d/m/Y h:i A" } }, { name: 'wMaterialId', index: 'wMaterialId', hidden: true }, { name: 'BrandName', index: 'BrandName' }, { name: 'Grade', index: 'Grade' }, { name: 'Weight', index: 'Weight' }, { name: 'sType', index: 'sType' }, { name: 'BagNo', index: 'BagNo', hidden: true }, ]; } else if (sType == "Packing") { colNames = ['wPackingId', 'Material Type', 'Weight', 'Type', 'Date-Time', 'Quatity', 'WareHouse']; colModel = [ { name: 'wPackingId', index: 'wPackingId', hidden: true }, { name: 'MaterialType', index: 'MaterialType' }, { name: 'Weight', index: 'Weight' }, { name: 'sType', index: 'sType' }, { name: 'wDateTime', index: 'wDateTime', formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "d/m/Y h:i A" } }, { name: 'Quatity', index: 'Quatity', hidden: true }, { name: 'WareHouse', index: 'WareHouse', hidden: true } ]; } else if (sType == "Clrs") { colNames = ['wColorId', 'Color Shade', 'Truck No', 'Date-Time', 'Quatity', 'WareHouse', 'NoBarrels']; colModel = [ { name: 'wColorId', index: 'wColorId', hidden: true }, { name: 'ColorShade', index: 'ColorShade', width: 100 }, //{ name: 'wSupplierId', index: 'wSupplierId', width: 90 }, { name: 'TruckNo', index: 'TruckNo', width: 90 }, { name: 'wDateTime', index: 'wDateTime', formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "d/m/Y h:i A" } }, { name: 'Quatity', index: 'Quatity', hidden: true }, { name: 'WareHouse', index: 'WareHouse', hidden: true }, { name: 'NoBarrels', index: 'NoBarrels', hidden: true } ]; } else if (sType == "Others") { colNames = ['wOtherId', 'Type', 'InvoicNo', 'Date-Time', 'Quatity', 'Weight', 'Stores']; colModel = [ { name: 'wOtherId', index: 'wOtherId', hidden: true }, { name: 'Type', index: 'Type' }, //{ name: 'wSupplierId', index: 'wSupplierId' }, { name: 'ChalanNo', index: 'ChalanNo' }, { name: 'wDateTime', index: 'wDateTime', formatter: 'date', formatoptions: { srcformat: "ISO8601Long", newformat: "d/m/Y h:i A" } }, { name: 'Quatity', index: 'Quatity', hidden: true }, { name: 'Weight', index: 'Weight', hidden: true }, { name: 'Stores', index: 'Stores', hidden: true } ]; } sType = sType; bindIssueGrid(oData, colNames, colModel, caption); } function bindIssueGrid(oData, colNames, colModel, caption) { jQuery("#grdTruck").jqGrid("GridUnload"); $("#grdTruck").jqGrid({ datatype: "local", colNames: colNames, colModel: colModel, multiselect: false, rowNum: 10, rowList: [10, 20, 50, 100], pager: $('#pager'), sortorder: "desc", gridview: true, rownumbers: true, viewrecords: true, ignoreCase: true, //height: 340, //width: 500, caption: caption, beforeRequest: function () { setTimeout(function () { $("#grdTruck").jqGrid('setGridWidth', $("#dvhgt").width() - 5, true); $("#grdTruck").jqGrid('setGridHeight', 200, true); }); }, ondblClickRow: function (rowId) { var rowData = jQuery(this).getRowData(rowId); bindRowData(rowData); }, onSelectRow: function (rowId, rowId1, asd) { } }); $("#grdTruck").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" }); jQuery("#grdTruck").jqGrid("clearGridData"); jQuery("#grdTruck").jqGrid('setGridParam', { datatype: 'local', data: JSON.parse(oData) }).trigger("reloadGrid"); } function ownChange() { $(".divPacking ,.divRaw ,.divClrs ,.divOthers").find('input[type=text]').val(""); $(".divPacking ,.divRaw ,.divClrs ,.divOthers").find('input[type=number]').val(""); $("#divMaterialIssue").find('select').val(-1); frmData.oData.wMaterialId = -1; var sType = $("input[name=rbtnOwn]:checked")[0].value; if (sType == "Raw") { $(".divRaw").show(); $(".divPacking").hide(); $(".divClrs").hide(); $(".divOthers").hide(); } else if (sType == "Packing") { $(".divPacking").show(); $(".divRaw").hide(); $(".divClrs").hide(); $(".divOthers").hide(); } else if (sType == "Others") { $(".divOthers").show(); $(".divClrs").hide(); $(".divRaw").hide(); $(".divPacking").hide(); } else if (sType == "Clrs") { $(".divClrs").show(); $(".divOthers").hide(); $(".divRaw").hide(); $(".divPacking").hide(); } } var sType = ""; function bindRowData(rowData) { $(".divPacking ,.divRaw ,.divClrs ,.divOthers").find('input[type=text]').val(null); $(".divPacking ,.divRaw ,.divClrs ,.divOthers").find('input[type=number]').val(null); sType = $("input[name='rbtnOwn']:checked").val(); if (sType == "Raw") { frmData.oData.wMaterialId = rowData.wMaterialId; $('#ddlBrand').val(rowData.BrandName); $('#txtGrade').val(rowData.Grade); $('#txtTotalWt').val(rowData.Weight); $('#txtBagNo').val(rowData.BagNo); $("input[name=rbtnOwn1][value='" + rowData.sType + "']").prop('checked', true); } else if (sType == "Packing") { frmData.oData.wMaterialId = rowData.wPackingId; $('#txtMaterialPack').val(rowData.MaterialType); $('#txtTotalWtPack').val(rowData.Weight); $('#txtQtyPack').val(rowData.Quatity); $('#txtWare').val(rowData.WareHouse); $("input[name=rbtnOwnPack][value='" + rowData.sType + "']").prop('checked', true); } else if (sType == "Others") { frmData.oData.wMaterialId = rowData.wOtherId; $('#txtMaterial').val(rowData.Type); $('#txtInvoice').val(rowData.ChalanNo); $('#txtQty').val(rowData.Quatity); $('#txtTotalWtOthrs').val(rowData.Weight); $('#txtStore').val(rowData.Stores); } else if (sType == "Clrs") { frmData.oData.wMaterialId = rowData.wColorId; $('#txtColorShade').val(rowData.ColorShade); $('#txtTruckno').val(rowData.TruckNo); $('#txtBarrels').val(rowData.TruckNo); $('#txtQtyClrs').val(rowData.TruckNo); $('#txtWareDet').val(rowData.TruckNo); } }
atifkhan161/AspetProd
AspProdNet/Scripts/views/jMaterialIssue.js
JavaScript
mit
11,032
'use strict'; const mongoose = require('mongoose'); const { Schema } = mongoose; const transactionSchema = new Schema({ id: { type: Number, required: true, }, cardId: { type: Number, required: true, }, userId: { type: Number, required: true, }, type: String, data: Schema.Types.Mixed, time: { type: Date, default: Date.now, }, sum: String, }); module.exports = mongoose.model('Transaction', transactionSchema);
NAlexandrov/yaw
source/models/schema/transaction.js
JavaScript
mit
469
/** * Sends an AJAX request to a url of our choice as either a POST or GET * @param {string} type - Set to either "POST" or "GET" to indicate the type of response we want * @param {string} url - The URL to send the request to * @param {function} [success] - A function to run if the call succeeds * @param {function} [error] - A function to run if the request errors out * @param {variant} params - An "&" delimited string of "key=value" pairs that can be sent as AJAX or an object with key value pairs * @returns {AJAXRequest} - The request that was sent */ KIP.Functions.AJAXRequest = function (type, url, success, error, params){ var req, key, pOut; req = false; // Try to get an HTML Request try { req = new XMLHttpRequest(); } catch (e) { // If it failed, it could be because we're in IE, so try that try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){ // If that failed too, then we'll try the other IE specific method try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // And if we still can't get anything, then we're out of options return false; } } } // If we couldn't grab a request, quit if (!req) return false; // If we don't have a success function, create a generic blank one if (typeof success !== 'function') { success = function () {}; } // If we don't have an error function, create a generic blank one if (typeof error !== 'function') { error = function() {}; } // Make sure we handle both forms of inputs for parameters pOut = ""; if ((typeof params) !== (typeof "abc")) { for (key in params) { if (params.hasOwnProperty(key)) { // Append the appropriate PHP delimiter if (pOut.length > 0) { pOut += "&"; } // Make sure we add the key-value pair, properly escaped pOut += (escape(key) + "=" + escape(params[key])); } } // Save the params as a string to send to the PHP params = pOut; } // When the request is ready to run, try running it. req.onreadystatechange = function(){ if(req.readyState === 4){ return req.status === 200 ? success(req.responseText) : error(req.responseText); } }; // If it's a GET request... if (type === "GET"){ // ... send our request. req.open("GET", url, true); // If it's a POST request... }else if (type === "POST"){ // ... open the connection ... req.open("POST", url, true); // ... pull in the data for the POST ... req.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // ... and send the data. req.send(params); } // Return the total request return req; };
kipprice/toolkip.js
server.js
JavaScript
mit
2,747
var isArray = Array.isArray || function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; var binarySearch = require('./binarySearch'); var mean = function (data) { var sum = 0; for (var i = 0; i < data.length; i++) { sum += data[i]; } return sum / data.length; }; var splitVals = function (data, splits) { if (splits === 0 || data.length === 0) { return []; } var meanVal = mean(data); var split = binarySearch(data, meanVal); while (data[split] === meanVal) { split += 1; } var below = data.slice(0, split); var above = data.slice(split); return splitVals(below, splits - 1).concat([meanVal]).concat(splitVals(above, splits - 1)); }; var nestedMeans = function (data, ranges) { // Check parameters if (!isArray(data)) { throw new Error("data should be an array!"); } var lg = Math.log(ranges) / Math.log(2); if (lg !== Math.round(lg)) { throw new Error("ranges should be a power of two"); } // Handle edge cases if (data.length === 0 || ranges === 0) { return []; } // Sort the array data.sort(function (a, b) { return a > b ? 1 : a < b ? -1 : 0; }); return [data[0]].concat(splitVals(data, lg)).concat(data[data.length - 1] + 1); }; nestedMeans.rounded = function (data, ranges) { var result = []; var calculated = nestedMeans(data, ranges); for (var i = 0; i < calculated.length; i++) { result.push(Math.floor(calculated[i])); } return result; }; nestedMeans.scale = require('./scale')(nestedMeans); nestedMeans.scaleRounded = require('./scale')(nestedMeans.rounded); module.exports = nestedMeans;
rubenv/nested-means
lib/index.js
JavaScript
mit
1,735
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; import { set } from '@ember/object'; export default Route.extend({ can: service(), features: service(), headData: service(), model(params) { let self = this; return this.store .findRecord('provider', params.provider_id, { include: 'consortium,consortium-organizations,contacts' }) .then(function (provider) { set(self, 'headData.title', provider.displayName); set(self, 'headData.description', provider.description); set(self, 'headData.image', provider.logoUrl); return provider; }) .catch(function (reason) { console.debug(reason); self.get('flashMessages').warning(reason); self.transitionTo('/'); }); }, redirect(model) { if (this.can.cannot('read provider', model)) { this.transitionTo('index'); } }, actions: { queryParamsDidChange() { this.refresh(); } } });
datacite/bracco
app/routes/providers/show.js
JavaScript
mit
1,019
var DOCUMENTATION_OPTIONS = { URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), VERSION: '0.3.5', LANGUAGE: 'None', COLLAPSE_INDEX: false, BUILDER: 'html', FILE_SUFFIX: '.html', LINK_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt', NAVIGATION_WITH_KEYS: false };
survey-methods/samplics
docs/source/_build/html/_static/documentation_options.js
JavaScript
mit
355
import { parseShorthand } from './utils.js'; import forOwn from 'lodash-es/forOwn'; import isString from 'lodash-es/isString'; import isUndefined from 'lodash-es/isUndefined'; /** * Sets up the handler to determine if we should advance the tour * @private */ function _setupAdvanceOnHandler(selector) { return (event) => { if (this.isOpen()) { const targetIsEl = this.el && event.target === this.el; const targetIsSelector = !isUndefined(selector) && event.target.matches(selector); if (targetIsSelector || targetIsEl) { this.tour.next(); } } }; } /** * Bind the event handler for advanceOn */ export function bindAdvance() { // An empty selector matches the step element const { event, selector } = parseShorthand(this.options.advanceOn, ['selector', 'event']); const handler = _setupAdvanceOnHandler.call(this, selector); // TODO: this should also bind/unbind on show/hide const el = document.querySelector(selector); if (!isUndefined(selector) && el) { el.addEventListener(event, handler); } else { document.body.addEventListener(event, handler, true); } this.on('destroy', () => { return document.body.removeEventListener(event, handler, true); }); } /** * Bind events to the buttons for next, back, etc * @param {Object} cfg An object containing the config options for the button * @param {HTMLElement} el The element for the button */ export function bindButtonEvents(cfg, el) { cfg.events = cfg.events || {}; if (!isUndefined(cfg.action)) { // Including both a click event and an action is not supported cfg.events.click = cfg.action; } forOwn(cfg.events, (handler, event) => { if (isString(handler)) { const page = handler; handler = () => this.tour.show(page); } el.dataset.buttonEvent = true; el.addEventListener(event, handler); // Cleanup event listeners on destroy this.on('destroy', () => { el.removeAttribute('data-button-event'); el.removeEventListener(event, handler); }); }); } /** * Add a click listener to the cancel link that cancels the tour * @param {HTMLElement} link The cancel link element */ export function bindCancelLink(link) { link.addEventListener('click', (e) => { e.preventDefault(); this.cancel(); }); } /** * Take an array of strings and look up methods by name, then bind them to `this` * @param {String[]} methods The names of methods to bind */ export function bindMethods(methods) { methods.map((method) => { this[method] = this[method].bind(this); }); }
HubSpot/shepherd
src/js/bind.js
JavaScript
mit
2,585
/** * Created by Armaldio on 06/02/2017. */ module.exports = class SpriteExtended extends Sprite { constructor (name, texture) { super(name, "sprite"); this.texture = texture; this.setup(); } preload () { game.load.image(this.name, this.path); } setup () { //this.addXXX(name, script, description); this.addAction("Set X", "SetX", "Set X position of the sprite", () => { }); this.addExpression("Get X", "GetX", "Get X position of the sprite", () => { }); } };
Xtruct/Editor
ExampleProject/plugins/SpriteExtended.js
JavaScript
mit
491
/** * @author: * @date: 2016/1/21 */ define(["core/js/layout/Panel", "core/js/controls/ToolStripItem", "core/js/CommonConstant"], function (Panel,ToolStripItem,CommonConstant) { var view = Panel.extend({ /*Panel的配置项 start*/ title:"表单-", help:"内容", brief:"摘要", /*Panel 配置 End*/ beforeInitializeHandle:function(options, triggerEvent){ this._super(); this.mainRegion={ comXtype:$Component.TREE, comConf:{ data:[this.getModuleTree("core/js/base/AbstractView")], } }; var that = this; this.footerRegion = { comXtype: $Component.TOOLSTRIP, textAlign: $TextAlign.RIGHT, comConf: { /*Panel的配置项 start*/ spacing: CommonConstant.Spacing.DEFAULT, itemOptions: [{ themeClass: ToolStripItem.ThemeClass.PRIMARY, text: "展开所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().expandAll(); }, }, { themeClass: ToolStripItem.ThemeClass.PRIMARY, text: "折叠所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().collapseAll(); }, }, { themeClass: ToolStripItem.ThemeClass.PRIMARY, text: "销毁树", onclick: function (e) { that.getMainRegionRef().getComRef().destroy(); }, }, { themeClass: ToolStripItem.ThemeClass.PRIMARY, text: "修改树节点信息", onclick: function (e) { that.getMainRegionRef().getComRef().setData([ {title: "node1"} ]); }, }, { themeClass: ToolStripItem.ThemeClass.PRIMARY, text: "重新加载树", onclick: function (e) { that.getMainRegionRef().getComRef().reload(); /*//此种方式同setData that.getMainRegionRef().getComRef().reload([ {title: "node1"} ]);*/ }, }, { themeClass: ToolStripItem.ThemeClass.PRIMARY, text: "切换选择状态", onclick: function (e) { that.getMainRegionRef().getComRef().toggleSelect(); }, }, { themeClass: ToolStripItem.ThemeClass.PRIMARY, text: "获取被选择的节点(仅包含父节点)", onclick: function (e) { var selectedNodes = that.getMainRegionRef().getComRef().getSelectedNodes(true); console.info(selectedNodes); }, }, { themeClass: ToolStripItem.ThemeClass.PRIMARY, text: "获取被选择的节点", onclick: function (e) { var selectedNodes = that.getMainRegionRef().getComRef().getSelectedNodes(false); console.info(selectedNodes); }, }] /*Panel 配置 End*/ } }; }, getModuleTree:function(moduleName,arr){ var va = window.rtree.tree[moduleName]; var tree = {title: moduleName}; if(!arr){ arr = []; }else{ if(_.contains(arr,moduleName)){ return false; } } arr.push(moduleName); if(va&&va.deps&&va.deps.length>0){ tree.children = []; tree.folder=true; for(var i=0;i<va.deps.length;i++){ var newTree = this.getModuleTree(va.deps[i],arr); if(newTree){ tree.children.push(newTree); }else{ if(!tree.count){ tree.count = 0; } tree.count++; } } } return tree; } }); return view; });
huangfeng19820712/hfast
example/view/tree/tree.js
JavaScript
mit
5,394
var ACTIONS = { CUT: 0, EASE: 1, LINEAR: 2 } function TimelineEvent() { this.start = null; this.end = null; this.action = null; this.from = 0; this.to = 0; this.duration = 0; } function parseStoryline( story ) { var result = {}; for( var v in story ) { if( story.hasOwnProperty( v ) ) { var storyboard = []; story[ v ].forEach( function( e ) { var start = e.match( /([^\s]+)/ ); var event = new TimelineEvent(); if( e.indexOf( 'cut to' ) != -1 ) { event.start = parseFloat( start[ 1 ] ); event.action = ACTIONS.CUT; var v = e.match( /[^\s]+ cut to ([^\s]+)/ ); event.from = parseFloat( v[ 1 ] ); event.to = event.from; event.end = event.start; } if( e.indexOf( 'ease to' ) != -1 ) { event.end = parseFloat( start[ 1 ] ); event.action = ACTIONS.EASE; event.from = 0; var v = e.match( /[^\s]+ ease to ([^\s]+)/ ); event.to = parseFloat( v[ 1 ] ); } if( e.indexOf( 'linear to' ) != -1 ) { event.end = parseFloat( start[ 1 ] ); event.action = ACTIONS.LINEAR; event.from = 0; var v = e.match( /[^\s]+ linear to ([^\s]+)/ ); event.to = parseFloat( v[ 1 ] ); } storyboard.push( event ); } ); storyboard.forEach( function( e, i ) { if( e.action === ACTIONS.EASE || e.action == ACTIONS.LINEAR ) { e.start = storyboard[ i - 1 ].end; e.from = storyboard[ i - 1 ].to; } e.duration = e.end - e.start; } ); storyboard.forEach( function( e, i ) { if( e.action === ACTIONS.CUT ) { if( storyboard[ i + 1 ] ) { e.end = storyboard[ i + 1 ].start; } } } ); storyboard.forEach( function( e, i ) { console.log( e.from + '(' + e.start + ')' + ' to ' + e.to + '(' + e.end + ') in ' + e.duration ); } ); result[ v ] = storyboard; } } return result; } function getPointInStoryline( storyline, t, value ) { if( !storyline[ value ] ) return null; for( var j = 0; j < storyline[ value ].length; j++ ) { var e = storyline[ value ][ j ]; if( e.start <= t && e.end > t ) { return e; } } return null; } function averageData( story, t, value ) { var p; if( t > story[ value ][ story[ value ].length - 1 ].end ) { p = story[ value ][ story[ value ].length - 1 ]; } else { p = getPointInStoryline( story, t, value ); } if( !p ) return null; if( p.action === ACTIONS.CUT ) { return p.from; } if( p.action === ACTIONS.EASE ) { var et = ( t - p.start ) / p.duration; et = Math.max( Math.min( et, 1 ), 0 ); var easing; if ( ( et *= 2 ) < 1 ) easing = 0.5 * et * et; else easing = - 0.5 * ( --et * ( et - 2 ) - 1 ); var v = p.from + ( easing * ( p.to - p.from ) ); return v; } if( p.action === ACTIONS.LINEAR ) { var et = ( t - p.start ) / p.duration; et = Math.max( Math.min( et, 1 ), 0 ); var v = p.from + ( et * ( p.to - p.from ) ); return v; } } function setValue( original, value ) { if( value !== null ) return value; return original }
spite/cruciform
js/timeline.js
JavaScript
mit
3,148
(function ($, Typer) { 'use strict'; var root = document.documentElement; var getRect = Typer.getRect; var container = $('<div style="position:absolute;top:0;left:0;">')[0]; var handles = new shim.WeakMap(); var allLayers = {}; var freeDiv = []; var state = {}; var lastState = {}; var mousedown = false; var activeTyper; var activeHandle; var hoverNode; var oldLayers; var newLayers; var timeout; function TyperCanvas() { state.timestamp = activeTyper.getSelection().timestamp; state.rect = getRect(activeTyper).translate(root.scrollLeft, root.scrollTop); $.extend(this, { typer: activeTyper, pointerX: state.x || 0, pointerY: state.y || 0, mousedown: mousedown, hoverNode: hoverNode || null, activeHandle: activeHandle || null, editorReflow: !lastState.rect || !Typer.rectEquals(lastState.rect, state.rect), pointerMoved: lastState.x != state.x || lastState.y != state.y, selectionChanged: lastState.timestamp !== state.timestamp }); $.extend(lastState, state); } function TyperCanvasHandle(cursor, done) { this.cursor = cursor || 'pointer'; this.done = done; } function init() { var repl = { N: 'typer-visualizer', G: 'background', S: 'selection', X: 'transparent' }; var style = '<style>.has-N{caret-color:X;}.has-N:focus{outline:none;}.has-N::S,.has-N ::S{G:X;}.has-N::-moz-S,.has-N ::-moz-S{G:X;}@keyframes caret{0%{opacity:1;}100%{opacity:0;}}</style>'; $(document.body).append(style.replace(/\b[A-Z]/g, function (v) { return repl[v] || v; })).append(container); $(container).mousedown(function (e) { if (e.buttons & 1) { activeHandle = handles.get(e.target); Typer.draggable(e, activeTyper.element).always(function () { (activeHandle.done || $.noop).call(activeHandle); activeHandle = null; }); e.preventDefault(); } }); $(document.body).on('mousedown mousemove mouseup', function (e) { state.x = e.clientX; state.y = e.clientY; hoverNode = activeTyper && activeTyper.nodeFromPoint(state.x, state.y); clearTimeout(timeout); if (e.type === 'mousemove') { timeout = setTimeout(refresh, 0); } else { mousedown = e.buttons & 1; timeout = setTimeout(refresh, 0, true); } }); $(window).on('scroll resize orientationchange focus', refresh); } function computeFillRects(range) { var start = Typer.getAbstractSide('inline-start', range.startContainer); var end = Typer.getAbstractSide('inline-end', range.startContainer); var result = []; $.each(Typer.getRects(range), function (i, v) { if (Math.abs(v[start] - v[end]) <= 1) { v[end] += 5; } result.forEach(function (prev) { if (Math.abs(v.left - prev.right) <= 1) { prev.right = v.left; } if (Math.abs(v.top - prev.bottom) <= 1) { prev.bottom = v.top; } }); result.unshift(v); }); return result; } function addLayer(name, callback) { allLayers[name] = [callback, [], {}, true]; } function addObject(kind, state, rect, css, handle) { for (var i = 0, len = oldLayers.length; i < len; i++) { if (oldLayers[i].state === state && oldLayers[i].kind === kind) { newLayers[newLayers.length] = oldLayers.splice(i, 1)[0]; return; } } newLayers[newLayers.length] = { kind: kind, state: state, rect: rect || ('top' in state ? state : Typer.getRect), css: css, handle: handle }; } function refresh(force) { force = force === true; clearTimeout(timeout); if (activeTyper && (force || activeTyper.focused(true))) { var canvas = new TyperCanvas(); if (force || canvas.editorReflow || canvas.selectionChanged || canvas.pointerMoved) { $.each(allLayers, function (i, v) { newLayers = v[1]; oldLayers = newLayers.splice(0); if (v[3] !== false) { v[0].call(null, canvas, v[2]); } oldLayers.forEach(function (v) { freeDiv[freeDiv.length] = $(v.dom).detach().removeAttr('style')[0]; handles.delete(v.dom); }); newLayers.forEach(function (v) { if (force || !v.dom || canvas.editorReflow || $.isFunction(v.rect)) { var dom = v.dom || (v.dom = $(freeDiv.pop() || document.createElement('div')).appendTo(container)[0]); $(dom).css($.extend({ position: 'absolute', cursor: (v.handle || '').cursor, pointerEvents: v.handle ? 'all' : 'none' }, v.css, Typer.ui.cssFromRect('top' in v.rect ? v.rect : v.rect(v.state), container))); handles.set(dom, v.handle); } }); }); } } } $.extend(TyperCanvas.prototype, { refresh: function () { setTimeout(refresh, 0, true); }, toggleLayer: function (name, visible) { var needRefresh = false; name.split(' ').forEach(function (v) { needRefresh |= visible ^ (allLayers[v] || '')[3]; (allLayers[v] || {})[3] = visible; }); if (needRefresh) { setTimeout(refresh, 0, true); } }, fill: function (range, color, handle) { var style = {}; style.background = color || 'rgba(0,31,81,0.2)'; if (range instanceof Node || 'top' in range) { addObject('f', range, null, style, handle); } else { var arr = []; Typer.iterate(activeTyper.createSelection(range).createTreeWalker(-1, function (v) { if (Typer.rangeCovers(range, v.element)) { arr[arr.length] = getRect(v); return 2; } if (Typer.is(v, Typer.NODE_ANY_ALLOWTEXT)) { arr.push.apply(arr, computeFillRects(Typer.createRange(range, Typer.createRange(v.element, 'content')))); return 2; } return 1; })); arr.forEach(function (v) { addObject('f', v, null, style, handle); }); } }, drawCaret: function (caret) { addObject('k', caret, null, { animation: 'caret 0.5s infinite alternate ease-in', outline: '1px solid rgba(0,31,81,0.8)' }); }, drawBorder: function (element, width, color, lineStyle, inset) { var style = {}; style.border = parseFloat(width) + 'px ' + (lineStyle || 'solid') + ' ' + (color || 'black'); style.margin = inset ? '0px' : -parseFloat(width) + 'px'; style.boxSizing = inset ? 'border-box' : 'auto'; addObject('b', element, null, style); }, drawLine: function (x1, y1, x2, y2, width, color, lineStyle, handle) { var dx = x2 - x1; var dy = y2 - y1; var style = {}; style.borderTop = parseFloat(width) + 'px ' + (lineStyle || 'solid') + ' ' + (color || 'black'); style.transformOrigin = '0% 50%'; style.transform = 'translateY(-50%) rotate(' + Math.atan2(dy, dx) + 'rad)'; addObject('l', Typer.toPlainRect(x1, y1, x1 + (Math.sqrt(dy * dy + dx * dx)), y1), null, style, handle); }, drawHandle: function (element, pos, size, image, handle) { var style = {}; style.border = '1px solid #999'; style.background = 'white' + (image ? ' url("' + image + '")' : ''); size = size || 8; addObject('c', element, function () { var r = getRect(element); var x = Typer.ui.matchWSDelim(pos, 'left right') || 'centerX'; var y = Typer.ui.matchWSDelim(pos, 'top bottom') || 'centerY'; r.left -= size; r.top -= size; return Typer.toPlainRect(r[x], r[y], r[x] + size, r[y] + size); }, style, handle); } }); addLayer('selection', function (canvas) { var selection = canvas.typer.getSelection(); var startNode = selection.startNode; if (selection.isCaret) { if ('caretColor' in root.style) { canvas.drawCaret(selection.baseCaret); } } else if (Typer.is(startNode, Typer.NODE_WIDGET) === selection.focusNode) { canvas.fill(startNode.element); } else { canvas.fill(selection.getRange()); } }); Typer.widgets.visualizer = { init: function (e) { $(e.typer.element).addClass('has-typer-visualizer'); if (!init.init) { init(); init.init = true; } }, focusin: function (e) { activeTyper = e.typer; Typer.ui.setZIndex(container, activeTyper.element); refresh(true); }, focusout: function (e) { activeTyper = null; $(container).children().detach(); }, contentChange: function (e) { refresh(true); }, stateChange: function (e) { refresh(); } }; Typer.defaultOptions.visualizer = true; Typer.canvas = { addLayer: addLayer, handle: function (cursor, done) { return new TyperCanvasHandle(cursor, done); } }; })(jQuery, Typer);
misonou/jquery-typer
src/canvas.js
JavaScript
mit
10,564
import $ from 'jquery'; import { clearStyles } from '../util'; export default function () { let jews = {}; jews.title = $('.sec_subject .subject_area').text(); jews.content = clearStyles($('#cont_newstext')[0].cloneNode(true)).innerHTML; jews.reporters = [{ name: $('.sec_subject .source').text() }]; return jews; }
teslamint/jews
src/impl/KBS.js
JavaScript
mit
349
/*globals jQuery:false _:false Node:false*/ (function ( $, _, window ) { var XPath = {}; XPath.getXPath = function(element) { if (element && element.id) return '//*[@id="' + element.id + '"]'; else return this.getTreeXPath(element); }; /** * Gets an XPath for an element tree. */ XPath.getTreeXPath = function(element) { var uniqueClasses, siblingClasses, classList, paths = []; // Use nodeName (instead of localName) so namespace prefix is included (if any). for (; element && element.nodeType == 1; element = element.parentNode) { // Check if the element has an id if (element.id) { paths.splice(0, 0, '/*[@id="' + element.id + '"]'); break; } uniqueClasses = null; classList = element.className.split(/\s+/); // Count siblings var index = 0; for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) { // Ignore document type declaration. if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) continue; if (sibling.nodeName == element.nodeName) { ++index; siblingClasses = sibling.className.split(/\s+/); var diff = _.difference(classList, siblingClasses); if (!uniqueClasses) uniqueClasses = diff; else uniqueClasses = _.intersection(diff, uniqueClasses); } } var pathIndex, tagName = element.nodeName.toLowerCase(); if (uniqueClasses && uniqueClasses.length) pathIndex = '[@class="' + uniqueClasses[0] + '"]'; else pathIndex = (index ? "[" + (index+1) + "]" : element.nextSibling ? "[" + 1 + "]" : ""); paths.splice(0, 0, tagName + pathIndex); } return paths.length ? "/" + paths.join("/") : null; }; (function($) { $.fn.getAttributes = function() { var attributes = { keys: [], values: [] }; if(!this.length) return this; $.each(this[0].attributes, function(index, attr) { attributes.push({ key: attr.name, value: attr.value }); attributes.keys.push(attr.name); attributes.values.push(attr.value); }); return attributes; }; })(jQuery); /** * Utility method for finding the first common ancestor for * a group of elements. */ function commonAncestor(jnodes) { var i, nodes = $.makeArray(jnodes), node1 = nodes.pop(), method = "contains" in node1 ? "contains" : "compareDocumentPosition", test = method === "contains" ? 1 : 0x0010; rocking: while (node1) { node1 = node1.parentNode; i = nodes.length; while (i--) { if ((node1[method](nodes[i]) & test) !== test) continue rocking; } return node1; } return null; } /** * Utility function that finds the parent among a list of elements. */ var findParent = function(elements) { var out; $(elements).each(function() { var isParent = true; var element = this; $(elements).not(element).each(function() { if (!$(element).has(this).length) { isParent = false; return false; } }); if (isParent) { out = element; return false; } }); return out; }; /** * Relative XPath. * First we find the first element with * the text inside it. Then we construct a relative XPath to the other. */ XPath.relativeXPath = function($rel, $target) { var rel = $rel[0], target = $target[0], paths = []; // Find Parent var parent = commonAncestor([rel, target]); if (!parent) return null; // Add the element we want the XPath to be relative to. paths.push('//' + rel.nodeName.toLowerCase() + '[contains(text(), "' + $rel.text() + '")]'); // Travel to the common parent. for (var el = rel; el !== parent && el; el = el.parentNode) { paths.push('..'); } // Travel to parent from target and reverse var components = []; for (; target !== parent && target ; target = target.parentNode) { // Count siblings var index = 0; for (var sibling = target.previousSibling; sibling; sibling = sibling.previousSibling) { // Ignore document type declaration. if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) continue; if (sibling.nodeName == target.nodeName) { ++index; } } var pathIndex, tagName = target.nodeName.toLowerCase(); pathIndex = (index ? "[" + (index+1) + "]" : target.nextSibling ? "[" + 1 + "]" : ""); components.splice(0, 0, tagName + pathIndex); } return paths.concat(components).join('/') }; XPath.getElementsByXPath = function(xpath, doc) { var nodes = []; try { var result = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null); for (var item = result.iterateNext(); item; item = result.iterateNext()) { if (item.nodeType !== 1) item = item.parentNode || item.ownerElement; nodes.push(item); } } catch (ex) { // Invalid xpath expressions make their way here sometimes. If that happens, // we still want to return an empty set without an exception. } return nodes; }; $.fn.xpath = function () { return XPath.getXPath(this[0]); }; $.xpath = function(xpath, document) { // If both args is a jquery element, we want to find the closest xpath // between them. var argIsElement = (xpath instanceof $) && (document instanceof $); if (argIsElement) return XPath.relativeXPath(xpath, document); if (!document) document = window.document; var returns, elements = $(XPath.getElementsByXPath(xpath, document)); if (!elements.length) return $([]); elements = $.unique(elements); var parent = findParent(elements); if (parent) return $(parent); else return $(elements[0]); }; }(jQuery, _, window));
mludv/table-xpath
source/javascripts/jquery.xpath.js
JavaScript
mit
6,174
export { default as socket } from './Socket'; export { default as storage } from './Storage'; export { default as youtube } from './YouTube'; export { default as uploads } from './Uploads';
upnextfm/upnextfm
web/src/js/api/index.js
JavaScript
mit
190
(function(w, d) { 'use strict';
millerlogic/GrindstoneJS
src/templates/Intro.js
JavaScript
mit
33
.factory('playerService', ['$log', function($log) { var Player = function(name){ this.name = name this.final = null this.score = { aces: null, twos: null, threes: null, fours: null, fives: null, sixes: null, bonus: null, threeOfAKind: null, fourOfAKind: null, fullHouse: null, smallStraight: null, largeStraight: null, yahtzee: null, chance: null } this.scoreField = function(diceArray, fieldName) { var points = 0; var num1s = 0; var num2s = 0; var num3s = 0; var num4s = 0; var num5s = 0; var num6s = 0; diceArray.forEach(function(die){ if (die.value == 1) { num1s += 1; } if (die.value == 2) { num2s += 1; } if (die.value == 3) { num3s += 1; } if (die.value == 4) { num4s += 1; } if (die.value == 5) { num5s += 1; } if (die.value == 6) { num6s += 1; } }) var totals = [num1s, num2s, num3s, num4s, num5s, num6s]; switch (fieldName) { case 'aces': diceArray.forEach(function(die){ if (die.value == 1) { points += 1; } }) if (points === 0) { points = "Bust" } this.score.aces = points break; case 'twos': diceArray.forEach(function(die){ if (die.value == 2) { points += 2; } }) if (points === 0) { points = "Bust" } this.score.twos = points break; case 'threes': diceArray.forEach(function(die){ if (die.value == 3) { points += 3; } }) if (points === 0) { points = "Bust" } this.score.threes = points break; case 'fours': diceArray.forEach(function(die){ if (die.value == 4) { points += 4; } }) if (points === 0) { points = "Bust" } this.score.fours = points break; case 'fives': diceArray.forEach(function(die){ if (die.value == 5) { points += 5; } }) if (points === 0) { points = "Bust" } this.score.fives = points break; case 'sixes': diceArray.forEach(function(die){ if (die.value == 6) { points += 6; } }) if (points === 0) { points = "Bust" } this.score.sixes = points break; case 'threeOfAKind': this.score.threeOfAKind = 'Bust' totals.forEach(function(number){ if (number >= 3 ) { diceArray.forEach(function(die){ points += die.value }) this.score.threeOfAKind = points } }.bind(this)) break; case 'fourOfAKind': this.score.fourOfAKind = 'Bust' totals.forEach(function(number){ if (number >= 4 ) { diceArray.forEach(function(die){ points += die.value }) this.score.fourOfAKind = points } }.bind(this)) break; case 'fullHouse': if (totals.indexOf(2) !== -1 && totals.indexOf(3) !== -1) { this.score.fullHouse = 25 } else { this.score.fullHouse = "Bust" } break; case 'smallStraight': $log.log(totals.indexOf(1)) if (num1s >= 1 && num2s >= 1 && num3s >= 1 && num4s >= 1 ) { this.score.smallStraight = 30 } else if (num2s >= 1 && num3s >= 1 && num4s >= 1 && num5s >= 1 ) { this.score.smallStraight = 30 } else if (num3s >= 1 && num4s >= 1 && num5s >= 1 && num6s >= 1 ) { this.score.smallStraight = 30 } else { this.score.smallStraight = "Bust" } break; case 'largeStraight': if (num1s >= 1 && num2s >= 1 && num3s >= 1 && num4s >= 1 && num5s >= 1 ) { this.score.largeStraight = 40 } else if (num2s >= 1 && num3s >= 1 && num4s >= 1 && num5s >= 1 && num6s >= 1 ) { this.score.largeStraight = 40 } else { this.score.largeStraight = "Bust" } break; case 'yahtzee': if (totals.indexOf(5) !== -1) { this.score.yahtzee = 50 } else { this.score.yahtzee = "Bust" } break; case 'chance': diceArray.forEach(function(die){ points += die.value; }) this.score.chance = points break; default: //Statements executed when none of the values match the value of the expression break; } } } var newPlayer = function(name){ return new Player(name) } return { newPlayer: newPlayer } }])
AJPcodes/yahtzee
client/scripts/services/player.js
JavaScript
mit
5,343
/* * * The PostRegPage component displays whether a user * is registered to vote or not after using the root * page interface to check. */ import React from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import PostRegForm from 'containers/PostRegForm'; import SocialButtons from 'components/SocialButtons'; import * as selectors from './selectors'; import * as actions from './actions'; import styles from './styles.scss'; import EmailModal from 'components/EmailModal'; export class PostRegPage extends React.Component { // eslint-disable-line react/prefer-stateless-function componentDidMount() { this.props.dispatch(actions.showModal()); } render() { let registered = 'registering'; if (this.props.params.registered === 'true') { registered = 'registered'; } if (this.props.params.registered === 'false') { registered = 'not registered'; } let emailModal = (<EmailModal {...this.props} submitEmail={this.props.onSubmitEmail} className={styles.email} registered={registered} state={this.props.params.state} />); // no voter registration if (this.props.params.state === 'ND') { emailModal = (<EmailModal {...this.props} submitEmail={this.props.onSubmitEmail} className={styles.email} registered="voting" state={this.props.params.state} />); } let postRegForm = (<PostRegForm registered={registered} state={this.props.params.state} />); // same day voter registration if (['NH', 'WY', 'MN'].indexOf(this.props.params.state) >= 0) { postRegForm = (<PostRegForm registered="registered" state={this.props.params.state} />); } return ( <div className={styles.postRegPage}> {emailModal} <div> {postRegForm} <div className={styles.social}> <SocialButtons /> </div> </div> </div> ); } } PostRegPage.propTypes = { params: React.PropTypes.object, onSubmitEmail: React.PropTypes.func, dispatch: React.PropTypes.func, closeModal: React.PropTypes.func, isOpen: React.PropTypes.bool, }; function mapDispatchToProps(dispatch, ownProps) { return { onSubmitEmail: (evt) => { evt.preventDefault(); dispatch(actions.submitEmail(ownProps.params)); }, closeModal: () => { dispatch(actions.closeModal()); }, dispatch, }; } const mapStateToProps = createStructuredSelector({ isOpen: selectors.selectIsOpen(), }); export default connect(mapStateToProps, mapDispatchToProps)(PostRegPage);
elainewlin/Executive
app/containers/PostRegPage/index.js
JavaScript
mit
2,566
/** * @author Kevin Boogaard <{@link http://www.kevinboogaard.com/}> * @author Alex Antonides <{@link http://www.alex-antonides.com/}> * @license {@link https://github.com/kevinboogaard/Sports_World-Ball_Pit/blob/master/LICENSE} * @ignore */ var ballpit = ballpit || {}; /** * @namespace Event */ this.Event; // For documentation purposes. ballpit.Event = ballpit.Event || {}; /** * @property {String} ON_BALL_ALIGN * @memberof Event * @readonly */ ballpit.Event.ON_BALL_ALIGN = "on_ball_align"; /** * @property {String} ON_BALLS_SPAWNED * @memberof Event * @readonly */ ballpit.Event.ON_BALLS_SPAWNED = "on_balls_spawned"; ballpit.BallController = (function () { /** * @class BallController * @constructor * @param {TileLayer} layer - The layer that the ballcontroller is controlling. * @param {BallContainer} ballContainer - The ball container. */ function BallController(layer, ballContainer) { /** * @property {TileLayer} _Layer - The layer that the ballcontroller is controlling. * @private */ this._layer = layer; /** * @property {BallContainer} _BallContainer - The ball container given. * @private */ this._ballContainer = ballContainer; /** * @property {Array} _Rows - The tiles of the Main Layer. * @private */ this._rows = this._layer.tiledata; /** * @property {BallHelper} _Helper - The ball helper of the controller. * @private */ this._helper = new ballpit.BallHelper(this._layer, this._ballContainer); Listener.Listen(ballpit.Event.ON_BALL_ALIGN, this, this._onBallAlign.bind(this), this); Listener.Listen(ballpit.Event.ON_BALL_DESTINATION_REACHED, this, this._onBallDestinationReached.bind(this)); } var p = BallController.prototype; /** * @method Initialize * @memberof BallController * @public */ p.Initialize = function () { var len = this._layer.width; for (var x = 0; x < len; x++) { this._spawnColumn(x, true); } }; /** * @method Swap * @memberof BallController * @public * @param {TileModel} selected - The selected tile. * @param {TileModel} targeted - The targeted tile. */ p.Swap = function (selected, targeted) { if (selected === targeted) throw new Error("Can't swap the selected with the selected"); // Get the occupiers of the selected tiles. var selected_occupier = selected.occupier; var targeted_occupier = targeted.occupier; // Swap the occupiers. selected.occupier = targeted_occupier; targeted.occupier = selected_occupier; selected_occupier.beginning = selected; targeted_occupier.beginning = targeted; // Change the position of the balls also. if (selected_occupier) selected_occupier.SwapTo(targeted.position); if (targeted_occupier) targeted_occupier.SwapTo(selected.position); }; /** * @method Move * @memberof BallController * @public * @param {TileModel} selected - The selected tile. * @param {TileModel} targeted - The targeted tile. */ p.Move = function (selected, targeted) { if (selected === targeted) throw new Error("Can't swap the selected with the selected"); // Get the occupiers of the selected tiles. var selected_occupier = selected.occupier; var targeted_occupier = targeted.occupier; // Swap the occupiers. selected.occupier = targeted_occupier; targeted.occupier = selected_occupier; // Change the position of the balls also. if (selected_occupier) selected_occupier.MoveTo(targeted.position); if (targeted_occupier) targeted_occupier.MoveTo(selected.position); }; /** * @method DropColumn * @memberof BallController * @public * @param {Number} tileX - The x position of the column the controller needs to drop. */ p.DropColumn = function (tileX) { var len = this._rows.length; for (var y = len -1; y >= 0; y--) { var row = this._rows[y]; var row_len = row.length; for (var x = 0; x < row_len ; x++) { if (x === tileX) { var tile = row[x]; if (this.CanMove(tile)) { this.DropBall(tile); } } } } }; /** * @method DropBall * @memberof BallController * @public * @param {TileModel} tile - The tile the controller needs to drop. */ p.DropBall = function (tile) { var lowest = this._helper.GetLowestBeneath(tile); if (tile !== lowest) { tile.occupier.state = ballpit.BallStates.MOVING; this.Move(tile, lowest); } }; /** * @method RestoreColumn * @memberof BallController * @public * @param {Number} tileX - The x position of the column the controller needs to restore. * @param {Boolean} [forceType = false] */ p.RestoreColumn = function (tileX, forceType) { var y_spawns = []; var len = this._rows.length; for (var y = len -1; y >= 0; y--) { var row = this._rows[y]; var row_len = row.length; for (var x = 0; x < row_len ; x++) { if (!y_spawns[x]) y_spawns[x] = -1; if (x === tileX) { var tile = row[x]; if (this.CanMove(tile) === false) { var position = this._layer.TilePositionToScreenPosition(new Vector2(tile.tileposition.x, y_spawns[x])); y_spawns[x]--; var ball = null; var type = tile.properties.type || "random"; if (forceType !== true) type = "random"; if (type === "random") { ball = this._ballContainer.AddRandomBall(position); } else { ball = this._ballContainer.AddBall(position, type); } tile.occupier = ball; ball.MoveTo(tile.position); ball.state = ballpit.BallStates.MOVING; } } } } }; /** * @method _SpawnColumn * @memberof BallController * @public * @param {Number} tileX - The x position of the column the controller needs to restore. * @param {Boolean} [forceType = false] */ p._spawnColumn = function (tileX, forceType) { var len = this._rows.length; for (var y = len -1; y >= 0; y--) { var row = this._rows[y]; var row_len = row.length; for (var x = 0; x < row_len ; x++) { if (x === tileX) { var tile = row[x]; if (this.CanMove(tile) === false) { var position = this._layer.TilePositionToScreenPosition(new Vector2(tile.tileposition.x, tile.tileposition.y)); var ball = null; var type = tile.properties.type || "random"; if (forceType !== true) type = "random"; if (type === "random") { ball = this._ballContainer.AddRandomBall(position); } else { ball = this._ballContainer.AddBall(position, type); } tile.occupier = ball; ball.MoveTo(tile.position); ball.state = ballpit.BallStates.MOVING; } } } } }; /** * @method CanMove * @memberof BallController * @param {TileModel} tile * @returns {Boolean} */ p.CanMove = function (tile) { return (tile !== null && tile.occupier instanceof ballpit.BallModel); }; /** * @method CanSwap * @memberof BallController * @param {TileModel} tile * @param {TileModel} target * @returns {Boolean} */ p.CanSwap = function (tile, target) { if (!this.CanMove(tile) || !this.CanMove(target)) return false; var ball_current = tile.occupier; var ball_target = target.occupier; tile.occupier = ball_target; target.occupier = ball_current; var tile_aligned = this._helper.GetAligned(tile); var target_aligned = this._helper.GetAligned(target); tile.occupier = ball_current; target.occupier = ball_target; if (tile_aligned.length === 0 && target_aligned.length === 0) return false; else return true; }; /** * @method _OnBallDestinationReached * @memberof BallController * @private * @param {Object} caller - The caller of the event * @param {Object} params - The parameters the caller has given. * @param {BallModel} params.ball * @ignore */ p._onBallDestinationReached = function (caller, params) { var tile_current = this._layer.GetTileByOccupier(params.ball); var ball_current = params.ball; ball_current.position = tile_current.position.Clone(); ball_current.state = ballpit.BallStates.IDLING; var aligned = this._helper.GetAligned(tile_current, ball_current.type); if (aligned.length > 0) { Listener.Dispatch(ballpit.Event.ON_BALL_ALIGN, this, { "owner": tile_current, "aligned": aligned }); } }; /** * @method _OnBallAlign * @memberof BallController * @private * @param {Object} caller - The caller of the event * @param {Object} params - The parameters the caller has given. * @param {TileModel} params.owner * @param {Array} params.aligned - Array of TIleModels that are aligned with the owner. * @ignore */ p._onBallAlign = function (caller, params) { var tiles = params.aligned; var rowsAffected = []; tiles.push(params.owner); var len = tiles.length; for (var i = len - 1; i >= 0; i--) { var tile = tiles[i]; var occupier = tile.occupier; this._ballContainer.RemoveBall(occupier); tiles[i].occupier = null; if (!rowsAffected.contains(tile.tileposition.x)) { rowsAffected.push(tile.tileposition.x); } } var col_len = rowsAffected.length; for (var j = 0; j < col_len; j++) { this.DropColumn(rowsAffected[j]); this.RestoreColumn(rowsAffected[j]); } }; /** * @method Dispose * @memberof BallController * @public */ p.Dispose = function () { delete this._layer; delete this._ballContainer; delete this._rows; this._helper.Dispose(); delete this._helper; Listener.Mute(ballpit.Event.ON_BALL_ALIGN, this); Listener.Mute(ballpit.Event.ON_BALL_DESTINATION_REACHED, this); }; return BallController; })();
kevinboogaard/Sports_World-Ball_Pit
advancedgames.ballpit.game/src/controllers/ballcontroller.js
JavaScript
mit
11,441
/** * Created by Administrator on 2017-09-25. */ /** * Created by Administrator on 2017-09-18. */ require(['common', 'jquery.metisMenu', 'layui', 'layers','ajaxurl','tools','text!/assets/popup/nodel-source.html', 'text!/assets/popup/del-source.html',], function (common, undefined, layui, layer,ajaxurl,tool,nodelSource,delSource) { var main = { /** * 表单提交 */ createForm: function () { var that = this; layui.use(['form'], function () { var form = layui.form; //添加客户备注 form.on('submit(formAddRemark)', function(data){ // console.log(data.field.mark_name) var x ,temp = []; for (x in data.field){ if(data.field[x] == ''){ layer.toast('请输入内容!', { icon: 2, anim: 6 }); return false; } temp.push(data.field[x]); } var nary = temp.sort(); for(var j=0,len=nary.length-1;j<len;j++){ if($.trim(nary[j])== $.trim(nary[j+1])){ layer.toast('内容重复,请从新输入!', { icon: 2, anim: 6 }); return false; } } that.addRemark(vm.sourceInfo); that.sourceDele(vm.sourceId); return false; }); }); }, /* 获取列表数据 */ getSourceInfo: function() { tool.ajax({ url:ajaxurl.setting.sourceView, type:'get', success:function(result){ if(result.code == 1 ){ var temp = []; if(result.data.list == null){ temp.push({name: '', err: ''}); }else{ var lens = result.data.list.length; if(lens){ for(var i = 0; i < lens; i++){ temp.push({name: result.data.list[i].name, id:result.data.list[i].id,cid:result.data.list[i].cid}); } } } vm.sourceInfo = temp; main.createForm(); }else{ layers.toast(result.message); } } }); }, /** * [sourceDele description] 提交删除id来源 */ sourceDele:function(data){ tool.ajax({ url: ajaxurl.setting.sourceDele, data:{ id:data, }, type: 'post', success: function(result){ if(result.code == 1){ // layer.toast('删除成功!', { // icon: 1, // anim: 1 // }); // setTimeout(function() { // common.closeTab(); // }, 1000); }else{ layer.toast(result.message); } } }); return false; }, /** * [addRemark description] 提交编辑来源 */ addRemark:function(data){ tool.ajax({ url: ajaxurl.setting.sourceEdit, data:{ data:data, }, type: 'post', success: function(result){ if(result.code == 1){ layer.toast('编辑成功!', { icon: 1, anim: 1 }); setTimeout(function() { common.closeTab(); }, 1000); }else{ // vm.tipsRemarkWord = result.message layer.toast(result.message); } } }); return false; }, /** * [addRemark description] 查询来源 */ sourceCheck:function(indexs,id,that){ tool.ajax({ url: ajaxurl.setting.sourceCheck, data:{ id:id, }, type: 'post', success: function(result){ if(result.code == 1){ //检测出此来源没有客户绑定,弹窗 main.delSource(indexs,id,that); }else{ //有客户绑定 弹窗 main.nodelSource(); } } }); return false; }, /** * 有客户使用此来源弹窗 */ nodelSource: function () { layer.confirm({ title: '提示', btn: ['确定'], content: nodelSource, btn1: function(index, layero){ // btn 1 确定回调 } }); }, /** * 无客户使用此来源弹窗 */ delSource: function (indexs,id,that) { layer.confirm({ title: '提示', content: delSource, btn2: function(index, layero){ // btn 1 确定回调 that.sourceInfo.splice(indexs, 1); console.log(id) if(id){ vm.sourceId.push({id:id}); } } }); }, Customer:function(num){ if (!num) { layer.toast('请输入内容!', { icon: 2, anim: 6 }); return false; } } }; /* 实例化vue */ var vm = new Vue({ el: "#app", data: { sourceInfo: { name:'', id:'', cid:'' }, sourceId: [], addRemarkShow: false, addRemarkVal: '',//客户备注的错误提示 addGroupShow: false, //客户分组是否显示 }, methods: { //增加input框 addInput: function(){ this.sourceInfo.push({name:'',id:0,cid:''}); }, //删除 removeMobile: function(index){ var that = this,id = this.sourceInfo[index].id; main.sourceCheck(index,id,that); }, //input失去焦点验证 checkCustomer:function(event,num,index){ main.Customer(num); }, // 取消数据提交 cancelAdd:function(){ common.closeTab(); }, }, }); var _init = function() { main.getSourceInfo(); }; _init(); });
ifyour/Mr.Stock.CRM
js/app/configure-source.js
JavaScript
mit
7,605
'use strict'; /** * Removes server error when user updates input */ angular.module('familyConnectionApp') .directive('mongooseError', function () { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attrs, ngModel) { element.on('keydown', function() { return ngModel.$setValidity('mongoose', true); }); } }; });
binarysqueeze/family-connections-mean-stack
client/components/mongoose-error/mongoose-error.directive.js
JavaScript
mit
400
var i2c = require('i2c'); //the address of the wire var HMC5883l_ADDR = 0x1e; var HMC5883l_CRA = 0x00; var HMC5883l_CRB = 0x01; var HMC5883l_MODE = 0x02; var HMC5883l_DATA_X_MSB = 0x03; var HMC5883l_DATA_X_LSB = 0x04; var HMC5883l_DATA_Z_MSB = 0x05; var HMC5883l_DATA_Z_LSB = 0x06; var HMC5883l_DATA_Y_MSB = 0x07; var HMC5883l_DATA_Y_LSB = 0x08; var HMC5883l_STATUS = 0x09; var HMC5883l_ID_A = 0x0A; var HMC5883l_ID_B = 0x0B; var HMC5883l_ID_C = 0x0C; var HMC5883l_READ = 0x3D; var HMC5883l_WRITE = 0x3C; var x_offset = -10; var y_offset = 10; var scale = 0.92; var x_out = -1; var y_out = -1; var z_out = -1; var bearing = -1; var exports = module.exports = {} ; var i2cdevice; exports.Initialize = function(Callback) { //sets up the device i2cdevice = new i2c(HMC5883l_ADDR, {device: '/dev/i2c-1'}); i2cdevice.setAddress(HMC5883l_ADDR); Callback(); } exports.SetUp = function(Callback) { console.log("Starting setup") var bytes = [HMC5883l_CRA, 0x70]; WriteData(HMC5883l_WRITE, bytes, function(err) { bytes = [HMC5883l_CRB, 0xA0]; WriteData(HMC5883l_WRITE, bytes, function(err) { bytes = [HMC5883l_MODE, 0x00]; WriteData(HMC5883l_WRITE, bytes, function(err) { console.log("Successful setup"); }); }); }); Callback(); } function ReadData(Register, Bytes, Callback) { i2cdevice.readBytes(Register, Bytes, function(err, data) { var ParsedData; if(Bytes == 1) { ParsedData = data.readUInt8(0); } else if(Bytes == 2) { ParsedData = data.readUInt16BE(0); } Callback(err, ParsedData); }); } //sends the LSB first. The device wants the MSB first. function WriteData(Register, ByteArray, Callback) { i2cdevice.writeBytes(Register, ByteArray, function(err) { Callback(err); }); } exports.readX = function(Callback) { ReadData(HMC5883l_DATA_X_MSB, 1, function(err, data) { x_out = (data - x_offset+2) * scale; Callback(err, x_out); }); } exports.readY = function(Callback) { ReadData(HMC5883l_DATA_X_MSB, 1, function(err, data) { y_out = (data - y_offset+2) * scale; Callback(err, y_out); }); } exports.readZ = function(Callback) { ReadData(HMC5883l_DATA_X_MSB, 1, function(err, data) { z_out = data * scale; Callback(err, z_out); }); } exports.bearing = function(Callback) { readX(function(err, data){ console.log(data); }); readY(function(err, data){ console.log(data); }); bearing = Math.atan2(y_out, x_out) + .48; if(bearing < 0) { bearing += 2 * Math.PI; } bearing = bearing * (180 / Math.PI); Callback(bearing); }
argonauthills/hmc5883l
hmc2.js
JavaScript
mit
2,700
var path = require('path'); // Cargar ORM var Sequelize = require('sequelize'); // Usar BBDD SQLite: // DATABASE_URL = sqlite:/// // DATABASE_STORAGE = quiz.sqlite // Usar BBDD Postgres: // DATABASE_URL = postgres://user:passwd@host:port/database var url, storage; if (!process.env.DATABASE_URL) { url = "sqlite:///"; storage = "quiz.sqlite"; } else { url = process.env.DATABASE_URL; storage = process.env.DATABASE_STORAGE || ""; } var sequelize = new Sequelize(url, { storage: storage, omitNull: true }); // Importar la definicion de la tabla Quiz de quiz.js var Quiz = sequelize.import(path.join(__dirname,'quiz')); // Importar la definicion de la tabla Comments de comment.js var Comment = sequelize.import(path.join(__dirname,'comment')); // Importar la definicion de la tabla Users de user.js var User = sequelize.import(path.join(__dirname,'user')); // Importar la definicion de la tabla Attachments de attachment.js var Attachment = sequelize.import(path.join(__dirname,'attachment')); // Favoritos: // Un Usuario tiene muchos quizzes favoritos. // Un quiz tiene muchos fans (los usuarios que lo han marcado como favorito) User.belongsToMany(Quiz, {as: 'Favourites', through: 'Favourites'}); Quiz.belongsToMany(User, {as: 'Fans', through: 'Favourites'}); // Relaciones entre modelos Comment.belongsTo(Quiz); Quiz.hasMany(Comment); // Relacion 1 a N entre User y Quiz: User.hasMany(Quiz, {foreignKey: 'AuthorId'}); Quiz.belongsTo(User, {as: 'Author', foreignKey: 'AuthorId'}); // Relacion 1-a-1 ente Quiz y Attachment Attachment.belongsTo(Quiz); Quiz.hasOne(Attachment); // Relacion 1 a N entre User y Comment Comment.belongsTo(User, {as: 'Author', foreignKey: 'AuthorId'}); User.hasMany(Comment, {foreignKey: 'AuthorId'}) exports.Quiz = Quiz; // exportar definición de tabla Quiz exports.Comment = Comment; // exportar definición de tabla Comments exports.User = User; // exportar definición de tabla Users exports.Attachment = Attachment; // exportar definición de tabla Attachments
alexchaniz/Quiz2016
models/index.js
JavaScript
mit
2,157
/** * Created by zad on 17/4/25. */ import {COUNT} from '../../constants/ActionTypes'; export function countAdd() { return {type: COUNT.COUNT_ADD_SYNC}; } export function countAddAsync() { return {type: COUNT.COUNT_ADD_ASYNC}; } export function countMinus() { return {type: COUNT.COUNT_MINUS_SYNC}; }
zadzbw/webpack2-react-demo
src/actions/Count/CountAction.js
JavaScript
mit
312
// test-exports.js // © 2013 Harald Rudell <harald@therudells.com> MIT License var gExports = require('../tasks/exports') // https://github.com/haraldrudell/mochawrapper var assert = require('mochawrapper') exports['Exports:'] = { 'Exports': function () { assert.exportsTest(gExports, 0, null, 'function') }, 'TODO': function () { }, }
haraldrudell/grunts
test/test-exports.js
JavaScript
mit
347
require('browser-env')(['window', 'document', 'navigator']) document.body.innerHTML = ` <select id="basic"> <option value="1 a">a</option> <option value="2 b" data-placeholder>b</option> <option value="3 c">c</option> </select> <select name="" id="secondary"> <option value="1">e</option> <option value="2">d</option> <option value="3">f</option> <option value="4">g</option> <option value="5">y</option> </select> <select name="" id="third"> <option>e</option> <option value="2">d</option> <option value="3">f</option> <option value="4">g</option> <option value="5'4">y</option> </select> <select name="" id="nasty"> <option value="{&quot;id&quot;: &quot;13&quot;, &quot;text&quot;:&quot;十堰市&quot;}">十堰市</option> <option value="{&quot;id&quot;: &quot;14&quot;, &quot;text&quot;:&quot;咸宁市&quot;}">咸宁市</option> <option value="{&quot;id&quot;: &quot;15&quot;, &quot;text&quot;:&quot;孝感市&quot;}">孝感市</option> <option value="{&quot;id&quot;: &quot;16&quot;, &quot;text&quot;:&quot;宜昌市&quot;}">宜昌市</option> <option value="{&quot;id&quot;: &quot;17&quot;, &quot;text&quot;:&quot;恩施土家族苗族自治州&quot;}">恩施土家族苗族自治州</option> <option value="{&quot;id&quot;: &quot;18&quot;, &quot;text&quot;:&quot;武汉市&quot;}">武汉市</option> <option value="{&quot;id&quot;: &quot;19&quot;, &quot;text&quot;:&quot;省直辖行政单位&quot;}">省直辖行政单位</option> <option value="{&quot;id&quot;: &quot;20&quot;, &quot;text&quot;:&quot;荆州市&quot;}">荆州市</option> <option value="{&quot;id&quot;: &quot;21&quot;, &quot;text&quot;:&quot;荆门市&quot;}">荆门市</option> <option value="{&quot;id&quot;: &quot;22&quot;, &quot;text&quot;:&quot;襄樊市&quot;}">襄樊市</option> <option value="{&quot;id&quot;: &quot;23&quot;, &quot;text&quot;:&quot;鄂州市&quot;}">鄂州市</option> <option value="{&quot;id&quot;: &quot;24&quot;, &quot;text&quot;:&quot;随州市&quot;}">随州市</option> <option value="{&quot;id&quot;: &quot;25&quot;, &quot;text&quot;:&quot;黄冈市&quot;}">黄冈市</option> <option value="{&quot;id&quot;: &quot;26&quot;, &quot;text&quot;:&quot;黄石市&quot;}">黄石市</option> </select> `
kajyr/jquery-prettyselect
tests/helpers/setup-browser-env.js
JavaScript
mit
2,465
/*jslint nomen:true*/ /*global define*/ define([ 'underscore', 'backbone', 'orotranslation/js/translator', 'oroui/js/mediator', 'oroui/js/messenger', 'oroconfig/js/form/default', 'oroui/js/modal', 'jquery' ], function(_, Backbone, __, mediator, messenger, formDefault, Modal, $) { 'use strict'; /** * @extends Backbone.View */ return Backbone.View.extend({ defaults: { pageReload: false }, events: { 'click :input[type=reset]': 'resetHandler', 'submit': 'submitHandler' }, /** * @param options Object */ initialize: function(options) { this.options = _.defaults(options || {}, this.defaults, this.options); formDefault(); }, /** * Resets form and default value checkboxes. * * @param event */ resetHandler: function(event) { var $checkboxes = this.$el.find('.parent-scope-checkbox input'); var confirm = new Modal({ title: __('Confirmation'), okText: __('OK'), cancelText: __('Cancel'), content: __('Settings will be restored to saved values. Please confirm you want to continue.'), className: 'modal modal-primary', okButtonClass: 'btn-primary btn-large' }); confirm.on('ok', _.bind(function() { this.$el.get(0).reset(); this.$el.find('.select2').each(function(key, elem) { var $elem = $(elem); var data = $elem.data('selected-data'); $elem.select2('val', data, true); }); $checkboxes.trigger('change'); }, this)); confirm.open(); event.preventDefault(); }, /** * Reloads page on form submit if reloadPage is set to true. */ submitHandler: function() { if (this.options.pageReload) { mediator.once('page:update', function() { messenger.notificationMessage('info', __('Please wait until page will be reloaded...')); // force reload without hash navigation window.location.reload(); }); mediator.once('page:afterChange', function() { // Show loading until page is fully reloaded mediator.execute('showLoading'); }); } } }); });
ramunasd/platform
src/Oro/Bundle/ConfigBundle/Resources/public/js/form/config-form.js
JavaScript
mit
2,651
var Put = require('bufferput'); var buffertools = require('buffertools'); var hex = function(hex) { return new Buffer(hex, 'hex'); }; exports.livenet = { name: 'livenet', magic: hex('3b423124'), addressVersion: 0x3F, privKeyVersion: 153, P2SHVersion: 85, hkeyPublicVersion: 0x02cfbede, hkeyPrivateVersion: 0x02cfbf60, genesisBlock: { hash: hex('00003e0095045e13231b44e4d5624aac6c708a23833fb653c614385cb4cb6a48'), merkle_root: hex('ecfc7fe9e53bda0f4fcb767ad8c1b82efba397d313bf4af1e245c78939dc99de'), height: 0, nonce: 89122, version: 1, prev_hash: buffertools.fill(new Buffer(32), 0), timestamp: 1431325505, bits: 520159231, }, dnsSeeds: [ 'node1.shellcoinwallet.com', 'node2.shellcoinwallet.com', 'node3.shellcoinwallet.com', '120.25.227.124', '120.25.150.205', '62.210.105.88' ], defaultClientPort: 31000 }; exports.mainnet = exports.livenet; exports.testnet = { name: 'testnet', magic: hex('0b110907'), addressVersion: 0x6f, privKeyVersion: 239, P2SHVersion: 196, hkeyPublicVersion: 0x043587cf, hkeyPrivateVersion: 0x04358394, genesisBlock: { hash: hex('43497FD7F826957108F4A30FD9CEC3AEBA79972084E90EAD01EA330900000000'), merkle_root: hex('3BA3EDFD7A7B12B27AC72C3E67768F617FC81BC3888A51323A9FB8AA4B1E5E4A'), height: 0, nonce: 414098458, version: 1, prev_hash: buffertools.fill(new Buffer(32), 0), timestamp: 1296688602, bits: 486604799, }, dnsSeeds: [ 'testnet-seed.bitcoin.petertodd.org', 'testnet-seed.bluematt.me' ], defaultClientPort: 18333 };
shellpay/bitcore
networks.js
JavaScript
mit
1,584
$.fn.get = function(index) { return typeof index == "number" ? this.objects[index] : this.objects; };
Zoweb/SJQ
src/fn/get.js
JavaScript
mit
105
/********************************************************************************************************************* * * Various DOM utilities. * *********************************************************************************************************************/ /** * Wraps one element in another. * * @param {HTMLElement} el - the element to be wrapped * @param {HTMLElement} elWrap - the element with which to wrap it. */ function wrap( el, elWrap ) { // 1. insert the wrapper el.parentNode.insertBefore( elWrap, el ); // 2. detatch + reattatch el.parentNode.removeChild(el); elWrap.appendChild(el); } /** * Creates a new element based on the given name and attributes. * * @param {string} sElement - the name of the element to create. * @param {object} oAttr - an object containing attributes to add (optional) * @param {string} sContent - any content to insert (optional) * @return {HTMLElement} the newly-created element. */ function create( sElement, oAttr = {}, sContent = null ) { // 1. create the element const el = document.createElement( sElement ); // 2. if we have any classes if ( oAttr.class !== undefined ) { oAttr.class.split( /\s+/ ).forEach( sC => el.classList.add( sC )); delete oAttr.class; } // 3. everything else… Object.keys( oAttr ).forEach( k => { el.setAttribute( k, oAttr[k] ); }) // 4. insert content, where applicable if (sContent !== null) { el.appendChild( document.createTextNode( sContent )); } return el; } /** * Removes all children from an element. * * @param {HTMLElement} el - the element to remove */ function empty( el ) { while (el.firstChild !== null) { el.firstChild.remove(); } } /** * Binds multiple event listeners in one go. This is similar to jQuery on(), only in vanilla JS. * * @param {HTMLElement} el - the element to bind on * @param {String} sEvents - a space-separated list of events to bind. * @param {callable} fnListener - the listener to bind. */ function multibind( el, sEvents, fnListener ) { sEvents.trim().split( /\s+/ ).forEach( sEv => el.addEventListener( sEv, fnListener )); } /** * Like querySelectorAll, but also includes the top-level node if it matches the selector. * * @param {HTMLElement} elNode - the element to search from. * @param {String} sSelector - the selector to search for. * @return {Array} an array (not nodelist) of matching elements. */ function querySelectorAllWithSelf( elNode, sSelector ) { // 0. sanity check if ( elNode.querySelectorAll === undefined ) { return []; } // 1. normal query const aElMatches = [].slice.call( elNode.querySelectorAll( sSelector )); // 2. push, if we also match if ( elNode.matches( sSelector )) { aElMatches.unshift( elNode ); } return aElMatches; } module.exports = { wrap, create, empty, multibind , querySelectorAllWithSelf };
jonpearse/jonpearse.net
app/assets/javascripts/util/dom-utils.js
JavaScript
mit
2,918
function date_time(id) { date = new Date; year = date.getFullYear(); month = date.getMonth(); months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'Jully', 'August', 'September', 'October', 'November', 'December'); d = date.getDate(); day = date.getDay(); days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); h = date.getHours(); if(h<10) { h = "0"+h; } m = date.getMinutes(); if(m<10) { m = "0"+m; } s = date.getSeconds(); if(s<10) { s = "0"+s; } result_date = ''+days[day]+', '+months[month]+' '+d; document.getElementById(id).innerHTML = result_date; setTimeout('date_time("'+id+'");','1000'); return true; }
luiighi2693/karma
karmathegame/js/date_time.js
JavaScript
mit
928
var worstSeries = []; for (i = 0; i < worstIssuers.length; i++) { worstSeries.push(timeseries[worstIssuers[i]]); } var top10series = []; for (i = 0; i < topIssuers.length; i++) { top10series.push(timeseries[topIssuers[i]]); } var filteredIssuers = []; function filterIssuers() { // clear filteredIssuers but keep aliases to it while (filteredIssuers.length > 0) { filteredIssuers.shift(); } filteredIssuers.push("Worst CAs"); filteredIssuers.push("Top 10 CAs"); var sliderValue = document.getElementById("minimumIssuance").value; var minimumIssuance = Math.ceil(Math.pow(maxIssuance, sliderValue / 100)); var output = document.getElementById("minimumIssuanceOutput"); output.value = minimumIssuance; var issuerInMozillaDB = document.getElementById("issuerInMozillaDB").checked; for (var index in issuers) { var issuer = issuers[index]; if (issuer.totalIssuance >= minimumIssuance && issuer.issuerInMozillaDB == issuerInMozillaDB) { filteredIssuers.push(issuer.issuer); } } } $('#autocomplete').autocomplete({ source: filteredIssuers, minLength: 0, select: function(event, suggestion) { makeChart(suggestion.item.value); } }); function escapeName(name) { return name.replace(/[^A-Za-z0-9]/g, "_").replace(/(^[0-9])/, "_$1"); } function getChartData(name, continuation) { var escapedName = escapeName(name); var req = new XMLHttpRequest(); req.open("GET", "data/" + escapedName + ".json", true); req.onreadystatechange = function() { if (req.readyState == XMLHttpRequest.DONE && req.status == 200) { var data = JSON.parse(req.responseText); continuation(data); } }; req.send(); } var commonLegend = { enabled: true, layout: "vertical", align: "right", verticalAlign: "middle", borderWidth: 2 }; function makeChart(name) { clearExamples(); var commonYAxis = [{ max: 1.0, min: 0.0 }, { min: 0, opposite: false }]; if (name == "Worst CAs") { new Highcharts.StockChart({ legend: commonLegend, series: worstSeries, yAxis: commonYAxis }); } else if (name == "Top 10 CAs") { var top10tsChart = new Highcharts.StockChart({ legend: commonLegend, series: top10series, yAxis: commonYAxis }); document.getElementById("autocomplete").value = name; } else { getChartData(name, function(seriesAndExamples) { new Highcharts.StockChart({ legend: commonLegend, series: seriesAndExamples.series, yAxis: commonYAxis }); makeExamples(seriesAndExamples.examples); var checkbox = document.getElementById("issuerInMozillaDB"); checkbox.checked = issuers[escapeName(name)].issuerInMozillaDB; }); } document.getElementById("autocomplete").value = name; var search = "?" + encodeURIComponent(name); history.replaceState(null, "", location.origin + location.pathname + search); } function clearChildren(id) { var element = document.getElementById(id); while (element.children.length > 0) { element.children[0].remove(); } } function clearExamples() { clearChildren("examplesHeader"); clearChildren("examplesBody"); } var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; function stringEndsWith(string, suffix) { if (suffix.length > string.length) { return false; } var index = string.indexOf(suffix, string.length - suffix.length); return index != -1; } function makeExamples(examples) { // e.g. 'COMODO ECC Domain Validation Secure Server CA 2' has a perfect // score, so there are no examples of bad certificates issued by it. if (!examples) { return; } var examplesHeader = document.getElementById("examplesHeader"); var examplesBody = document.getElementById("examplesBody"); var exampleTypes = []; for (var key of Object.keys(examples)) { if (stringEndsWith(key, "Example") && examples[key]) { exampleTypes.push(key.substring(0, key.indexOf("Example"))); } } for (var example of exampleTypes) { var header = document.createElement("th"); var lastSeen = new Date(examples[example + "LastSeen"]); header.textContent = example + " (last seen " + lastSeen.getDate() + " " + months[lastSeen.getMonth()] + " " + lastSeen.getFullYear() + ")"; examplesHeader.appendChild(header); var td = document.createElement("td"); var pem = examples[example + "Example"] .replace(/[\r\n]/g, "") .replace(/-----(BEGIN|END) CERTIFICATE-----/g, ""); var frame = document.createElement("iframe"); frame.width = "600px"; frame.height = "600px"; frame.src = "certsplainer/?" + pem; td.appendChild(frame); examplesBody.appendChild(td); } } // Strangely, it looks like passing in values for legend and yAxis don't work, // so they have to be specified with each chart created. Highcharts.setOptions({ chart: { renderTo: "timeseries" } }); filterIssuers(); makeChart(location.search ? decodeURIComponent(location.search.substring(1)) : filteredIssuers[0]);
mozkeeler/sunlight
dashboard/index.js
JavaScript
mit
5,151
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.services' is found in services.js // 'starter.controllers' is found in controllers.js angular.module('starter', ['ionic', 'starter.controllers', 'starter.services']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleLightContent(); } }); }) .config(function($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider // setup an abstract state for the tabs directive .state('tab', { url: "/tab", abstract: true, templateUrl: "templates/tabs.html" }) // Each tab has its own nav history stack: .state('tab.devices', { url: '/devices', views: { 'tab-devices': { templateUrl: 'templates/tab-devices.html', controller: 'DevicesCtrl' } } }) .state('tab.device-detail', { url: '/devices/:id', views: { 'tab-devices': { templateUrl: 'templates/device-detail.html', controller: 'DeviceCtrl' } } }) .state('tab.settings', { url: '/settings', views: { 'tab-settings': { templateUrl: 'templates/tab-settings.html', controller: 'SettingsCtrl' } } }) .state('tab.settings-detail', { url: '/settings/:setting', views: { 'tab-settings': { templateUrl: 'templates/settings-detail.html', controller: 'SettingsDetailCtrl' } } }); // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/tab/devices'); });
baritonehands/TinyScreen_Smartwatch_Ionic
www/js/app.js
JavaScript
mit
2,393
/** * Created by jason on 9/12/14. */ // I act a repository for the remote friend collection. angular.module('core').service( "CoreDialogsService", function( $http, $q ) { // Return public API. return({ CreateNutritionProfileInstanceCtrl: CreateNutritionProfileInstanceCtrl, StartTourDialogCtrl: StartTourDialogCtrl }); // --- // PUBLIC METHODS. // --- function StartTourDialogCtrl($scope, $modalInstance) { $scope.ok = function () { $modalInstance.close(); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }; function CreateNutritionProfileInstanceCtrl($scope, $modalInstance){ $scope.nutritionProfile = {}; $scope.sexOptions = [ 'Male', 'Female' ]; $scope.heightFeetOptions = [ 1, 2, 3, 4, 5, 6, 7, 8]; $scope.heightInchesOptions = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; $scope.selected = { nutritionProfile: $scope.nutritionProfile, deficitTarget: $scope.deficitTarget, proteinPercentageTarget: $scope.proteinPercentageTarget, carbohydratesPercentageTarget: $scope.carbohydratesPercentageTarget, fatPercentageTarget: $scope.fatPercentageTarget, age: $scope.age, heightFeet: $scope.heightFeet, heightInches: $scope.heightInches, gender: $scope.gender, weight: $scope.weight }; $scope.ok = function () { $modalInstance.close($scope.selected); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }; // --- // PRIVATE METHODS. // --- // I transform the successful response, unwrapping the application data // from the API response payload. function handleSuccess( response ) { return response.data; } // I transform the error response, unwrapping the application dta from // the API response payload. function handleError( response ) { // The API response from the server should be returned in a // nomralized format. However, if the request was not handled by the // server (or what not handles properly - ex. server error), then we // may have to normalize it on our end, as best we can. if ( ! angular.isObject( response.data ) || ! response.data.message ) { return( $q.reject( "An unknown error occurred." ) ); } // Otherwise, use expected error message. return( $q.reject( response.data.message ) ); } } );
jre247/NutritionManager
public/modules/core/services/coreDialogsService.client.service.js
JavaScript
mit
2,995
import axios from 'axios'; import { getCookie } from '../actions/common'; import { hostname } from '../actions/index'; export function getForm(form_id, option) { if(option) { let config = { 'headers': { 'Authorization': ('JWT ' + getCookie('fb_sever_token')) } } if(option.useAuthorize) { axios.get(`${hostname}form?id=${form_id}`, config).then((data) => { if(typeof(option.callbackDone) === "function") option.callbackDone(data.data); return true; }, (error) => { if(typeof(option.callbackError) === "function") option.callbackError(error); return false; }); } else { axios.get(`${hostname}form?id=${form_id}`).then((data) => { if(typeof(option.callbackDone) === "function") option.callbackDone(data.data); return true; }, (error) => { if(typeof(option.callbackError) === "function") option.callbackError(error); return false; }); } } return false; } export function CreateFrom(bodyData, option) { let config = { 'headers': { 'Authorization': ('JWT ' + getCookie('fb_sever_token')) } } axios.post(`${hostname}form`, bodyData, config).then((response) => { if(option && typeof(option.callbackDone) === "function") option.callbackDone(response); return true; }, (error) => { if(option && typeof(option.callbackError) === "function") option.callbackError(response); return false; }) } export function EditForm(bodyData, option) { return CreateFrom(bodyData, option); } export function saveResponse(form_id, responseBody, option) { let config = { 'headers': { 'Authorization': ('JWT ' + getCookie('fb_sever_token')) } } axios.put(`${hostname}form?id=${form_id}`, responseBody, config).then((response) => { if(option && typeof(option.callbackDone) === "function") option.callbackDone(response); return true; }, (error) => { if(option && typeof(option.callbackError) === "function") option.callbackError(response); return false; }) } export function deleteForm(form_id, option) { let config = { 'headers': { 'Authorization': ('JWT ' + getCookie('fb_sever_token')) } } axios.delete(`${hostname}form`, config).then((response) => { if(option && typeof(option.callbackDone) === "function") option.callbackDone(response); return true; }, (error) => { if(option && typeof(option.callbackError) === "function") option.callbackError(response); return false; }) }
thipokKub/Clique-WebFront-Personnal
src/container/auxlillaryForm.js
JavaScript
mit
2,792
var _instance = null; function IO(config) { if (_instance) return _instance.plugins; this.config = config || {}; this.info('Initializing IO ...'); this.plugins = {}; this.pub = {}; this.info('Initializing Plugins ...'); for (var i in this.config.plugins) { if (!this.loadPlugin(this.config.plugins[i])) throw "Unable to initalize IO"; } this.info('IO successfully initialized'); _instance = this; return this.pub; } /* @desc: Register plugin */ IO.prototype.register = function(name, fnName, fn) { if (!this.plugins.hasOwnProperty(name)) { this.plugins[name] = {}; this.pub[name] = {}; this.config[name] = this.config[name] || {}; } if (fnName || fn) { if (this.plugins[name][fnName]) console.log('Warning -> [' + fnName + '] already declared for plugin [' + name + ']'); this.plugins[name][fnName] = fn; if (fnName.indexOf('_') !== 0) this.pub[name][fnName] = fn; } return this.register.bind(this, name); }; /* @desc: Initialise plugin */ IO.prototype.loadPlugin = function(name) { var plugin = null; var fn = null; var _call = [this]; if (this.plugins[name]) return true; // Load plugin try { plugin = require(__dirname + '/../io-' + name); } catch (e) { this.debug('Unable to load plugin [' + name + '][' + e.message + ']'); return false; } // If no deps, instanciate directly if (typeof plugin === "function") { fn = plugin; } else if (Array.isArray(plugin) && (fn = plugin.splice(plugin.length - 1)[0]) && typeof fn === 'function') { for (var i in plugin) { if (!this.plugins[plugin[i]] && !this.loadPlugin(plugin[i])) return false; _call.push(this.plugins[plugin[i]]); } } else { this.debug('Unable to load plugin [' + name + '][No function found]'); return false; } fn.apply(plugin, _call); return true; }; IO.prototype.info = function () { if (this.config.INFO !== false) { var now = new Date(); process.stderr.write('\033[36;1m> Info - ' + now.getDate() + '-' + (now.getMonth() + 1) + '-' + now.getFullYear() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()); process.stderr.write(':\033[0m \033[36m'); process.stderr.write('\033[0m'); console.error.apply(null, Array.prototype.slice.call(arguments)); } }; IO.prototype.debug = function () { if (this.config.DEBUG !== false) { var now = new Date(); process.stderr.write('\033[31;1m> Debug - ' + now.getDate() + '-' + (now.getMonth() + 1) + '-' + now.getFullYear() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()); process.stderr.write(':\033[0m \033[31m'); console.error.apply(null, Array.prototype.slice.call(arguments)); process.stderr.write('\033[0m'); } }; module.exports = IO;
romualdr/pinyin-game
modules/io-core/index.js
JavaScript
mit
2,708
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var sheet = require('@emotion/sheet'); var Stylis = _interopDefault(require('@emotion/stylis')); var weakMemoize = _interopDefault(require('@emotion/weak-memoize')); // https://github.com/thysultan/stylis.js/tree/master/plugins/rule-sheet // inlined to avoid umd wrapper and peerDep warnings/installing stylis // since we use stylis after closure compiler var delimiter = '/*|*/'; var needle = delimiter + '}'; function toSheet(block) { if (block) { Sheet.current.insert(block + '}'); } } var Sheet = { current: null }; var ruleSheet = function ruleSheet(context, content, selectors, parents, line, column, length, ns, depth, at) { switch (context) { // property case 1: { switch (content.charCodeAt(0)) { case 64: { // @import Sheet.current.insert(content + ';'); return ''; } // charcode for l case 108: { // charcode for b // this ignores label if (content.charCodeAt(2) === 98) { return ''; } } } break; } // selector case 2: { if (ns === 0) return content + delimiter; break; } // at-rule case 3: { switch (ns) { // @font-face, @page case 102: case 112: { Sheet.current.insert(selectors[0] + content); return ''; } default: { return content + (at === 0 ? delimiter : ''); } } } case -2: { content.split(needle).forEach(toSheet); } } }; var removeLabel = function removeLabel(context, content) { if (context === 1 && // charcode for l content.charCodeAt(0) === 108 && // charcode for b content.charCodeAt(2) === 98 // this ignores label ) { return ''; } }; var isBrowser = typeof document !== 'undefined'; var rootServerStylisCache = {}; var getServerStylisCache = isBrowser ? undefined : weakMemoize(function () { var getCache = weakMemoize(function () { return {}; }); var prefixTrueCache = {}; var prefixFalseCache = {}; return function (prefix) { if (prefix === undefined || prefix === true) { return prefixTrueCache; } if (prefix === false) { return prefixFalseCache; } return getCache(prefix); }; }); var createCache = function createCache(options) { if (options === undefined) options = {}; var key = options.key || 'css'; var stylisOptions; if (options.prefix !== undefined) { stylisOptions = { prefix: options.prefix }; } var stylis = new Stylis(stylisOptions); if (process.env.NODE_ENV !== 'production') { // $FlowFixMe if (/[^a-z-]/.test(key)) { throw new Error("Emotion key must only contain lower case alphabetical characters and - but \"" + key + "\" was passed"); } } var inserted = {}; // $FlowFixMe var container; if (isBrowser) { container = options.container || document.head; var nodes = document.querySelectorAll("style[data-emotion-" + key + "]"); Array.prototype.forEach.call(nodes, function (node) { var attrib = node.getAttribute("data-emotion-" + key); // $FlowFixMe attrib.split(' ').forEach(function (id) { inserted[id] = true; }); if (node.parentNode !== container) { container.appendChild(node); } }); } var _insert; if (isBrowser) { stylis.use(options.stylisPlugins)(ruleSheet); _insert = function insert(selector, serialized, sheet, shouldCache) { var name = serialized.name; Sheet.current = sheet; if (process.env.NODE_ENV !== 'production' && serialized.map !== undefined) { var map = serialized.map; Sheet.current = { insert: function insert(rule) { sheet.insert(rule + map); } }; } stylis(selector, serialized.styles); if (shouldCache) { cache.inserted[name] = true; } }; } else { stylis.use(removeLabel); var serverStylisCache = rootServerStylisCache; if (options.stylisPlugins || options.prefix !== undefined) { stylis.use(options.stylisPlugins); // $FlowFixMe serverStylisCache = getServerStylisCache(options.stylisPlugins || rootServerStylisCache)(options.prefix); } var getRules = function getRules(selector, serialized) { var name = serialized.name; if (serverStylisCache[name] === undefined) { serverStylisCache[name] = stylis(selector, serialized.styles); } return serverStylisCache[name]; }; _insert = function _insert(selector, serialized, sheet, shouldCache) { var name = serialized.name; var rules = getRules(selector, serialized); if (cache.compat === undefined) { // in regular mode, we don't set the styles on the inserted cache // since we don't need to and that would be wasting memory // we return them so that they are rendered in a style tag if (shouldCache) { cache.inserted[name] = true; } if ( // using === development instead of !== production // because if people do ssr in tests, the source maps showing up would be annoying process.env.NODE_ENV === 'development' && serialized.map !== undefined) { return rules + serialized.map; } return rules; } else { // in compat mode, we put the styles on the inserted cache so // that emotion-server can pull out the styles // except when we don't want to cache it which was in Global but now // is nowhere but we don't want to do a major right now // and just in case we're going to leave the case here // it's also not affecting client side bundle size // so it's really not a big deal if (shouldCache) { cache.inserted[name] = rules; } else { return rules; } } }; } if (process.env.NODE_ENV !== 'production') { // https://esbench.com/bench/5bf7371a4cd7e6009ef61d0a var commentStart = /\/\*/g; var commentEnd = /\*\//g; stylis.use(function (context, content) { switch (context) { case -1: { while (commentStart.test(content)) { commentEnd.lastIndex = commentStart.lastIndex; if (commentEnd.test(content)) { commentStart.lastIndex = commentEnd.lastIndex; continue; } throw new Error('Your styles have an unterminated comment ("/*" without corresponding "*/").'); } commentStart.lastIndex = 0; break; } } }); stylis.use(function (context, content, selectors) { switch (context) { case -1: { var flag = 'emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason'; var unsafePseudoClasses = content.match(/(:first|:nth|:nth-last)-child/g); if (unsafePseudoClasses && cache.compat !== true) { unsafePseudoClasses.forEach(function (unsafePseudoClass) { var ignoreRegExp = new RegExp(unsafePseudoClass + ".*\\/\\* " + flag + " \\*\\/"); var ignore = ignoreRegExp.test(content); if (unsafePseudoClass && !ignore) { console.error("The pseudo class \"" + unsafePseudoClass + "\" is potentially unsafe when doing server-side rendering. Try changing it to \"" + unsafePseudoClass.split('-child')[0] + "-of-type\"."); } }); } break; } } }); } var cache = { key: key, sheet: new sheet.StyleSheet({ key: key, container: container, nonce: options.nonce, speedy: options.speedy }), nonce: options.nonce, inserted: inserted, registered: {}, insert: _insert }; return cache; }; exports.default = createCache;
jpoeng/jpoeng.github.io
node_modules/@emotion/cache/dist/cache.cjs.dev.js
JavaScript
mit
8,359
module.exports = { "req": { "method": "get", "path": "/movies" }, "res": { "status": 200, "body": function(ctx){ ctx.body = ("Hello world!") }, "headers": { "Content-Type": "text/plain" } } }
apiejs/apik
routes/movies.js
JavaScript
mit
241
/* * Performance test suite using benchmark.js */ require([ "external/benchmark/benchmark", "external/requirejs-domready/domReady!", "external/requirejs-text/text!selectors.css" ], function( Benchmark, document, selectors ) { // Convert selectors to an array selectors = selectors.split("\n"); var // Used to indicate whether console profiling is begin run profiling, trim, // Class manipulation // IE doesn't match non-breaking spaces with \s rtrim = /\S/.test("\xA0") ? (/^[\s\xA0]+|[\s\xA0]+$/g) : /^\s+|\s+$/g, rspaces = /\s+/, ptrim = String.prototype.trim, // Test HTML file name in the data folder testHtml = "selector", // Construct search parameters object urlParams = (function() { var parts, value, params = {}, search = location.search.substring(1).split("&"), i = 0, len = search.length; for ( ; i < len; i++ ) { parts = search[i].split("="); value = parts[1]; // Cast booleans and treat no value as true params[ decodeURIComponent(parts[0]) ] = value && value !== "true" ? value === "false" ? false : decodeURIComponent( value ) : true; } return params; })(), // Whether to allow the use of QSA by the selector engines useQSA = urlParams.qsa || false, // Benchmark options maxTime = 0.5, minSamples = 3, // Keep track of all iframes iframes = {}, // Keeps track of which benches had errors errors = {}, // Selector engines engines = { "qsa": "d.querySelectorAll( s )", 'asdf':'Asdf.Selector.select(s,d)', //"jquery-1.7.2/jquery": "jQuery.find( s, d )", // "jquery-1.8.3/jquery": "jQuery.find( s, d )", //"sizzle-old/sizzle": "Sizzle( s, d )", "sizzle/sizzle": "Sizzle( s, d )", // "dojo/dojo": "dojo.query( s, d )", "mootools-slick/slick": "Slick.search( d, s )" //"nwmatcher/nwmatcher": "NW.Dom.select( s, d )" }, // Keeps track of overall scores scores = (function() { var engine, scores = {}; for ( engine in engines ) { scores[ engine ] = 0; } return scores; })(), // Keeps track of the number of elements returned returned = (function() { var engine, returned = {}; for ( engine in engines ) { returned[ engine ] = {}; } return returned; })(), // Just counts the engines numEngines = (function() { var engine, count = 0; for ( engine in engines ) { count++; } return count; })(), selectorIndex = 0; // Expose iframeCallbacks window.iframeCallbacks = {}; /** * Trim leading and trailing whitespace * * @private * @param {String} str The string to trim */ trim = ptrim ? function( str ) { return ptrim.call( str ); } : function( str ) { return str.replace( rtrim, "" ); }; /** * A shortcut for getElementById * * @private * @param {String} id The ID with which to query the DOM */ function get( id ) { return document.getElementById( id ); } /** * Adds the given class to the element if it does not exist * * @private * @param {Element} elem The element on which to add the class * @param {String} classStr The class to add */ function addClass( elem, classStr ) { classStr = classStr.split( rspaces ); var c, cls = " " + elem.className + " ", i = 0, len = classStr.length; for ( ; i < len; ++i ) { c = classStr[ i ]; if ( c && cls.indexOf(" " + c + " ") < 0 ) { cls += c + " "; } } elem.className = trim( cls ); } /** * Removes a given class on the element * * @private * @param {Element} elem The element from which to remove the class * @param {String} classStr The class to remove */ function removeClass( elem, classStr ) { var cls, len, i; if ( classStr !== undefined ) { classStr = classStr.split( rspaces ); cls = " " + elem.className + " "; i = 0; len = classStr.length; for ( ; i < len; ++i ) { cls = cls.replace(" " + classStr[ i ] + " ", " "); } cls = trim( cls ); } else { // Remove all classes cls = ""; } if ( elem.className !== cls ) { elem.className = cls; } } /** * Runs the console profiler if available * * @param {String} name The name of the profile */ function profile( name ) { if ( window.console && typeof console.profile !== "undefined" && !profiling ) { profiling = true; console.profile( name ); } } /** * Stops console profiling if available * * @param {String} name The name of the profile */ function profileEnd( name ) { if ( profiling ) { profiling = false; console.profileEnd( name ); } } /** * Retrieves the position of the first column * of the row that has just been tested */ function firstTestedColumn() { return selectorIndex * (numEngines + 1) + 1; } /** * Add random number to the url to stop caching * * @private * @param {String} value The url to which to add cache control * @returns {String} Returns the new url * * @example url("data/test.html") * // => "data/test.html?10538358428943" * * @example url("data/test.php?foo=bar") * // => "data/test.php?foo=bar&10538358345554" */ function url( value ) { return value + (/\?/.test( value ) ? "&" : "?") + new Date().getTime() + "" + parseInt( Math.random() * 100000, 10 ); } /** * Gets the Hz, i.e. operations per second, of `bench` adjusted for the * margin of error. * * @private * @param {Object} bench The benchmark object. * @returns {Number} Returns the adjusted Hz. */ function getHz( bench ) { return 1 / ( bench.stats.mean + bench.stats.moe ); } /** * Determines the common number of elements found by the engines. * If there are only 2 engines, this will just return the first one. * * @private * @param {String} selector The selector for which to check returned elements */ function getCommonReturn( selector ) { var engine, count, common, max = 0, counts = {}; for ( engine in returned ) { count = returned[ engine ][ selector ]; if ( count ) { count = count.length; counts[ count ] = (counts[ count ] || 0) + 1; } } for ( count in counts ) { if ( counts[ count ] > max ) { max = counts[ count ]; common = count; } } return +common; } /** * Adds all of the necessary headers and rows * for all selector engines * * @private */ function buildTable() { var engine, i = 0, len = selectors.length, headers = "<th class='small selector'>selectors</th>", emptyColumns = "", rows = ""; // Build out headers for ( engine in engines ) { headers += "<th class='text-right'>" + engine.match( /^[^/]+/ )[ 0 ] + "</th>"; emptyColumns += "<td class='text-right' data-engine='" + engine + "'>&nbsp;</td>"; } // Build out initial rows for ( ; i < len; i++ ) { rows += "<tr><td id='selector" + i + "' class='small selector'><span>" + selectors[i] + "</span></td>" + emptyColumns + "</tr>"; } rows += "<tr><td id='results' class='bold'>Total (more is better)</td>" + emptyColumns + "</tr>"; get("perf-table-headers").innerHTML = headers; get("perf-table-body").innerHTML = rows; } /** * Creates an iframe for use in testing a selector engine * * @private * @param {String} engine Indicates which selector engine to load in the fixture * @param {String} suite Name of the Benchmark Suite to use * @param {Number} callbackIndex Index of the iframe callback for this iframe * @returns {Element} Returns the iframe */ function createIframe( engine, suite, callbackIndex ) { var src = url( "./data/" + testHtml + ".html?engine=" + encodeURIComponent( engine ) + "&suite=" + encodeURIComponent( suite ) + "&callback=" + callbackIndex + "&qsa=" + useQSA ), iframe = document.createElement("iframe"); iframe.setAttribute( "src", src ); iframe.style.cssText = "width: 500px; height: 500px; position: absolute; " + "top: -600px; left: -600px; visibility: hidden;"; document.body.appendChild( iframe ); iframes[ suite ].push( iframe ); return iframe; } /** * Runs a Benchmark suite from within an iframe * then destroys the iframe * Each selector is tested in a fresh iframe * * @private * @param {Object} suite Benchmark Suite to which to add tests * @param {String} selector The selector being tested * @param {String} engine The selector engine begin tested * @param {Function} iframeLoaded Callback to call when the iframe has loaded */ function addTestToSuite( suite, selector, engine, iframeLoaded ) { /** * Run selector tests with a particular engine in an iframe * * @param {Function} r Require in the context of the iframe * @param {Object} document The document of the iframe */ function test( document ) { var win = this, select = new Function( "w", "s", "d", "return " + (engine !== "qsa" ? "w." : "") + engines[ engine ] ); suite.add( engine, function() { returned[ engine ][ selector ] = select( win, selector, document ); }); if ( typeof iframeLoaded !== "undefined" ) { iframeLoaded(); } } // Called by the iframe var index, name = suite.name, callbacks = window.iframeCallbacks[ name ]; index = callbacks.push(function() { var self = this, args = arguments; setTimeout(function() { test.apply( self, args ); }, 0 ); }) - 1; // Load fixture in iframe and add it to the list createIframe( engine, name, index ); } /** * Tests a selector in all selector engines * * @private * @param {String} selector Selector to test */ function testSelector( selector ) { var engine, suite = Benchmark.Suite( selector ), name = suite.name, count = numEngines; /** * Called when an iframe has loaded for a test. * Need to wait until all iframes * have loaded to run the suite */ function loaded() { // Run the suite if ( --count === 0 ) { suite.run(); } } // Add spots for iframe callbacks and iframes window.iframeCallbacks[ name ] = []; iframes[ name ] = []; // Add the tests to the new suite for ( engine in engines ) { addTestToSuite( suite, selector, engine, loaded ); } } /** * Adds the bench to the list of failures to indicate * failure on cycle. Aborts and returns false. * * @param {Object} event Benchmark.Event instance */ function onError() { errors[ this.id ] = true; this.abort(); return false; } /** * Callback for the start of each test * Adds the `pending` class to the selector column */ function onStart() { profile( selectors[selectorIndex] ); var selectorElem = get( "selector" + selectorIndex ); addClass( selectorElem, "pending" ); } /** * Adds the Hz result or "FAILURE" to the corresponding column for the engine */ function onCycle( event ) { var i = firstTestedColumn(), len = i + numEngines, tableBody = get("perf-table-body"), tds = tableBody.getElementsByTagName("td"), bench = event.target, hasError = errors[ bench.id ], textNode = document.createTextNode( hasError ? "FAILED" : Benchmark.formatNumber(getHz( bench ).toFixed( 2 )) + "o/s | " + returned[ bench.name ][ selectors[selectorIndex] ].length + " found" ); // Add the result to the row for ( ; i < len; i++ ) { if ( tds[i].getAttribute("data-engine") === bench.name ) { tds[i].appendChild( textNode ); if ( hasError ) { addClass( tds[i], "black" ); } break; } } } /** * Called after each test * - Removes the `pending` class from the row * - Adds the totals to the `scores` object * - Highlights the corresponding row appropriately * - Removes all iframes and their callbacks from memory * - Calls the next test OR finishes up by: * * adding the `complete` class to body * * adding the totals to the table * * determining the fastest overall and slowest overall */ function onComplete() { profileEnd( selectors[selectorIndex] ); var fastestHz, slowestHz, elem, attr, j, jlen, td, ret, i = firstTestedColumn(), // Determine different elements returned selector = selectors[ selectorIndex ], common = getCommonReturn( selector ), len = i + numEngines, selectorElem = get( "selector" + selectorIndex ), tableBody = get("perf-table-body"), tds = tableBody.getElementsByTagName("td"), fastest = this.filter("fastest"), slowest = this.filter("slowest"); removeClass( selectorElem, "pending" ); // Add up the scores this.forEach(function( bench ) { if ( errors[ bench.id ] ) { // No need to store this error anymore delete errors[ bench.id ]; } else { scores[ bench.name ] += getHz( bench ); } }); // Highlight different returned yellow, fastest green, and slowest red for ( ; i < len; i++ ) { td = tds[i]; attr = td.getAttribute("data-engine"); ret = returned[ attr ][ selector ]; if ( ret && ret.length !== common ) { addClass( td, "yellow" ); continue; } for ( j = 0, jlen = slowest.length; j < jlen; j++ ) { if ( slowest[j].name === attr ) { addClass( td, "red" ); } } for ( j = 0, jlen = fastest.length; j < jlen; j++ ) { if ( fastest[j].name === attr ) { addClass( td, "green" ); } } } // Remove all added iframes for this suite for ( i = 0, len = iframes[ this.name ].length; i < len; i++ ) { document.body.removeChild( iframes[ this.name ].pop() ); } delete iframes[ this.name ]; // Remove all callbacks on the window for this suite window.iframeCallbacks[ this.name ] = null; try { // Errors in IE delete window.iframeCallbacks[ this.name ]; } catch ( e ) {} if ( ++selectorIndex < selectors.length ) { testSelector( selectors[selectorIndex] ); } else { addClass( document.body, "complete" ); // Get the fastest and slowest slowest = fastest = undefined; fastestHz = 0; slowestHz = Infinity; for ( i in scores ) { if ( scores[i] > fastestHz ) { fastestHz = scores[i]; fastest = i; } else if ( scores[i] < slowestHz ) { slowestHz = scores[i]; slowest = i; } // Format scores for display scores[i] = Benchmark.formatNumber( scores[i].toFixed(2) ) + "o/s"; } // Add conclusion to the header elem = document.createElement("h3"); elem.innerHTML = "The fastest is <i>" + fastest + " (" + scores[ fastest ] + ")</i>. " + "The slowest is <i>" + slowest + " (" + scores[ slowest ] + ")</i>."; get("header").appendChild( elem ); // Add totals to table i = firstTestedColumn(); while ( (elem = tds[ i++ ]) ) { attr = elem.getAttribute("data-engine"); if ( attr === fastest ) { addClass( elem, "green" ); } else if ( attr === slowest ) { addClass( elem, "red" ); } elem.appendChild( document.createTextNode( scores[ attr ] ) ); } } } /* Benchmark Options ---------------------------------------------------------------------- */ Benchmark.options.async = true; Benchmark.options.maxTime = maxTime; Benchmark.options.minSamples = minSamples; Benchmark.options.onError = onError; /* Benchmark Suite Options ---------------------------------------------------------------------- */ Benchmark.Suite.options.onStart = onStart; Benchmark.Suite.options.onCycle = onCycle; Benchmark.Suite.options.onComplete = onComplete; // Kick it off buildTable(); testSelector( selectors[selectorIndex] ); });
Asdfjs/Asdf
test/speed/speed.js
JavaScript
mit
15,537
import { platform } from '../core/platform.js'; import { Mat4 } from '../math/mat4.js'; import { Quat } from '../math/quat.js'; import { Vec3 } from '../math/vec3.js'; /** @typedef {import('./xr-finger.js').XrFinger} XrFinger */ /** @typedef {import('./xr-hand.js').XrHand} XrHand */ const tipJointIds = platform.browser && window.XRHand ? [ 'thumb-tip', 'index-finger-tip', 'middle-finger-tip', 'ring-finger-tip', 'pinky-finger-tip' ] : []; const tipJointIdsIndex = {}; for (let i = 0; i < tipJointIds.length; i++) { tipJointIdsIndex[tipJointIds[i]] = true; } /** * Represents the joint of a finger. */ class XrJoint { /** * @type {number} * @private */ _index; /** * @type {string} * @private */ _id; /** * @type {XrHand} * @private */ _hand; /** * @type {XrFinger} * @private */ _finger; /** * @type {boolean} * @private */ _wrist; /** * @type {boolean} * @private */ _tip; /** * @type {number} * @private */ _radius = null; /** * @type {Mat4} * @private */ _localTransform = new Mat4(); /** * @type {Mat4} * @private */ _worldTransform = new Mat4(); /** * @type {Vec3} * @private */ _localPosition = new Vec3(); /** * @type {Quat} * @private */ _localRotation = new Quat(); /** * @type {Vec3} * @private */ _position = new Vec3(); /** * @type {Quat} * @private */ _rotation = new Quat(); /** * @type {boolean} * @private */ _dirtyLocal = true; /** * Create an XrJoint instance. * * @param {number} index - Index of a joint within a finger. * @param {string} id - Id of a joint based on WebXR Hand Input Specs. * @param {XrHand} hand - Hand that joint relates to. * @param {XrFinger} [finger] - Finger that joint is related to, can be null in case of wrist. * joint. * @hideconstructor */ constructor(index, id, hand, finger = null) { this._index = index; this._id = id; this._hand = hand; this._finger = finger; this._wrist = id === 'wrist'; this._tip = this._finger && !!tipJointIdsIndex[id]; } /** * @param {*} pose - XRJointPose of this joint. * @ignore */ update(pose) { this._dirtyLocal = true; this._radius = pose.radius; this._localPosition.copy(pose.transform.position); this._localRotation.copy(pose.transform.orientation); } /** @private */ _updateTransforms() { if (this._dirtyLocal) { this._dirtyLocal = false; this._localTransform.setTRS(this._localPosition, this._localRotation, Vec3.ONE); } const manager = this._hand._manager; const parent = manager.camera.parent; if (parent) { this._worldTransform.mul2(parent.getWorldTransform(), this._localTransform); } else { this._worldTransform.copy(this._localTransform); } } /** * Get the world space position of a joint. * * @returns {Vec3} The world space position of a joint. */ getPosition() { this._updateTransforms(); this._worldTransform.getTranslation(this._position); return this._position; } /** * Get the world space rotation of a joint. * * @returns {Quat} The world space rotation of a joint. */ getRotation() { this._updateTransforms(); this._rotation.setFromMat4(this._worldTransform); return this._rotation; } /** * Index of a joint within a finger, starting from 0 (root of a finger) all the way to tip of * the finger. * * @type {number} */ get index() { return this._index; } /** * Hand that joint relates to. * * @type {XrHand} */ get hand() { return this._hand; } /** * Finger that joint relates to. * * @type {XrFinger|null} */ get finger() { return this._finger; } /** * True if joint is a wrist. * * @type {boolean} */ get wrist() { return this._wrist; } /** * True if joint is a tip of a finger. * * @type {boolean} */ get tip() { return this._tip; } /** * The radius of a joint, which is a distance from joint to the edge of a skin. * * @type {number} */ get radius() { return this._radius || 0.005; } } export { XrJoint };
playcanvas/engine
src/xr/xr-joint.js
JavaScript
mit
4,730
(function () { 'use strict'; angular.module('scientilla-form') .component('scientillaFieldErrors', { templateUrl: 'partials/scientilla-field-errors.html', controller: scientillaFieldErrors, controllerAs: 'vm', bindings: { errors: '<' } }); scientillaFieldErrors.$inject = []; function scientillaFieldErrors() { const vm = this; vm.$onInit = function () { }; } })();
scientilla/scientilla
assets/js/app/form/scientilla-field-errors.component.js
JavaScript
mit
507
export default function addVariables() { const ordinalTimeSettings = this.config.time_cols.find(time_col => time_col.type === 'ordinal'); this.raw_data.forEach(d => { //Concatenate unit to measure if provided. d.soe_measure = d.hasOwnProperty(this.config.unit_col) ? `${d[this.config.measure_col]} (${d[this.config.unit_col]})` : d[this.config.measure_col]; //Identify unscheduled visits. d.unscheduled = false; if (ordinalTimeSettings) { if (this.config.unscheduled_visit_values) d.unscheduled = this.config.unscheduled_visit_values.indexOf(d[ordinalTimeSettings.value_col]) > -1; else if (this.config.unscheduled_visit_regex) d.unscheduled = this.config.unscheduled_visit_regex.test( d[ordinalTimeSettings.value_col] ); } //Add placeholder variable for non-grouped comparisons. d.soe_none = 'All Participants'; }); }
RhoInc/safety-outlier-explorer
src/callbacks/onInit/addVariables.js
JavaScript
mit
1,054
import { mutationWithClientMutationId } from 'graphql-relay'; import { GraphQLString, GraphQLNonNull, GraphQLBoolean, GraphQLInt, GraphQLList, } from 'graphql'; import GraphQLBigInt from 'graphql-bigint'; import GraphQLJSON from 'graphql-type-json'; import { getEntityByKey } from '../../../../gcp/datastore/queries'; import CircleType from '../CircleType'; import createCircle from './functions/createCircle'; const CreateCircleMutation = mutationWithClientMutationId({ name: 'createCircle', inputFields: { uid: { type: GraphQLString }, pii: { type: new GraphQLNonNull(GraphQLBoolean) }, parent: { type: GraphQLString }, slug: { type: GraphQLString }, public: { type: new GraphQLNonNull(GraphQLBoolean) }, passwordRequired: { type: GraphQLBoolean }, password: { type: GraphQLString }, viewers: { type: new GraphQLList(GraphQLString) }, type: { type: new GraphQLNonNull(GraphQLString) }, settings: { type: GraphQLJSON }, styles: { type: new GraphQLList(GraphQLString) }, tags: { type: new GraphQLList(GraphQLString) }, rating: { type: GraphQLString }, title: { type: GraphQLString }, subtitle: { type: GraphQLString }, description: { type: GraphQLString }, media: { type: GraphQLString }, icon: { type: GraphQLString }, creator: { type: new GraphQLNonNull(GraphQLString) }, editors: { type: new GraphQLList(GraphQLString) }, dateCreated: { type: GraphQLBigInt }, dateUpdated: { type: GraphQLBigInt }, string: { type: GraphQLString }, object: { type: GraphQLJSON }, number: { type: GraphQLInt }, boolean: { type: GraphQLBoolean }, line: { type: GraphQLString }, lines: { type: new GraphQLList(GraphQLString) }, linesMany: { type: new GraphQLList(GraphQLString) }, }, outputFields: { status: { type: GraphQLString, resolve: response => response.status, }, message: { type: GraphQLString, resolve: response => response.message, }, createdCircle: { type: CircleType, resolve: async payload => await getEntityByKey( 'circles', payload.createdEntityUid, payload.contextUserUid, ).then(response => response.entity), }, }, mutateAndGetPayload: async (inputFields, context) => await createCircle(inputFields, context.user.uid), }); export default CreateCircleMutation;
MyiWorlds/myiworlds.backend
src/schema/Types/Circle/Mutations/CreateCircleMutation.js
JavaScript
mit
2,413
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'image', 'nl', { alt: 'Alternatieve tekst', border: 'Rand', btnUpload: 'Naar server verzenden', button2Img: 'Wilt u de geselecteerde afbeeldingsknop vervangen door een eenvoudige afbeelding?', hSpace: 'HSpace', img2Button: 'Wilt u de geselecteerde afbeelding vervangen door een afbeeldingsknop?', infoTab: 'Informatie afbeelding', linkTab: 'Link', lockRatio: 'Afmetingen vergrendelen', menu: 'Eigenschappen afbeelding', resetSize: 'Afmetingen resetten', title: 'Eigenschappen afbeelding', titleButton: 'Eigenschappen afbeeldingsknop', upload: 'Upload', urlMissing: 'De URL naar de afbeelding ontbreekt.', vSpace: 'VSpace', validateBorder: 'Rand moet een heel nummer zijn.', validateHSpace: 'HSpace moet een heel nummer zijn.', validateVSpace: 'VSpace moet een heel nummer zijn.' } );
otto-torino/gino
ckeditor/plugins/image/lang/nl.js
JavaScript
mit
1,020
/** * Internal dependencies. */ var Rule = require('../rule'); var TrailingWhitespace = Rule.create({ error: 'Trailing whitespace detected', option: { key: 'twhite', type: 'boolean' }, on: { after: 'check' }, }); /** * Perform the check. * * @param {Source} source * @api public */ TrailingWhitespace.prototype.check = function(source) { this.source.eachLine(function(line, i) { if (line.length !== line.replace(/\s+$/,'').length) this.badLine(i); }, this); }; /** * Primary export. */ module.exports = TrailingWhitespace;
vesln/stylec
lib/stylec/rule/trailing-whitespace.js
JavaScript
mit
570
import React, { Text } from 'react-native' const Summary = ({ wrongAnswers, position, questionsLength }) => ( <Text style={styles.subHeader}> <Text style={{ color: '#f00' }}>Wrong Answers: {wrongAnswers}</Text> { ' - ' } Progress: {position + 1}/{questionsLength} </Text> ) export default Summary const styles = { subHeader: { alignSelf: 'center', padding: 5 } }
alanrsoares/nz-road-code
src/components/Summary.js
JavaScript
mit
396
require.ensure([], function(require) { require("./119.async.js"); require("./238.async.js"); require("./476.async.js"); require("./951.async.js"); }); module.exports = 952;
skeiter9/javascript-para-todo_demo
webapp/node_modules/webpack/benchmark/fixtures/952.async.js
JavaScript
mit
172
import React, { PropTypes } from 'react'; import ReactDOM from 'react-dom'; import Modal from 'react-bootstrap/lib/Modal' import Button from 'react-bootstrap/lib/Button' import { confirmable } from 'react-confirm'; class Confirmation extends React.Component { componentDidMount(){ ReactDOM.findDOMNode(this.refs.ok).focus(); } render() { const { okLabbel = 'OK', cancelLabel = 'Cancel', title, confirmation, show, proceed, dismiss, cancel, enableEscape = true, } = this.props; return ( <div className="static-modal"> <Modal show={show} onHide={dismiss} backdrop={enableEscape ? true : 'static'} keyboard={enableEscape} bsSize="sm"> <Modal.Header> <Modal.Title>{title}</Modal.Title> </Modal.Header> <Modal.Body> {confirmation} </Modal.Body> <Modal.Footer> <Button ref="ok" className='button-l' bsStyle="primary" onClick={proceed}>{okLabbel}</Button> <Button bsStyle="warning" onClick={cancel}>{cancelLabel}</Button> </Modal.Footer> </Modal> </div> ) } } Confirmation.propTypes = { okLabbel: PropTypes.string, cancelLabel: PropTypes.string, title: PropTypes.string, confirmation: PropTypes.string, show: PropTypes.bool, proceed: PropTypes.func, // called when ok button is clicked. cancel: PropTypes.func, // called when cancel button is clicked. dismiss: PropTypes.func, // called when backdrop is clicked or escaped. enableEscape: PropTypes.bool, } export default confirmable(Confirmation);
sulthan16/awesome-jr-frontend-sulthan
app/components/Confirmation/index.js
JavaScript
mit
1,643
import React from 'react'; import PropTypes from 'prop-types'; import { View, Text, StyleSheet, Image, Dimensions } from 'react-native'; import Dot from './components/Dot'; import HorizontalLine from './components/HorizontalLine'; const propTypes = { data: PropTypes.arrayOf( PropTypes.shape({ color: PropTypes.string, unit: PropTypes.string, values: PropTypes.arrayOf( PropTypes.arrayOf( PropTypes.number ) ) }) ), // takes array of series of data (array of arrays of {x, y}) chartWidth: PropTypes.number, // by default uses entire width of the device chartHeight: PropTypes.number, // by default 200 scaled px backgroundColor: PropTypes.string, // 'white' by default colors: PropTypes.arrayOf(PropTypes.string), // specify the colors for each series of data minY: PropTypes.number, maxY: PropTypes.number, minX: PropTypes.number, maxX: PropTypes.number, unitX: PropTypes.string, unitY: PropTypes.string, horizontalLinesAt: PropTypes.arrayOf(PropTypes.number), verticalLinesAt: PropTypes.arrayOf(PropTypes.number), } const defaultProps = { chartHeight: 200, chartWidth: Dimensions.get('window').width, backgroundColor: 'white' } class ScatterChart extends React.PureComponent { constructor(props) { super(props); this.state = { ratioX: undefined, ratioY: undefined, minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, horizontalLinesAt: undefined }; } render() { const { data, chartHeight, chartWidth, backgroundColor, colors, unitX, unitY } = this.props; const { minY, maxY, minX, maxX, horizontalLinesAt, verticalLinesAt } = this.state; const { getX, getY } = this; const windowHeight = Dimensions.get('window').height, windowWidth = Dimensions.get('window').width; const horizontalLines = horizontalLinesAt ? horizontalLinesAt.map((line, idx) => <HorizontalLine key={idx} bottom={getY(line)} width={chartWidth} displayText={`${line} ${unitY}`} />) : undefined; const verticalLines = verticalLinesAt ? verticalLinesAt.map((line, idx) => <View key={idx} style={{ opacity: .5, backgroundColor: 'gray', width: 1, height: chartHeight, bottom: 0, left: getX(line), position: 'absolute' }} />) : undefined; // const ref1 = ; // for (let i = 0; i < windowWidth; i++) { // points.push(<Dot key={points.length} left={i} bottom={Math.round(Math.random() * chartHeight)} />) // } let points = []; if (data) { for (let i = 0; i < data.length; i++) { const dataSeries = data[i]; for (let j = 0; j < dataSeries.values.length; j++) { const point = dataSeries.values[j]; points.push(<Dot key={`${i}_${j}`} left={getX(point[0])} bottom={getY(point[1])} color={dataSeries.color} />) } } } return ( <View style={{ height: chartHeight, backgroundColor: backgroundColor }}> {points} {horizontalLines} {verticalLines} {/* <View style={{ position: 'absolute', top: 42, opacity: .8, backgroundColor: 'transparent' }}> <Text style={{ fontSize: 6 }}>100%</Text> </View> */} </View> ); } componentWillReceiveProps(nextProps) { this.computeAxes(nextProps); } componentWillMount() { this.computeAxes(this.props); } computeAxes = async (props) => { const { data, minX, minY, maxX, maxY, chartWidth, chartHeight } = props; let { horizontalLinesAt, verticalLinesAt } = props; if (!data) { return; } // let minXData = data[0][0].x, maxXData = data[0][0].x, minYData = data[0][0].y, maxYData = data[0][0].y; // minimum extracted from data let seriesMinX = [], seriesMaxX = [], seriesMinY = [], seriesMaxY = []; data.forEach(dataSeries => { const xArr = dataSeries.values.map(point => point[0]); seriesMinX.push(Math.min.apply(null, xArr)); seriesMaxX.push(Math.max.apply(null, xArr)); const yArr = dataSeries.values.map(point => point[1]); seriesMinY.push(Math.min.apply(null, yArr)); seriesMaxY.push(Math.max.apply(null, yArr)); }); const _minX = typeof minX !== 'undefined' ? Math.min.apply(null, [minX, ...seriesMinX]) : Math.min.apply(null, seriesMinX); const _maxX = typeof maxX !== 'undefined' ? Math.max.apply(null, [maxX, ...seriesMaxX]) : Math.max.apply(null, seriesMaxX); const _minY = typeof minY !== 'undefined' ? Math.min.apply(null, [minY, ...seriesMinY]) : Math.min.apply(null, seriesMinY); const _maxY = typeof maxY !== 'undefined' ? Math.max.apply(null, [maxY, ...seriesMaxY]) : Math.max.apply(null, seriesMaxY); horizontalLinesAt || (horizontalLinesAt = []); const _horizontalLinesAt = []; for (let i = 0; i < horizontalLinesAt.length; i++) { const current = horizontalLinesAt[i]; if (current >= _minY && current <= _maxY) { _horizontalLinesAt.push(current) } } horizontalLinesAt = [..._horizontalLinesAt]; // if (horizontalLinesAt.indexOf(minY) === -1) { horizontalLinesAt = [minY, ...horizontalLinesAt]; } // if (horizontalLinesAt.indexOf(maxY) === -1) { horizontalLinesAt = [...horizontalLinesAt, maxY]; } await this.setState({ minX: _minX, maxX: _maxX, minY: _minY, maxY: _maxY, ratioX: chartWidth / (_maxX - _minX), ratioY: chartHeight / (_maxY - _minY), horizontalLinesAt, verticalLinesAt }); } getX = v => { const { minX, ratioX } = this.state; return (v - minX) * ratioX; } getY = v => { const { minY, ratioY } = this.state; return (v - minY) * ratioY; } } ScatterChart.propTypes = propTypes; ScatterChart.defaultProps = defaultProps export default ScatterChart;
malexandrum/react-native-scatter-chart
index.js
JavaScript
mit
6,322
'use strict'; var helpers = {}; /** * Check the type of the value * @return {string} The type of the given value */ var checkType = function (value) { if (typeof value === 'object') { if (Array.isArray(value)) { return 'array'; } else { return 'object'; } } else if (typeof value === 'string') { if (isNaN(parseInt(value)) === false) { return 'stringNumber'; } return 'string'; } else if (typeof value === 'number') { if (isNaN(value)) { return 'NaN'; } return 'number'; } else if (typeof value === 'boolean') { return 'boolean'; } }; helpers.checkType = checkType; /** * Check whether the value is empty or not. * @param {mixed} value a value to check. * @return {boolean} true if yes, false if no. */ var checkIfHave = function (value) { var returned = false; if (checkType(value) === 'object') { if (value === null) { return false; }else if (Object.keys(value) .length) { returned = true; } } else if (checkType(value) === 'array') { if (value.length !== 0) { returned = true; } } else if (checkType(value) === 'number') { return true; } else { if (value) { returned = true; } } return returned; }; helpers.checkIfHave = checkIfHave; /** * Check if errors array is empty or not. * @param {array} errorsArray errors array. * @return {boolean} true if has, false if not. */ var passed = function (errorsArray) { if (errorsArray.length === 0) { return true; } else { return false; } }; helpers.passed = passed; /** * Split the value by Colon * @param {string} validateRule string to split. * @return {array} an array that have 2 values, ruleName and ruleValue */ var splitByColon = function (validateRule) { var splitted = validateRule.split(':'); return splitted; }; helpers.splitByColon = splitByColon; /** * [splitBySepartor description] * @param {[type]} value [description] * @return {[type]} [description] */ var splitBySepartor = function (value) { if (!value) { return ''; } var splitted = value.split('|'); return splitted; }; helpers.splitBySepartor = splitBySepartor; export default helpers;
arabyalhomsi/larajs-validator
src/helpers.js
JavaScript
mit
2,273
var $ = require('./utils') var path = require('path') var url = require('url') var curRoot = '' var fs = require('fs') var mockjs = require('mockjs') var cheerio = require('cheerio') var isCompile = { mock: true, ms: true } var server = function (req, res, next) { var urlObj = url.parse(req.url, true) var extname = path.extname(urlObj.pathname) var absPath = path.join(curRoot, urlObj.pathname) var isMock = false var data, html if ($.isExists(absPath)) { switch (extname) { case '.html': case '.htm': data = fs.readFileSync(absPath) html = data.toString() html = $.getLrHtml(html) return res.end(html) case '.mock': if (isCompile.mock) { data = fs.readFileSync(absPath) html = data.toString() isMock = true eval('var tmpl = ' + data) data = JSON.stringify(mockjs.mock(tmpl)) return res.end(isCompile.ms ? getJsonData(data) : data) } case '.json': if (isCompile.ms) { data = fs.readFileSync(absPath) data = data.toString() return res.end(getJsonData(data)) } } } next() function getJsonData (data) { var pobj = path.parse(absPath) var msfile = path.join(pobj.dir, pobj.name + '.ms') if ($.isExists(msfile)) { // 存在ms文件 var handler = require(msfile) if ($.isFunction(handler)) { return handler(data, urlObj.query || {}, cheerio) } } return data } } server.getCompile = function (r) { return isCompile[r] } server.setRoot = function (r) { curRoot = r } server.setCompile = function (n, r) { isCompile[n] = r } module.exports = server
ksky521/mock-server
lib/mock-serve.js
JavaScript
mit
1,720
// All code points in the Greek Extended block as per Unicode v9.0.0: [ 0x1F00, 0x1F01, 0x1F02, 0x1F03, 0x1F04, 0x1F05, 0x1F06, 0x1F07, 0x1F08, 0x1F09, 0x1F0A, 0x1F0B, 0x1F0C, 0x1F0D, 0x1F0E, 0x1F0F, 0x1F10, 0x1F11, 0x1F12, 0x1F13, 0x1F14, 0x1F15, 0x1F16, 0x1F17, 0x1F18, 0x1F19, 0x1F1A, 0x1F1B, 0x1F1C, 0x1F1D, 0x1F1E, 0x1F1F, 0x1F20, 0x1F21, 0x1F22, 0x1F23, 0x1F24, 0x1F25, 0x1F26, 0x1F27, 0x1F28, 0x1F29, 0x1F2A, 0x1F2B, 0x1F2C, 0x1F2D, 0x1F2E, 0x1F2F, 0x1F30, 0x1F31, 0x1F32, 0x1F33, 0x1F34, 0x1F35, 0x1F36, 0x1F37, 0x1F38, 0x1F39, 0x1F3A, 0x1F3B, 0x1F3C, 0x1F3D, 0x1F3E, 0x1F3F, 0x1F40, 0x1F41, 0x1F42, 0x1F43, 0x1F44, 0x1F45, 0x1F46, 0x1F47, 0x1F48, 0x1F49, 0x1F4A, 0x1F4B, 0x1F4C, 0x1F4D, 0x1F4E, 0x1F4F, 0x1F50, 0x1F51, 0x1F52, 0x1F53, 0x1F54, 0x1F55, 0x1F56, 0x1F57, 0x1F58, 0x1F59, 0x1F5A, 0x1F5B, 0x1F5C, 0x1F5D, 0x1F5E, 0x1F5F, 0x1F60, 0x1F61, 0x1F62, 0x1F63, 0x1F64, 0x1F65, 0x1F66, 0x1F67, 0x1F68, 0x1F69, 0x1F6A, 0x1F6B, 0x1F6C, 0x1F6D, 0x1F6E, 0x1F6F, 0x1F70, 0x1F71, 0x1F72, 0x1F73, 0x1F74, 0x1F75, 0x1F76, 0x1F77, 0x1F78, 0x1F79, 0x1F7A, 0x1F7B, 0x1F7C, 0x1F7D, 0x1F7E, 0x1F7F, 0x1F80, 0x1F81, 0x1F82, 0x1F83, 0x1F84, 0x1F85, 0x1F86, 0x1F87, 0x1F88, 0x1F89, 0x1F8A, 0x1F8B, 0x1F8C, 0x1F8D, 0x1F8E, 0x1F8F, 0x1F90, 0x1F91, 0x1F92, 0x1F93, 0x1F94, 0x1F95, 0x1F96, 0x1F97, 0x1F98, 0x1F99, 0x1F9A, 0x1F9B, 0x1F9C, 0x1F9D, 0x1F9E, 0x1F9F, 0x1FA0, 0x1FA1, 0x1FA2, 0x1FA3, 0x1FA4, 0x1FA5, 0x1FA6, 0x1FA7, 0x1FA8, 0x1FA9, 0x1FAA, 0x1FAB, 0x1FAC, 0x1FAD, 0x1FAE, 0x1FAF, 0x1FB0, 0x1FB1, 0x1FB2, 0x1FB3, 0x1FB4, 0x1FB5, 0x1FB6, 0x1FB7, 0x1FB8, 0x1FB9, 0x1FBA, 0x1FBB, 0x1FBC, 0x1FBD, 0x1FBE, 0x1FBF, 0x1FC0, 0x1FC1, 0x1FC2, 0x1FC3, 0x1FC4, 0x1FC5, 0x1FC6, 0x1FC7, 0x1FC8, 0x1FC9, 0x1FCA, 0x1FCB, 0x1FCC, 0x1FCD, 0x1FCE, 0x1FCF, 0x1FD0, 0x1FD1, 0x1FD2, 0x1FD3, 0x1FD4, 0x1FD5, 0x1FD6, 0x1FD7, 0x1FD8, 0x1FD9, 0x1FDA, 0x1FDB, 0x1FDC, 0x1FDD, 0x1FDE, 0x1FDF, 0x1FE0, 0x1FE1, 0x1FE2, 0x1FE3, 0x1FE4, 0x1FE5, 0x1FE6, 0x1FE7, 0x1FE8, 0x1FE9, 0x1FEA, 0x1FEB, 0x1FEC, 0x1FED, 0x1FEE, 0x1FEF, 0x1FF0, 0x1FF1, 0x1FF2, 0x1FF3, 0x1FF4, 0x1FF5, 0x1FF6, 0x1FF7, 0x1FF8, 0x1FF9, 0x1FFA, 0x1FFB, 0x1FFC, 0x1FFD, 0x1FFE, 0x1FFF ];
mathiasbynens/unicode-data
9.0.0/blocks/Greek-Extended-code-points.js
JavaScript
mit
2,377
import './App.scss'; import React, { PropTypes } from 'react'; import { RouteHandler } from 'react-router'; import Header from '../Header'; //eslint-disable-line no-unused-vars import Navbar from '../Navbar'; import AppStore from '../../stores/AppStore.js'; import _ from 'lodash'; // // Component Class // ----------------------------------------------------------------------------- class App extends React.Component { constructor(props) { super(props); this.state = { navHidden: false, navFixedToTop: false }; this._appStoreChangeHandler = this._appStoreChangeHandler.bind(this); } static propTypes = { onSetTitle: PropTypes.func.isRequired, onSetMeta: PropTypes.func.isRequired }; componentDidMount() { AppStore.onChange(this._appStoreChangeHandler); this._appStoreChangeHandler(); } componentWillUnmount() { AppStore.offChange(this._appStoreChangeHandler); } shouldComponentUpdate(props, state) { return !_.matches(this.state, state); } render() { return ( <div className="App"> <Navbar ref="nav" hidden={this.state.navHidden} fixedToTop={this.state.navFixedToTop}/> <div className="content"> <RouteHandler/> </div> </div> ); } // // Event Handlers // ----------------------------------------------------------------------------- /** * Triggered on AppStore change * @private */ _appStoreChangeHandler() { var navHeight = React.findDOMNode(this.refs.nav).firstChild.clientHeight; if (AppStore.getScroll('y') > navHeight && AppStore.getScrollTotal('y') < -80) { this.setState({navHidden: false, navFixedToTop: true}); } else { this.setState({navHidden: false, navFixedToTop: false}); } } } export default App;
alexpalombaro/reactjs
src/components/App/App.js
JavaScript
mit
1,989
'use strict' const SOFT_EXIT_SIGNALS = ['SIGINT', 'SIGTERM'] for (let i = 0; i < SOFT_EXIT_SIGNALS.length; i++) { process.on(SOFT_EXIT_SIGNALS[i], process.exit) } module.exports = { SOFT_EXIT_SIGNALS }
davidmarkclements/0x
lib/preload/soft-exit.js
JavaScript
mit
207
import React from 'react'; import { BranchMixin } from 'baobab-react-mixins'; import { ResolveMixin } from '../../../src'; import { getUser } from '../../services'; export default React.createClass({ displayName: 'RootComponent', mixins: [BranchMixin, ResolveMixin], cursors: { user: ['user'], }, getResolverBindings() { return [ { cursor: this.cursors.user, service: getUser, transform: this.transformUser, }, ]; }, transformUser({ pk, type }) { return { pk, type, fromTransform: 'from transform', }; }, render() { return ( <div></div> ); }, });
Brogency/baobab-react-resolver
test/resolve-mixin/components/transform.js
JavaScript
mit
769
import React, { Component } from 'react' import { compose } from 'redux' import { connect } from 'react-redux' import { reduxForm } from 'redux-form' import * as actions from '../../actions' class Signup extends Component { constructor(props) { super(props); this.renderAlert = this.renderAlert.bind(this); } handleFormSubmit({ email, password, passwordConfirm }) { this.props.signupUser({ email, password }); } renderAlert() { if (this.props.errorMessage) { return ( <div className="alert alert-danger"> <strong>Oops!</strong> {this.props.errorMessage} </div> ); } } renderError(field) { const { touched, error } = field; // If the field has been touched and it has an error, show the error if (touched && error) { return <div className="error">{error}</div>; } else { return null; } } render() { const { handleSubmit, fields: { email, password, passwordConfirm }} = this.props; return ( <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> <fieldset className="form-group"> <label>Email:</label> <input {...email} className="form-control" /> {this.renderError(email)} </fieldset> <fieldset className="form-group"> <label>Password:</label> <input {...password} type="password" className="form-control" /> {/* if a user touched the field and if there is an error, render this component */} {this.renderError(password)} </fieldset> <fieldset className="form-group"> <label>Confirm password:</label> <input {...passwordConfirm} type="password" className="form-control" /> {this.renderError(passwordConfirm)} </fieldset> {this.renderAlert()} <button action="submit" className="btn btn-primary">Sign up</button> </form> ); } } function validate(formProps) { const errors = {}; const { email, password, passwordConfirm } = formProps; if (password !== passwordConfirm) { errors.password = 'Passwords must match' } if (!email) { errors.email = 'Please enter an email' } if (!password) { errors.password = 'Please enter a password' } if (!passwordConfirm) { errors.passwordConfirm = 'Please confirm password' } return errors; } const mapStateToProps = state => { return { errorMessage: state.auth.error }; }; export default compose( connect(mapStateToProps, actions), reduxForm({ form: 'signup', fields: ['email', 'password', 'passwordConfirm'], validate }) )(Signup)
tedjames/reduxAuth
src/components/auth/signup.js
JavaScript
mit
2,647
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { 'activityBar.activeBorder': '#54bef2', 'activityBar.background': '#111720', 'activityBar.border': '#111720', 'activityBar.foreground': '#cacde2', 'activityBarBadge.background': '#54bef2', 'activityBarBadge.foreground': '#00111a', 'badge.background': '#54bef2', 'badge.foreground': '#00111a', 'breadcrumb.activeSelectionForeground': '#54bef2', 'breadcrumb.background': '#111720', 'breadcrumb.focusForeground': '#cacde2', 'breadcrumb.foreground': '#7e8995', 'breadcrumbPicker.background': '#111720', 'button.background': '#54bef2', 'button.border': '#111720', 'button.foreground': '#00111a', 'button.hoverBackground': '#67e8f9', 'button.secondaryBackground': '#00111a50', 'button.secondaryForeground': '#d2d8e7', 'button.secondaryHoverBackground': '#00111a', 'charts.blue': '#54bef2', 'charts.foreground': '#cacde2', 'charts.green': '#82f1b1', 'charts.orange': '#ff9c66', 'charts.purple': '#c792ea', 'charts.red': '#fb7185', 'charts.yellow': '#ffcb6b', 'debugConsole.errorForeground': '#fb7185', 'debugConsole.infoForeground': '#cacde2', 'debugConsole.sourceForeground': '#54bef2', 'debugConsole.warningForeground': '#ffcb6b', 'debugConsoleInputIcon.foreground': '#54bef2', 'debugToolBar.background': '#111720', descriptionForeground: '#cacde2cc', 'diffEditor.insertedTextBackground': '#82f1b120', 'diffEditor.removedTextBackground': '#fb718560', 'dropdown.background': '#111720', 'dropdown.border': '#cacde210', 'editor.background': '#111720', 'editor.findMatchBackground': '#cacde240', 'editor.findMatchBorder': '#54bef2', 'editor.findMatchHighlightBackground': '#54bef260', 'editor.findMatchHighlightBorder': '#cacde210', 'editor.foreground': '#cacde2', 'editor.lineHighlightBackground': '#00111a50', 'editor.selectionBackground': '#54bef240', 'editor.selectionHighlightBackground': '#ffcb6b30', 'editorBracketMatch.background': '#00111a50', 'editorBracketMatch.border': '#54bef240', 'editorCodeLens.foreground': '#7e8995', 'editorCursor.foreground': '#ffcb6b', 'editorError.foreground': '#fb718540', 'editorGroup.border': '#111720', 'editorGroupHeader.tabsBackground': '#111720', 'editorGutter.addedBackground': '#82f1b140', 'editorGutter.deletedBackground': '#fb718540', 'editorGutter.modifiedBackground': '#54bef240', 'editorHoverWidget.background': '#111720', 'editorHoverWidget.border': '#cacde210', 'editorIndentGuide.activeBackground': '#5c6270', 'editorIndentGuide.background': '#7e899540', 'editorInfo.foreground': '#54bef240', 'editorInlayHint.background': '#2c313c', 'editorInlayHint.foreground': '#abb2bf', 'editorLineNumber.activeForeground': '#7e8995', 'editorLineNumber.foreground': '#5c6270', 'editorLink.activeForeground': '#d2d8e7', 'editorMarkerNavigation.background': '#54bef210', 'editorOverviewRuler.addedForeground': '#82f1b1', 'editorOverviewRuler.background': '#111720', 'editorOverviewRuler.border': '#111720', 'editorOverviewRuler.currentContentForeground': '#ffcb6b60', 'editorOverviewRuler.deletedForeground': '#fb7185', 'editorOverviewRuler.errorForeground': '#fb7185', 'editorOverviewRuler.findMatchForeground': '#67e8f9', 'editorOverviewRuler.incomingContentForeground': '#ffcb6b60', 'editorOverviewRuler.infoForeground': '#54bef2', 'editorOverviewRuler.modifiedForeground': '#ffcb6b', 'editorOverviewRuler.rangeHighlightForeground': '#67e8f930', 'editorOverviewRuler.selectionHighlightForeground': '#67e8f930', 'editorOverviewRuler.warningForeground': '#ffcb6b', 'editorOverviewRuler.wordHighlightForeground': '#ffcb6b30', 'editorOverviewRuler.wordHighlightStrongForeground': '#ffcb6b60', 'editorRuler.foreground': '#7e8995', 'editorSuggestWidget.background': '#111720', 'editorSuggestWidget.border': '#cacde210', 'editorSuggestWidget.focusHighlightForeground': '#54bef2', 'editorSuggestWidget.foreground': '#d2d8e7', 'editorSuggestWidget.highlightForeground': '#54bef2', 'editorSuggestWidget.selectedBackground': '#111720', 'editorSuggestWidget.selectedForeground': '#cacde2', 'editorWarning.foreground': '#ffcb6b40', 'editorWhitespace.foreground': '#cacde240', 'editorWidget.background': '#111720', 'editorWidget.border': '#54bef2', 'editorWidget.resizeBorder': '#54bef2', 'extensionButton.prominentBackground': '#54bef2cc', 'extensionButton.prominentHoverBackground': '#54bef2', focusBorder: '#11172000', foreground: '#cacde2', 'gitDecoration.conflictingResourceForeground': '#ffcb6bcc', 'gitDecoration.deletedResourceForeground': '#fb7185cc', 'gitDecoration.ignoredResourceForeground': '#5c6270', 'gitDecoration.modifiedResourceForeground': '#ffcb6bcc', 'gitDecoration.submoduleResourceForeground': '#c792eacc', 'gitDecoration.untrackedResourceForeground': '#82f1b1cc', 'gitlens.closedPullRequestIconColor': '#fb7185', 'gitlens.decorations.branchAheadForegroundColor': '#82f1b1', 'gitlens.decorations.branchBehindForegroundColor': '#ffcb6b', 'gitlens.decorations.branchDivergedForegroundColor': '#ff9c66', 'gitlens.decorations.branchMissingUpstreamForegroundColor': '#fb7185', 'gitlens.decorations.branchUnpublishedForegroundColor': '#82f1b1', 'gitlens.gutterBackgroundColor': '#00111a60', 'gitlens.gutterForegroundColor': '#cacde2', 'gitlens.gutterUncommittedForegroundColor': '#5c6270', 'gitlens.lineHighlightBackgroundColor': '#00111a60', 'gitlens.lineHighlightOverviewRulerColor': '#cacde2', 'gitlens.mergedPullRequestIconColor': '#c792ea', 'gitlens.openPullRequestIconColor': '#82f1b1', 'gitlens.trailingLineBackgroundColor': '#00111a50', 'gitlens.trailingLineForegroundColor': '#cacde240', 'gitlens.unpublishedCommitIconColor': '#82f1b1', 'gitlens.unpulledChangesIconColor': '#ffcb6b', 'gitlens.unpushlishedChangesIconColor': '#82f1b1', 'icon.foreground': '#cacde2', 'input.background': '#00111a50', 'input.border': '#111720', 'input.foreground': '#d2d8e7', 'input.placeholderForeground': '#cacde240', 'inputOption.activeBackground': '#00111a60', 'inputOption.activeBorder': '#cacde210', 'inputValidation.errorBorder': '#fb718540', 'inputValidation.infoBorder': '#54bef240', 'inputValidation.warningBorder': '#ffcb6b40', 'keybindingLabel.background': '#00111a50', 'keybindingLabel.border': '#5c6270cc', 'keybindingLabel.bottomBorder': '#7e8995cc', 'keybindingLabel.foreground': '#d2d8e7', 'list.activeSelectionBackground': '#7e899560', 'list.activeSelectionForeground': '#ffffff', 'list.activeSelectionIconForeground': '#ffffff', 'list.dropBackground': '#00111a50', 'list.focusBackground': '#54bef220', 'list.focusForeground': '#ffffff', 'list.focusHighlightForeground': '#ffffff', 'list.highlightForeground': '#d2d8e7', 'list.hoverBackground': '#00111a50', 'list.hoverForeground': '#d2d8e7', 'list.inactiveSelectionBackground': '#111720', 'list.inactiveSelectionForeground': '#54bef2', 'listFilterWidget.background': '#111720', 'listFilterWidget.noMatchesOutline': '#cacde210', 'listFilterWidget.outline': '#cacde210', 'menu.background': '#111720', 'menu.foreground': '#d2d8e7', 'menu.selectionBackground': '#111720', 'menu.selectionForeground': '#54bef2', 'menu.separatorBackground': '#d2d8e7', 'menubar.selectionBackground': '#111720', 'menubar.selectionForeground': '#54bef2', 'notificationCenterHeader.background': '#111720', 'notificationCenterHeader.foreground': '#d2d8e7', 'notificationLink.foreground': '#c792ea', 'notifications.background': '#111720', 'notifications.foreground': '#d2d8e7', 'notificationsErrorIcon.foreground': '#fb7185', 'notificationsInfoIcon.foreground': '#00111a50', 'notificationsWarningIcon.foreground': '#ffcb6b', 'panel.background': '#111720', 'panel.border': '#111720', 'panel.dropBorder': '#c792ea', 'panelTitle.activeBorder': '#54bef2', 'panelTitle.activeForeground': '#ffffff', 'panelTitle.inactiveForeground': '#7e8995', 'peekView.border': '#cacde210', 'peekViewEditor.background': '#c792ea10', 'peekViewEditor.matchHighlightBackground': '#54bef240', 'peekViewEditorGutter.background': '#c792ea10', 'peekViewResult.background': '#c792ea10', 'peekViewResult.matchHighlightBackground': '#54bef240', 'peekViewResult.selectionBackground': '#7e899540', 'peekViewTitle.background': '#c792ea10', 'peekViewTitleDescription.foreground': '#cacde240', 'pickerGroup.foreground': '#54bef2', 'progressBar.background': '#54bef2', 'scrollbar.shadow': '#11172000', 'scrollbarSlider.activeBackground': '#54bef240', 'scrollbarSlider.background': '#54bef230', 'scrollbarSlider.hoverBackground': '#111720', 'selection.background': '#54bef240', 'settings.checkboxBackground': '#111720', 'settings.checkboxForeground': '#cacde2', 'settings.dropdownBackground': '#111720', 'settings.dropdownForeground': '#cacde2', 'settings.headerForeground': '#54bef2', 'settings.modifiedItemIndicator': '#54bef2', 'settings.numberInputBackground': '#111720', 'settings.numberInputForeground': '#cacde2', 'settings.textInputBackground': '#111720', 'settings.textInputForeground': '#cacde2', 'sideBar.background': '#111720', 'sideBar.border': '#111720', 'sideBar.foreground': '#7e8995', 'sideBarSectionHeader.background': '#111720', 'sideBarSectionHeader.border': '#111720', 'sideBarTitle.foreground': '#cacde2', 'statusBar.background': '#111720', 'statusBar.border': '#111720', 'statusBar.debuggingBackground': '#54bef2', 'statusBar.debuggingForeground': '#00111a', 'statusBar.foreground': '#7e8995', 'statusBar.noFolderBackground': '#111720', 'statusBarItem.hoverBackground': '#00111a50', 'statusBarItem.prominentForeground': '#00111a', 'statusBarItem.remoteBackground': '#54bef2', 'statusBarItem.remoteForeground': '#00111a', 'tab.activeBorder': '#d19a66', 'tab.activeForeground': '#cacde2', 'tab.activeModifiedBorder': '#7e8995', 'tab.border': '#111720', 'tab.inactiveBackground': '#111720', 'tab.inactiveForeground': '#7e8995', 'tab.unfocusedActiveBorder': '#7e8995', 'tab.unfocusedActiveForeground': '#cacde2', 'terminal.ansiBlack': '#5c6270', 'terminal.ansiBlue': '#54bef2', 'terminal.ansiBrightBlack': '#7e8995', 'terminal.ansiBrightBlue': '#54bef2', 'terminal.ansiBrightCyan': '#67e8f9', 'terminal.ansiBrightGreen': '#82f1b1', 'terminal.ansiBrightMagenta': '#c792ea', 'terminal.ansiBrightRed': '#fb7185', 'terminal.ansiBrightWhite': '#ffffff', 'terminal.ansiBrightYellow': '#ffcb6b', 'terminal.ansiCyan': '#67e8f9', 'terminal.ansiGreen': '#82f1b1', 'terminal.ansiMagenta': '#c792ea', 'terminal.ansiRed': '#fb7185', 'terminal.ansiWhite': '#ffffff', 'terminal.ansiYellow': '#ffcb6b', 'terminalCursor.background': '#00111a', 'terminalCursor.foreground': '#cacde2', 'textCodeBlock.background': '#7e8995', 'textLink.activeForeground': '#54bef2', 'textLink.foreground': '#54bef2', 'textPreformat.foreground': '#7e8995', 'titleBar.activeBackground': '#111720', 'titleBar.activeForeground': '#d2d8e7', 'titleBar.border': '#111720', 'titleBar.inactiveBackground': '#111720', 'titleBar.inactiveForeground': '#7e8995', 'toolbar.hoverBackground': '#00111a50', 'widget.shadow': '#00111a10', //"activityBar.dropBorder": "#cacde2", //"activityBar.inactiveForeground": "#cacde266", //"banner.background": "#7e899560", //"banner.foreground": "#ffffff", //"banner.iconForeground": "#54bef240", //"charts.lines": "#cacde280", //"checkbox.background": "#111720", //"checkbox.border": "#cacde210", //"checkbox.foreground": "#f0f0f0", //"debugExceptionWidget.background": "#420b0d", //"debugExceptionWidget.border": "#a31515", //"debugIcon.breakpointCurrentStackframeForeground": "#ffcc00", //"debugIcon.breakpointDisabledForeground": "#848484", //"debugIcon.breakpointForeground": "#e51400", //"debugIcon.breakpointStackframeForeground": "#89d185", //"debugIcon.breakpointUnverifiedForeground": "#848484", //"debugIcon.continueForeground": "#75beff", //"debugIcon.disconnectForeground": "#f48771", //"debugIcon.pauseForeground": "#75beff", //"debugIcon.restartForeground": "#89d185", //"debugIcon.startForeground": "#89d185", //"debugIcon.stepBackForeground": "#75beff", //"debugIcon.stepIntoForeground": "#75beff", //"debugIcon.stepOutForeground": "#75beff", //"debugIcon.stepOverForeground": "#75beff", //"debugIcon.stopForeground": "#f48771", //"debugTokenExpression.boolean": "#4e94ce", //"debugTokenExpression.error": "#f48771", //"debugTokenExpression.name": "#c586c0", //"debugTokenExpression.number": "#b5cea8", //"debugTokenExpression.string": "#ce9178", //"debugTokenExpression.value": "#cccccc99", //"debugView.exceptionLabelBackground": "#6c2022", //"debugView.exceptionLabelForeground": "#cacde2", //"debugView.stateLabelBackground": "#88888844", //"debugView.stateLabelForeground": "#cacde2", //"debugView.valueChangedHighlight": "#569cd6", //"diffEditor.diagonalFill": "#cccccc33", //"dropdown.foreground": "#f0f0f0", //"editor.findRangeHighlightBackground": "#3a3d4166", //"editor.focusedStackFrameHighlightBackground": "#7abd7a4d", //"editor.foldBackground": "#54bef213", //"editor.hoverHighlightBackground": "#264f7840", //"editor.inactiveSelectionBackground": "#54bef220", //"editor.inlineValuesBackground": "#ffc80033", //"editor.inlineValuesForeground": "#ffffff80", //"editor.lineHighlightBorder": "#282828", //"editor.linkedEditingBackground": "#ff00004d", //"editor.rangeHighlightBackground": "#ffffff0b", //"editor.snippetFinalTabstopHighlightBorder": "#525252", //"editor.snippetTabstopHighlightBackground": "#7c7c7c4d", //"editor.stackFrameHighlightBackground": "#ffff0033", //"editor.symbolHighlightBackground": "#54bef260", //"editor.wordHighlightBackground": "#575757b8", //"editor.wordHighlightStrongBackground": "#004972b8", //"editorActiveLineNumber.foreground": "#c6c6c6", //"editorBracketHighlight.foreground1": "#ffd700", //"editorBracketHighlight.foreground2": "#da70d6", //"editorBracketHighlight.foreground3": "#179fff", //"editorBracketHighlight.foreground4": "#00000000", //"editorBracketHighlight.foreground5": "#00000000", //"editorBracketHighlight.foreground6": "#00000000", //"editorBracketHighlight.unexpectedBracket.foreground": "#ff1212cc", //"editorGhostText.foreground": "#ffffff56", //"editorGroup.dropBackground": "#53595d80", //"editorGroupHeader.noTabsBackground": "#111720", //"editorGutter.background": "#111720", //"editorGutter.commentRangeForeground": "#c5c5c5", //"editorGutter.foldingControlForeground": "#cacde2", //"editorHint.foreground": "#eeeeeeb3", //"editorHoverWidget.foreground": "#cacde2", //"editorHoverWidget.statusBarBackground": "#141c26", //"editorLightBulb.foreground": "#ffcc00", //"editorLightBulbAutoFix.foreground": "#75beff", //"editorMarkerNavigationError.background": "#fb718540", //"editorMarkerNavigationError.headerBackground": "#fb718506", //"editorMarkerNavigationInfo.background": "#54bef240", //"editorMarkerNavigationInfo.headerBackground": "#54bef206", //"editorMarkerNavigationWarning.background": "#ffcb6b40", //"editorMarkerNavigationWarning.headerBackground": "#ffcb6b06", //"editorOverviewRuler.bracketMatchForeground": "#a0a0a0", //"editorOverviewRuler.commonContentForeground": "#60606066", //"editorPane.background": "#111720", //"editorSuggestWidget.selectedIconForeground": "#ffffff", //"editorUnnecessaryCode.opacity": "#000000aa", //"editorWidget.foreground": "#cacde2", //"errorForeground": "#f48771", //"extensionBadge.remoteBackground": "#54bef2", //"extensionBadge.remoteForeground": "#00111a", //"extensionButton.prominentForeground": "#00111a", //"extensionIcon.starForeground": "#ff8e00", //"gitDecoration.addedResourceForeground": "#81b88b", //"gitDecoration.renamedResourceForeground": "#73c991", //"gitDecoration.stageDeletedResourceForeground": "#c74e39", //"gitDecoration.stageModifiedResourceForeground": "#e2c08d", //"gitlens.decorations.addedForegroundColor": "#81b88b", //"gitlens.decorations.branchUpToDateForegroundColor": "#7e8995", //"gitlens.decorations.copiedForegroundColor": "#73c991", //"gitlens.decorations.deletedForegroundColor": "#fb7185cc", //"gitlens.decorations.ignoredForegroundColor": "#5c6270", //"gitlens.decorations.modifiedForegroundColor": "#ffcb6bcc", //"gitlens.decorations.renamedForegroundColor": "#73c991", //"gitlens.decorations.untrackedForegroundColor": "#82f1b1cc", //"inputOption.activeForeground": "#ffffff", //"inputValidation.errorBackground": "#5a1d1d", //"inputValidation.infoBackground": "#063b49", //"inputValidation.warningBackground": "#352a05", //"interactive.activeCodeBorder": "#cacde210", //"interactive.inactiveCodeBorder": "#111720", //"list.deemphasizedForeground": "#8c8c8c", //"list.errorForeground": "#f88070", //"list.filterMatchBackground": "#54bef260", //"list.filterMatchBorder": "#cacde210", //"list.focusOutline": "#11172000", //"list.invalidItemForeground": "#b89500", //"list.warningForeground": "#cca700", //"merge.commonContentBackground": "#60606029", //"merge.commonHeaderBackground": "#60606066", //"merge.currentContentBackground": "#40c8ae33", //"merge.currentHeaderBackground": "#40c8ae80", //"merge.incomingContentBackground": "#40a6ff33", //"merge.incomingHeaderBackground": "#40a6ff80", //"minimap.errorHighlight": "#ff1212b3", //"minimap.findMatchHighlight": "#d18616", //"minimap.selectionHighlight": "#264f78", //"minimap.warningHighlight": "#ffcb6b40", //"minimapGutter.addedBackground": "#587c0c", //"minimapGutter.deletedBackground": "#94151b", //"minimapGutter.modifiedBackground": "#0c7d9d", //"minimapSlider.activeBackground": "#54bef220", //"minimapSlider.background": "#54bef218", //"minimapSlider.hoverBackground": "#11172080", //"notebook.cellBorderColor": "#111720", //"notebook.cellEditorBackground": "#cacde20a", //"notebook.cellInsertionIndicator": "#11172000", //"notebook.cellStatusBarItemHoverBackground": "#ffffff26", //"notebook.cellToolbarSeparator": "#80808059", //"notebook.focusedCellBorder": "#11172000", //"notebook.focusedEditorBorder": "#11172000", //"notebook.inactiveFocusedCellBorder": "#111720", //"notebook.selectedCellBackground": "#111720", //"notebook.selectedCellBorder": "#111720", //"notebook.symbolHighlightBackground": "#ffffff0b", //"notebookScrollbarSlider.activeBackground": "#54bef240", //"notebookScrollbarSlider.background": "#54bef230", //"notebookScrollbarSlider.hoverBackground": "#111720", //"notebookStatusErrorIcon.foreground": "#f48771", //"notebookStatusRunningIcon.foreground": "#cacde2", //"notebookStatusSuccessIcon.foreground": "#89d185", //"notifications.border": "#111720", //"panelSection.border": "#111720", //"panelSection.dropBackground": "#53595d80", //"panelSectionHeader.background": "#80808033", //"peekViewResult.fileForeground": "#ffffff", //"peekViewResult.lineForeground": "#bbbbbb", //"peekViewResult.selectionForeground": "#ffffff", //"peekViewTitleLabel.foreground": "#ffffff", //"pickerGroup.border": "#3f3f46", //"ports.iconRunningProcessForeground": "#54bef2", //"problemsErrorIcon.foreground": "#fb718540", //"problemsInfoIcon.foreground": "#54bef240", //"problemsWarningIcon.foreground": "#ffcb6b40", //"quickInput.background": "#111720", //"quickInput.foreground": "#cacde2", //"quickInputList.focusBackground": "#7e899560", //"quickInputList.focusForeground": "#ffffff", //"quickInputList.focusIconForeground": "#ffffff", //"quickInputTitle.background": "#ffffff1b", //"rust_analyzer.inlayHints.background": "#11223300", //"rust_analyzer.inlayHints.background.chainingHints": "#11223300", //"rust_analyzer.inlayHints.background.parameterHints": "#11223300", //"rust_analyzer.inlayHints.background.typeHints": "#11223300", //"rust_analyzer.inlayHints.foreground": "#a0a0a0f0", //"rust_analyzer.inlayHints.foreground.chainingHints": "#a0a0a0f0", //"rust_analyzer.inlayHints.foreground.parameterHints": "#a0a0a0f0", //"rust_analyzer.inlayHints.foreground.typeHints": "#a0a0a0f0", //"rust_analyzer.syntaxTreeBorder": "#ffffff", //"sash.hoverBorder": "#11172000", //"scm.providerBorder": "#454545", //"searchEditor.findMatchBackground": "#54bef23f", //"searchEditor.findMatchBorder": "#cacde20b", //"searchEditor.textInputBorder": "#111720", //"settings.checkboxBorder": "#cacde210", //"settings.dropdownBorder": "#cacde210", //"settings.dropdownListBorder": "#54bef2", //"settings.focusedRowBackground": "#80808024", //"settings.focusedRowBorder": "#ffffff1f", //"settings.numberInputBorder": "#111720", //"settings.rowHoverBackground": "#80808012", //"settings.textInputBorder": "#111720", //"sideBar.dropBackground": "#53595d80", //"sideBarSectionHeader.foreground": "#7e8995", //"statusBar.debuggingBorder": "#111720", //"statusBar.noFolderBorder": "#111720", //"statusBar.noFolderForeground": "#7e8995", //"statusBarItem.activeBackground": "#ffffff2e", //"statusBarItem.errorBackground": "#c72e0f", //"statusBarItem.errorForeground": "#ffffff", //"statusBarItem.prominentBackground": "#00000080", //"statusBarItem.prominentHoverBackground": "#0000004d", //"statusBarItem.warningBackground": "#d98d0040", //"statusBarItem.warningForeground": "#ffffff", //"symbolIcon.arrayForeground": "#cacde2", //"symbolIcon.booleanForeground": "#cacde2", //"symbolIcon.classForeground": "#ee9d28", //"symbolIcon.colorForeground": "#cacde2", //"symbolIcon.constantForeground": "#cacde2", //"symbolIcon.constructorForeground": "#b180d7", //"symbolIcon.enumeratorForeground": "#ee9d28", //"symbolIcon.enumeratorMemberForeground": "#75beff", //"symbolIcon.eventForeground": "#ee9d28", //"symbolIcon.fieldForeground": "#75beff", //"symbolIcon.fileForeground": "#cacde2", //"symbolIcon.folderForeground": "#cacde2", //"symbolIcon.functionForeground": "#b180d7", //"symbolIcon.interfaceForeground": "#75beff", //"symbolIcon.keyForeground": "#cacde2", //"symbolIcon.keywordForeground": "#cacde2", //"symbolIcon.methodForeground": "#b180d7", //"symbolIcon.moduleForeground": "#cacde2", //"symbolIcon.namespaceForeground": "#cacde2", //"symbolIcon.nullForeground": "#cacde2", //"symbolIcon.numberForeground": "#cacde2", //"symbolIcon.objectForeground": "#cacde2", //"symbolIcon.operatorForeground": "#cacde2", //"symbolIcon.packageForeground": "#cacde2", //"symbolIcon.propertyForeground": "#cacde2", //"symbolIcon.referenceForeground": "#cacde2", //"symbolIcon.snippetForeground": "#cacde2", //"symbolIcon.stringForeground": "#cacde2", //"symbolIcon.structForeground": "#cacde2", //"symbolIcon.textForeground": "#cacde2", //"symbolIcon.typeParameterForeground": "#cacde2", //"symbolIcon.unitForeground": "#cacde2", //"symbolIcon.variableForeground": "#75beff", //"tab.activeBackground": "#111720", //"tab.inactiveModifiedBorder": "#7e899580", //"tab.lastPinnedBorder": "#585858", //"tab.unfocusedActiveBackground": "#111720", //"tab.unfocusedActiveModifiedBorder": "#7e899580", //"tab.unfocusedInactiveBackground": "#111720", //"tab.unfocusedInactiveForeground": "#7e899580", //"tab.unfocusedInactiveModifiedBorder": "#7e899540", //"terminal.border": "#111720", //"terminal.dropBackground": "#53595d80", //"terminal.foreground": "#cccccc", //"terminal.selectionBackground": "#ffffff40", //"terminal.tab.activeBorder": "#d19a66", //"testing.iconErrored": "#f14c4c", //"testing.iconFailed": "#f14c4c", //"testing.iconPassed": "#73c991", //"testing.iconQueued": "#cca700", //"testing.iconSkipped": "#848484", //"testing.iconUnset": "#848484", //"testing.message.error.decorationForeground": "#fb718540", //"testing.message.error.lineBackground": "#ff000033", //"testing.message.info.decorationForeground": "#cacde280", //"testing.peekBorder": "#fb718540", //"testing.peekHeaderBackground": "#fb718506", //"testing.runAction": "#73c991", //"textBlockQuote.background": "#7f7f7f1a", //"textBlockQuote.border": "#007acc80", //"textSeparator.foreground": "#ffffff2e", //"toolbar.activeBackground": "#00131d50", //"tree.indentGuidesStroke": "#585858", //"tree.tableColumnsBorder": "#cccccc20", //"welcomePage.progress.background": "#00111a50", //"welcomePage.progress.foreground": "#54bef2", //"welcomePage.tileBackground": "#111720", //"welcomePage.tileHoverBackground": "#141c26", //"welcomePage.tileShadow.": "#00111a10", //"activityBar.activeBackground": null, //"activityBar.activeFocusBorder": null, //"contrastActiveBorder": null, //"contrastBorder": null, //"debugToolBar.border": null, //"diffEditor.border": null, //"diffEditor.insertedTextBorder": null, //"diffEditor.removedTextBorder": null, //"dropdown.listBackground": null, //"editor.findRangeHighlightBorder": null, //"editor.rangeHighlightBorder": null, //"editor.selectionForeground": null, //"editor.selectionHighlightBorder": null, //"editor.snippetFinalTabstopHighlightBackground": null, //"editor.snippetTabstopHighlightBorder": null, //"editor.symbolHighlightBorder": null, //"editor.wordHighlightBorder": null, //"editor.wordHighlightStrongBorder": null, //"editorCursor.background": null, //"editorError.background": null, //"editorError.border": null, //"editorGhostText.border": null, //"editorGroup.background": null, //"editorGroup.emptyBackground": null, //"editorGroup.focusedEmptyBorder": null, //"editorGroupHeader.border": null, //"editorGroupHeader.tabsBorder": null, //"editorHint.border": null, //"editorInfo.background": null, //"editorInfo.border": null, //"editorUnnecessaryCode.border": null, //"editorWarning.background": null, //"editorWarning.border": null, //"inputValidation.errorForeground": null, //"inputValidation.infoForeground": null, //"inputValidation.warningForeground": null, //"list.inactiveFocusBackground": null, //"list.inactiveFocusOutline": null, //"list.inactiveSelectionIconForeground": null, //"menu.border": null, //"menu.selectionBorder": null, //"menubar.selectionBorder": null, //"merge.border": null, //"minimap.background": null, //"notebook.cellHoverBackground": null, //"notebook.focusedCellBackground": null, //"notebook.inactiveSelectedCellBorder": null, //"notebook.outputContainerBackgroundColor": null, //"notificationCenter.border": null, //"notificationToast.border": null, //"panelInput.border": null, //"panelSectionHeader.border": null, //"panelSectionHeader.foreground": null, //"peekViewEditor.matchHighlightBorder": null, //"quickInput.list.focusBackground": null, //"tab.activeBorderTop": null, //"tab.hoverBackground": null, //"tab.hoverBorder": null, //"tab.hoverForeground": null, //"tab.unfocusedActiveBorderTop": null, //"tab.unfocusedHoverBackground": null, //"tab.unfocusedHoverBorder": null, //"tab.unfocusedHoverForeground": null, //"terminal.background": null, //"testing.message.info.lineBackground": null, //"toolbar.hoverOutline": null, //"walkThrough.embeddedEditorBackground": null, //"welcomePage.background": null, //"welcomePage.buttonBackground": null, //"welcomePage.buttonHoverBackground": null, //"window.activeBorder": null, //"window.inactiveBorder": null }; //# sourceMappingURL=ocean.js.map
ealbertos/dotfiles
vscode.symlink/extensions/zhuangtongfa.material-theme-3.13.6/out/themes/data/ocean.js
JavaScript
mit
28,812
const Sequelize = require('sequelize'); module.exports = (sequelize) => { return sequelize.define('User', { created_at: { allowNull: false, type: Sequelize.DATE, }, deleted_at: { allowNull: true, type: Sequelize.DATE, }, email: { allowNull: false, type: Sequelize.STRING, }, first_name: { allowNull: false, type: Sequelize.STRING, }, household_uuid: { allowNull: false, type: Sequelize.UUID, }, last_name: { allowNull: false, type: Sequelize.STRING, }, updated_at: { allowNull: false, type: Sequelize.DATE, }, uuid: { allowNull: false, defaultValue: Sequelize.UUIDV4, primaryKey: true, type: Sequelize.UUID, }, }, { paranoid: true, tableName: 'users', timestamps: true, }); };
gabrieltanchen/xpns-api
app/models/user.js
JavaScript
mit
868
var async = require('async'); var rest = require('unirest'); var http = require('http'); var read_quorum = 2 var write_quorum = 1 var peers = require('../p2p.js').peers; var host_by_port = require('../p2p.js').host_by_port exports.sloppy_write = function(key, val, callback) { var tx = { id: make_id(), key: key, val: val, ts: (new Date).getTime() } console.log('1. sloppy proposal of ' + write_quorum + ' to peers: ', JSON.stringify(tx)); ask_with_quorum("propose", create_tasks(tx, propose), write_quorum, function(err, responses) { if (callback.called) return; if (has_quorum(responses, write_quorum)) { console.log('2. proposal accepted by quorum of ' + write_quorum); tx.quorum = true; ask_with_quorum("commit", create_tasks(tx, commit), write_quorum, function(err, responses) { if (has_quorum(responses, write_quorum)) { console.log('3. commit accepted by quorum of ' + write_quorum); callback.called = true; callback(err, tx) } }); } else if (!tx.quorum) { console.log('2. failure - sending rollback to peers', err); ask_with_quorum("rollback", create_tasks(tx, rollback), write_quorum, function(err) { callback.called = true; callback(err, tx) }); } }); }; exports.smart_read = function(key, callback) { console.log('Reading the data "' + key + '" with quorum of ' + read_quorum + ' from peers'); ask_with_quorum("read", create_tasks(key, read), read_quorum, function(err, responses) {; var result = get_agreed_result(responses); if (result.response && !callback.called) { value = valueof(result.response); console.log("Agreed value '" + value + "' based on " + responses.length + " responses"); callback.called = true; callback(null, value); } process_disagreement(result); }); } create_tasks = function(arg, task_factory) { var tasks = [] peers().forEach(function(peer) { task = task_factory(arg, peer); task.id = peer.port; tasks.push(task); }); return tasks; } propose = function(tx, peer) { return function(callback) { var url = "http://" + peer.host + ":" + peer.port + "/quorum/propose"; console.log("Sending %s to url %s", JSON.stringify(tx), url) rest.post(url) .timeout(10000) .headers({ 'Content-Type': 'application/json' }) .send(JSON.stringify(tx)) .end(function(response) { callback(response); }); } } commit = function(tx, peer) { return function(callback) { var url = "http://" + peer.host + ":" + peer.port + "/quorum/commit/" + tx.id; rest.post(url).end(function(response) { callback(response); }); }; } rollback = function(tx, peer) { return function(callback) { var url = "http://" + peer.host + ":" + peer.port + "/quorum/rollback/" + tx.id; rest.post(url).end(function(response) { callback(response); }); }; } read = function(key, peer) { return function(callback) { var url = "http://" + peer.host + ":" + peer.port + "/quorum/read/" + key; rest.get(url).end(function(response) { callback(response); }); }; } ask_with_quorum = function(what, tasks, quorum, callback) { var votes = 0; var responses = []; var queue = async.queue(function(task, callback) { task(callback); }, 3); queue.drain = function() { if (votes < quorum) { var err = "- " + what + ": quorum of " + quorum + " not reached, " + responses.length + " responses, " + votes + " valid votes"; console.log(err); callback(err, responses); } } tasks.forEach(function(task) { queue.push(task, function(response) { responses.push(response); if (response.statusCode == 200 || response.statusCode == 404) { votes++; console.log("- " + what + ": vote from " + task.id + ": " + response.statusCode); if (responses.length >= quorum) { callback(null, responses); } } else { console.log("- " + what + ": vote from " + task.id + ": " + response.statusCode); } }); }); } has_quorum = function(responses, quorum) { var total = 0; for (var response of responses) { if (response.statusCode == 200) total++; } return total == quorum; } get_agreed_result = function(responses) { var has_value = []; var not_found = []; console.log("Total responses: " + responses.length); for (var response of responses) { if (response.statusCode == 200) has_value.push(response); else if (response.statusCode == 404) not_found.push(response); } var disagreements = []; var agreed_response = null; if (not_found.length >= read_quorum) { disagreements = has_value; agreed_response = not_found[0]; } else if (has_value.length >= read_quorum) { disagreements = not_found.slice(); var results = {}; for (var response of has_value) { value = response.body.val; if (!results[value]) { results[value] = {}; results[value].count = 1; results[value].response = response; } else { results[value].count++; } if (results[value].count >= read_quorum && !agreed_response) { console.log("We have an agreed response", JSON.stringify(response.body)); agreed_response = response; } } var num_of_results = Object.keys(results).length; if (num_of_results > 1) { if (agreed_response) { console.log("We have a disagreement: " + num_of_results + " different results!"); delete results[agreed_response.body.val]; Object.keys(results).forEach(function(key, index) { disagreements.push(results[key].response); }); } } } console.log("- total 200s:", has_value.length, agreed_response ? "" : "(inconclusive)"); console.log("- total 404s:", not_found.length); return { response: agreed_response, responses: responses, disagreements: disagreements }; } process_disagreement = function(result) { if (result.disagreements.length == 0) return; console.log('\nDisagreements to process: ', result.disagreements.length); for (var disagreement of result.disagreements) { var port = disagreement.headers['x-sys-id']; var host = host_by_port(port); var body = result.response.body; var url = "http://" + host + ":" + port + "/quorum/repair"; console.log('- repairing ' + port + ':', JSON.stringify(body)) rest.post(url) .headers({ 'Content-Type': 'application/json' }) .send(JSON.stringify(body)) .end(); } } make_id = function() { return Math.random().toString(36).substring(2, 5); } success = function(err) { return !err ? 'success' : err } valueof = function(response) { if (response && response.statusCode == 200) return response.body.val; else return undefined; }
bbossola/sysdist
AP/quorum.js
JavaScript
mit
7,753
var autoload = require('auto-load'); module.exports = { handlers: autoload(__dirname + '/handlers'), middlewares: autoload(__dirname + '/middlewares'), helpers: autoload(__dirname + '/helpers') };
hexanom/sfdc-rt.anyfetch.com
lib/index.js
JavaScript
mit
205
'use strict'; var http = require('http'); var https = require('https'); var urlLib = require('url'); var util = require('util'); var zlib = require('zlib'); var querystring = require('querystring'); var objectAssign = require('object-assign'); var infinityAgent = require('infinity-agent'); var duplexify = require('duplexify'); var isStream = require('is-stream'); var readAllStream = require('read-all-stream'); var timedOut = require('timed-out'); var prependHttp = require('prepend-http'); var lowercaseKeys = require('lowercase-keys'); var isRedirect = require('is-redirect'); var NestedErrorStacks = require('nested-error-stacks'); function GotError(message, nested) { NestedErrorStacks.call(this, message, nested); objectAssign(this, nested, {nested: this.nested}); } util.inherits(GotError, NestedErrorStacks); GotError.prototype.name = 'GotError'; function got(url, opts, cb) { if (typeof url !== 'string' && typeof url !== 'object') { throw new GotError('Parameter `url` must be a string or object, not ' + typeof url); } if (typeof opts === 'function') { cb = opts; opts = {}; } opts = objectAssign( { protocol: 'http:' }, typeof url === 'string' ? urlLib.parse(prependHttp(url)) : url, opts ); opts.headers = objectAssign({ 'user-agent': 'https://github.com/sindresorhus/got', 'accept-encoding': 'gzip,deflate' }, lowercaseKeys(opts.headers)); if (opts.pathname) { opts.path = opts.pathname; } if (opts.query) { if (typeof opts.query !== 'string') { opts.query = querystring.stringify(opts.query); } opts.path = opts.pathname + '?' + opts.query; delete opts.query; } var encoding = opts.encoding; var body = opts.body; var json = opts.json; var timeout = opts.timeout; var proxy; var redirectCount = 0; delete opts.encoding; delete opts.body; delete opts.json; delete opts.timeout; if (json) { opts.headers.accept = opts.headers.accept || 'application/json'; } if (body) { if (typeof body !== 'string' && !Buffer.isBuffer(body) && !isStream.readable(body)) { throw new GotError('options.body must be a ReadableStream, string or Buffer'); } opts.method = opts.method || 'POST'; if (!opts.headers['content-length'] && !opts.headers['transfer-encoding'] && !isStream.readable(body)) { var length = typeof body === 'string' ? Buffer.byteLength(body) : body.length; opts.headers['content-length'] = length; } } opts.method = opts.method || 'GET'; // returns a proxy stream to the response // if no callback has been provided if (!cb) { proxy = duplexify(); // forward errors on the stream cb = function (err, data, response) { proxy.emit('error', err, data, response); }; } if (proxy && json) { throw new GotError('got can not be used as stream when options.json is used'); } function get(opts, cb) { var fn = opts.protocol === 'https:' ? https : http; var url = urlLib.format(opts); if (opts.agent === undefined) { opts.agent = infinityAgent[fn === https ? 'https' : 'http'].globalAgent; if (process.version.indexOf('v0.10') === 0 && fn === https && ( typeof opts.ca !== 'undefined' || typeof opts.cert !== 'undefined' || typeof opts.ciphers !== 'undefined' || typeof opts.key !== 'undefined' || typeof opts.passphrase !== 'undefined' || typeof opts.pfx !== 'undefined' || typeof opts.rejectUnauthorized !== 'undefined')) { opts.agent = new infinityAgent.https.Agent({ ca: opts.ca, cert: opts.cert, ciphers: opts.ciphers, key: opts.key, passphrase: opts.passphrase, pfx: opts.pfx, rejectUnauthorized: opts.rejectUnauthorized }); } } var req = fn.request(opts, function (response) { var statusCode = response.statusCode; var res = response; // auto-redirect only for GET and HEAD methods if (isRedirect(statusCode) && 'location' in res.headers && (opts.method === 'GET' || opts.method === 'HEAD')) { // discard response res.resume(); if (++redirectCount > 10) { cb(new GotError('Redirected 10 times. Aborting.'), undefined, res); return; } var redirectUrl = urlLib.resolve(url, res.headers.location); var redirectOpts = objectAssign(opts, urlLib.parse(redirectUrl)); if (proxy) { proxy.emit('redirect', res, redirectOpts); } get(redirectOpts, cb); return; } if (proxy) { proxy.emit('response', res); } if (['gzip', 'deflate'].indexOf(res.headers['content-encoding']) !== -1) { res = res.pipe(zlib.createUnzip()); } if (statusCode < 200 || statusCode > 299) { readAllStream(res, encoding, function (err, data) { err = new GotError(opts.method + ' ' + url + ' response code is ' + statusCode + ' (' + http.STATUS_CODES[statusCode] + ')', err); err.code = statusCode; if (data && json) { try { data = JSON.parse(data); } catch (e) { err = new GotError('Parsing ' + url + ' response failed', new GotError(e.message, err)); } } cb(err, data, response); }); return; } // pipe the response to the proxy if in proxy mode if (proxy) { proxy.setReadable(res); return; } readAllStream(res, encoding, function (err, data) { if (err) { err = new GotError('Reading ' + url + ' response failed', err); } else if (json && statusCode !== 204) { // only parse json if the option is enabled, and the response // is not a 204 (empty reponse) try { data = JSON.parse(data); } catch (e) { err = new GotError('Parsing ' + url + ' response failed', e); } } cb(err, data, response); }); }).once('error', function (err) { cb(new GotError('Request to ' + url + ' failed', err)); }); if (timeout) { timedOut(req, timeout); } if (!proxy) { if (isStream.readable(body)) { body.pipe(req); } else { req.end(body); } return; } if (body) { proxy.write = function () { throw new Error('got\'s stream is not writable when options.body is used'); }; if (isStream.readable(body)) { body.pipe(req); } else { req.end(body); } return; } if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') { proxy.setWritable(req); return; } req.end(); } get(opts, cb); return proxy; } [ 'get', 'post', 'put', 'patch', 'head', 'delete' ].forEach(function (el) { got[el] = function (url, opts, cb) { if (typeof opts === 'function') { cb = opts; opts = {}; } return got(url, objectAssign({}, opts, {method: el.toUpperCase()}), cb); }; }); module.exports = got;
mattdesl/got
index.js
JavaScript
mit
6,633
export default { name: 'session', initialize: function(application) { application.inject('controller', 'session', 'service:session'); application.inject('route', 'session', 'service:session'); application.inject('component', 'session', 'service:session'); application.inject('component', 'router', 'router:main'); } };
crossroads/shared.goodcity
app/initializers/session.js
JavaScript
mit
341
import { expect } from 'chai'; //sampleを書いておこうと思ったけどアホほどあるので辞めた。 describe('example', () => { it('.not絡み', () => { expect("a").to.not.equal("bar"); expect({ foo:'baz'}).to.have.property('foo').and.not.equal('bar'); }); });
defvar/toyctron
test/sample.spec.js
JavaScript
mit
289
'use strict'; var url = require('url'); var qs = require('qs'); var _ = require('lodash'); var Promise = require('bluebird'); var dataPackageApi = require('../data-package-api'); var stateParams = require('./params'); var history = require('./history'); var theme = require('./theme'); var visualizationsService = require('../visualizations'); var maxDimensionValuesForColumns = 50; function getHierarchiesWithLimitedDimensionValues(hierarchies, minValueCount, maxValueCount) { return _.chain(hierarchies) .map(function(hierarchy) { var result = _.extend({}, hierarchy); result.dimensions = _.filter(hierarchy.dimensions, function(dimension) { var n = dimension.values.length; return (n >= minValueCount) && (n <= maxValueCount); }); if (result.dimensions.length > 0) { return result; } }) .filter() .value(); } function loadDataPackages(authToken, packageId, userId) { var promises = []; // Load package specified by packageId - it should be always available, // but hidden if (packageId) { promises.push(dataPackageApi.getDataPackages(authToken, packageId)); } // Load packages for logged-in user if (userId) { promises.push(dataPackageApi.getDataPackages(authToken, null, userId)); } else { promises.push(Promise.resolve([])); } return Promise.all(promises).then(function(results) { var result = _.clone(_.last(results)); if (results.length > 1) { var hiddenPackage = _.first(results[0]); var found = !!_.find(result, {id: hiddenPackage.id}); if (!found) { hiddenPackage.isHidden = true; result.push(hiddenPackage); } } return result; }); } function loadDataPackage(packageId, initialParams) { return dataPackageApi.getDataPackage(packageId, true) .then(function(packageModel) { var params = _.extend( stateParams.init(packageModel, initialParams), { babbageApiUrl: dataPackageApi.apiConfig.url, cosmopolitanApiUrl: dataPackageApi.apiConfig.cosmoUrl } ); return { package: packageModel, params: params, history: history.init() }; }); } function fullyPopulateModel(state) { return dataPackageApi.loadDimensionsValues(state.package, null, state.params.filters) .then(function(packageModel) { packageModel.columnHierarchies = getHierarchiesWithLimitedDimensionValues(packageModel.hierarchies, 1, maxDimensionValuesForColumns); // Get some special hierarchies packageModel.seriesHierarchies = getHierarchiesWithLimitedDimensionValues( packageModel.hierarchies, 1, 10); // Update dateTime hierarchies list packageModel.dateTimeHierarchies = getHierarchiesWithLimitedDimensionValues( packageModel.dateTimeHierarchies, 2, Number.MAX_VALUE); return state; }); } function partiallyPopulateModel(state) { var selectedGroup = _.first(state.params.groups); if (selectedGroup) { var hierarchy = _.find(state.package.hierarchies, function(hierarchy) { return !!_.find(hierarchy.dimensions, { key: selectedGroup }); }); if (hierarchy) { return dataPackageApi.loadDimensionsValues(state.package, hierarchy.dimensions) .then(function(packageModel) { return state; }); } } return Promise.resolve(state); } function parseUrl(pageUrl) { var urlParams = url.parse(pageUrl || ''); urlParams.query = qs.parse(urlParams.query); var path = urlParams.pathname || ''; if (path.substr(0, 1) == '/') { path = path.substr(1, path.length); } if (path.substr(-1, 1) == '/') { path = path.substr(0, path.length - 1); } path = path.split('/'); var result = urlParams.query; result.packageId = null; if (path.length == 1) { result.packageId = path[0]; } if ((path.length == 2) && (path[0] == 'embed')) { result.packageId = path[1]; } if ((path.length == 3) && (path[0] == 'embed')) { result.packageId = path[2]; var visualization = visualizationsService.findVisualization({ embed: path[1] }); if (visualization) { result.visualizations = [visualization.id]; } } return result; } function choosePackage(dataPackages, packageId) { var dataPackage = _.find(dataPackages, function(item) { return item.id == packageId; }); if (!dataPackage) { dataPackage = _.first(dataPackages); } return dataPackage ? dataPackage.id : null; } function getInitialState(dataPackages, pageUrl) { var urlParams = parseUrl(pageUrl); var packageId = choosePackage(dataPackages, urlParams.packageId); if (packageId) { // If package identified by url does not exist - // invalidate other params from url if (packageId != urlParams.packageId) { urlParams = { packageId: packageId }; } return loadDataPackage(packageId, urlParams); } return Promise.reject(new Error('No packages available')); } function getAvailableSorting(state) { var packageModel = state.package; var params = state.params; return _.chain([ _.find(packageModel.measures, function(item) { return params.measures.indexOf(item.key) >= 0; }), _.find(packageModel.dimensions, function(item) { return params.groups.indexOf(item.key) >= 0; }) ]) .filter() .map(function(item) { return { label: item.label, key: item.sortKey || item.key }; }) .value(); } function getCurrencySign(state) { var measure = _.first(state.params.measures); measure = _.find(state.package.measures, {key: measure}); return measure ? measure.currency : null; } // Helper functions for `buildBreadcrumbs()` function getBaseFilters(filters, dimensions) { var result = {}; _.each(filters, function(values, key) { var dimension = _.find(dimensions, {key: key}); if (!dimension) { result[key] = values; } }); return result; } function getSelectedFilters(state) { var params = state.params; var packageModel = state.package; return _.chain(params.filters) .map(function(valueKeys, dimensionKey) { var dimension = _.find(packageModel.dimensions, { key: dimensionKey }); var values = _.filter(dimension.values, function(item) { return !!_.find(valueKeys, function(key) { return key == item.key; }); }); return { dimensionLabel: dimension.label, dimensionKey: dimension.key, valueLabel: _.map(values, function(item) { return item.label; }), valueKey: _.map(values, function(item) { return item.key; }) }; }) .filter() .sortBy('dimensionLabel') .value(); } function buildBreadcrumbs(state) { var params = state.params; var packageModel = state.package; var result = []; var groupKey = null; if (_.isArray(params.drilldown) && (params.drilldown.length > 0)) { groupKey = _.first(params.drilldown).dimension; } else { groupKey = _.first(params.groups); } var hierarchy = _.find(packageModel.hierarchies, function(hierarchy) { return !!_.find(hierarchy.dimensions, {key: groupKey}); }); if (hierarchy) { result.push({ label: hierarchy.label, index: 0 }); _.each(params.drilldown, function(item, index) { var dimension = _.find(hierarchy.dimensions, {key: item.dimension}); if (dimension) { var value = _.find(dimension.values, {key: item.filter}); if (value) { result.push({ label: value.label, index: index + 1 }); } } }); } return result; } function translateHierarchies(state, i18n) { _.forEach(state.package.hierarchies, function(hierarchy) { hierarchy.label = i18n(hierarchy.label); }); } // embedParams is an object with options for creating embed url. // Allowed properties: // `visualization`: value from `<visualization>.embed` property; // `protocol`, `host`, `port` - values to be appended to url; // `base` - base url to be added to `path` part function buildUrl(params, embedParams) { var query = {}; if (!!params.lang) { query.lang = params.lang; } if (!!params.theme) { query.theme = params.theme; } if (params.measures.length > 0) { query.measure = _.first(params.measures); } _.each(['groups', 'series', 'rows', 'columns'], function(axis) { if (params[axis].length > 0) { query[axis] = params[axis]; } }); query.filters = _.cloneDeep(params.filters); if (_.isArray(params.drilldown)) { _.each(params.drilldown, function(item) { // When drilldown - replace filters for all drilldown // dimensions: they cannot be selected by user, but ensure // that there are no any garbage query.filters[item.dimension] = [item.filter]; }); } if (params.orderBy.key) { query.order = params.orderBy.key + '|' + params.orderBy.direction; } if ((params.visualizations.length > 0) && !embedParams) { query.visualizations = params.visualizations; } var path = '/' + params.packageId; if (embedParams) { path = '/embed/' + embedParams.visualization + path; if (embedParams.base) { var base = embedParams.base; if (base.substr(0, 1) != '/') { base = '/' + base; } if (base.substr(-1, 1) == '/') { base = base.substr(0, base.length - 1); } path = base + path; } } embedParams = embedParams || {}; // to simplify next lines return url.format({ protocol: embedParams.protocol, hostname: embedParams.host, port: embedParams.port, pathname: path, search: qs.stringify(query, { arrayFormat: 'brackets', encode: false }) }); } function hasDrillDownVisualizations(params) { var result = false; if (_.isArray(params.visualizations)) { var visualizations = visualizationsService.getVisualizationsByIds( params.visualizations); _.each(visualizations, function(item) { if (item.type == 'drilldown') { result = true; return true; } }); } return result; } module.exports.params = stateParams; module.exports.history = history; module.exports.theme = theme; module.exports.loadDataPackages = loadDataPackages; module.exports.loadDataPackage = loadDataPackage; module.exports.parseUrl = parseUrl; module.exports.getInitialState = getInitialState; module.exports.fullyPopulateModel = fullyPopulateModel; module.exports.partiallyPopulateModel = partiallyPopulateModel; module.exports.getAvailableSorting = getAvailableSorting; module.exports.getCurrencySign = getCurrencySign; module.exports.getSelectedFilters = getSelectedFilters; module.exports.buildBreadcrumbs = buildBreadcrumbs; module.exports.buildUrl = buildUrl; module.exports.translateHierarchies = translateHierarchies; module.exports.hasDrillDownVisualizations = hasDrillDownVisualizations;
borysyuk/fiscal-data-package-viewer
app/front/scripts/services/os-viewer/index.js
JavaScript
mit
11,008
/** * Criteria.js * * @description :: * @humpback-docs :: https://github.com/CaliStyle/humpback/wiki/Models#alert * @sails-docs :: http://sailsjs.org/#!documentation/models */ var _ = require('lodash'); var _super = require('humpback-hook/api/models/Criteria'); _.merge(exports, _super); _.merge(exports, { /** * Extend the Model * https://github.com/CaliStyle/humpback-hook/blob/master/api/models/Criteria.js * @exmaple: * attributes : { * foo : {type: 'string'} * }, * bar: function(values, next){ * next(); * } */ });
CaliStyle/humpback
api/models/Criteria.js
JavaScript
mit
567
Package.describe({ name: "vulcan:posts", summary: "Vulcan posts package", version: '1.6.0', git: "https://github.com/TelescopeJS/telescope-posts.git" }); Package.onUse(function (api) { api.versionsFrom(['METEOR@1.0']); api.use([ 'vulcan:core@1.6.0', 'vulcan:events@1.6.0', ]); api.mainModule("lib/server.js", "server"); api.mainModule("lib/client.js", "client"); });
acidsound/Telescope
packages/vulcan-posts/package.js
JavaScript
mit
398
var test = require('tape'); var immediate = require("../lib"); test("Handlers do execute", function (t) { immediate(function () { t.ok(true, 'handler executed'); t.end(); }); }); test("Handlers do not execute in the same event loop turn as the call to `setImmediate`", function (t) { var handlerCalled = false; function handler() { handlerCalled = true; t.ok(true, 'handler called'); t.end(); } immediate(handler); t.notOk(handlerCalled); }); test("big test", function (t) { //mainly for optimizition testing var i = 1000; function doStuff() { i--; if(!i) { t.ok(true, 'big one works'); t.end(); } else { immediate(doStuff); } } immediate(doStuff); }); if (process.browser && typeof Worker !== 'undefined') { test("worker", function (t) { var worker = new Worker('./test/worker.js'); worker.onmessage = function (e) { t.equal(e.data, 'pong'); t.end(); }; worker.postMessage('ping'); }); } test('test errors', function (t) { t.plan(7); var order = 0; process.once('uncaughtException', function(err) { t.ok(true, err.message); t.equals(2, order++, 'error is third'); immediate(function () { t.equals(5, order++, 'schedualed in error is last'); }); }); immediate(function (num1, num2) { t.equals(num1, order++, 'first one works'); immediate(function (num) { t.equals(num, order++, 'recursive one is 4th'); }, num2); }, 0, 4); immediate(function () { t.equals(1, order++, 'second one starts'); throw(new Error('an error is thrown')); }); immediate(function () { t.equals(3, order++, '3rd schedualed happens after the error'); }); });
calvinmetcalf/immediate
test/tests.js
JavaScript
mit
1,805
'use strict'; describe('Service: CompanyService', function () { // load the service's module beforeEach(module('stockDogApp')); // instantiate service var CompanyService; beforeEach(inject(function (_CompanyService_) { CompanyService = _CompanyService_; })); it('should do something', function () { expect(!!CompanyService).toBe(true); }); });
sourcewalker/stockdog
test/spec/services/companyservice.js
JavaScript
mit
373
'use strict'; const assert = require('assert'); const mockRequire = require('mock-require'); const mockBindings = require('./mocks/bindings'); const mockLinux = require('./mocks/linux'); const mockI2c = require('./mocks/i2c.node'); const sinon = require('sinon'); mockRequire('bindings', mockBindings); const i2c = require('../i2c-bus'); describe('readWordSync', () => { let i2c1; beforeEach(() => { mockLinux.mockI2c1(); i2c1 = i2c.openSync(1); sinon.stub(mockI2c, 'setAddrSync').callsFake(() => {}); sinon.stub(mockI2c, 'readWordSync').callsFake( (device, cmd) => { return 0xaa55; } ); }); it('reads word from register', () => { const addr = 0x1; const cmd = 0x2; const word = i2c1.readWordSync(addr, cmd); assert.strictEqual(word, 0xaa55); assert(mockI2c.setAddrSync.calledOnce); assert.strictEqual(mockI2c.setAddrSync.firstCall.args.length, 3); const actualAddr = mockI2c.setAddrSync.firstCall.args[1]; assert.strictEqual(addr, actualAddr); assert(mockI2c.readWordSync.calledOnce); assert.strictEqual(mockI2c.readWordSync.firstCall.args.length, 2); const actualCmd = mockI2c.readWordSync.firstCall.args[1]; assert.strictEqual(cmd, actualCmd); }); afterEach(() => { mockI2c.setAddrSync.restore(); mockI2c.readWordSync.restore(); i2c1.closeSync(); mockLinux.restore(); }); });
fivdi/i2c-bus
test/readWordSync.js
JavaScript
mit
1,415
/* The MIT License (MIT) Copyright (c) 2013 Fernando Bevilacqua 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 CODEBOT = new function() { var mShortcuts = null; var mUI = null; var mIO = null; var mEditors = null; var mSettings = null; var mSignals = null; var mJobs = null; var mPlugins = null; var mSelf; // Contain configuration parameters loaded from the app.json file. This file // is loaded before everything and it can guide how Codebot should init and // bootstrap itself. this.STATIC_APP_CONFIG = {}; /** * Get config params in the "codebot" section of the content loaded with the app.json file. * * @param {string} thePropertyName Name of the config property being read. * @param {[type]} theDefaultValue If the informed property does not exist in the config content, return this value instead. */ this.config = function(thePropertyName, theDefaultValue) { var aEntries = this.STATIC_APP_CONFIG && this.STATIC_APP_CONFIG['codebot'] ? this.STATIC_APP_CONFIG['codebot'] : {}; return (thePropertyName in aEntries) ? aEntries[thePropertyName] : theDefaultValue; }; var handleError = function(theMsg, theUrl, theLineNumber) { // Show some nice information to the user mUI.toast(Codebot.UI.TOAST_ERROR, '<h2>An error just occured</h2><p>' + theMsg + '</p>'); // Log the error and run in circles \o/ console.error("Error occured: " + theMsg); return false; }; this.loadScript = function(thePath) { console.log('CODEBOT [core] Loading script: ' + thePath); $('body').append('<script type="text/javascript" src="' + thePath + '"></script>'); }; this.loadStyle = function(thePath) { console.log('CODEBOT [core] Loading style: ' + thePath); $('body').append('<link href="' + thePath + '" rel="stylesheet" type="text/css">'); }; this.writeTabToDisk = function(theTab) { var aEditor = theTab.editor; if(aEditor) { mIO.writeFile(theTab.node, aEditor.getContent(), function() { theTab.setDirty(false); console.log('Tab data written to disk!');} ); } }; this.showDebugger= function() { if(typeof(require) == 'function') { var aGui = require('nw.gui'); var aWin = aGui.Window.get(); aWin.showDevTools(); } }; this.setIODriver = function(theIODriver) { mIO = theIODriver; console.log('CODEBOT [IO driver] ' + mIO.driver); mIO.init(); }; this.setLoadingScreenVisibility = function(theStatus) { if(theStatus) { $('#loading').fadeIn(); $('#wrapper').hide(); } else { $('#loading').fadeOut(); $('#wrapper').show(); } }; this.init = function(theIODriver) { console.log('CODEBOT [core] Initializing...'); mSelf = this; // Make Codebot catch all erros. window.onerror = handleError; mSelf.setIODriver(theIODriver || new CodebotIO()); mJobs = new CodebotJobs(); mEditors = new Codebot.Editors(); mShortcuts = new Codebot.Shortcuts(); mUI = new CodebotUI(); mSettings = new Codebot.Settings(); mSignals = new CodebotSignals(); mPlugins = new Codebot.Plugins(); mJobs.init(); mSettings.init(mSelf); mSettings.load(function() { mEditors.init(mSelf); mUI.init(mSelf); mPlugins.init(mSelf); mPlugins.load(); mShortcuts.init(mSelf); console.log('CODEBOT [core] Done, ready to rock!'); mSignals.ready.dispatch(); if(!mSelf.config('keepLoadingScreen', false)) { mSelf.setLoadingScreenVisibility(false); } mSelf.showDebugger(); }); }; // getters this.__defineGetter__("editors", function() { return mEditors; }); this.__defineGetter__("ui", function() { return mUI; }); this.__defineGetter__("io", function() { return mIO; }); this.__defineGetter__("settings", function() { return mSettings; }); this.__defineGetter__("shortcuts", function() { return mShortcuts; }); this.__defineGetter__("signals", function() { return mSignals; }); this.__defineGetter__("jobs", function() { return mJobs; }); this.__defineGetter__("plugins", function() { return mPlugins; }); };
Dovyski/Codebot
js/codebot.js
JavaScript
mit
5,133
var peerHandler = function(conn) { conn.on('open', function () { console.log('open'); helpers.instructionToggle(false); if (shared.gyro !== undefined) { shared.gyro.disconnect(); shared.gyro.toggleFreeze(); } }); conn.on('close', function () { console.log('closed'); helpers.instructionToggle(true); if (shared.gyro !== undefined) { shared.gyro.connect(); shared.gyro.toggleFreeze(); } }); conn.on('data', function (data){ helpers.manipulateScene(data,conn); }); };
jssolichin/infinite-mondrian
public/js/peerHandler.js
JavaScript
mit
612
/*! * Google Analytics Library * https://github.com/open-city/google-analytics-lib * * Copyright 2012, Nick Rougeux and Derek Eder of Open City * Licensed under the MIT license. * https://github.com/open-city/google-analytics-lib/wiki/License * * Date: 5/9/2012 * */ var analyticsTrackingCode = 'UA-85170613-1'; //enter your tracking code here var _gaq = _gaq || []; _gaq.push(['_setAccount', analyticsTrackingCode]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); _trackClickEventWithGA = function (category, action, label) { if (typeof(_gaq) != 'undefined') _gaq.push(['_setAccount', analyticsTrackingCode]); _gaq.push(['_trackEvent', category, action, label]); }; jQuery(function () { jQuery('a').click(function () { var $a = jQuery(this); var href = $a.attr("href"); //links going to outside sites if (href.match(/^http/i) && !href.match(document.domain)) { _trackClickEventWithGA("Outgoing", "Click", href); } //direct links to files if (href.match(/\.(avi|css|doc|docx|exe|gif|js|jpg|mov|mp3|pdf|png|ppt|pptx|rar|txt|vsd|vxd|wma|wmv|xls|xlsx|zip)$/i)) { _trackClickEventWithGA("Downloads", "Click", href); } //email links if (href.match(/^mailto:/i)) { _trackClickEventWithGA("Emails", "Click", href); } }); });
CodeandoGuadalajara/codeandoguadalajara.github.io
js/analytics_lib.js
JavaScript
mit
1,622
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { dev: { options: { style: 'expanded', }, files: { 'css/bootstrap-buttons.css' : 'scss/bootstrap-buttons.scss' } } }, watch: { css: { files: '**/*.scss', tasks: ['sass'] } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); //grunt.registerTask('default',['sass','watch']); grunt.registerTask('default',['sass']); }
Code-Lobster/LobsterDoc-documentation-template
gruntfile.js
JavaScript
mit
573
/** * jquery.colme.js * * @authors lopis, carlosmtx * @dependencies: jquery, jqueryui.resizable * @moto: é um plugin e vai ficar awesome * @moto2: o que é que nós não fazemos? nada. * * @class Colme * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ 'use strict'; var $; function Colme(options) { /** * Each table node is kept in this object, accessible * with the Id of the node (selectors.span) */ var tableNodes = {}; var floater = {}; if (!options.selectors) { options.selectors = {}; } if (!options.attributes) { options.attributes = {}; } if (!options.modules){ options.modules = {}; } var classes = { head : ( options.selectors.head ? options.selectors.head : 'cm-thead' ), body : ( options.selectors.body ? options.selectors.body : 'cm-tbody' ), row : ( options.selectors.row ? options.selectors.row : 'cm-tr' ), th : ( options.selectors.th ? options.selectors.th : 'cm-th' ), td : ( options.selectors.td ? options.selectors.td : 'cm-td' ), }; var selectors = { head : '.'+ classes.head , body : '.'+ classes.body , row : '.'+ classes.row , th : '.'+ classes.th , td : '.'+ classes.td }; var modules = { resize : options.modules.resize === false ? false : true, draggable: options.modules.draggable === false ? false : true, stickyH : options.modules.stickyHead === false ? false : true, toggleC : options.modules.toggleable === false ? false : true, addMarkup: options.modules.markup === false ? false : true, }; var attributes = { id : ( options.attributes.id ? options.attributes.id : 'data-cm-id' ), // column id span : ( options.attributes.span ? options.attributes.span : 'data-cm-span' ), // colspan property floater : 'cm-floater', }; var table = options.table; var head = table.find(selectors.head); var body = table.find(selectors.body); var root ; /** * @method toggleable * Enables hiding and showing groups of columns. * To trigger a column toggle, trigger 'colme:hideColumn' event on the table. */ this.toggleable = function() { var hideCol = function (event, groupId) { var elems = table.find('.' + groupId); var elem = table.find('[' + attributes.id + '=' + groupId + ']'); // The head of the column group if (!elem.is(':visible')) { return; } var node = tableNodes[groupId]; elems.addClass('cm-hidden'); // Hides descendant elems.filter(selectors.th).each(function () { table.trigger('colme:hidden', $(this).attr(attributes.id)); }); elem.addClass('cm-hidden'); table.trigger('colme:hidden', groupId); for ( var parent = node.parent; parent; parent = parent.parent) { //parent.DOMelement.width(parent.DOMelement.width() - width); // Removes self width from ancestors parent.setCellWidth(); } table.trigger('colme:reflow'); }; var showCol = function (event, groupId) { var elem = table.find('[' + attributes.id + '=' + groupId + ']'); // The head of the column group var elems = table.find('.' + groupId); // The other cells if (elem.is(':visible')) { return; } elems.removeClass('cm-hidden'); // Shows descendant elems.filter(selectors.th).each(function () { table.trigger('colme:shown', $(this).attr(attributes.id)); }); var node = tableNodes[groupId]; var width = node.getWidth(); var parent = node.parent; elem.removeClass('cm-hidden'); // Shows self table.trigger('colme:shown', groupId); for (; parent; parent = parent.parent) { /* Updates its width and that of its descendants */ if ( parent.parent){ parent.DOMelement.removeClass('cm-hidden'); table.trigger('colme:shown', parent.id); parent.DOMelement.width( parent.DOMelement.width() + width ); parent.setCellWidth(); } } table.trigger('colme:reflow'); }; table.on('colme:hideColumn',hideCol); table.on('colme:showColumn',showCol ); table.on('colme:toggleColumn',function(event,groupId){ var elem = table.find('[' + attributes.id + '=' + groupId + ']').first(); if ( !elem.is(':visible')){ showCol(event,groupId); return; } hideCol(event,groupId); }); }; /* * Returns an object representing the current layout. */ this.getLayout = function() { var layout = {}; for ( var i in tableNodes ){ layout[i] = tableNodes[i].toObject(); } return layout; }; /* * Applies the layout specified by "layout" */ this.setLayout = function( layout ) { if ( typeof layout == 'string'){ layout = JSON.parse(layout); } var currNode; for ( var i in layout ){ currNode = tableNodes[layout[i].id]; //currNode.width = layout[i].width; var aux={}; for ( var j in currNode.children ){ aux[ currNode.children[j].id ] = currNode.children[j]; } var newChildren =[]; for ( var k in layout[i].children ){ newChildren.push( aux[ layout[i].children[k].id] ); } currNode.children = newChildren; } applyOrderWidthAndVisibility(layout); }; /** * Applies order, width and visibility */ function applyOrderWidthAndVisibility (layout) { var stack = [{node :root , index :0}]; do{ var current = stack[stack.length-1]; if (current.node.children.length === 0 && current.node.parent) { table.find('.' + current.node.parent.id).each(function () { /* Appends node to own row */ $(this).parent().append($(this)); $(this).removeClass('cm-hidden'); }).width(layout[current.node.id].width).addClass(!layout[current.node.id].visible ? 'cm-hidden' : ''); /* Apply width and visibility to itself */ stack.pop(); continue; // because there are not more children } if (current.index >= current.node.children.length) { stack.pop(); continue; // because there are not more children } if (current.index === 0 && current.node.parent) { /* Appends node to own row */ current.node.DOMelement.parent().append(current.node.DOMelement); /* Apply width to itself */ current.node.DOMelement.width(layout[current.node.id].width); /* Set visiblity */ current.node.DOMelement.removeClass('cm-hidden'); current.node.DOMelement.addClass(!layout[current.node.id].visible? 'cm-hidden' : ''); } stack.push({node: current.node.children[current.index++], index : 0}); } while ( stack.length > 1); table.trigger('colme:reflow'); } /** * Makes miracles. * * @author Your Heart * @param {Hapiness} lots_of - The stuff dreams are made of. */ function doYouBelieveInMiracles() { return 'Hey! Thank You for using this plugin! We really had a blast making it! Kisses if you are a hot girl!'; } /** * @method resizable * Makes columns resizable * @author lopis * @author carlosmtx */ this.resizable = function() { var colIds = head.find(selectors.th + '[' + attributes.id + ']'); $('<style>.ui-resizable-helper::after{height: '+table.height()+'px;}</style>').appendTo('head'); $(colIds).each(function () { $(this).resizable({ handles : 'e', distance : 3 , helper : 'ui-resizable-helper', start : function (event, ui) { $(ui.helper).height(ui.originalSize.height); $(ui.helper).css('top', table.offset().top); }, stop : function(event, ui) { var initialWidth = ui.originalSize.width; var finalWidth = ui.size.width; var delta = finalWidth - initialWidth; var absDelta = Math.abs(delta); var sign = delta > 0 ? 1 : -1; var element = $(ui.element.context); //var span = element.attr(attributes.span); var resizeRootNode = tableNodes[element.attr(attributes.id)]; resizeRootNode.DOMelement.width( resizeRootNode.getWidthResize(initialWidth) ); resizeRootNode.resizeAcumulator =0; resizeRootNode.resizeAmount = absDelta; var stack = [ {iterated : false , node : resizeRootNode } ]; var childrenNodes =[{iterated : false , node : resizeRootNode }]; var leafNodes = []; //var lost =0; // Traversing the tree // ------------------- do{ var current = stack[stack.length -1]; //The current node and all its children were already visited //---------------------------------------------------------- if ( current.iterated ){ stack.pop(); if ( !current.node.isVisible() ){ continue; } current.node.parent.resizeAcumulator += current.node.resizeAcumulator; continue; } //The node children must be visited to determine the current node width change //---------------------------------------------------------------------------- for ( var child = 0 ; child < current.node.children.length ; child++ ){ var theNew = {iterated : false , node : current.node.children[child] }; theNew.node.resizeAmount = Math.floor( current.node.resizeAmount * theNew.node.getWidth() / current.node.getWidth() ); theNew.node.minimumWidth = Math.ceil( current.node.getImmutableWidth() * theNew.node.DOMelement.width() / current.node.DOMelement.width() ); theNew.node.resizeAcumulator= 0; stack.push(theNew); childrenNodes.push(theNew); } //The current node is a final node , the current node can be resized without problem if ( current.node.children.length === 0 && current.node.isVisible()){ current.node.resizeAcumulator = current.node.resizeAmount; if ( sign < 0){ var parentRestric= false; var childRestric = false; if ( current.node.minimumWidth > current.node.getWidth() - current.node.resizeAmount ){ parentRestric = current.node.getWidth() - current.node.minimumWidth; } if ( current.node.resizeAmount > current.node.getMutableWidth() ){ childRestric = current.node.getMutableWidth() - 1; } if ( parentRestric || childRestric ){ parentRestric = parentRestric === false ? Number.MAX_VALUE : parentRestric; childRestric = childRestric === false ? Number.MAX_VALUE : childRestric; current.node.resizeAcumulator = parentRestric < childRestric ? parentRestric : childRestric; } } leafNodes.push(current); } //The current node was visited //---------------------------- current.iterated = true; } while ( stack.length > 1); // Applying possible width to all the descendant nodes for ( var i = 0 ; i < childrenNodes.length ; i++){ childrenNodes[i].node.DOMelement.width( childrenNodes[i].node.resizeAcumulator * sign + childrenNodes[i].node.getMutableWidth() ); } // Applying possible width to all the body elements for ( i = 0 ; i < leafNodes.length ; i++){ var id = leafNodes[i].node.parent.DOMelement.attr(attributes.id); body.find( '.' + id ).width( leafNodes[i].node.getMutableWidth() ); } // Applying possible width to all parent nodes for( var ancestor = resizeRootNode.parent; ancestor ; ancestor = ancestor.parent) { ancestor.DOMelement.width( ancestor.getMutableWidth() + resizeRootNode.resizeAcumulator * sign ); } table.trigger('colme:reflow'); } }); $(this).on('resizestart', function (e) { e.stopPropagation(); }); }); }; /** * @method draggable * Enables dragging columns or column groups. Columns can be dragged within their group. */ this.draggable = function() { // Initialize handler for column dragging head.find(selectors.th).mousedown(function(event) { // Prevents children from triggering this event // Only accepts left click to drag if (event.target != this || event.which != 1) { return; } //$(selectors.th).unbind('mousedown'); /** Width of this column (or column group) **/ var width = $(this).width(); var groupId = $(this).attr(attributes.id); /** Initial position of the element in the page **/ floater.startPosX = $(this).offset().left - $(window).scrollLeft(); floater.startPosY = $(this).offset().top + $(window).scrollTop(); floater.mouseOffsetX = event.pageX - floater.startPosX; floater.groupId = groupId; var parentNode = tableNodes[groupId].parent.DOMelement; if (!parentNode || parentNode.length < 1) { parentNode = head; } floater.lowerBoundX = parentNode.offset().left + floater.mouseOffsetX; floater.upperBoundX = parentNode.offset().left + parentNode.width() + floater.mouseOffsetX - width; /** Create a placeholder where the cells before moved are **/ var headerClass = selectors.th.replace('.',''); var bodyClass = selectors.td.replace('.',''); var placeholderHeader = $('<div>', {class: 'cm-drag-placeholder ' + headerClass, width: width}); var placeholderBody = $('<div>', {class: 'cm-drag-placeholder ' + bodyClass, width: width}); $(this).after(placeholderHeader.clone()); // Add placeholder infront of itself head.find(selectors.row).each(function () { // Then to the "children" in the header afterLastOfType($(this), groupId, placeholderHeader.clone()); }); body.find(selectors.row).each(function () { // And in the children in the body afterLastOfType($(this), groupId, placeholderBody.clone()); }); /** Copy cells of this col group into the floater **/ var floaterHead = floater.DOMelement.find(selectors.head); var floaterBody = floater.DOMelement.find(selectors.body); head.find(selectors.row).each(function () { var thisRowCells = $(this).find('.' + groupId + ' ,[' + attributes.id + '=' + groupId + ']'); var newRow = $('<div>', {class: selectors.row.replace('.','')}); newRow.append(thisRowCells); // Moves cells to the new row in the floater floaterHead.append(newRow); }); body.find(selectors.row).each(function () { var thisRowCells = $(this).find('.' + groupId); var newRow = $('<div>', {class: selectors.row.replace('.','')}); newRow.append(thisRowCells); // Moves cells to the new row in the floater floaterBody.append(newRow); }); refreshFloater(event); /** Sets initial position of the floater **/ floater.DOMelement.css('top', head.offset().top - $(document).scrollTop()); floater.DOMelement.css('left', -floater.mouseOffsetX); /** Bind position of the floater to mouse movement **/ $(window).mousemove(function(event) { refreshFloater(event); refreshPlaceHolder(event); }); $(window).mouseup(stopDrag); // Because this is a drag event, it starts selecting text. So this disables it. // Because this is a sow task, it's down in the end of this function. $('*').css('user-select', 'none'); }); }; /** * Utility function to add 'afterElement' after the last found element with a given class 'groupId' * * @param {Object} element - The element where it will be inserted. * @param {String} groupId - The id. * @param {Object} afterElement - The element being inserted into 'element'. * @author lopis */ function afterLastOfType (element, groupId, afterElement) { var lastOfGroup = element.find('.' + groupId).last(); if (lastOfGroup.length > 0) { lastOfGroup.after(afterElement); } } /** * Updates the position of the floater with the current position of the mouse. Restricts * the position of the floater to the limits of the col group (defined in floater). * * @param {Event} e - The mouse move event. * @author lopis */ function refreshFloater (e) { var scrollLeft = $(window).scrollLeft(); var pos = Math.max(Math.min(e.pageX, floater.upperBoundX- scrollLeft), floater.lowerBoundX- scrollLeft); floater.DOMelement.css('transform', 'translate3D('+pos+'px, 0, 0)'); //floater.DOMelement.find(selectors.head).css('transform', 'translateY('+(30+$(window).scrollTop())+'px)'); } /** * No offense intended. I have seen and enjoyed drag shows. * But this specific drag event stops here. * * @author lopis */ function stopDrag () { var floaterHead = floater.DOMelement.find(selectors.head); var floaterBody = floater.DOMelement.find(selectors.body); var placeHolder = $('.cm-drag-placeholder'); var rowToUpdate = placeHolder.first().parents(selectors.row); floater.DOMelement.css('left', -1000); /** Removes mouse binds **/ $(window).unbind('mousemove'); $(window).unbind('mouseup'); /** Prepends content of the floater to the placeholder **/ floaterHead.find(selectors.row).each(function (rowIndex) { var thisRowCells = $(this).find(selectors.th); head.find(selectors.row).eq(rowIndex).find('.cm-drag-placeholder').before(thisRowCells); }); floaterBody.find(selectors.row).each(function (rowIndex) { var thisRowCells = $(this).find(selectors.td); body.find(selectors.row).eq(rowIndex).find('.cm-drag-placeholder').before(thisRowCells); }); /* Apply current column order in the tree */ var newChildren = []; rowToUpdate.find('.' + tableNodes[floater.groupId].parent.id).each(function () { newChildren.push($(this).attr(attributes.id)); }); tableNodes[floater.groupId].parent.children.sort(function (arg1, arg2) { return newChildren.indexOf(arg1.id) - newChildren.indexOf(arg2.id); }); /** Removes the placeholder **/ $('.cm-drag-placeholder').remove(); /** Clears the drag **/ floater.DOMelement.find(selectors.row).remove(); table.trigger('colme:reflow'); } /** * @method refreshPlaceHolder * When the floater moves, try to move the * columns around, changing the position of * the placeholder. * * @author lopis */ function refreshPlaceHolder (event) { var firstPlaceholder = table.find('.cm-drag-placeholder').first(); var offset = firstPlaceholder.offset().left; var prevSibling = firstPlaceholder.prev(); var nextSibling = firstPlaceholder.next(); // Position relative to element is (pageX-offset). // Position is bound to the col group var scrollLeft = $(window).scrollLeft(); var mouseX = Math.max(Math.min(event.pageX + scrollLeft, floater.upperBoundX), floater.lowerBoundX) - floater.mouseOffsetX; if (mouseX >= offset + nextSibling.width() * 0.4) { movePlaceholder(firstPlaceholder, true, nextSibling.attr(attributes.id)); } else if (mouseX <= offset - prevSibling.width() * 0.6) { movePlaceholder(firstPlaceholder, false, prevSibling.attr(attributes.id)); } else { } } /** * When the floater moves beyond a certain point, the placeholder jumps forward or backward. * @param {Boolean} isForward - True if the placeholder should move forward, false otherwise. * @author lopis */ function movePlaceholder (firstPlaceholder, isForward, siblingId) { floater.DOMelement.find(selectors.row).each(function (rowIndex) { var tableRow = table.find(selectors.row).eq(rowIndex); var span = tableRow.find('.' + siblingId + ',[' + attributes.id + '=' + siblingId + ']').length; if (isForward) { tableRow.find('.cm-drag-placeholder').each(function () { $(this).siblings().addBack().eq($(this).index() + span).after($(this)); }); } else { tableRow.find('.cm-drag-placeholder').each(function () { $(this).siblings().addBack().eq($(this).index() - span).before($(this)); }); } }); } /** * @method headerSticky * Makes the header sticky when the container scrolls past the top. * * @param {Object} container - An object, typically as returned by '$(window)', that is being scrolled on. */ this.headerSticky = function(container) { container.scroll(function () { var scrollTop = container.scrollTop(); var offsetTop = container.offset() ? 0 : table.offset().top; var offsetBottom = table.height() - head.height(); if (scrollTop > offsetTop + offsetBottom) { head.css('transform', 'translate3d(0,'+offsetBottom+'px,0)'); } else if(scrollTop > offsetTop) { head.css('transform', 'translate3d(0,'+(scrollTop-offsetTop)+'px,0)'); } else { head.css('transform', 'translate3d(0px)'); } }); container.scroll(); // triggers the repositioning of the header }; /** * @method updateTable * When the table structure has been manually changed, such as when lines or columns * have been inserted or removed, the table tree must be updated, or [colme] won't behave correctly. * * @author lopis */ this.updateTable = function() { // Refreshed the table tree representation. for ( var i = 0; i < tableNodes.length; i++) { delete tableNodes[i]; } createTree(); root.setCellWidth(); table.trigger('colme:isReady'); }; this.refreshWidth = function(node) { node.resizeAmount = 0; node.resizeAcumulator = 0; for( var child in node.children){ this.refreshWidth(node.children[child]); } if ( node.parent ){ if (node.children.length) { node.DOMelement.width( node.getWidthResize(node.resizeAcumulator ) ); } node.parent.resizeAcumulator += node.getWidth(); } }; /** * Creates a tree representation of the table using the colspan values to * establish relationships between columns. * * @author carlosmtx * @author lopis */ function createTree(){ var colCount=0; head.find(selectors.row).first().find(selectors.th).each(function () { var c = parseInt($(this).attr(attributes.span)); colCount += !c ? 1 : c; }); root = new Node(undefined,colCount,0); var headerRows = head.find(selectors.row); var currParents = [root]; // Iteration through each row //------------------------------- for ( var i = 0; i < headerRows.length; i++) { var newParents=[]; var currentOffset = 0; var ths = $( headerRows[i] ).find(selectors.th); // Iterating through each th inside a row //--------------------------------------- for ( var j = 0 ; j < ths.length ; j++ ){ var colspan = $(ths[j]).attr(attributes.span); colspan = parseInt( !colspan ? '1' : colspan); var newChild = 0; // Checking which parent is the newChild parent (?) // ------------------------------------------------ for( var k = 0 ; k < currParents.length ; k++){ if ( currentOffset < currParents[k].colspanOffset + currParents[k].colspan ){ var newChildId = 'cm-'+i+'-'+j+'-'+k ; $(ths[j]).addClass(currParents[k].classes); $(ths[j]).addClass(currParents[k].id); $(ths[j]).attr(attributes.id, newChildId); newChild = new Node( currParents[k], colspan, currentOffset, newChildId ); tableNodes[newChild.id] = newChild; currParents[k].addChild( newChild ); break; } } newParents.push(newChild); currentOffset += colspan; } currParents = newParents; } var thCursor = 0; var tdCursor = 0; var rows = body.find(selectors.row); var tds = body.find(selectors.td); /* Searches which 'parent' this cell belongs to by * using the values of the colspan */ head.find(selectors.row).last().find(selectors.th).each(function () { var thNode = tableNodes[$(this).attr(attributes.id)]; thCursor += thNode.colspan; while(tdCursor < thCursor) { rows.each(function () { $(this).children().eq(tdCursor).addClass(thNode.classes + ' ' + thNode.id); }); tdCursor += $(tds[tdCursor]).attr(attributes.span) ? $(tds[tdCursor]).attr(attributes.span) : 1; } }); /* Transverses the tree to collect its leaf nodes */ var leafs=[]; for ( var node in tableNodes){ if ( tableNodes[node].children.length === 0){ leafs.push(tableNodes[node]); } } /* Connects the last row of the header (the 'leafs') to the first row of the body */ var firstRow = body.find(selectors.row).first(); for ( var leaf = 0 ; leaf < leafs.length ; leaf++){ firstRow.find('.' + leafs[leaf].id ).each(function(index){ var newNode = new Node( leafs[leaf] , 1 , 0, leafs[leaf].id + '--' + leaf + '--' + index); newNode.DOMelement = $(this); leafs[leaf].addChild(newNode); tableNodes[newNode.id] = newNode; newNode.DOMelement.attr(attributes.id, newNode.id); }); } } function addMarkup(){ var rows = head.find(selectors.row); rows.each(function(){ $(this).children('div').each( function(){ $(this).addClass(classes.th); }); }); rows = body.find(selectors.row); rows.each(function(){ $(this).children('div').each( function(){ $(this).addClass(classes.td); }); }); } if ( modules.addMarkup ){ addMarkup(); } createTree(); this.refreshWidth(root); /* Inits jquery plugin and sets handlers for resizing */ if ( modules.resize ) { this.resizable(); } /* Creates floater and sets dragging handlers */ if ( modules.draggable ) { var currentFloater = $('#' + attributes.floater); if (currentFloater.length === 0) { floater.DOMelement = $('<div>', {id: attributes.floater}); floater.DOMelement.append($('<div>', {class: selectors.head.replace('.','')})); floater.DOMelement.append($('<div>', {class: selectors.body.replace('.','')})); floater.DOMelement.css({position: 'fixed'}); table.append(floater.DOMelement); } else { floater.DOMelement = currentFloater; } this.draggable(); } /* Sets scroll handlers to control table header */ if ( modules.stickyH ) { this.headerSticky(options.sticky); } /* Sets toggling handlers */ if (modules.toggleC) { this.toggleable(); } doYouBelieveInMiracles(); table.trigger('colme:isReady'); /** * The structure that defines the table is represented internally by a tree, composed of Nodes. * The tree can be transversed in both directions to allow propagation of actions up and down. * The tree never changes after performing an action on the table. If changes occur, the tree must be * refreshed with this.updateTable(). * * @param {Node} parent - The direct ancestor * @param {int} colspan - Colspan of this cell * @param {int} colspanOffset - Sum of colspans before this cell * @param {String} newId - And ID for this cell * * @author carlosmtx * @author lopis */ function Node (parent,colspan,colspanOffset,newId){ this.parent = parent; this.children = []; this.colspan = colspan; this.colspanOffset = colspanOffset; // Only used to build the tree this.id = !newId ? 'cm-root' : newId; this.classes = ''; this.DOMelement = head.find('['+attributes.id+'='+newId+']'); //This Elements exist to help the tree traversing when resizing //------------------------------------------------- this.resizeAcumulator = 0; this.resizeAmount = 0; this.minimumWidth = 0; if (this.parent) { this.classes = this.parent.classes + ' ' + this.parent.id; } this.addChild = function(child){ this.children.push(child); }; this.getWidth = function(){ return this.DOMelement.width() + parseInt(this.DOMelement.css('border-left-width')) + parseInt(this.DOMelement.css('border-right-width')) + parseInt(this.DOMelement.css('padding-left')) + parseInt(this.DOMelement.css('padding-right'))+ parseInt(this.DOMelement.css('margin-right'))+ parseInt(this.DOMelement.css('margin-left')); }; this.getWidthResize = function(targetWidth){ return targetWidth - ( parseInt(this.DOMelement.css('border-left-width')) + parseInt(this.DOMelement.css('border-right-width')) + parseInt(this.DOMelement.css('padding-left')) + parseInt(this.DOMelement.css('padding-right'))+ parseInt(this.DOMelement.css('margin-right'))+ parseInt(this.DOMelement.css('margin-left')) ); }; this.getImmutableWidth = function(){ return parseInt(this.DOMelement.css('border-left-width')) + parseInt(this.DOMelement.css('border-right-width')) + parseInt(this.DOMelement.css('padding-left')) + parseInt(this.DOMelement.css('padding-right'))+ parseInt(this.DOMelement.css('margin-right'))+ parseInt(this.DOMelement.css('margin-left')); }; this.getMutableWidth = function(){ return parseInt( this.DOMelement.width() ); }; this.isVisible = function(){ if ( !this.DOMelement){ return true; } return this.DOMelement.hasClass('cm-hidden') ? false : true; }; this.toJSON = function() { return { colspan : this.colspan, id : this.id, children : this.children }; }; this.toObject = function() { var obj = { colspan : this.colspan, id : this.id, width : this.DOMelement.width(), children : [], visible : !this.DOMelement.hasClass('cm-hidden'), }; for ( var i in this.children ){ obj.children.push( this.children[i].toObject() ); } return obj; }; /** * Visits all descendants and set its width equal * to the sum of the width of its descendants * * @author lopis */ this.setCellWidth = function () { if (!this.children || this.children.length < 1) { return this.DOMelement.is(':visible') ? this.getWidth() : 0; } else { var width = 0; for (var i = 0; i < this.children.length; i++) { width += this.children[i].setCellWidth(); } if (width === 0) { this.DOMelement.addClass('cm-hidden'); } else { this.DOMelement.width(this.getWidthResize(width)); this.DOMelement.removeClass('cm-hidden'); } return width; } }; } } $.fn.colme = function(options) { options.table = this; var c = new Colme(options); /* Public functions */ return { getLayout: c.getLayout, setLayout: c.setLayout, }; };
lopis/colme
js/jquery.colme.js
JavaScript
mit
37,101
/* eslint-env browser */ import React, { Component } from 'react'; import QuestionDetail from '../parts/QuestionDetail'; import * as CommonQuestionParts from '../parts/CommonQuestionParts'; /** 設問:複数行テキスト */ export default class TextQuestion extends Component { render() { const { survey, options, replacer, question } = this.props; const name = question.getOutputName(); return ( <div className="TextQuestion"> { CommonQuestionParts.title(question, replacer) } { CommonQuestionParts.description(question, replacer) } <div className="question"> <textarea name={name} id={name} className="freetext" rows="6" cols="40" data-output-no={survey.findOutputNoFromName(name)} data-response-key="value" data-response-multiple={false} data-parsley-required /> </div> { options.isShowDetail() ? <QuestionDetail optional {...this.props} /> : null } </div> ); } }
jirokun/survey-designer-js
lib/runtime/components/questions/TextQuestion.js
JavaScript
mit
1,073
module.exports = function () { var base = { webroot: "./wwwroot/", node_modules: "./node_modules/" }; var config = { /** * Files paths */ angular: base.node_modules + "@angular/**/*.js", app: "App/**/*.*", appDest: base.webroot + "app", js: base.webroot + "js/**/*.js", css: base.webroot + "css/**/*.css", lib: base.webroot + "lib/", node_modules: base.node_modules, angularWebApi: base.node_modules + "angular2-in-memory-web-api/*.js", corejs: base.node_modules + "core-js/client/shim*.js", zonejs: base.node_modules + "zone.js/dist/zone*.js", reflectjs: base.node_modules + "reflect-metadata/Reflect*.js", systemjs: base.node_modules + "systemjs/dist/*.js", rxjs: base.node_modules + "rxjs/**/*.js", jasminejs: base.node_modules + "jasmine-core/lib/jasmine-core/*.*" }; return config; };
daltoncabrera/possytem
PosSystem/src/PosSystem/gulp.config.js
JavaScript
mit
969
module.exports.run = async (client, message, args) => { var roll = Math.floor(Math.random() * 8) let arg1 = args.slice(1) let arg2 = args.slice(0, 1) if (roll >= 4) { message.channel.send({embed: { color: 10790566, description: 'Mon choix est: ' + arg1 + '\nroll: ' + roll }}) } else { message.channel.send({embed: { color: 10790566, description: 'Mon choix est: ' + arg2 + '\nroll: ' + roll }}) } }
Commantary/discord-bot-comabot
module/choice.js
JavaScript
mit
454
/** * Line Style Copyright (c) 2014 Miguel Castillo. * * Licensed under MIT */ define(function(require /*, exports, module*/) { "use strict"; var EditorManager = brackets.getModule("editor/EditorManager"); var PreferencesManager = brackets.getModule("preferences/PreferencesManager"); var prefs = PreferencesManager.getExtensionPrefs("brackets-line-style"); var mainTmpl = require("text!main.tmpl"); var $style = $("<style id='line-style'>").appendTo("head"); prefs.definePreference("height", "string", "").on("change", function() { var lineHeight = prefs.get("height"); if (lineHeight) { $style.text(Mustache.render(mainTmpl, { height: lineHeight })); } else { $style.text(""); } refreshEditor(); }); function refreshEditor() { var editor = EditorManager.getActiveEditor(); if (editor) { setTimeout(function() { editor.refresh(); }); } } });
MiguelCastillo/Brackets-LineStyle
main.js
JavaScript
mit
985
var mongoose = require('mongoose'); var User = require('./../models/user.model'); var Chat = require('./../models/chat.model'); exports.index = function(req, res) { res.render('login'); }; exports.chat = function(req, res) { var email = req.session.email; console.log('email', email); User.getFriends(email, function(err, dude) { if (err) console.log('err', err); var data = { user: dude, }; res.render('index', { initialState: JSON.stringify(data) }); }); } exports.postLogin = function(req, res) { var email = req.body.email; User.getFriends(email, function(err, dude) { if (err) console.log('err', err); var url = '/' if (dude) { req.session.email = email; url = '/chat' } res.send({url: url}); }); } exports.getMessages = function(req, res) { Chat.getLastMsgs(req.body, function(err, docs) { if (err) res.send({err: console.log('err', err)}); else { res.send({ messages: docs }); } }); }
juancjara/my-hangout
routes/main.route.js
JavaScript
mit
1,026